repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Tinchosan/wingpanel
admin/lib/vendor/mpdf/mpdf/tmp/ttfontdata/dejavusanscondensed.cw127.php
2055
<?php $rangeid=122; $prevcid=126; $prevwidth=754; $interval=false; $range=array ( 32 => array ( 0 => 286, 1 => 360, 2 => 414, 3 => 754, 4 => 572, 5 => 855, 6 => 702, 7 => 247, ), 40 => array ( 0 => 351, 1 => 351, 'interval' => true, ), 42 => array ( 0 => 450, 1 => 754, 2 => 286, 3 => 325, 4 => 286, 5 => 303, ), 48 => array ( 0 => 572, 1 => 572, 'interval' => true, 2 => 572, 3 => 572, 4 => 572, 5 => 572, 6 => 572, 7 => 572, 8 => 572, 9 => 572, ), 58 => array ( 0 => 303, 1 => 303, 'interval' => true, ), 60 => array ( 0 => 754, 1 => 754, 'interval' => true, 2 => 754, ), 63 => array ( 0 => 478, 1 => 900, 2 => 615, 3 => 617, 4 => 628, 5 => 693, 6 => 568, 7 => 518, 8 => 697, 9 => 677, ), 73 => array ( 0 => 265, 1 => 265, 'interval' => true, ), 75 => array ( 0 => 590, 1 => 501, 2 => 776, 3 => 673, 4 => 708, 5 => 542, 6 => 708, 7 => 625, 8 => 571, 9 => 549, 10 => 659, 11 => 615, 12 => 890, 13 => 616, 14 => 549, 15 => 616, 16 => 351, 17 => 303, 18 => 351, 19 => 754, ), 95 => array ( 0 => 450, 1 => 450, 'interval' => true, ), 97 => array ( 0 => 551, 1 => 571, 2 => 495, 3 => 571, 4 => 554, 5 => 316, 6 => 571, 7 => 570, ), 105 => array ( 0 => 250, 1 => 250, 'interval' => true, ), 107 => array ( 0 => 521, 1 => 250, 2 => 876, 3 => 570, 4 => 550, ), 112 => array ( 0 => 571, 1 => 571, 'interval' => true, ), 114 => array ( 0 => 370, 1 => 469, 2 => 353, 3 => 570, 4 => 532, 5 => 736, ), 120 => array ( 0 => 532, 1 => 532, 'interval' => true, ), 122 => array ( 0 => 472, 1 => 572, 2 => 303, 3 => 572, 4 => 754, ), );
gpl-3.0
09zwcbupt/undergrad_thesis
ext/poxdesk/qx/component/skeleton/contribution/trunk/source/class/custom/theme/modern/Decoration.tmpl.js
280
/* ************************************************************************ Copyright: License: Authors: ************************************************************************ */ qx.Theme.define("${Namespace}.theme.modern.Decoration", { decorations : { } });
gpl-3.0
xctcc/embrr
setting.php
7543
<?php include ('lib/twitese.php'); $title = "Settings"; include ('inc/header.php'); if (!loginStatus()) header('location: login.php'); ?> <script src="js/colorpicker.js"></script> <script src="js/setting.js"></script> <link rel="stylesheet" href="css/colorpicker.css" /> <div id="statuses" class="column round-left"> <div id="setting"> <div id="setting_nav"> <?php $settingType = isset($_GET['t'])? $_GET['t'] : 1; switch($settingType){ case 'profile': ?> <span class="subnavLink"><a href="setting.php">Customize</a></span><span class="subnavNormal">Profile</span> <?php break; default: ?> <span class="subnavNormal">Customize</span><span class="subnavLink"><a href="setting.php?t=profile">Profile</a></span> <?php } ?> </div> <?php switch($settingType){ case 'profile': $user = getTwitter()->veverify(true); ?> <form id="setting_form" action="ajax/uploadImage.php?do=profile" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Avatar</legend> <ol> <li style="display:inline-block"><img src="<?php echo isset($_COOKIE['imgurl']) ? $_COOKIE['imgurl'] : getAvatar($user->profile_image_url)?>" id="avatarimg"></img></li> <ol style="margin-left:29px"> <li><input type="file" name="image" id="profile_image"/></li> <li><input type="submit" id="AvatarUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> </ol></ol> </fieldset> </form> <form id="setting_form" action="ajax/uploadImage.php?do=background" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Background</legend> <ol> <li style="display:inline-block"><img src="<?php echo getAvatar($user->profile_background_image_url)?>" id="backgroundimg" style="max-width: 460px;"></img></li> <li><input type="file" name="image" id="profile_background"/></li> <li><input type="submit" id="BackgroundUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> <li> <input id="tile" type="checkbox" <?php echo $user->profile_background_tile ? 'checked="checked"' : '' ?> /> <label>Tile the profile background</label> </li> </ol> </fieldset> </form> <form id="setting_form" action="ajax/updateProfile.php" method="post"> <fieldset class="settings"> <legend>Literature</legend> <table id="setting_table"> <tr> <td class="setting_title">Name: </td> <td><input class="setting_input" type="text" name="name" value="<?php echo isset($user->name) ? $user->name : ''?>" /></td> </tr> <tr> <td class="setting_title">URL: </td> <td><input class="setting_input" type="text" name="url" value="<?php if (!isset($user->url)) echo ''; else { $hops = array(); $newurl = expandRedirect($user->url, $hops); echo $newurl; } ?>" /></td> </tr> <tr> <td class="setting_title">Location: </td> <td><input class="setting_input" type="text" name="location" value="<?php echo isset($user->location) ? $user->location : '' ?>" /></td> </tr> <tr> <td class="setting_title">Bio: </td><td><small style="margin-left:5px;vertical-align: top;">*Max 160 chars</small></td> </tr><tr> <td></td> <td><textarea id="setting_text" name="description"><?php echo isset($user->description) ? $user->description : '' ?></textarea></td> </tr> </table> <input type="submit" id="saveProfile" class="btn" value="Save" /> </fieldset> <?php break; default: ?> <form id="style_form" action="setting.php" method="post"> <fieldset class="settings"> <legend>Utility</legend> <input id="proxifyAvatar" type="checkbox" /> <label>Proxify the Avatar</label> <br /><br /> <input id="autoscroll" type="checkbox" /> <label>Timeline Autopaging</label> <br /><br /> <input id="sidebarscroll" type="checkbox" /> <label>Fixed Sidebar</label> <br /><br /> Share to Twitter: <a class="share" title="Drag me to share!" href="javascript:var%20d=document,w=window,f='<?php echo $base_url."/share.php" ?>',l=d.location,e=encodeURIComponent,p='?u='+e(l.href)+'&t='+e(d.title)+'&d='+e(w.getSelection?w.getSelection().toString():d.getSelection?d.getSelection():d.selection.createRange().text)+'&s=bm';a=function(){if(!w.open(f+p,'sharer','toolbar=0,status=0,resizable=0,width=600,height=300,left=175,top=150'))l.href=f+'.new'+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}void(0);">Share</a> <small>(Bookmark this link for future use)</small> </fieldset> <fieldset class="settings"> <legend>Media Preview</legend> <input id="showpic" type="checkbox" checked="checked" /> <label>Enable Images Preview</label> <small>(Supports common image hostings)</small> <br /><br /> <input id="mediaPreSelect" type="checkbox" checked="checked" /> <label>Enable Videos Preview</label> <small>(Supports Xiami and Tudou)</small><br /> </fieldset> <fieldset class="settings"> <legend>Auto Refresh Interval</legend> <label>Home Page</label> <select id="homeInterval" name="homeInterval" value="<?php echo getCookie('homeInterval')?>"> <option value="1">1 min</option> <option value="2" selected="selected">2 min (Default)</option> <option value="3">3 min</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> <label>Updates Page</label> <select id="updatesInterval" name="updatesInterval" value="<?php echo getCookie('updatesInterval')?>"> <option value="1">1 min</option> <option value="2">2 min</option> <option value="3" selected="selected">3 min (Default)</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> </fieldset> <fieldset class="settings"> <legend>UI Preferences</legend> <input id="twitterbg" type="checkbox" /> <label>Use twitter account background</label> <br /><br /> <input id="shownick" type="checkbox" /> <label>Use nickname instead of username</label> <br /><br /> <label>Background Color</label> <input class="bg_input" type="text" id="bodyBg" name="bodyBg" value="<?php echo getDefCookie("Bgcolor","") ?>" /> <small>(Choose your favorite color here)</small> <br /><br /> <label>Font Size</label> <select id="fontsize" name="fontsize" value="<?php echo getCookie('fontsize')?>"> <option value="12px">Small</option> <option value="13px" selected="selected">Middle(Default)</option> <option value="14px">Large</option> <option value="15px">Extra Large</option> </select> <small>(Set the font size)</small> <br /><br /> <label>Customize CSS</label> <small>(You can put your own CSS hack here, or your Twitter style code)</small> <br /> <label>Tips:</label> <small>You must use <a href="http://i.zou.lu/csstidy/" target="_blank" title="Powered by Showfom">CSSTidy</a> to compress your stylesheet.</small> <br /> <textarea type="text" id="myCSS" name="myCSS" value="" /><?php echo getDefCookie("myCSS","") ?></textarea> </fieldset> <?php } ?> <a id="reset_link" href="#" title="You will lose all customized settings!">Reset to default</a> </form> </div> </div> <?php include ('inc/sidebar.php'); include ('inc/footer.php'); ?>
gpl-3.0
GDevs/mission-farpoint
ogre/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp
6592
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreGLRenderSystemCommon.h" #include "OgreFrustum.h" #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN #include <OgreEGLWindow.h> #endif namespace Ogre { void GLRenderSystemCommon::_makeProjectionMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Calc matrix elements Real w = (1.0f / tanThetaY) / aspect; Real h = 1.0f / tanThetaY; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } // NB This creates Z in range [-1,1] // // [ w 0 0 0 ] // [ 0 h 0 0 ] // [ 0 0 q qn ] // [ 0 0 -1 0 ] dest = Matrix4::ZERO; dest[0][0] = w; dest[1][1] = h; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GLRenderSystemCommon::_makeProjectionMatrix(Real left, Real right, Real bottom, Real top, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Real width = right - left; Real height = top - bottom; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = 2 * nearPlane / width; dest[0][2] = (right+left) / width; dest[1][1] = 2 * nearPlane / height; dest[1][2] = (top+bottom) / height; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GLRenderSystemCommon::_makeOrthoMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Real thetaX = thetaY * aspect; Real tanThetaX = tanThetaY * aspect; // Math::Tan(thetaX); Real half_w = tanThetaX * nearPlane; Real half_h = tanThetaY * nearPlane; Real iw = 1.0f / half_w; Real ih = 1.0f / half_h; Real q; if (farPlane == 0) { q = 0; } else { q = 2.0f / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = iw; dest[1][1] = ih; dest[2][2] = -q; dest[2][3] = -(farPlane + nearPlane) / (farPlane - nearPlane); dest[3][3] = 1; } void GLRenderSystemCommon::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, bool forGpuProgram) { // Thanks to Eric Lenyel for posting this calculation at www.terathon.com // Calculate the clip-space corner point opposite the clipping plane // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and // transform it into camera space by multiplying it // by the inverse of the projection matrix Vector4 q; q.x = (Math::Sign(plane.normal.x) + matrix[0][2]) / matrix[0][0]; q.y = (Math::Sign(plane.normal.y) + matrix[1][2]) / matrix[1][1]; q.z = -1.0F; q.w = (1.0F + matrix[2][2]) / matrix[2][3]; // Calculate the scaled plane vector Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d); Vector4 c = clipPlane4d * (2.0F / (clipPlane4d.dotProduct(q))); // Replace the third row of the projection matrix matrix[2][0] = c.x; matrix[2][1] = c.y; matrix[2][2] = c.z + 1.0F; matrix[2][3] = c.w; } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLRenderSystemCommon::_destroyInternalResources(RenderWindow* pRenderWnd) { static_cast<EGLWindow*>(pRenderWnd)->_destroyInternalResources(); } void GLRenderSystemCommon::_createInternalResources(RenderWindow* pRenderWnd, void* window, void* config) { static_cast<EGLWindow*>(pRenderWnd) ->_createInternalResources(reinterpret_cast<EGLNativeWindowType>(window), config); } #endif }
gpl-3.0
sergiocazzolato/snapd
interfaces/builtin/network_control.go
11137
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016-2017 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package builtin import ( "github.com/snapcore/snapd/osutil" ) const networkControlSummary = `allows configuring networking and network namespaces` const networkControlBaseDeclarationSlots = ` network-control: allow-installation: slot-snap-type: - core deny-auto-connection: true ` const networkControlConnectedPlugAppArmor = ` # Description: Can configure networking and network namespaces via the standard # 'ip netns' command (man ip-netns(8)). This interface is restricted because it # gives wide, privileged access to networking and should only be used with # trusted apps. #include <abstractions/nameservice> /run/systemd/resolve/stub-resolv.conf rk, # systemd-resolved (not yet included in nameservice abstraction) # # Allow access to the safe members of the systemd-resolved D-Bus API: # # https://www.freedesktop.org/wiki/Software/systemd/resolved/ # # This API may be used directly over the D-Bus system bus or it may be used # indirectly via the nss-resolve plugin: # # https://www.freedesktop.org/software/systemd/man/nss-resolve.html # #include <abstractions/dbus-strict> dbus send bus=system path="/org/freedesktop/resolve1" interface="org.freedesktop.resolve1.Manager" member="Resolve{Address,Hostname,Record,Service}" peer=(name="org.freedesktop.resolve1"), dbus (send) bus=system path="/org/freedesktop/resolve1" interface="org.freedesktop.resolve1.Manager" member="SetLink{DNS,MulticastDNS,Domains,LLMNR}" peer=(label=unconfined), #include <abstractions/ssl_certs> capability net_admin, capability net_raw, capability setuid, # ping capability net_broadcast, # openvswitchd # Allow protocols except those that we blacklist in # /etc/modprobe.d/blacklist-rare-network.conf network appletalk, network bridge, network inet, network inet6, network ipx, network packet, network pppox, network sna, @{PROC}/@{pid}/net/ r, @{PROC}/@{pid}/net/** r, # used by sysctl, et al @{PROC}/sys/ r, @{PROC}/sys/net/ r, @{PROC}/sys/net/core/ r, @{PROC}/sys/net/core/** rw, @{PROC}/sys/net/ipv{4,6}/ r, @{PROC}/sys/net/ipv{4,6}/** rw, @{PROC}/sys/net/netfilter/ r, @{PROC}/sys/net/netfilter/** rw, @{PROC}/sys/net/nf_conntrack_max rw, # For advanced wireless configuration /sys/kernel/debug/ieee80211/ r, /sys/kernel/debug/ieee80211/** rw, # read netfilter module parameters /sys/module/nf_*/ r, /sys/module/nf_*/parameters/{,*} r, # networking tools /{,usr/}{,s}bin/arp ixr, /{,usr/}{,s}bin/arpd ixr, /{,usr/}{,s}bin/bridge ixr, /{,usr/}{,s}bin/dhclient Pxr, # use ixr instead if want to limit to snap dirs /{,usr/}{,s}bin/dhclient-script ixr, /{,usr/}{,s}bin/ifconfig ixr, /{,usr/}{,s}bin/ifdown ixr, /{,usr/}{,s}bin/ifquery ixr, /{,usr/}{,s}bin/ifup ixr, /{,usr/}{,s}bin/ip ixr, /{,usr/}{,s}bin/ipmaddr ixr, /{,usr/}{,s}bin/iptunnel ixr, /{,usr/}{,s}bin/iw ixr, /{,usr/}{,s}bin/nameif ixr, /{,usr/}{,s}bin/netstat ixr, # -p not supported /{,usr/}{,s}bin/nstat ixr, /{,usr/}{,s}bin/ping ixr, /{,usr/}{,s}bin/ping6 ixr, /{,usr/}{,s}bin/pppd ixr, /{,usr/}{,s}bin/pppdump ixr, /{,usr/}{,s}bin/pppoe-discovery ixr, #/{,usr/}{,s}bin/pppstats ixr, # needs sys_module /{,usr/}{,s}bin/route ixr, /{,usr/}{,s}bin/routef ixr, /{,usr/}{,s}bin/routel ixr, /{,usr/}{,s}bin/rtacct ixr, /{,usr/}{,s}bin/rtmon ixr, /{,usr/}{,s}bin/ss ixr, /{,usr/}{,s}bin/sysctl ixr, /{,usr/}{,s}bin/tc ixr, /{,usr/}{,s}bin/wpa_action ixr, /{,usr/}{,s}bin/wpa_cli ixr, /{,usr/}{,s}bin/wpa_passphrase ixr, /{,usr/}{,s}bin/wpa_supplicant ixr, /dev/rfkill rw, /sys/class/rfkill/ r, /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/{,**} r, /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/state w, # For reading the address of a particular ethernet interface /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/net/*/address r, # arp network netlink dgram, # ip, et al /etc/iproute2/{,**} r, /etc/iproute2/rt_{protos,realms,scopes,tables} w, /etc/iproute2/rt_{protos,tables}.d/* w, # ping - child profile would be nice but seccomp causes problems with that /{,usr/}{,s}bin/ping ixr, /{,usr/}{,s}bin/ping6 ixr, network inet raw, network inet6 raw, # pppd capability setuid, @{PROC}/@{pid}/loginuid r, @{PROC}/@{pid}/mounts r, # static host tables /etc/hosts w, # resolvconf /{,usr/}sbin/resolvconf ixr, /run/resolvconf/{,**} rk, /run/resolvconf/** w, /etc/resolvconf/{,**} r, /{,usr/}lib/resolvconf/* ix, # Required by resolvconf /{,usr/}bin/run-parts ixr, /etc/resolvconf/update.d/* ix, # wpa_suplicant /{,var/}run/wpa_supplicant/ w, /{,var/}run/wpa_supplicant/** rw, /etc/wpa_supplicant/{,**} ixr, #ifup,ifdown, dhclient /{,var/}run/dhclient.*.pid rw, /var/lib/dhcp/ r, /var/lib/dhcp/** rw, /run/network/ifstate* rw, /run/network/.ifstate* rw, /run/network/ifup-* rw, /run/network/ifdown-* rw, # route /etc/networks r, /etc/ethers r, /etc/rpc r, # TUN/TAP - https://www.kernel.org/doc/Documentation/networking/tuntap.txt # # We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices # are virtual and don't show up in /dev /dev/net/tun rw, # Access to sysfs interfaces for tun/tap device settings. /sys/devices/virtual/net/tap*/** rw, # access to bridge sysfs interfaces for bridge settings /sys/devices/virtual/net/*/bridge/* rw, # Network namespaces via 'ip netns'. In order to create network namespaces # that persist outside of the process and be entered (eg, via # 'ip netns exec ...') the ip command uses mount namespaces such that # applications can open the /run/netns/NAME object and use it with setns(2). # For 'ip netns exec' it will also create a mount namespace and bind mount # network configuration files into /etc in that namespace. See man ip-netns(8) # for details. capability sys_admin, # for setns() network netlink raw, / r, /run/netns/ r, # only 'r' since snap-confine will create this for us /run/netns/* rw, mount options=(rw, rshared) -> /run/netns/, mount options=(rw, bind) /run/netns/ -> /run/netns/, mount options=(rw, bind) / -> /run/netns/*, umount /, # 'ip netns identify <pid>' and 'ip netns pids foo'. Intenionally omit 'ptrace # (trace)' here since ip netns doesn't actually need to trace other processes. capability sys_ptrace, # 'ip netns exec foo /bin/sh' mount options=(rw, rslave) /, mount options=(rw, rslave), # LP: #1648245 umount /sys/, # Eg, nsenter --net=/run/netns/... <command> /{,usr/}{,s}bin/nsenter ixr, ` const networkControlConnectedPlugSecComp = ` # Description: Can configure networking and network namespaces via the standard # 'ip netns' command (man ip-netns(8)). This interface is restricted because it # gives wide, privileged access to networking and should only be used with # trusted apps. # for ping and ping6 capset # Network namespaces via 'ip netns'. In order to create network namespaces # that persist outside of the process and be entered (eg, via # 'ip netns exec ...') the ip command uses mount namespaces such that # applications can open the /run/netns/NAME object and use it with setns(2). # For 'ip netns exec' it will also create a mount namespace and bind mount # network configuration files into /etc in that namespace. See man ip-netns(8) # for details. bind mount umount umount2 unshare setns - CLONE_NEWNET # For various network related netlink sockets socket AF_NETLINK - NETLINK_ROUTE socket AF_NETLINK - NETLINK_FIB_LOOKUP socket AF_NETLINK - NETLINK_INET_DIAG socket AF_NETLINK - NETLINK_XFRM socket AF_NETLINK - NETLINK_DNRTMSG socket AF_NETLINK - NETLINK_ISCSI socket AF_NETLINK - NETLINK_RDMA socket AF_NETLINK - NETLINK_GENERIC # for receiving kobject_uevent() net messages from the kernel socket AF_NETLINK - NETLINK_KOBJECT_UEVENT ` /* https://www.kernel.org/doc/Documentation/networking/tuntap.txt * * We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices * are virtual and don't show up in /dev */ var networkControlConnectedPlugUDev = []string{ `KERNEL=="rfkill"`, `KERNEL=="tun"`, } var networkControlConnectedPlugMount = []osutil.MountEntry{{ Name: "/var/lib/snapd/hostfs/var/lib/dhcp", Dir: "/var/lib/dhcp", Options: []string{"bind", "rw", osutil.XSnapdIgnoreMissing()}, }} // TODO: Add a layer that derives this sort of data from mount entry, like the // one above, into a set of apparmor rules for snap-update-ns, like the ones // below. // // When setting up a mount entry, we also need corresponding // snap-updates-ns rules. Eg, if have: // []osutil.MountEntry{{ // Name: "/foo/bar", // Dir: "/bar", // Options: []string{"rw", "bind"}, // }} // Then you can expect to need: // /foo/ r, // /foo/bar/ r, // mount options=(rw bind) /foo/bar/ -> /bar/, // umount /bar/, // ... // You'll need 'r' rules for all the directories that need to be traversed, // starting from the root directory all the way down to the directory being // mounted. This is required by the safe bind mounting trick employed by // snap-update-ns. // // You'll need 'rw' rules to support cases when snap-update-ns is expected to // create the missing directory, before performing the bind mount. Note that // there are two sides, one side is the host visible through // /var/lib/snapd/hostfs and the other side is everything else. To support // writes to the host side you need to coordinate with the trespassing rules // implemented in snap-update-ns/system.go. var networkControlConnectedPlugUpdateNSAppArmor = ` /var/ r, /var/lib/ r, /var/lib/snapd/ r, /var/lib/snapd/hostfs/ r, /var/lib/snapd/hostfs/var/ r, /var/lib/snapd/hostfs/var/lib/ r, /var/lib/snapd/hostfs/var/lib/dhcp/ r, /var/lib/dhcp/ r, mount options=(rw bind) /var/lib/snapd/hostfs/var/lib/dhcp/ -> /var/lib/dhcp/, umount /var/lib/dhcp/, ` func init() { registerIface(&commonInterface{ name: "network-control", summary: networkControlSummary, implicitOnCore: true, implicitOnClassic: true, baseDeclarationSlots: networkControlBaseDeclarationSlots, connectedPlugAppArmor: networkControlConnectedPlugAppArmor, connectedPlugSecComp: networkControlConnectedPlugSecComp, connectedPlugUDev: networkControlConnectedPlugUDev, connectedPlugMount: networkControlConnectedPlugMount, connectedPlugUpdateNSAppArmor: networkControlConnectedPlugUpdateNSAppArmor, suppressPtraceTrace: true, suppressSysModuleCapability: true, // affects the plug snap because of mount backend affectsPlugOnRefresh: true, }) }
gpl-3.0
zhangf911/fibjs
vender/v8/src/runtime/runtime-compiler.cc
15913
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/arguments.h" #include "src/compiler.h" #include "src/deoptimizer.h" #include "src/frames.h" #include "src/full-codegen.h" #include "src/messages.h" #include "src/runtime/runtime-utils.h" #include "src/v8threads.h" #include "src/vm-state-inl.h" namespace v8 { namespace internal { RUNTIME_FUNCTION(Runtime_CompileLazy) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); #ifdef DEBUG if (FLAG_trace_lazy && !function->shared()->is_compiled()) { PrintF("[unoptimized: "); function->PrintName(); PrintF("]\n"); } #endif // Compile the target function. DCHECK(function->shared()->allows_lazy_compilation()); Handle<Code> code; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, code, Compiler::GetLazyCode(function)); DCHECK(code->kind() == Code::FUNCTION || code->kind() == Code::OPTIMIZED_FUNCTION); function->ReplaceCode(*code); return *code; } RUNTIME_FUNCTION(Runtime_CompileOptimized) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_BOOLEAN_ARG_CHECKED(concurrent, 1); Compiler::ConcurrencyMode mode = concurrent ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT; Handle<Code> code; Handle<Code> unoptimized(function->shared()->code()); if (Compiler::GetOptimizedCode(function, unoptimized, mode).ToHandle(&code)) { // Optimization succeeded, return optimized code. function->ReplaceCode(*code); } else { // Optimization failed, get unoptimized code. if (isolate->has_pending_exception()) { // Possible stack overflow. return isolate->heap()->exception(); } code = Handle<Code>(function->shared()->code(), isolate); if (code->kind() != Code::FUNCTION && code->kind() != Code::OPTIMIZED_FUNCTION) { ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, code, Compiler::GetUnoptimizedCode(function)); } function->ReplaceCode(*code); } DCHECK(function->code()->kind() == Code::FUNCTION || function->code()->kind() == Code::OPTIMIZED_FUNCTION || function->IsInOptimizationQueue()); return function->code(); } RUNTIME_FUNCTION(Runtime_NotifyStubFailure) { HandleScope scope(isolate); DCHECK(args.length() == 0); Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate); DCHECK(AllowHeapAllocation::IsAllowed()); delete deoptimizer; return isolate->heap()->undefined_value(); } class ActivationsFinder : public ThreadVisitor { public: Code* code_; bool has_code_activations_; explicit ActivationsFinder(Code* code) : code_(code), has_code_activations_(false) {} void VisitThread(Isolate* isolate, ThreadLocalTop* top) { JavaScriptFrameIterator it(isolate, top); VisitFrames(&it); } void VisitFrames(JavaScriptFrameIterator* it) { for (; !it->done(); it->Advance()) { JavaScriptFrame* frame = it->frame(); if (code_->contains(frame->pc())) has_code_activations_ = true; } } }; RUNTIME_FUNCTION(Runtime_NotifyDeoptimized) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_SMI_ARG_CHECKED(type_arg, 0); Deoptimizer::BailoutType type = static_cast<Deoptimizer::BailoutType>(type_arg); Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate); DCHECK(AllowHeapAllocation::IsAllowed()); Handle<JSFunction> function = deoptimizer->function(); Handle<Code> optimized_code = deoptimizer->compiled_code(); DCHECK(optimized_code->kind() == Code::OPTIMIZED_FUNCTION); DCHECK(type == deoptimizer->bailout_type()); // Make sure to materialize objects before causing any allocation. JavaScriptFrameIterator it(isolate); deoptimizer->MaterializeHeapObjects(&it); delete deoptimizer; JavaScriptFrame* frame = it.frame(); RUNTIME_ASSERT(frame->function()->IsJSFunction()); DCHECK(frame->function() == *function); // Avoid doing too much work when running with --always-opt and keep // the optimized code around. if (FLAG_always_opt || type == Deoptimizer::LAZY) { return isolate->heap()->undefined_value(); } // Search for other activations of the same function and code. ActivationsFinder activations_finder(*optimized_code); activations_finder.VisitFrames(&it); isolate->thread_manager()->IterateArchivedThreads(&activations_finder); if (!activations_finder.has_code_activations_) { if (function->code() == *optimized_code) { if (FLAG_trace_deopt) { PrintF("[removing optimized code for: "); function->PrintName(); PrintF("]\n"); } function->ReplaceCode(function->shared()->code()); // Evict optimized code for this function from the cache so that it // doesn't get used for new closures. function->shared()->EvictFromOptimizedCodeMap(*optimized_code, "notify deoptimized"); } } else { // TODO(titzer): we should probably do DeoptimizeCodeList(code) // unconditionally if the code is not already marked for deoptimization. // If there is an index by shared function info, all the better. Deoptimizer::DeoptimizeFunction(*function); } return isolate->heap()->undefined_value(); } static bool IsSuitableForOnStackReplacement(Isolate* isolate, Handle<JSFunction> function) { // Keep track of whether we've succeeded in optimizing. if (function->shared()->optimization_disabled()) return false; // If we are trying to do OSR when there are already optimized // activations of the function, it means (a) the function is directly or // indirectly recursive and (b) an optimized invocation has been // deoptimized so that we are currently in an unoptimized activation. // Check for optimized activations of this function. for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) { JavaScriptFrame* frame = it.frame(); if (frame->is_optimized() && frame->function() == *function) return false; } return true; } RUNTIME_FUNCTION(Runtime_CompileForOnStackReplacement) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); Handle<Code> caller_code(function->shared()->code()); // We're not prepared to handle a function with arguments object. DCHECK(!function->shared()->uses_arguments()); RUNTIME_ASSERT(FLAG_use_osr); // Passing the PC in the javascript frame from the caller directly is // not GC safe, so we walk the stack to get it. JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); if (!caller_code->contains(frame->pc())) { // Code on the stack may not be the code object referenced by the shared // function info. It may have been replaced to include deoptimization data. caller_code = Handle<Code>(frame->LookupCode()); } uint32_t pc_offset = static_cast<uint32_t>(frame->pc() - caller_code->instruction_start()); #ifdef DEBUG DCHECK_EQ(frame->function(), *function); DCHECK_EQ(frame->LookupCode(), *caller_code); DCHECK(caller_code->contains(frame->pc())); #endif // DEBUG BailoutId ast_id = caller_code->TranslatePcOffsetToAstId(pc_offset); DCHECK(!ast_id.IsNone()); Compiler::ConcurrencyMode mode = isolate->concurrent_osr_enabled() && (function->shared()->ast_node_count() > 512) ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT; Handle<Code> result = Handle<Code>::null(); OptimizedCompileJob* job = NULL; if (mode == Compiler::CONCURRENT) { // Gate the OSR entry with a stack check. BackEdgeTable::AddStackCheck(caller_code, pc_offset); // Poll already queued compilation jobs. OptimizingCompileDispatcher* dispatcher = isolate->optimizing_compile_dispatcher(); if (dispatcher->IsQueuedForOSR(function, ast_id)) { if (FLAG_trace_osr) { PrintF("[OSR - Still waiting for queued: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } return NULL; } job = dispatcher->FindReadyOSRCandidate(function, ast_id); } if (job != NULL) { if (FLAG_trace_osr) { PrintF("[OSR - Found ready: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } result = Compiler::GetConcurrentlyOptimizedCode(job); } else if (IsSuitableForOnStackReplacement(isolate, function)) { if (FLAG_trace_osr) { PrintF("[OSR - Compiling: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } MaybeHandle<Code> maybe_result = Compiler::GetOptimizedCode(function, caller_code, mode, ast_id); if (maybe_result.ToHandle(&result) && result.is_identical_to(isolate->builtins()->InOptimizationQueue())) { // Optimization is queued. Return to check later. return NULL; } } // Revert the patched back edge table, regardless of whether OSR succeeds. BackEdgeTable::Revert(isolate, *caller_code); // Check whether we ended up with usable optimized code. if (!result.is_null() && result->kind() == Code::OPTIMIZED_FUNCTION) { DeoptimizationInputData* data = DeoptimizationInputData::cast(result->deoptimization_data()); if (data->OsrPcOffset()->value() >= 0) { DCHECK(BailoutId(data->OsrAstId()->value()) == ast_id); if (FLAG_trace_osr) { PrintF("[OSR - Entry at AST id %d, offset %d in optimized code]\n", ast_id.ToInt(), data->OsrPcOffset()->value()); } // TODO(titzer): this is a massive hack to make the deopt counts // match. Fix heuristics for reenabling optimizations! function->shared()->increment_deopt_count(); if (result->is_turbofanned()) { // TurboFanned OSR code cannot be installed into the function. // But the function is obviously hot, so optimize it next time. function->ReplaceCode( isolate->builtins()->builtin(Builtins::kCompileOptimized)); } else { // Crankshafted OSR code can be installed into the function. function->ReplaceCode(*result); } return *result; } } // Failed. if (FLAG_trace_osr) { PrintF("[OSR - Failed: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } if (!function->IsOptimized()) { function->ReplaceCode(function->shared()->code()); } return NULL; } RUNTIME_FUNCTION(Runtime_TryInstallOptimizedCode) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); // First check if this is a real stack overflow. StackLimitCheck check(isolate); if (check.JsHasOverflowed()) { SealHandleScope shs(isolate); return isolate->StackOverflow(); } isolate->optimizing_compile_dispatcher()->InstallOptimizedFunctions(); return (function->IsOptimized()) ? function->code() : function->shared()->code(); } bool CodeGenerationFromStringsAllowed(Isolate* isolate, Handle<Context> context) { DCHECK(context->allow_code_gen_from_strings()->IsFalse()); // Check with callback if set. AllowCodeGenerationFromStringsCallback callback = isolate->allow_code_gen_callback(); if (callback == NULL) { // No callback set and code generation disallowed. return false; } else { // Callback set. Let it decide if code generation is allowed. VMState<EXTERNAL> state(isolate); return callback(v8::Utils::ToLocal(context)); } } RUNTIME_FUNCTION(Runtime_CompileString) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, source, 0); CONVERT_BOOLEAN_ARG_CHECKED(function_literal_only, 1); // Extract native context. Handle<Context> context(isolate->native_context()); // Check if native context allows code generation from // strings. Throw an exception if it doesn't. if (context->allow_code_gen_from_strings()->IsFalse() && !CodeGenerationFromStringsAllowed(isolate, context)) { Handle<Object> error_message = context->ErrorMessageForCodeGenerationFromStrings(); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewEvalError(MessageTemplate::kCodeGenFromStrings, error_message)); } // Compile source string in the native context. ParseRestriction restriction = function_literal_only ? ONLY_SINGLE_FUNCTION_LITERAL : NO_PARSE_RESTRICTION; Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate); Handle<JSFunction> fun; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, fun, Compiler::GetFunctionFromEval(source, outer_info, context, SLOPPY, restriction, RelocInfo::kNoPosition)); return *fun; } static ObjectPair CompileGlobalEval(Isolate* isolate, Handle<String> source, Handle<SharedFunctionInfo> outer_info, Handle<Object> receiver, LanguageMode language_mode, int scope_position) { Handle<Context> context = Handle<Context>(isolate->context()); Handle<Context> native_context = Handle<Context>(context->native_context()); // Check if native context allows code generation from // strings. Throw an exception if it doesn't. if (native_context->allow_code_gen_from_strings()->IsFalse() && !CodeGenerationFromStringsAllowed(isolate, native_context)) { Handle<Object> error_message = native_context->ErrorMessageForCodeGenerationFromStrings(); Handle<Object> error; MaybeHandle<Object> maybe_error = isolate->factory()->NewEvalError( MessageTemplate::kCodeGenFromStrings, error_message); if (maybe_error.ToHandle(&error)) isolate->Throw(*error); return MakePair(isolate->heap()->exception(), NULL); } // Deal with a normal eval call with a string argument. Compile it // and return the compiled function bound in the local context. static const ParseRestriction restriction = NO_PARSE_RESTRICTION; Handle<JSFunction> compiled; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, compiled, Compiler::GetFunctionFromEval(source, outer_info, context, language_mode, restriction, scope_position), MakePair(isolate->heap()->exception(), NULL)); return MakePair(*compiled, *receiver); } RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval) { HandleScope scope(isolate); DCHECK(args.length() == 6); Handle<Object> callee = args.at<Object>(0); // If "eval" didn't refer to the original GlobalEval, it's not a // direct call to eval. // (And even if it is, but the first argument isn't a string, just let // execution default to an indirect call to eval, which will also return // the first argument without doing anything). if (*callee != isolate->native_context()->global_eval_fun() || !args[1]->IsString()) { return MakePair(*callee, isolate->heap()->undefined_value()); } DCHECK(args[4]->IsSmi()); DCHECK(is_valid_language_mode(args.smi_at(4))); LanguageMode language_mode = static_cast<LanguageMode>(args.smi_at(4)); DCHECK(args[5]->IsSmi()); Handle<SharedFunctionInfo> outer_info(args.at<JSFunction>(2)->shared(), isolate); return CompileGlobalEval(isolate, args.at<String>(1), outer_info, args.at<Object>(3), language_mode, args.smi_at(5)); } } // namespace internal } // namespace v8
gpl-3.0
sandaru1/codejam
www/lib/symfony/filter/sfCacheFilter.class.php
6072
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfCacheFilter deals with page caching and action caching. * * @package symfony * @subpackage filter * @author Fabien Potencier <[email protected]> * @version SVN: $Id: sfCacheFilter.class.php 13564 2008-11-30 21:34:25Z fabien $ */ class sfCacheFilter extends sfFilter { protected $cacheManager = null, $request = null, $response = null, $routing = null, $cache = array(); /** * Initializes this Filter. * * @param sfContext $context The current application context * @param array $parameters An associative array of initialization parameters * * @return bool true, if initialization completes successfully, otherwise false * * @throws <b>sfInitializationException</b> If an error occurs while initializing this Filter */ public function initialize($context, $parameters = array()) { parent::initialize($context, $parameters); $this->cacheManager = $context->getViewCacheManager(); $this->request = $context->getRequest(); $this->response = $context->getResponse(); $this->routing = $context->getRouting(); } /** * Executes this filter. * * @param sfFilterChain $filterChain A sfFilterChain instance */ public function execute($filterChain) { // execute this filter only once, if cache is set and no GET or POST parameters if (!sfConfig::get('sf_cache')) { $filterChain->execute(); return; } if ($this->executeBeforeExecution()) { $filterChain->execute(); } $this->executeBeforeRendering(); } public function executeBeforeExecution() { // register our cache configuration $this->cacheManager->registerConfiguration($this->context->getModuleName()); $uri = $this->routing->getCurrentInternalUri(); if (is_null($uri)) { return true; } // page cache $cacheable = $this->cacheManager->isCacheable($uri); if ($cacheable && $this->cacheManager->withLayout($uri)) { $inCache = $this->cacheManager->getPageCache($uri); $this->cache[$uri] = $inCache; if ($inCache) { // page is in cache, so no need to run execution filter return false; } } return true; } /** * Executes this filter. */ public function executeBeforeRendering() { // cache only 200 HTTP status if (200 != $this->response->getStatusCode()) { return; } $uri = $this->routing->getCurrentInternalUri(); // save page in cache if (isset($this->cache[$uri]) && false === $this->cache[$uri]) { $this->setCacheExpiration($uri); $this->setCacheValidation($uri); // set Vary headers foreach ($this->cacheManager->getVary($uri, 'page') as $vary) { $this->response->addVaryHttpHeader($vary); } $this->cacheManager->setPageCache($uri); } // cache validation $this->checkCacheValidation(); } /** * Sets cache expiration headers. * * @param string An internal URI */ protected function setCacheExpiration($uri) { // don't add cache expiration (Expires) if // * the client lifetime is not set // * the response already has a cache validation (Last-Modified header) // * the Expires header has already been set if (!$lifetime = $this->cacheManager->getClientLifeTime($uri, 'page')) { return; } if ($this->response->hasHttpHeader('Last-Modified')) { return; } if (!$this->response->hasHttpHeader('Expires')) { $this->response->setHttpHeader('Expires', $this->response->getDate(time() + $lifetime), false); $this->response->addCacheControlHttpHeader('max-age', $lifetime); } } /** * Sets cache validation headers. * * @param string An internal URI */ protected function setCacheValidation($uri) { // don't add cache validation (Last-Modified) if // * the client lifetime is set (cache.yml) // * the response already has a Last-Modified header if ($this->cacheManager->getClientLifeTime($uri, 'page')) { return; } if (!$this->response->hasHttpHeader('Last-Modified')) { $this->response->setHttpHeader('Last-Modified', $this->response->getDate(time()), false); } if (sfConfig::get('sf_etag')) { $etag = '"'.md5($this->response->getContent()).'"'; $this->response->setHttpHeader('ETag', $etag); } } /** * Checks cache validation headers. */ protected function checkCacheValidation() { // Etag support if (sfConfig::get('sf_etag')) { $etag = '"'.md5($this->response->getContent()).'"'; if ($this->request->getHttpHeader('IF_NONE_MATCH') == $etag) { $this->response->setStatusCode(304); $this->response->setHeaderOnly(true); if (sfConfig::get('sf_logging_enabled')) { $this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('ETag matches If-None-Match (send 304)'))); } } } // conditional GET support // never in debug mode if ($this->response->hasHttpHeader('Last-Modified') && !sfConfig::get('sf_debug')) { $lastModified = $this->response->getHttpHeader('Last-Modified'); $lastModified = $lastModified[0]; if ($this->request->getHttpHeader('IF_MODIFIED_SINCE') == $lastModified) { $this->response->setStatusCode(304); $this->response->setHeaderOnly(true); if (sfConfig::get('sf_logging_enabled')) { $this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('Last-Modified matches If-Modified-Since (send 304)'))); } } } } }
gpl-3.0
pajlada/acquisition
src/itemconstants.h
632
#pragma once const int PIXELS_PER_SLOT = 47; const int INVENTORY_SLOTS = 12; enum FRAME_TYPES { FRAME_TYPE_NORMAL = 0, FRAME_TYPE_MAGIC = 1, FRAME_TYPE_RARE = 2, FRAME_TYPE_UNIQUE = 3, FRAME_TYPE_GEM = 4, FRAME_TYPE_CURRENCY = 5, }; enum ELEMENTAL_DAMAGE_TYPES { ED_FIRE = 4, ED_COLD = 5, ED_LIGHTNING = 6, }; const int LINKH_HEIGHT = 16; const int LINKH_WIDTH = 38; const int LINKV_HEIGHT = LINKH_WIDTH; const int LINKV_WIDTH = LINKH_HEIGHT; const int MAX_EXPANDABLE_ITEMS = 1000; const int PIXELS_PER_MINIMAP_SLOT = 10; const int MINIMAP_SIZE = INVENTORY_SLOTS * PIXELS_PER_MINIMAP_SLOT;
gpl-3.0
miuirussia/KJBE
src/org/apache/bcel/generic/GETFIELD.java
4938
package org.apache.bcel.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.apache.bcel.Constants; import org.apache.bcel.ExceptionConstants; /** * GETFIELD - Fetch field from object * <PRE>Stack: ..., objectref -&gt; ..., value</PRE> * OR * <PRE>Stack: ..., objectref -&gt; ..., value.word1, value.word2</PRE> * * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @version $Id: GETFIELD.java,v 1.2 2006/08/23 13:48:30 andos Exp $ */ public class GETFIELD extends FieldInstruction implements ExceptionThrower, StackConsumer, StackProducer { /** * */ private static final long serialVersionUID = -6510928743515082496L; /** * Empty constructor needed for the Class.newInstance() statement in * Instruction.readInstruction(). Not to be used otherwise. */ GETFIELD() { } public GETFIELD(int index) { super(Constants.GETFIELD, index); } public int produceStack(ConstantPoolGen cpg) { return getFieldSize(cpg); } public Class[] getExceptions() { Class[] cs = new Class[2 + ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length]; System.arraycopy(ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION, 0, cs, 0, ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length); cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length + 1] = ExceptionConstants.INCOMPATIBLE_CLASS_CHANGE_ERROR; cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length] = ExceptionConstants.NULL_POINTER_EXCEPTION; return cs; } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ public void accept(Visitor v) { v.visitExceptionThrower(this); v.visitStackConsumer(this); v.visitStackProducer(this); v.visitTypedInstruction(this); v.visitLoadClass(this); v.visitCPInstruction(this); v.visitFieldOrMethod(this); v.visitFieldInstruction(this); v.visitGETFIELD(this); } }
gpl-3.0
malin1993ml/h-store
third_party/cpp/berkeleydb/src/xa/xa_map.c
2959
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 1996, 2015 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ #include "db_config.h" #include "db_int.h" #include "dbinc/txn.h" #include "dbinc_auto/xa_ext.h" /* * This file contains all the mapping information that we need to support * the DB/XA interface. */ /* * __db_rmid_to_env * Return the environment associated with a given XA rmid. * * PUBLIC: int __db_rmid_to_env __P((int, ENV **)); */ int __db_rmid_to_env(rmid, envp) int rmid; ENV **envp; { ENV *env; *envp = NULL; if (TAILQ_EMPTY(&DB_GLOBAL(envq))) TAILQ_INIT(&DB_GLOBAL(envq)); /* * When we map an rmid, move that environment to be the first one in * the list of environments, so we acquire the correct environment * in DB->open. */ for (env = TAILQ_FIRST(&DB_GLOBAL(envq)); env != NULL; env = TAILQ_NEXT(env, links)) { if (env->xa_rmid == rmid) { *envp = env; if (env != TAILQ_FIRST(&DB_GLOBAL(envq))) { TAILQ_REMOVE(&DB_GLOBAL(envq), env, links); TAILQ_INSERT_HEAD(&DB_GLOBAL(envq), env, links); } return (0); } } return (1); } /* * __db_xid_to_txn * Return the txn that corresponds to this XID. * * PUBLIC: int __db_xid_to_txn __P((ENV *, XID *, TXN_DETAIL **)); */ int __db_xid_to_txn(env, xid, tdp) ENV *env; XID *xid; TXN_DETAIL **tdp; { DB_TXNMGR *mgr; DB_TXNREGION *region; u_int8_t *gid; mgr = env->tx_handle; region = mgr->reginfo.primary; /* * Search the internal active transaction table to find the * matching xid. If this is a performance hit, then we * can create a hash table, but I doubt it's worth it. */ TXN_SYSTEM_LOCK(env); gid = (u_int8_t *)(xid->data); SH_TAILQ_FOREACH(*tdp, &region->active_txn, links, __txn_detail) if (memcmp(gid, (*tdp)->gid, sizeof((*tdp)->gid)) == 0) break; TXN_SYSTEM_UNLOCK(env); /* * This returns an error, because TXN_SYSTEM_{UN}LOCK may return * an error. */ return (0); } /* * __db_map_rmid * Create a mapping between the specified rmid and environment. * * PUBLIC: void __db_map_rmid __P((int, ENV *)); */ void __db_map_rmid(rmid, env) int rmid; ENV *env; { env->xa_rmid = rmid; TAILQ_INSERT_HEAD(&DB_GLOBAL(envq), env, links); } /* * __db_unmap_rmid * Destroy the mapping for the given rmid. * * PUBLIC: int __db_unmap_rmid __P((int)); */ int __db_unmap_rmid(rmid) int rmid; { ENV *e; for (e = TAILQ_FIRST(&DB_GLOBAL(envq)); e->xa_rmid != rmid; e = TAILQ_NEXT(e, links)) ; if (e == NULL) return (EINVAL); TAILQ_REMOVE(&DB_GLOBAL(envq), e, links); return (0); } /* * __db_unmap_xid * Destroy the mapping for the specified XID. * * PUBLIC: void __db_unmap_xid __P((ENV *, XID *, size_t)); */ void __db_unmap_xid(env, xid, off) ENV *env; XID *xid; size_t off; { TXN_DETAIL *td; COMPQUIET(xid, NULL); td = R_ADDR(&env->tx_handle->reginfo, off); memset(td->gid, 0, sizeof(td->gid)); }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/skia/src/sksl/ast/SkSLASTSuffixExpression.h
878
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SKSL_ASTSUFFIXEXPRESSION #define SKSL_ASTSUFFIXEXPRESSION #include "SkSLASTSuffix.h" #include "SkSLASTExpression.h" namespace SkSL { /** * An expression with an associated suffix. */ struct ASTSuffixExpression : public ASTExpression { ASTSuffixExpression(std::unique_ptr<ASTExpression> base, std::unique_ptr<ASTSuffix> suffix) : INHERITED(base->fPosition, kSuffix_Kind) , fBase(std::move(base)) , fSuffix(std::move(suffix)) {} std::string description() const override { return fBase->description() + fSuffix->description(); } const std::unique_ptr<ASTExpression> fBase; const std::unique_ptr<ASTSuffix> fSuffix; typedef ASTExpression INHERITED; }; } // namespace #endif
gpl-3.0
prey/prey-node-client
lib/agent/actions/alarm/mac.js
98
exports.play = 'afplay'; exports.raise_volume = 'osascript -e "set Volume 10"'; // unmutes as well
gpl-3.0
metasfresh/metasfresh-webui-api
src/main/java/de/metas/ui/web/window/exceptions/InvalidDocumentStateException.java
1498
package de.metas.ui.web.window.exceptions; import org.adempiere.exceptions.AdempiereException; import de.metas.ui.web.window.datatypes.DocumentPath; import de.metas.ui.web.window.model.Document; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @SuppressWarnings("serial") public class InvalidDocumentStateException extends AdempiereException { public InvalidDocumentStateException(final Document document, final String reason) { super(buildMsg(document.getDocumentPath(), reason)); } public InvalidDocumentStateException(final DocumentPath documentPath, final String reason) { super(buildMsg(documentPath, reason)); } private static String buildMsg(final DocumentPath documentPath, final String reason) { return "Document " + documentPath + " state is invalid: " + reason; } }
gpl-3.0
happyjack27/autoredistrict
src/org/apache/commons/math3/ode/FieldSecondaryEquations.java
3524
/* * 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.math3.ode; import org.apache.commons.math3.RealFieldElement; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MaxCountExceededException; /** * This interface allows users to add secondary differential equations to a primary * set of differential equations. * <p> * In some cases users may need to integrate some problem-specific equations along * with a primary set of differential equations. One example is optimal control where * adjoined parameters linked to the minimized Hamiltonian must be integrated. * </p> * <p> * This interface allows users to add such equations to a primary set of {@link * FirstOrderFieldDifferentialEquations first order differential equations} * thanks to the {@link FieldExpandableODE#addSecondaryEquations(FieldSecondaryEquations)} * method. * </p> * @see FirstOrderFieldDifferentialEquations * @see FieldExpandableODE * @param <T> the type of the field elements * @since 3.6 */ public interface FieldSecondaryEquations<T extends RealFieldElement<T>> { /** Get the dimension of the secondary state parameters. * @return dimension of the secondary state parameters */ int getDimension(); /** Initialize equations at the start of an ODE integration. * <p> * This method is called once at the start of the integration. It * may be used by the equations to initialize some internal data * if needed. * </p> * @param t0 value of the independent <I>time</I> variable at integration start * @param primary0 array containing the value of the primary state vector at integration start * @param secondary0 array containing the value of the secondary state vector at integration start * @param finalTime target time for the integration */ void init(T t0, T[] primary0, T[] secondary0, T finalTime); /** Compute the derivatives related to the secondary state parameters. * @param t current value of the independent <I>time</I> variable * @param primary array containing the current value of the primary state vector * @param primaryDot array containing the derivative of the primary state vector * @param secondary array containing the current value of the secondary state vector * @return derivative of the secondary state vector * @exception MaxCountExceededException if the number of functions evaluations is exceeded * @exception DimensionMismatchException if arrays dimensions do not match equations settings */ T[] computeDerivatives(T t, T[] primary, T[] primaryDot, T[] secondary) throws MaxCountExceededException, DimensionMismatchException; }
gpl-3.0
DanVanAtta/triplea
game-relay-server/README.md
327
# Game-Relay-Server Game-relay-server that acts as a network bridge. Any message sent to the relay server is re-broadcast to all connected clients. The relay-server can be launched as a standalone or launched when hosting a game. Game hosts will connect to the relay server they themselves launched and will act as a client.
gpl-3.0
ThaFireDragonOfDeath/qupzilla
src/plugins/TestPlugin/translations/ja_JP.ts
1372
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ja_JP" version="2.1"> <context> <name>TestPlugin</name> <message> <location filename="../testplugin.cpp" line="122"/> <source>Close</source> <translation>閉じる</translation> </message> <message> <location filename="../testplugin.cpp" line="133"/> <source>Example Plugin Settings</source> <translation>拡張の設定例</translation> </message> <message> <location filename="../testplugin.cpp" line="163"/> <source>My first plugin action</source> <translation>拡張の動作確認</translation> </message> <message> <location filename="../testplugin.cpp" line="178"/> <source>Hello</source> <translation>Hello</translation> </message> <message> <location filename="../testplugin.cpp" line="178"/> <source>First plugin action works :-)</source> <translation>拡張の動作は正常です :-)</translation> </message> </context> <context> <name>TestPlugin_Sidebar</name> <message> <location filename="../testplugin_sidebar.cpp" line="32"/> <location filename="../testplugin_sidebar.cpp" line="40"/> <source>Testing Sidebar</source> <translation>サイドバーを試す</translation> </message> </context> </TS>
gpl-3.0
cvjena/artos
docs/PyARTOS/html/functions_0x65.html
11119
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>PyARTOS: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">PyARTOS &#160;<span id="projectnumber">1.0</span> </div> <div id="projectbrief">Python interface to libartos</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index__"><span>_</span></a></li> <li><a href="functions_0x61.html#index_a"><span>a</span></a></li> <li><a href="functions_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_0x64.html#index_d"><span>d</span></a></li> <li class="current"><a href="functions_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_0x68.html#index_h"><span>h</span></a></li> <li><a href="functions_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_0x77.html#index_w"><span>w</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('functions_0x65.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all class members with links to the classes they belong to:</div> <h3><a class="anchor" id="index_e"></a>- e -</h3><ul> <li>enableSkipping : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_setup_dialog_1_1_setup_dialog.html#a6fb30020102cbe172304e2cd24b27502">PyARTOS.GUI.SetupDialog.SetupDialog</a> </li> <li>entrClassname : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_model_catalogue_1_1_learn_dialog.html#a532b7268057d81fad02a0a589cb2784d">PyARTOS.GUI.ModelCatalogue.LearnDialog</a> </li> <li>entrImgDir : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_model_catalogue_1_1_learn_dialog.html#a570b5818aa74d8743a0b546e492affcf">PyARTOS.GUI.ModelCatalogue.LearnDialog</a> </li> <li>entrModelDir : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_batch_window_1_1_batch_window.html#a815d8092035feec5ae673e5cc479102d">PyARTOS.GUI.BatchWindow.BatchWindow</a> , <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_camera_window_1_1_camera_window.html#a7b7ef5f98136021400a3f6bb640a0901">PyARTOS.GUI.CameraWindow.CameraWindow</a> , <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_model_catalogue_1_1_catalogue_window.html#a7600365b28d87ef4d53c04239082b8bb">PyARTOS.GUI.ModelCatalogue.CatalogueWindow</a> </li> <li>entrPath : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_setup_dialog_1_1_setup_dialog.html#a1b1b2722d9b669a4ecdace0595c23bc8">PyARTOS.GUI.SetupDialog.SetupDialog</a> </li> <li>entrSynset : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_model_catalogue_1_1_learn_dialog.html#afe2a504a63996c5e957c3cde49565fe3">PyARTOS.GUI.ModelCatalogue.LearnDialog</a> </li> <li>enumerateDevices() : <a class="el" href="class_py_a_r_t_o_s_1_1_camera_1_1_cv_capture_1_1_capture.html#a0a27406650c86a94e8d231b8236f2b8e">PyARTOS.Camera.CvCapture.Capture</a> , <a class="el" href="class_py_a_r_t_o_s_1_1_camera_1_1_pygame_capture_1_1_capture.html#a5f630f803b7bf05cd838f74cc83dc8c4">PyARTOS.Camera.PygameCapture.Capture</a> , <a class="el" href="class_py_a_r_t_o_s_1_1_camera_1_1_win_capture_1_1_capture.html#ab3a96bfc0b50a132d56749932399db9a">PyARTOS.Camera.WinCapture.Capture</a> </li> <li>errcode : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1_lib_a_r_t_o_s_exception.html#aa7a52dfb4a3d460a995774536e5bc8e7">PyARTOS.artos_wrapper.LibARTOSException</a> </li> <li>errmsg : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1_lib_a_r_t_o_s_exception.html#a843791aa61809753494940763f3c9bc7">PyARTOS.artos_wrapper.LibARTOSException</a> </li> <li>errmsgs : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1_lib_a_r_t_o_s_exception.html#a24d323dcbba863739eb5cb5a967d2f6d">PyARTOS.artos_wrapper.LibARTOSException</a> </li> <li>explanatoryText : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_setup_dialog_1_1_setup_dialog.html#a3d6e962f489fdf17b31cbcd0caf5f86d">PyARTOS.GUI.SetupDialog.SetupDialog</a> </li> <li>export() : <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_batch_window_1_1_detection_popup_menu.html#a066d4c883e655b1fda530d87fe90cd03">PyARTOS.GUI.BatchWindow.DetectionPopupMenu</a> , <a class="el" href="class_py_a_r_t_o_s_1_1_g_u_i_1_1_model_catalogue_1_1_h_o_g_inspector.html#aa10b8ad1cc72476411f972017bfa6ee1">PyARTOS.GUI.ModelCatalogue.HOGInspector</a> </li> <li>extract_images_from_synset : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1___lib_a_r_t_o_s.html#a74921b2338da3407b0f7362387ae0f2f">PyARTOS.artos_wrapper._LibARTOS</a> </li> <li>extract_mixed_images : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1___lib_a_r_t_o_s.html#a16385a184039c144b90f7dd7c0269465">PyARTOS.artos_wrapper._LibARTOS</a> </li> <li>extract_samples_from_synset : <a class="el" href="class_py_a_r_t_o_s_1_1artos__wrapper_1_1___lib_a_r_t_o_s.html#aa8ba57eac30538b3ca943ddba67e3767">PyARTOS.artos_wrapper._LibARTOS</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Thu May 22 2014 22:45:29 for PyARTOS by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.4 </li> </ul> </div> </body> </html>
gpl-3.0
greguly/woocommerce
README.md
3462
<p align="center"><a href="https://woocommerce.com/"><img src="https://woocommerce.com/wp-content/themes/woo/images/[email protected]" alt="WooCommerce"></a></p> <p align="center"> <a href="https://packagist.org/packages/woocommerce/woocommerce"><img src="https://poser.pugx.org/woocommerce/woocommerce/license" alt="license"></a> <a href="https://packagist.org/packages/woocommerce/woocommerce"><img src="https://poser.pugx.org/woocommerce/woocommerce/v/stable" alt="Latest Stable Version"></a> <img src="https://img.shields.io/wordpress/plugin/dt/woocommerce.svg" alt="WordPress.org downloads"> <img src="https://img.shields.io/wordpress/plugin/r/woocommerce.svg" alt="WordPress.org rating"> <a href="https://travis-ci.org/woocommerce/woocommerce"><img src="https://travis-ci.org/woocommerce/woocommerce.svg?branch=master" alt="Build Status"></a> <a href="https://scrutinizer-ci.com/g/woocommerce/woocommerce/?branch=master"><img src="https://scrutinizer-ci.com/g/woocommerce/woocommerce/badges/quality-score.png?b=master" alt="Scrutinizer Code Quality"></a> <a href="https://codecov.io/gh/woocommerce/woocommerce"><img src="https://codecov.io/gh/woocommerce/woocommerce/branch/master/graph/badge.svg" alt="codecov"></a> </p> Welcome to the WooCommerce repository on GitHub. Here you can browse the source, look at open issues and keep track of development. We recommend all developers to follow the [WooCommerce development blog](https://woocommerce.wordpress.com/) to stay up to date about everything happening in the project. You can also [follow @DevelopWC](https://twitter.com/DevelopWC) on Twitter for the latest development updates. If you are not a developer, please use the [WooCommerce plugin page](https://wordpress.org/plugins/woocommerce/) on WordPress.org. ## Documentation * [WooCommerce Documentation](https://docs.woocommerce.com/) * [WooCommerce Developer Documentation](https://github.com/woocommerce/woocommerce/wiki) * [WooCommerce Code Reference](https://docs.woocommerce.com/wc-apidocs/) * [WooCommerce REST API Docs](https://woocommerce.github.io/woocommerce-rest-api-docs/) ## Reporting Security Issues To disclose a security issue to our team, [please submit a report via HackerOne here](https://hackerone.com/automattic/). ## Support This repository is not suitable for support. Please don't use our issue tracker for support requests, but for core WooCommerce issues only. Support can take place through the appropriate channels: * If you have a problem, you may want to start with the [self help guide](https://docs.woocommerce.com/document/woocommerce-self-service-guide/). * The [WooCommerce.com premium support portal](https://woocommerce.com/contact-us/ ) for customers who have purchased themes or extensions. * [Our community forum on wp.org](https://wordpress.org/support/plugin/woocommerce) which is available for all WooCommerce users. * The WooCommerce Help and Share Facebook group. * For customizations, you may want to check our list of [WooExperts](https://woocommerce.com/experts/) or [Codeable](https://codeable.io/). Support requests in issues on this repository will be closed on sight. ## Contributing to WooCommerce If you have a patch or have stumbled upon an issue with WooCommerce core, you can contribute this back to the code. Please read our [contributor guidelines](https://github.com/woocommerce/woocommerce/blob/master/.github/CONTRIBUTING.md) for more information how you can do this.
gpl-3.0
xubinux/xbin-store
xbin-store-web-admin/src/main/resources/static/pages/tables/simple.html
42144
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>AdminLTE 2 | Simple Tables</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.6 --> <link rel="stylesheet" href="../../plugins/bootstrap/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="../../index2.html" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>R</b>C</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>xbin-store-admin </b>LTE</span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success">4</span> </a> <ul class="dropdown-menu"> <li class="header">你有4个消息</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <h4> 运营团队 <small><i class="fa fa-clock-o"></i> 5 分钟</small> </h4> <p>为什么要使用龙果模板?</p> </a> </li> <!-- end message --> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> 设计团队 <small><i class="fa fa-clock-o"></i> 2 小时</small> </h4> <p>为什么要使用龙果模板?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> 开发者 <small><i class="fa fa-clock-o"></i> 今天</small> </h4> <p>为什么要使用龙果模板?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user3-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> 销售部 <small><i class="fa fa-clock-o"></i> 昨天</small> </h4> <p>为什么要使用龙果模板?</p> </a> </li> <li> <a href="#"> <div class="pull-left"> <img src="../../dist/img/user4-128x128.jpg" class="img-circle" alt="User Image"> </div> <h4> 测试员 <small><i class="fa fa-clock-o"></i> 2 天前</small> </h4> <p>为什么要使用龙果模板?</p> </a> </li> </ul> </li> <li class="footer"><a href="#">查看所有消息</a></li> </ul> </li> <!-- Notifications: style can be found in dropdown.less --> <li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">你有10个通知</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 今天有 5 人加入 </a> </li> <li> <a href="#"> <i class="fa fa-warning text-yellow"></i> 很长的描述,可能在这里不适合展示 </a> </li> <li> <a href="#"> <i class="fa fa-users text-red"></i> 5 新用户 </a> </li> <li> <a href="#"> <i class="fa fa-shopping-cart text-green"></i> 25 销售额 </a> </li> <li> <a href="#"> <i class="fa fa-user text-red"></i> 你更改了你的用户名 </a> </li> </ul> </li> <li class="footer"><a href="#">显示全部</a></li> </ul> </li> <!-- Tasks: style can be found in dropdown.less --> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">你有9个任务</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> <li><!-- Task item --> <a href="#"> <h3> 设计一些按钮 <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% 完成</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> 创造一个好的主题 <small class="pull-right">40%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">40% 完成</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> 使用龙果模板 <small class="pull-right">60%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">60% 完成</span> </div> </div> </a> </li> <!-- end task item --> <li><!-- Task item --> <a href="#"> <h3> 活动规则设定 <small class="pull-right">80%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">80% 完成</span> </div> </div> </a> </li> <!-- end task item --> </ul> </li> <li class="footer"> <a href="#">查看所有任务</a> </li> </ul> </li> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="../../dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <span class="hidden-xs">龙果一号</span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> 龙果一号 - 超级管理员 <small>2016-09 加入</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="row"> <div class="col-xs-4 text-center"> <a href="#">下属</a> </div> <div class="col-xs-4 text-center"> <a href="#">销售额</a> </div> <div class="col-xs-4 text-center"> <a href="#">朋友</a> </div> </div> <!-- /.row --> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">简介</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">退出</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../../dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Alexander Pierce</p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <!-- search form --> <form action="#" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu"> <li class="header">MAIN NAVIGATION</li> <li class="treeview"> <a href="#"> <i class="fa fa-dashboard"></i> <span>面板</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../dashboard.html"><i class="fa fa-circle-o"></i> 面板 v1</a></li> <li><a href="../../index2.html"><i class="fa fa-circle-o"></i> 面板 v2</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-files-o"></i> <span>界面布局</span> <span class="pull-right-container"> <span class="label label-primary pull-right">4</span> </span> </a> <ul class="treeview-menu"> <li><a href="../layout/top-nav.html"><i class="fa fa-circle-o"></i>头部导航</a></li> <li><a href="../layout/boxed.html"><i class="fa fa-circle-o"></i>盒装布局</a></li> <li><a href="../layout/fixed.html"><i class="fa fa-circle-o"></i>固定导航</a></li> <li><a href="../layout/collapsed-sidebar.html"><i class="fa fa-circle-o"></i>隐藏侧栏</a></li> <li><a href="index.html"><i class="fa fa-circle-o"></i>非跳转模式</a></li> </ul> </li> <li> <a href="../widgets.html"> <i class="fa fa-th"></i> <span>小组件</span> <span class="pull-right-container"> <small class="label pull-right bg-green">new</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-pie-chart"></i> <span>图表</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../charts/chartjs.html"><i class="fa fa-circle-o"></i> ChartJS</a></li> <li><a href="../charts/morris.html"><i class="fa fa-circle-o"></i> Morris</a></li> <li><a href="../charts/flot.html"><i class="fa fa-circle-o"></i> Flot</a></li> <li><a href="../charts/inline.html"><i class="fa fa-circle-o"></i> Inline charts</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-laptop"></i> <span>UI 元素</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../UI/general.html"><i class="fa fa-circle-o"></i> 一般</a></li> <li><a href="../UI/icons.html"><i class="fa fa-circle-o"></i> 图标</a></li> <li><a href="../UI/buttons.html"><i class="fa fa-circle-o"></i> 按钮</a></li> <li><a href="../UI/sliders.html"><i class="fa fa-circle-o"></i> 滑块</a></li> <li><a href="../UI/timeline.html"><i class="fa fa-circle-o"></i> 时间</a></li> <li><a href="../UI/modals.html"><i class="fa fa-circle-o"></i> 提示</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-edit"></i> <span>表单</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../forms/general.html"><i class="fa fa-circle-o"></i> 一般</a></li> <li><a href="../forms/advanced.html"><i class="fa fa-circle-o"></i> 高级</a></li> <li><a href="../forms/editors.html"><i class="fa fa-circle-o"></i> 编辑</a></li> </ul> </li> <li class="active treeview"> <a href="#"> <i class="fa fa-table"></i> <span>表格</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li class="active"><a href="../tables/simple.html"><i class="fa fa-circle-o"></i> 普通表格</a></li> <li><a href="../tables/data.html"><i class="fa fa-circle-o"></i> 数据表格</a></li> </ul> </li> <li> <a href="../calendar.html"> <i class="fa fa-calendar"></i> <span>日历</span> <span class="pull-right-container"> <small class="label pull-right bg-red">3</small> <small class="label pull-right bg-blue">17</small> </span> </a> </li> <li> <a href="../mailbox/mailbox.html"> <i class="fa fa-envelope"></i> <span>邮箱</span> <span class="pull-right-container"> <small class="label pull-right bg-yellow">12</small> <small class="label pull-right bg-green">16</small> <small class="label pull-right bg-red">5</small> </span> </a> </li> <li class="treeview"> <a href="#"> <i class="fa fa-folder"></i> <span>实例</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="../examples/invoice.html"><i class="fa fa-circle-o"></i> Invoice</a></li> <li><a href="../examples/profile.html"><i class="fa fa-circle-o"></i> Profile</a></li> <li><a href="../examples/login.html"><i class="fa fa-circle-o"></i> Login</a></li> <li><a href="../examples/register.html"><i class="fa fa-circle-o"></i> Register</a></li> <li><a href="../examples/lockscreen.html"><i class="fa fa-circle-o"></i> Lockscreen</a></li> <li><a href="../examples/404.html"><i class="fa fa-circle-o"></i> 404 Error</a></li> <li><a href="../examples/500.html"><i class="fa fa-circle-o"></i> 500 Error</a></li> <li><a href="../examples/blank.html"><i class="fa fa-circle-o"></i> Blank Page</a></li> <li><a href="../examples/pace.html"><i class="fa fa-circle-o"></i> Pace Page</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-share"></i> <span>多级菜单</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i>一级菜单</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i>一级菜单 <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> 二级菜单</a></li> <li> <a href="#"><i class="fa fa-circle-o"></i> 二级菜单 <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> 三级菜单</a></li> <li><a href="#"><i class="fa fa-circle-o"></i> 三级菜单</a></li> </ul> </li> </ul> </li> <li><a href="#"><i class="fa fa-circle-o"></i>一级菜单</a></li> </ul> </li> <li><a href="../../documentation/index.html"><i class="fa fa-book"></i> <span>文档</span></a></li> <li class="header">LABELS</li> <li><a href="#"><i class="fa fa-circle-o text-red"></i> <span>重要</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-yellow"></i> <span>警告</span></a></li> <li><a href="#"><i class="fa fa-circle-o text-aqua"></i> <span>消息</span></a></li> </ul> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Simple Tables <small>preview of simple tables</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Tables</a></li> <li class="active">Simple</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-6"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Bordered Table</h3> </div> <!-- /.box-header --> <div class="box-body"> <table class="table table-bordered"> <tr> <th style="width: 10px">#</th> <th>Task</th> <th>Progress</th> <th style="width: 40px">Label</th> </tr> <tr> <td>1.</td> <td>Update software</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-danger" style="width: 55%"></div> </div> </td> <td><span class="badge bg-red">55%</span></td> </tr> <tr> <td>2.</td> <td>Clean database</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 70%"></div> </div> </td> <td><span class="badge bg-yellow">70%</span></td> </tr> <tr> <td>3.</td> <td>Cron job running</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-primary" style="width: 30%"></div> </div> </td> <td><span class="badge bg-light-blue">30%</span></td> </tr> <tr> <td>4.</td> <td>Fix and squish bugs</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 90%"></div> </div> </td> <td><span class="badge bg-green">90%</span></td> </tr> </table> </div> <!-- /.box-body --> <div class="box-footer clearfix"> <ul class="pagination pagination-sm no-margin pull-right"> <li><a href="#">&laquo;</a></li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">&raquo;</a></li> </ul> </div> </div> <!-- /.box --> <div class="box"> <div class="box-header"> <h3 class="box-title">Condensed Full Width Table</h3> </div> <!-- /.box-header --> <div class="box-body no-padding"> <table class="table table-condensed"> <tr> <th style="width: 10px">#</th> <th>Task</th> <th>Progress</th> <th style="width: 40px">Label</th> </tr> <tr> <td>1.</td> <td>Update software</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-danger" style="width: 55%"></div> </div> </td> <td><span class="badge bg-red">55%</span></td> </tr> <tr> <td>2.</td> <td>Clean database</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 70%"></div> </div> </td> <td><span class="badge bg-yellow">70%</span></td> </tr> <tr> <td>3.</td> <td>Cron job running</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-primary" style="width: 30%"></div> </div> </td> <td><span class="badge bg-light-blue">30%</span></td> </tr> <tr> <td>4.</td> <td>Fix and squish bugs</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 90%"></div> </div> </td> <td><span class="badge bg-green">90%</span></td> </tr> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> <div class="col-md-6"> <div class="box"> <div class="box-header"> <h3 class="box-title">Simple Full Width Table</h3> <div class="box-tools"> <ul class="pagination pagination-sm no-margin pull-right"> <li><a href="#">&laquo;</a></li> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">&raquo;</a></li> </ul> </div> </div> <!-- /.box-header --> <div class="box-body no-padding"> <table class="table"> <tr> <th style="width: 10px">#</th> <th>Task</th> <th>Progress</th> <th style="width: 40px">Label</th> </tr> <tr> <td>1.</td> <td>Update software</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-danger" style="width: 55%"></div> </div> </td> <td><span class="badge bg-red">55%</span></td> </tr> <tr> <td>2.</td> <td>Clean database</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 70%"></div> </div> </td> <td><span class="badge bg-yellow">70%</span></td> </tr> <tr> <td>3.</td> <td>Cron job running</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-primary" style="width: 30%"></div> </div> </td> <td><span class="badge bg-light-blue">30%</span></td> </tr> <tr> <td>4.</td> <td>Fix and squish bugs</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 90%"></div> </div> </td> <td><span class="badge bg-green">90%</span></td> </tr> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> <div class="box"> <div class="box-header"> <h3 class="box-title">Striped Full Width Table</h3> </div> <!-- /.box-header --> <div class="box-body no-padding"> <table class="table table-striped"> <tr> <th style="width: 10px">#</th> <th>Task</th> <th>Progress</th> <th style="width: 40px">Label</th> </tr> <tr> <td>1.</td> <td>Update software</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-danger" style="width: 55%"></div> </div> </td> <td><span class="badge bg-red">55%</span></td> </tr> <tr> <td>2.</td> <td>Clean database</td> <td> <div class="progress progress-xs"> <div class="progress-bar progress-bar-yellow" style="width: 70%"></div> </div> </td> <td><span class="badge bg-yellow">70%</span></td> </tr> <tr> <td>3.</td> <td>Cron job running</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-primary" style="width: 30%"></div> </div> </td> <td><span class="badge bg-light-blue">30%</span></td> </tr> <tr> <td>4.</td> <td>Fix and squish bugs</td> <td> <div class="progress progress-xs progress-striped active"> <div class="progress-bar progress-bar-success" style="width: 90%"></div> </div> </td> <td><span class="badge bg-green">90%</span></td> </tr> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Responsive Hover Table</h3> <div class="box-tools"> <div class="input-group input-group-sm" style="width: 150px;"> <input type="text" name="table_search" class="form-control pull-right" placeholder="Search"> <div class="input-group-btn"> <button type="submit" class="btn btn-default"><i class="fa fa-search"></i></button> </div> </div> </div> </div> <!-- /.box-header --> <div class="box-body table-responsive no-padding"> <table class="table table-hover"> <tr> <th>ID</th> <th>User</th> <th>Date</th> <th>Status</th> <th>Reason</th> </tr> <tr> <td>183</td> <td>John Doe</td> <td>11-7-2014</td> <td><span class="label label-success">Approved</span></td> <td>Bacon ipsum dolor sit amet salami venison chicken flank fatback doner.</td> </tr> <tr> <td>219</td> <td>Alexander Pierce</td> <td>11-7-2014</td> <td><span class="label label-warning">Pending</span></td> <td>Bacon ipsum dolor sit amet salami venison chicken flank fatback doner.</td> </tr> <tr> <td>657</td> <td>Bob Doe</td> <td>11-7-2014</td> <td><span class="label label-primary">Approved</span></td> <td>Bacon ipsum dolor sit amet salami venison chicken flank fatback doner.</td> </tr> <tr> <td>175</td> <td>Mike Doe</td> <td>11-7-2014</td> <td><span class="label label-danger">Denied</span></td> <td>Bacon ipsum dolor sit amet salami venison chicken flank fatback doner.</td> </tr> </table> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> </div> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.3.6 </div> <strong>Copyright &copy; 2014-2016 <a href="http://almsaeedstudio.com">Almsaeed Studio</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Create the tabs --> <ul class="nav nav-tabs nav-justified control-sidebar-tabs"> <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li> <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <!-- Home tab content --> <div class="tab-pane" id="control-sidebar-home-tab"> <h3 class="control-sidebar-heading">最近的活动</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-birthday-cake bg-red"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">我的生日</h4> <p>四月二十四</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-user bg-yellow"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">更新我的资料</h4> <p>新手机号码 (+86)1234567890</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-envelope-o bg-light-blue"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">添加邮箱地址</h4> <p>[email protected]</p> </div> </a> </li> <li> <a href="javascript:void(0)"> <i class="menu-icon fa fa-file-code-o bg-green"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">写个256字的描述</h4> <p>执行时间5秒</p> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> <h3 class="control-sidebar-heading">任务进度</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> 自定义模板的设计 <span class="label label-danger pull-right">70%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-danger" style="width: 70%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> 更新简历 <span class="label label-success pull-right">95%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-success" style="width: 95%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> 获取积分 <span class="label label-warning pull-right">50%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-warning" style="width: 50%"></div> </div> </a> </li> <li> <a href="javascript:void(0)"> <h4 class="control-sidebar-subheading"> 后端框架 <span class="label label-primary pull-right">68%</span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-primary" style="width: 68%"></div> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> </div> <!-- /.tab-pane --> <!-- Settings tab content --> <div class="tab-pane" id="control-sidebar-settings-tab"> <form method="post"> <h3 class="control-sidebar-heading">一般设置</h3> <div class="form-group"> <label class="control-sidebar-subheading"> 面板的使用报告 <input type="checkbox" class="pull-right" checked> </label> <p> 有关此常规设置选项的一些信息 </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> 允许邮件重定向 <input type="checkbox" class="pull-right" checked> </label> <p> 其他可用的选项集 </p> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> 在帖子中公开作者姓名 <input type="checkbox" class="pull-right" checked> </label> <p> 允许用户在博客帖子中显示自己的名字 </p> </div> <!-- /.form-group --> <h3 class="control-sidebar-heading">聊天设置</h3> <div class="form-group"> <label class="control-sidebar-subheading"> 显示我是否在线 <input type="checkbox" class="pull-right" checked> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> 关闭通知 <input type="checkbox" class="pull-right"> </label> </div> <!-- /.form-group --> <div class="form-group"> <label class="control-sidebar-subheading"> 删除的聊天记录 <a href="javascript:void(0)" class="text-red pull-right"><i class="fa fa-trash-o"></i></a> </label> </div> <!-- /.form-group --> </form> </div> <!-- /.tab-pane --> </div> </aside> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="../../plugins/jQuery/jquery-2.2.3.min.js"></script> <!-- Bootstrap 3.3.6 --> <script src="../../plugins/bootstrap/js/bootstrap.min.js"></script> <!-- Slimscroll --> <script src="../../plugins/slimScroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="../../plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="../../dist/js/app.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="../../dist/js/demo.js"></script> </body> </html>
gpl-3.0
gencer/gitextensions
GitUI/CommandsDialogs/SettingsDialog/Pages/FormBrowseRepoSettingsPage.cs
1850
using GitCommands; using GitCommands.Utils; namespace GitUI.CommandsDialogs.SettingsDialog.Pages { public partial class FormBrowseRepoSettingsPage : SettingsPageWithHeader { public FormBrowseRepoSettingsPage() { InitializeComponent(); Text = "Browse repository window"; Translate(); } protected override void Init(ISettingsPageHost aPageHost) { base.Init(aPageHost); BindSettingsWithControls(); } protected override void SettingsToPage() { chkShowRevisionInfoNextToRevisionGrid.Checked = AppSettings.ShowRevisionInfoNextToRevisionGrid; chkShowRevisionInfoNextToRevisionGrid.Visible = !EnvUtils.IsMonoRuntime(); base.SettingsToPage(); } protected override void PageToSettings() { AppSettings.ShowRevisionInfoNextToRevisionGrid = chkShowRevisionInfoNextToRevisionGrid.Checked; base.PageToSettings(); } private void BindSettingsWithControls() { AddSettingBinding(AppSettings.ShowConEmuTab, chkChowConsoleTab); AddSettingBinding(AppSettings.ConEmuStyle, _NO_TRANSLATE_cboStyle); AddSettingBinding(AppSettings.ConEmuTerminal, cboTerminal); AddSettingBinding(AppSettings.ConEmuFontSize, cboFontSize); AddSettingBinding(AppSettings.ShowGpgInformation, chkShowGpgInformation); } private void chkChowConsoleTab_CheckedChanged(object sender, System.EventArgs e) { groupBoxConsoleSettings.Enabled = chkChowConsoleTab.Checked; } public static SettingsPageReference GetPageReference() { return new SettingsPageReferenceByType(typeof(FormBrowseRepoSettingsPage)); } } }
gpl-3.0
niuran1993/Deskera-HRMS
mavenTimesheet/src/test/java/com/mycompany/mavenTimesheet/AppTest.java
1470
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.mycompany.mavenTimesheet; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
gpl-3.0
jjskuld/NecroBot
PoGo.NecroBot.Logic/State/StateMachine.cs
3212
#region using directives using System; using System.IO; using System.Threading; using System.Threading.Tasks; using PoGo.NecroBot.Logic.Event; using PoGo.NecroBot.Logic.Logging; using PoGo.NecroBot.Logic.Model.Settings; using PokemonGo.RocketAPI.Exceptions; #endregion namespace PoGo.NecroBot.Logic.State { public class StateMachine { private IState _initialState; public Task AsyncStart(IState initialState, Session session, string subPath, CancellationToken cancellationToken = default(CancellationToken)) { return Task.Run(() => Start(initialState, session, subPath, cancellationToken), cancellationToken); } public void SetFailureState(IState state) { _initialState = state; } public async Task Start(IState initialState, Session session, string subPath, CancellationToken cancellationToken = default(CancellationToken)) { var state = initialState; var profilePath = Path.Combine(Directory.GetCurrentDirectory(), subPath); var profileConfigPath = Path.Combine(profilePath, "config"); FileSystemWatcher configWatcher = new FileSystemWatcher(); configWatcher.Path = profileConfigPath; configWatcher.Filter = "config.json"; configWatcher.NotifyFilter = NotifyFilters.LastWrite; configWatcher.EnableRaisingEvents = true; configWatcher.Changed += (sender, e) => { if (e.ChangeType == WatcherChangeTypes.Changed) { session.LogicSettings = new LogicSettings(GlobalSettings.Load(subPath)); configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents; configWatcher.EnableRaisingEvents = !configWatcher.EnableRaisingEvents; Logger.Write(" ##### config.json ##### ", LogLevel.Info); } }; do { try { state = await state.Execute(session, cancellationToken); } catch (InvalidResponseException) { session.EventDispatcher.Send(new ErrorEvent { Message = "Niantic Servers unstable, throttling API Calls." }); } catch (OperationCanceledException) { session.EventDispatcher.Send(new ErrorEvent {Message = "Current Operation was canceled."}); state = _initialState; } catch (Exception ex) { session.EventDispatcher.Send(new ErrorEvent {Message = "Pokemon Servers might be offline / unstable. Trying again..."}); Thread.Sleep(1000); session.EventDispatcher.Send(new ErrorEvent { Message = "Error: " + ex }); state = _initialState; } } while (state != null); configWatcher.EnableRaisingEvents = false; configWatcher.Dispose(); } } }
gpl-3.0
petrzjunior/Marlin
Marlin/src/module/thermistor/thermistor_67.h
2274
/** * Marlin 3D Printer Firmware * Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma once // R25 = 500 KOhm, beta25 = 3800 K, 4.7 kOhm pull-up, SliceEngineering 450 °C Thermistor const short temptable_67[][2] PROGMEM = { { OV( 22 ), 500 }, { OV( 23 ), 490 }, { OV( 25 ), 480 }, { OV( 27 ), 470 }, { OV( 29 ), 460 }, { OV( 32 ), 450 }, { OV( 35 ), 440 }, { OV( 38 ), 430 }, { OV( 41 ), 420 }, { OV( 45 ), 410 }, { OV( 50 ), 400 }, { OV( 55 ), 390 }, { OV( 60 ), 380 }, { OV( 67 ), 370 }, { OV( 74 ), 360 }, { OV( 82 ), 350 }, { OV( 91 ), 340 }, { OV( 102 ), 330 }, { OV( 114 ), 320 }, { OV( 127 ), 310 }, { OV( 143 ), 300 }, { OV( 161 ), 290 }, { OV( 181 ), 280 }, { OV( 204 ), 270 }, { OV( 229 ), 260 }, { OV( 259 ), 250 }, { OV( 290 ), 240 }, { OV( 325 ), 230 }, { OV( 364 ), 220 }, { OV( 407 ), 210 }, { OV( 453 ), 200 }, { OV( 501 ), 190 }, { OV( 551 ), 180 }, { OV( 603 ), 170 }, { OV( 655 ), 160 }, { OV( 706 ), 150 }, { OV( 755 ), 140 }, { OV( 801 ), 130 }, { OV( 842 ), 120 }, { OV( 879 ), 110 }, { OV( 910 ), 100 }, { OV( 936 ), 90 }, { OV( 948 ), 85 }, { OV( 958 ), 80 }, { OV( 975 ), 70 }, { OV( 988 ), 60 }, { OV( 998 ), 50 }, { OV(1006 ), 40 }, { OV(1011 ), 30 }, { OV(1013 ), 25 }, { OV(1015 ), 20 }, { OV(1018 ), 10 }, { OV(1020 ), 0 }, { OV(1021 ), -10 }, { OV(1022 ), -20 } };
gpl-3.0
genome/dgi-db
lib/genome/importers/dsl/with_drugs_and_genes.rb
1201
module Genome module Importers module DSL module WithDrugsAndGenes attr_accessor :gene_claim, :drug_claim def initialize(item_id, importer_instance, row_instance) super(item_id, importer_instance, row_instance, 'interaction_claim') end def gene(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @gene_claim_id = @importer.create_gene_claim(name: val, nomenclature: opts[:nomenclature]) node = GeneNode.new(@gene_claim_id, @importer, @row) node.instance_eval(&block) end end def drug(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @drug_claim_id = @importer.create_drug_claim(name: val, nomenclature: opts[:nomenclature], primary_name: opts[:transform].call(@row.send(opts[:primary_name]))) node = DrugNode.new(@drug_claim_id, @importer, @row) node.instance_eval(&block) end end end end end end
gpl-3.0
AEnterprise/Buildcraft-Additions
src/main/java/buildcraftAdditions/ModIntegration/Buildcraft/Triggers/TriggerDoneCharging.java
1093
package buildcraftAdditions.ModIntegration.Buildcraft.Triggers; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; import buildcraftAdditions.tileEntities.TileChargingStation; /** * Copyright (c) 2014, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class TriggerDoneCharging extends BasicTrigger { public TriggerDoneCharging() { super("doneCharging", "TriggerDoneCharging"); } @Override public boolean isTriggerActive(TileEntity target, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { if (target instanceof TileChargingStation) { TileChargingStation chargingStation = (TileChargingStation) target; return chargingStation.getProgress() == 1; } return false; } }
gpl-3.0
japeto/TMotive
application/static/css/tahoe-theme-aqua.css
591
body { background: #7aa0f1; font-family: Arial, Helvetica, sans-serif; font-size: 12px; font-family: 'Raleway', sans-serif; } .navbar { color:#EEE; background: #377491; min-height: 10px !important; } .navbar-top-links li a { color: #EEE; } .navbar-top-links li a:hover { color: #888; } .navbar-top-links .dropdown-user { color: #D5D2CB; background: #377491; } .sidebar ul li { background: #7aa0f1; } .sidebar ul li a{ color:#FFF; } .sidebar ul li a:hover{ color:#FFF; background: #0099CB; } .sidebar ul li a.active { color :#fff; background: #2D9FC4; }
gpl-3.0
wdzhou/mantid
Framework/PythonInterface/inc/MantidPythonInterface/kernel/Registry/SequenceTypeHandler.h
2138
#ifndef MANTID_PYTHONINTERFACE_SEQUENCETYPEHANDLER_H_ #define MANTID_PYTHONINTERFACE_SEQUENCETYPEHANDLER_H_ /** Copyright &copy; 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source This file is part of Mantid. Mantid is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Mantid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ #include "MantidPythonInterface/kernel/Registry/TypedPropertyValueHandler.h" namespace Mantid { namespace PythonInterface { namespace Registry { /** * A specialisation of PropertyValueHander to handle coercing a Python * value into a C++ sequence/array property. The template type ContainerType * should contain a type called value_type indicating the element type. */ template <typename ContainerType> struct DLLExport SequenceTypeHandler : TypedPropertyValueHandler<ContainerType> { /// Call to set a named property where the value is some container type void set(Kernel::IPropertyManager *alg, const std::string &name, const boost::python::object &value) const override; /// Call to create a name property where the value is some container type std::unique_ptr<Kernel::Property> create(const std::string &name, const boost::python::object &defaultValue, const boost::python::object &validator, const unsigned int direction) const override; }; } } } #endif /* MANTID_PYTHONINTERFACE_SEQUENCETYPEHANDLER_H_ */
gpl-3.0
Boyang--Li/ardupilot
libraries/AP_BattMonitor/AP_BattMonitor.cpp
14002
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include "AP_BattMonitor.h" #include "AP_BattMonitor_Analog.h" #include "AP_BattMonitor_SMBus.h" #include "AP_BattMonitor_Bebop.h" extern const AP_HAL::HAL& hal; const AP_Param::GroupInfo AP_BattMonitor::var_info[] = { // @Param: _MONITOR // @DisplayName: Battery monitoring // @Description: Controls enabling monitoring of the battery's voltage and current // @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop // @User: Standard AP_GROUPINFO("_MONITOR", 0, AP_BattMonitor, _monitoring[0], BattMonitor_TYPE_NONE), // @Param: _VOLT_PIN // @DisplayName: Battery Voltage sensing pin // @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2. // @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4 // @User: Standard AP_GROUPINFO("_VOLT_PIN", 1, AP_BattMonitor, _volt_pin[0], AP_BATT_VOLT_PIN), // @Param: _CURR_PIN // @DisplayName: Battery Current sensing pin // @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3. // @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4 // @User: Standard AP_GROUPINFO("_CURR_PIN", 2, AP_BattMonitor, _curr_pin[0], AP_BATT_CURR_PIN), // @Param: _VOLT_MULT // @DisplayName: Voltage Multiplier // @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1. // @User: Advanced AP_GROUPINFO("_VOLT_MULT", 3, AP_BattMonitor, _volt_multiplier[0], AP_BATT_VOLTDIVIDER_DEFAULT), // @Param: _AMP_PERVOLT // @DisplayName: Amps per volt // @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17. // @Units: Amps/Volt // @User: Standard AP_GROUPINFO("_AMP_PERVOLT", 4, AP_BattMonitor, _curr_amp_per_volt[0], AP_BATT_CURR_AMP_PERVOLT_DEFAULT), // @Param: _AMP_OFFSET // @DisplayName: AMP offset // @Description: Voltage offset at zero current on current sensor // @Units: Volts // @User: Standard AP_GROUPINFO("_AMP_OFFSET", 5, AP_BattMonitor, _curr_amp_offset[0], 0), // @Param: _CAPACITY // @DisplayName: Battery capacity // @Description: Capacity of the battery in mAh when full // @Units: mAh // @Increment: 50 // @User: Standard AP_GROUPINFO("_CAPACITY", 6, AP_BattMonitor, _pack_capacity[0], AP_BATT_CAPACITY_DEFAULT), // 7 & 8 were used for VOLT2_PIN and VOLT2_MULT #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // @Param: _WATT_MAX // @DisplayName: Maximum allowed power (Watts) // @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable. // @Units: Watts // @Increment: 1 // @User: Advanced AP_GROUPINFO("_WATT_MAX", 9, AP_BattMonitor, _watt_max[0], AP_BATT_MAX_WATT_DEFAULT), #endif // 10 is left for future expansion #if AP_BATT_MONITOR_MAX_INSTANCES > 1 // @Param: 2_MONITOR // @DisplayName: Battery monitoring // @Description: Controls enabling monitoring of the battery's voltage and current // @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop // @User: Standard AP_GROUPINFO("2_MONITOR", 11, AP_BattMonitor, _monitoring[1], BattMonitor_TYPE_NONE), // @Param: 2_VOLT_PIN // @DisplayName: Battery Voltage sensing pin // @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2. // @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4 // @User: Standard AP_GROUPINFO("2_VOLT_PIN", 12, AP_BattMonitor, _volt_pin[1], AP_BATT_VOLT_PIN), // @Param: 2_CURR_PIN // @DisplayName: Battery Current sensing pin // @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3. // @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4 // @User: Standard AP_GROUPINFO("2_CURR_PIN", 13, AP_BattMonitor, _curr_pin[1], AP_BATT_CURR_PIN), // @Param: 2_VOLT_MULT // @DisplayName: Voltage Multiplier // @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1. // @User: Advanced AP_GROUPINFO("2_VOLT_MULT", 14, AP_BattMonitor, _volt_multiplier[1], AP_BATT_VOLTDIVIDER_DEFAULT), // @Param: 2_AMP_PERVOL // @DisplayName: Amps per volt // @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17. // @Units: Amps/Volt // @User: Standard AP_GROUPINFO("2_AMP_PERVOL", 15, AP_BattMonitor, _curr_amp_per_volt[1], AP_BATT_CURR_AMP_PERVOLT_DEFAULT), // @Param: 2_AMP_OFFSET // @DisplayName: AMP offset // @Description: Voltage offset at zero current on current sensor // @Units: Volts // @User: Standard AP_GROUPINFO("2_AMP_OFFSET", 16, AP_BattMonitor, _curr_amp_offset[1], 0), // @Param: 2_CAPACITY // @DisplayName: Battery capacity // @Description: Capacity of the battery in mAh when full // @Units: mAh // @Increment: 50 // @User: Standard AP_GROUPINFO("2_CAPACITY", 17, AP_BattMonitor, _pack_capacity[1], AP_BATT_CAPACITY_DEFAULT), #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // @Param: 2_WATT_MAX // @DisplayName: Maximum allowed current // @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable. // @Units: Amps // @Increment: 1 // @User: Advanced AP_GROUPINFO("2_WATT_MAX", 18, AP_BattMonitor, _watt_max[1], AP_BATT_MAX_WATT_DEFAULT), #endif #endif // AP_BATT_MONITOR_MAX_INSTANCES > 1 AP_GROUPEND }; // Default constructor. // Note that the Vector/Matrix constructors already implicitly zero // their values. // AP_BattMonitor::AP_BattMonitor(void) : _num_instances(0) { AP_Param::setup_object_defaults(this, var_info); } // init - instantiate the battery monitors void AP_BattMonitor::init() { // check init has not been called before if (_num_instances != 0) { return; } #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO // force monitor for bebop _monitoring[0] = BattMonitor_TYPE_BEBOP; #endif // create each instance for (uint8_t instance=0; instance<AP_BATT_MONITOR_MAX_INSTANCES; instance++) { uint8_t monitor_type = _monitoring[instance]; switch (monitor_type) { case BattMonitor_TYPE_ANALOG_VOLTAGE_ONLY: case BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT: state[instance].instance = instance; drivers[instance] = new AP_BattMonitor_Analog(*this, instance, state[instance]); _num_instances++; break; case BattMonitor_TYPE_SMBUS: state[instance].instance = instance; #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 drivers[instance] = new AP_BattMonitor_SMBus_PX4(*this, instance, state[instance]); #else drivers[instance] = new AP_BattMonitor_SMBus_I2C(*this, instance, state[instance]); #endif _num_instances++; break; case BattMonitor_TYPE_BEBOP: #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO state[instance].instance = instance; drivers[instance] = new AP_BattMonitor_Bebop(*this, instance, state[instance]); _num_instances++; #endif break; } // call init function for each backend if (drivers[instance] != NULL) { drivers[instance]->init(); } } } // read - read the voltage and current for all instances void AP_BattMonitor::read() { for (uint8_t i=0; i<_num_instances; i++) { if (drivers[i] != NULL && _monitoring[i] != BattMonitor_TYPE_NONE) { drivers[i]->read(); } } } // healthy - returns true if monitor is functioning bool AP_BattMonitor::healthy(uint8_t instance) const { return instance < _num_instances && _BattMonitor_STATE(instance).healthy; } bool AP_BattMonitor::is_powering_off(uint8_t instance) const { return instance < _num_instances && _BattMonitor_STATE(instance).is_powering_off; } /// has_current - returns true if battery monitor instance provides current info bool AP_BattMonitor::has_current(uint8_t instance) const { // check for analog voltage and current monitor or smbus monitor if (instance < _num_instances && drivers[instance] != NULL) { return (_monitoring[instance] == BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT || _monitoring[instance] == BattMonitor_TYPE_SMBUS || _monitoring[instance] == BattMonitor_TYPE_BEBOP); } // not monitoring current return false; } /// voltage - returns battery voltage in volts float AP_BattMonitor::voltage(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).voltage; } else { return 0.0f; } } /// current_amps - returns the instantaneous current draw in amperes float AP_BattMonitor::current_amps(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).current_amps; } else { return 0.0f; } } /// current_total_mah - returns total current drawn since start-up in amp-hours float AP_BattMonitor::current_total_mah(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).current_total_mah; } else { return 0.0f; } } /// capacity_remaining_pct - returns the % battery capacity remaining (0 ~ 100) uint8_t AP_BattMonitor::capacity_remaining_pct(uint8_t instance) const { if (instance < _num_instances && drivers[instance] != NULL) { return drivers[instance]->capacity_remaining_pct(); } else { return 0; } } /// exhausted - returns true if the voltage remains below the low_voltage for 10 seconds or remaining capacity falls below min_capacity_mah bool AP_BattMonitor::exhausted(uint8_t instance, float low_voltage, float min_capacity_mah) { // exit immediately if no monitors setup if (_num_instances == 0 || instance >= _num_instances) { return false; } // check voltage if ((state[instance].voltage > 0) && (low_voltage > 0) && (state[instance].voltage < low_voltage)) { // this is the first time our voltage has dropped below minimum so start timer if (state[instance].low_voltage_start_ms == 0) { state[instance].low_voltage_start_ms = AP_HAL::millis(); } else if (AP_HAL::millis() - state[instance].low_voltage_start_ms > AP_BATT_LOW_VOLT_TIMEOUT_MS) { return true; } } else { // acceptable voltage so reset timer state[instance].low_voltage_start_ms = 0; } // check capacity if current monitoring is enabled if (has_current(instance) && (min_capacity_mah > 0) && (_pack_capacity[instance] - state[instance].current_total_mah < min_capacity_mah)) { return true; } // if we've gotten this far then battery is ok return false; } #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // return true if any battery is pushing too much power bool AP_BattMonitor::overpower_detected() const { bool result = false; for (int instance = 0; instance < _num_instances; instance++) { result |= overpower_detected(instance); } return result; } bool AP_BattMonitor::overpower_detected(uint8_t instance) const { if (instance < _num_instances && _watt_max[instance] > 0) { float power = _BattMonitor_STATE(instance).current_amps * _BattMonitor_STATE(instance).voltage; return _BattMonitor_STATE(instance).healthy && (power > _watt_max[instance]); } return false; } #endif
gpl-3.0
ArduPilot/MissionPlanner
ExtLibs/DroneCAN/out/src/uavcan.protocol.debug.LogLevel.cs
1660
using uint8_t = System.Byte; using uint16_t = System.UInt16; using uint32_t = System.UInt32; using uint64_t = System.UInt64; using int8_t = System.SByte; using int16_t = System.Int16; using int32_t = System.Int32; using int64_t = System.Int64; using float32 = System.Single; using System; using System.Linq; using System.Runtime.InteropServices; using System.Collections.Generic; namespace DroneCAN { public partial class DroneCAN { static void encode_uavcan_protocol_debug_LogLevel(uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx) { uint8_t[] buffer = new uint8_t[8]; _encode_uavcan_protocol_debug_LogLevel(buffer, msg, chunk_cb, ctx, true); } static uint32_t decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer, uavcan_protocol_debug_LogLevel msg) { uint32_t bit_ofs = 0; _decode_uavcan_protocol_debug_LogLevel(transfer, ref bit_ofs, msg, true); return (bit_ofs+7)/8; } static void _encode_uavcan_protocol_debug_LogLevel(uint8_t[] buffer, uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx, bool tao) { memset(buffer,0,8); canardEncodeScalar(buffer, 0, 3, msg.value); chunk_cb(buffer, 3, ctx); } static void _decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer,ref uint32_t bit_ofs, uavcan_protocol_debug_LogLevel msg, bool tao) { canardDecodeScalar(transfer, bit_ofs, 3, false, ref msg.value); bit_ofs += 3; } } }
gpl-3.0
sawenzel/AliceO2
Detectors/TRD/base/include/TRDBase/ChamberNoise.h
1764
// Copyright 2019-2020 CERN and copyright holders of ALICE O2. // See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. // All rights not expressly granted are reserved. // // This software is distributed under the terms of the GNU General Public // License v3 (GPL Version 3), copied verbatim in the file "COPYING". // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. #ifndef O2_TRD_CHAMBERNOISE_H #define O2_TRD_CHAMBERNOISE_H /////////////////////////////////////////////////////////////////////////////// // // // TRD calibration class for ChamberNoise // // 2019 - Ported from various bits of AliRoot (SHTM) // // Originally stored in AliTRDCalDet and instantiated at DetNoise in ocdb // /////////////////////////////////////////////////////////////////////////////// #include "TRDBase/SimParam.h" #include "DataFormatsTRD/Constants.h" // class Geometry; namespace o2 { namespace trd { class ChamberNoise { public: ChamberNoise() = default; ~ChamberNoise() = default; // float getNoise(int p, int c, int s) const { return mNoise[o2::trd::Geometry::getDetector(p, c, s)]; }; float getNoise(int det) const { return mNoise[det]; }; void setNoise(int p, int c, int s, float noise) { mNoise[o2::trd::Geometry::getDetector(p, c, s)] = noise; }; void setNoise(int det, float noise) { mNoise[det] = noise; }; //bulk gets ? protected: std::array<float, constants::MAXCHAMBER> mNoise{}; }; } // namespace trd } // namespace o2 #endif
gpl-3.0
dibenede/NFD-NDNcomm2014
tools/nfd-status.cpp
29976
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2014, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis * * This file is part of NFD (Named Data Networking Forwarding Daemon). * See AUTHORS.md for complete list of NFD authors and contributors. * * NFD is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * NFD 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 * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. * * @author Jerald Paul Abraham <[email protected]> */ #include "version.hpp" #include <ndn-cxx/face.hpp> #include <ndn-cxx/name.hpp> #include <ndn-cxx/interest.hpp> #include <ndn-cxx/encoding/buffer-stream.hpp> #include <ndn-cxx/management/nfd-forwarder-status.hpp> #include <ndn-cxx/management/nfd-channel-status.hpp> #include <ndn-cxx/management/nfd-face-status.hpp> #include <ndn-cxx/management/nfd-fib-entry.hpp> #include <ndn-cxx/management/nfd-rib-entry.hpp> #include <ndn-cxx/management/nfd-strategy-choice.hpp> #include <boost/algorithm/string/replace.hpp> #include <list> namespace ndn { class NfdStatus { public: explicit NfdStatus(char* toolName) : m_toolName(toolName) , m_needVersionRetrieval(false) , m_needChannelStatusRetrieval(false) , m_needFaceStatusRetrieval(false) , m_needFibEnumerationRetrieval(false) , m_needRibStatusRetrieval(false) , m_needStrategyChoiceRetrieval(false) , m_isOutputXml(false) { } void usage() { std::cout << "Usage: \n " << m_toolName << " [options]\n\n" "Show NFD version and status information\n\n" "Options:\n" " [-h] - print this help message\n" " [-v] - retrieve version information\n" " [-c] - retrieve channel status information\n" " [-f] - retrieve face status information\n" " [-b] - retrieve FIB information\n" " [-r] - retrieve RIB information\n" " [-s] - retrieve configured strategy choice for NDN namespaces\n" " [-x] - output NFD status information in XML format\n" "\n" " [-V] - show version information of nfd-status and exit\n" "\n" "If no options are provided, all information is retrieved.\n" "If -x is provided, other options(-v, -c, etc.) are ignored, and all information is printed in XML format.\n" ; } void enableVersionRetrieval() { m_needVersionRetrieval = true; } void enableChannelStatusRetrieval() { m_needChannelStatusRetrieval = true; } void enableFaceStatusRetrieval() { m_needFaceStatusRetrieval = true; } void enableFibEnumerationRetrieval() { m_needFibEnumerationRetrieval = true; } void enableStrategyChoiceRetrieval() { m_needStrategyChoiceRetrieval = true; } void enableRibStatusRetrieval() { m_needRibStatusRetrieval = true; } void enableXmlOutput() { m_isOutputXml = true; } void onTimeout() { std::cerr << "Request timed out" << std::endl; runNextStep(); } void fetchSegments(const Data& data, void (NfdStatus::*onDone)()) { m_buffer->write((const char*)data.getContent().value(), data.getContent().value_size()); uint64_t currentSegment = data.getName().get(-1).toSegment(); const name::Component& finalBlockId = data.getMetaInfo().getFinalBlockId(); if (finalBlockId.empty() || finalBlockId.toSegment() > currentSegment) { m_face.expressInterest(data.getName().getPrefix(-1).appendSegment(currentSegment+1), bind(&NfdStatus::fetchSegments, this, _2, onDone), bind(&NfdStatus::onTimeout, this)); } else { return (this->*onDone)(); } } void escapeSpecialCharacters(std::string *data) { using boost::algorithm::replace_all; replace_all(*data, "&", "&amp;"); replace_all(*data, "\"", "&quot;"); replace_all(*data, "\'", "&apos;"); replace_all(*data, "<", "&lt;"); replace_all(*data, ">", "&gt;"); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchVersionInformation() { Interest interest("/localhost/nfd/status"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest( interest, bind(&NfdStatus::afterFetchedVersionInformation, this, _2), bind(&NfdStatus::onTimeout, this)); } void afterFetchedVersionInformation(const Data& data) { nfd::ForwarderStatus status(data.getContent()); std::string nfdId; if (data.getSignature().hasKeyLocator()) { const ndn::KeyLocator& locator = data.getSignature().getKeyLocator(); if (locator.getType() == KeyLocator::KeyLocator_Name) nfdId = locator.getName().toUri(); //todo: KeyDigest supporting } if (m_isOutputXml) { std::cout << "<generalStatus>"; std::cout << "<nfdId>" << nfdId << "</nfdId>"; std::cout << "<version>" << status.getNfdVersion() << "</version>"; std::cout << "<startTime>" << time::toString(status.getStartTimestamp(), "%Y-%m-%dT%H:%M:%S%F") << "</startTime>"; std::cout << "<currentTime>" << time::toString(status.getCurrentTimestamp(), "%Y-%m-%dT%H:%M:%S%F") << "</currentTime>"; std::cout << "<uptime>PT" << time::duration_cast<time::seconds>(status.getCurrentTimestamp() - status.getStartTimestamp()).count() << "S</uptime>"; std::cout << "<nNameTreeEntries>" << status.getNNameTreeEntries() << "</nNameTreeEntries>"; std::cout << "<nFibEntries>" << status.getNFibEntries() << "</nFibEntries>"; std::cout << "<nPitEntries>" << status.getNPitEntries() << "</nPitEntries>"; std::cout << "<nMeasurementsEntries>" << status.getNMeasurementsEntries() << "</nMeasurementsEntries>"; std::cout << "<nCsEntries>" << status.getNCsEntries() << "</nCsEntries>"; std::cout << "<packetCounters>"; std::cout << "<incomingPackets>"; std::cout << "<nInterests>" << status.getNInInterests() << "</nInterests>"; std::cout << "<nDatas>" << status.getNInDatas() << "</nDatas>"; std::cout << "</incomingPackets>"; std::cout << "<outgoingPackets>"; std::cout << "<nInterests>" << status.getNOutInterests() << "</nInterests>"; std::cout << "<nDatas>" << status.getNOutDatas() << "</nDatas>"; std::cout << "</outgoingPackets>"; std::cout << "</packetCounters>"; std::cout << "</generalStatus>"; } else { std::cout << "General NFD status:" << std::endl; std::cout << " nfdId=" << nfdId << std::endl; std::cout << " version=" << status.getNfdVersion() << std::endl; std::cout << " startTime=" << time::toIsoString(status.getStartTimestamp()) << std::endl; std::cout << " currentTime=" << time::toIsoString(status.getCurrentTimestamp()) << std::endl; std::cout << " uptime=" << time::duration_cast<time::seconds>(status.getCurrentTimestamp() - status.getStartTimestamp()) << std::endl; std::cout << " nNameTreeEntries=" << status.getNNameTreeEntries() << std::endl; std::cout << " nFibEntries=" << status.getNFibEntries() << std::endl; std::cout << " nPitEntries=" << status.getNPitEntries() << std::endl; std::cout << " nMeasurementsEntries=" << status.getNMeasurementsEntries() << std::endl; std::cout << " nCsEntries=" << status.getNCsEntries() << std::endl; std::cout << " nInInterests=" << status.getNInInterests() << std::endl; std::cout << " nOutInterests=" << status.getNOutInterests() << std::endl; std::cout << " nInDatas=" << status.getNInDatas() << std::endl; std::cout << " nOutDatas=" << status.getNOutDatas() << std::endl; } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchChannelStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/faces/channels"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedChannelStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedChannelStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<channels>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl; break; } offset += block.size(); nfd::ChannelStatus channelStatus(block); std::cout << "<channel>"; std::string localUri(channelStatus.getLocalUri()); escapeSpecialCharacters(&localUri); std::cout << "<localUri>" << localUri << "</localUri>"; std::cout << "</channel>"; } std::cout << "</channels>"; } else { std::cout << "Channels:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl; break; } offset += block.size(); nfd::ChannelStatus channelStatus(block); std::cout << " " << channelStatus.getLocalUri() << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchFaceStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/faces/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedFaceStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedFaceStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<faces>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl; break; } offset += block.size(); nfd::FaceStatus faceStatus(block); std::cout << "<face>"; std::cout << "<faceId>" << faceStatus.getFaceId() << "</faceId>"; std::string remoteUri(faceStatus.getRemoteUri()); escapeSpecialCharacters(&remoteUri); std::cout << "<remoteUri>" << remoteUri << "</remoteUri>"; std::string localUri(faceStatus.getLocalUri()); escapeSpecialCharacters(&localUri); std::cout << "<localUri>" << localUri << "</localUri>"; if (faceStatus.hasExpirationPeriod()) { std::cout << "<expirationPeriod>PT" << time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod()) .count() << "S" << "</expirationPeriod>"; } std::cout << "<packetCounters>"; std::cout << "<incomingPackets>"; std::cout << "<nInterests>" << faceStatus.getNInInterests() << "</nInterests>"; std::cout << "<nDatas>" << faceStatus.getNInDatas() << "</nDatas>"; std::cout << "</incomingPackets>"; std::cout << "<outgoingPackets>"; std::cout << "<nInterests>" << faceStatus.getNOutInterests() << "</nInterests>"; std::cout << "<nDatas>" << faceStatus.getNOutDatas() << "</nDatas>"; std::cout << "</outgoingPackets>"; std::cout << "</packetCounters>"; std::cout << "<byteCounters>"; std::cout << "<incomingBytes>" << faceStatus.getNInBytes() << "</incomingBytes>"; std::cout << "<outgoingBytes>" << faceStatus.getNOutBytes() << "</outgoingBytes>"; std::cout << "</byteCounters>"; if (faceStatus.getFlags() != 0) { std::cout << "<flags>"; if (faceStatus.isLocal()) { std::cout << "<local/>"; } if (faceStatus.isOnDemand()) { std::cout << "<on-demand/>"; } std::cout << "</flags>"; } std::cout << "</face>"; } std::cout << "</faces>"; } else { std::cout << "Faces:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl; break; } offset += block.size(); nfd::FaceStatus faceStatus(block); std::cout << " faceid=" << faceStatus.getFaceId() << " remote=" << faceStatus.getRemoteUri() << " local=" << faceStatus.getLocalUri(); if (faceStatus.hasExpirationPeriod()) { std::cout << " expires=" << time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod()) .count() << "s"; } std::cout << " counters={" << "in={" << faceStatus.getNInInterests() << "i " << faceStatus.getNInDatas() << "d " << faceStatus.getNInBytes() << "B}" << " out={" << faceStatus.getNOutInterests() << "i " << faceStatus.getNOutDatas() << "d " << faceStatus.getNOutBytes() << "B}" << "}"; if (faceStatus.isLocal()) std::cout << " local"; if (faceStatus.isOnDemand()) std::cout << " on-demand"; std::cout << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchFibEnumerationInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/fib/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedFibEnumerationInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedFibEnumerationInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<fib>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FibEntry TLV"; break; } offset += block.size(); nfd::FibEntry fibEntry(block); std::cout << "<fibEntry>"; std::string prefix(fibEntry.getPrefix().toUri()); escapeSpecialCharacters(&prefix); std::cout << "<prefix>" << prefix << "</prefix>"; std::cout << "<nextHops>"; for (std::list<nfd::NextHopRecord>::const_iterator nextHop = fibEntry.getNextHopRecords().begin(); nextHop != fibEntry.getNextHopRecords().end(); ++nextHop) { std::cout << "<nextHop>" ; std::cout << "<faceId>" << nextHop->getFaceId() << "</faceId>"; std::cout << "<cost>" << nextHop->getCost() << "</cost>"; std::cout << "</nextHop>"; } std::cout << "</nextHops>"; std::cout << "</fibEntry>"; } std::cout << "</fib>"; } else { std::cout << "FIB:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FibEntry TLV" << std::endl; break; } offset += block.size(); nfd::FibEntry fibEntry(block); std::cout << " " << fibEntry.getPrefix() << " nexthops={"; for (std::list<nfd::NextHopRecord>::const_iterator nextHop = fibEntry.getNextHopRecords().begin(); nextHop != fibEntry.getNextHopRecords().end(); ++nextHop) { if (nextHop != fibEntry.getNextHopRecords().begin()) std::cout << ", "; std::cout << "faceid=" << nextHop->getFaceId() << " (cost=" << nextHop->getCost() << ")"; } std::cout << "}" << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchStrategyChoiceInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/strategy-choice/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedStrategyChoiceInformationInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedStrategyChoiceInformationInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<strategyChoices>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode StrategyChoice TLV"; break; } offset += block.size(); nfd::StrategyChoice strategyChoice(block); std::cout << "<strategyChoice>"; std::string name(strategyChoice.getName().toUri()); escapeSpecialCharacters(&name); std::cout << "<namespace>" << name << "</namespace>"; std::cout << "<strategy>"; std::string strategy(strategyChoice.getStrategy().toUri()); escapeSpecialCharacters(&strategy); std::cout << "<name>" << strategy << "</name>"; std::cout << "</strategy>"; std::cout << "</strategyChoice>"; } std::cout << "</strategyChoices>"; } else { std::cout << "Strategy choices:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode StrategyChoice TLV" << std::endl; break; } offset += block.size(); nfd::StrategyChoice strategyChoice(block); std::cout << " " << strategyChoice.getName() << " strategy=" << strategyChoice.getStrategy() << std::endl; } } runNextStep(); } void fetchRibStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/rib/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedRibStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedRibStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<rib>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode RibEntry TLV"; break; } offset += block.size(); nfd::RibEntry ribEntry(block); std::cout << "<ribEntry>"; std::string prefix(ribEntry.getName().toUri()); escapeSpecialCharacters(&prefix); std::cout << "<prefix>" << prefix << "</prefix>"; std::cout << "<routes>"; for (std::list<nfd::Route>::const_iterator nextRoute = ribEntry.begin(); nextRoute != ribEntry.end(); ++nextRoute) { std::cout << "<route>" ; std::cout << "<faceId>" << nextRoute->getFaceId() << "</faceId>"; std::cout << "<origin>" << nextRoute->getOrigin() << "</origin>"; std::cout << "<cost>" << nextRoute->getCost() << "</cost>"; std::cout << "<flags>"; if (nextRoute->isChildInherit()) std::cout << "<childInherit/>"; if (nextRoute->isRibCapture()) std::cout << "<ribCapture/>"; std::cout << "</flags>"; if (!nextRoute->hasInfiniteExpirationPeriod()) { std::cout << "<expirationPeriod>PT" << time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod()) .count() << "S" << "</expirationPeriod>"; } std::cout << "</route>"; } std::cout << "</routes>"; std::cout << "</ribEntry>"; } std::cout << "</rib>"; } else { std::cout << "Rib:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode RibEntry TLV" << std::endl; break; } offset += block.size(); nfd::RibEntry ribEntry(block); std::cout << " " << ribEntry.getName().toUri() << " route={"; for (std::list<nfd::Route>::const_iterator nextRoute = ribEntry.begin(); nextRoute != ribEntry.end(); ++nextRoute) { if (nextRoute != ribEntry.begin()) std::cout << ", "; std::cout << "faceid=" << nextRoute->getFaceId() << " (origin=" << nextRoute->getOrigin() << " cost=" << nextRoute->getCost(); if (!nextRoute->hasInfiniteExpirationPeriod()) { std::cout << " expires=" << time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod()) .count() << "s"; } if (nextRoute->isChildInherit()) std::cout << " ChildInherit"; if (nextRoute->isRibCapture()) std::cout << " RibCapture"; std::cout << ")"; } std::cout << "}" << std::endl; } } runNextStep(); } void fetchInformation() { if (m_isOutputXml || (!m_needVersionRetrieval && !m_needChannelStatusRetrieval && !m_needFaceStatusRetrieval && !m_needFibEnumerationRetrieval && !m_needRibStatusRetrieval && !m_needStrategyChoiceRetrieval)) { enableVersionRetrieval(); enableChannelStatusRetrieval(); enableFaceStatusRetrieval(); enableFibEnumerationRetrieval(); enableRibStatusRetrieval(); enableStrategyChoiceRetrieval(); } if (m_isOutputXml) m_fetchSteps.push_back(bind(&NfdStatus::printXmlHeader, this)); if (m_needVersionRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchVersionInformation, this)); if (m_needChannelStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchChannelStatusInformation, this)); if (m_needFaceStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchFaceStatusInformation, this)); if (m_needFibEnumerationRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchFibEnumerationInformation, this)); if (m_needRibStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchRibStatusInformation, this)); if (m_needStrategyChoiceRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchStrategyChoiceInformation, this)); if (m_isOutputXml) m_fetchSteps.push_back(bind(&NfdStatus::printXmlFooter, this)); runNextStep(); m_face.processEvents(); } private: void printXmlHeader() { std::cout << "<?xml version=\"1.0\"?>"; std::cout << "<nfdStatus xmlns=\"ndn:/localhost/nfd/status/1\">"; runNextStep(); } void printXmlFooter() { std::cout << "</nfdStatus>"; runNextStep(); } void runNextStep() { if (m_fetchSteps.empty()) return; function<void()> nextStep = m_fetchSteps.front(); m_fetchSteps.pop_front(); nextStep(); } private: std::string m_toolName; bool m_needVersionRetrieval; bool m_needChannelStatusRetrieval; bool m_needFaceStatusRetrieval; bool m_needFibEnumerationRetrieval; bool m_needRibStatusRetrieval; bool m_needStrategyChoiceRetrieval; bool m_isOutputXml; Face m_face; shared_ptr<OBufferStream> m_buffer; std::deque<function<void()> > m_fetchSteps; }; } int main(int argc, char* argv[]) { int option; ndn::NfdStatus nfdStatus(argv[0]); while ((option = getopt(argc, argv, "hvcfbrsxV")) != -1) { switch (option) { case 'h': nfdStatus.usage(); return 0; case 'v': nfdStatus.enableVersionRetrieval(); break; case 'c': nfdStatus.enableChannelStatusRetrieval(); break; case 'f': nfdStatus.enableFaceStatusRetrieval(); break; case 'b': nfdStatus.enableFibEnumerationRetrieval(); break; case 'r': nfdStatus.enableRibStatusRetrieval(); break; case 's': nfdStatus.enableStrategyChoiceRetrieval(); break; case 'x': nfdStatus.enableXmlOutput(); break; case 'V': std::cout << NFD_VERSION_BUILD_STRING << std::endl; return 0; default: nfdStatus.usage(); return 1; } } try { nfdStatus.fetchInformation(); } catch (std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; return 2; } return 0; }
gpl-3.0
j-r0dd/RetroPie-Setup
scriptmodules/ports/minecraft.sh
1059
#!/usr/bin/env bash # This file is part of The RetroPie Project # # The RetroPie Project is the legal property of its developers, whose names are # too numerous to list here. Please refer to the COPYRIGHT.md file distributed with this source. # # See the LICENSE.md file at the top-level directory of this distribution and # at https://raw.githubusercontent.com/RetroPie/RetroPie-Setup/master/LICENSE.md # rp_module_id="minecraft" rp_module_desc="Minecraft - Pi Edition" rp_module_section="exp" rp_module_flags="!mali !x86" function depends_minecraft() { getDepends xorg matchbox } function install_bin_minecraft() { [[ -f "$md_inst/minecraft-pi" ]] && rm -rf "$md_inst/"* aptInstall minecraft-pi } function remove_minecraft() { aptRemove minecraft-pi } function configure_minecraft() { addPort "$md_id" "minecraft" "Minecraft" "xinit $md_inst/Minecraft.sh" cat >"$md_inst/Minecraft.sh" << _EOF_ #!/bin/bash xset -dpms s off s noblank matchbox-window-manager & /usr/bin/minecraft-pi _EOF_ chmod +x "$md_inst/Minecraft.sh" }
gpl-3.0
dymkowsk/mantid
Framework/SINQ/src/PoldiFitPeaks1D.cpp
7337
#include "MantidAPI/WorkspaceProperty.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/WorkspaceGroup.h" #include "MantidSINQ/PoldiFitPeaks1D.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidDataObjects/TableWorkspace.h" #include "MantidAPI/FunctionFactory.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" #include "MantidAPI/TableRow.h" #include "MantidSINQ/PoldiUtilities/UncertainValue.h" #include "MantidSINQ/PoldiUtilities/UncertainValueIO.h" #include "MantidAPI/CompositeFunction.h" namespace Mantid { namespace Poldi { using namespace Kernel; using namespace API; using namespace DataObjects; using namespace CurveFitting; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(PoldiFitPeaks1D) /// Algorithm's name for identification. @see Algorithm::name const std::string PoldiFitPeaks1D::name() const { return "PoldiFitPeaks1D"; } /// Algorithm's version for identification. @see Algorithm::version int PoldiFitPeaks1D::version() const { return 1; } /// Algorithm's category for identification. @see Algorithm::category const std::string PoldiFitPeaks1D::category() const { return "SINQ\\Poldi"; } void PoldiFitPeaks1D::init() { declareProperty( make_unique<WorkspaceProperty<Workspace2D>>("InputWorkspace", "", Direction::Input), "An input workspace containing a POLDI auto-correlation spectrum."); boost::shared_ptr<BoundedValidator<double>> minFwhmPerDirection = boost::make_shared<BoundedValidator<double>>(); minFwhmPerDirection->setLower(2.0); declareProperty( "FwhmMultiples", 2.0, minFwhmPerDirection, "Each peak will be fitted using x times FWHM data in each direction.", Direction::Input); std::vector<std::string> peakFunctions = FunctionFactory::Instance().getFunctionNames<IPeakFunction>(); auto peakFunctionNames = boost::make_shared<ListValidator<std::string>>(peakFunctions); declareProperty("PeakFunction", "Gaussian", peakFunctionNames, "Peak function that will be fitted to all peaks.", Direction::Input); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "PoldiPeakTable", "", Direction::Input), "A table workspace containing POLDI peak data."); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "OutputWorkspace", "RefinedPeakTable", Direction::Output), "Output workspace with refined peak data."); declareProperty(make_unique<WorkspaceProperty<Workspace>>( "FitPlotsWorkspace", "FitPlots", Direction::Output), "Plots of all peak fits."); m_backgroundTemplate = FunctionFactory::Instance().createInitialized( "name=UserFunction, Formula=A0 + A1*(x - x0)^2"); m_profileTies = "f1.x0 = f0.PeakCentre"; } void PoldiFitPeaks1D::setPeakFunction(const std::string &peakFunction) { m_profileTemplate = peakFunction; } PoldiPeakCollection_sptr PoldiFitPeaks1D::getInitializedPeakCollection( const DataObjects::TableWorkspace_sptr &peakTable) const { auto peakCollection = boost::make_shared<PoldiPeakCollection>(peakTable); peakCollection->setProfileFunctionName(m_profileTemplate); return peakCollection; } IFunction_sptr PoldiFitPeaks1D::getPeakProfile(const PoldiPeak_sptr &poldiPeak) const { IPeakFunction_sptr clonedProfile = boost::dynamic_pointer_cast<IPeakFunction>( FunctionFactory::Instance().createFunction(m_profileTemplate)); clonedProfile->setCentre(poldiPeak->q()); clonedProfile->setFwhm(poldiPeak->fwhm(PoldiPeak::AbsoluteQ)); clonedProfile->setHeight(poldiPeak->intensity()); IFunction_sptr clonedBackground = m_backgroundTemplate->clone(); auto totalProfile = boost::make_shared<CompositeFunction>(); totalProfile->initialize(); totalProfile->addFunction(clonedProfile); totalProfile->addFunction(clonedBackground); if (!m_profileTies.empty()) { totalProfile->addTies(m_profileTies); } return totalProfile; } void PoldiFitPeaks1D::setValuesFromProfileFunction( PoldiPeak_sptr poldiPeak, const IFunction_sptr &fittedFunction) const { CompositeFunction_sptr totalFunction = boost::dynamic_pointer_cast<CompositeFunction>(fittedFunction); if (totalFunction) { IPeakFunction_sptr peakFunction = boost::dynamic_pointer_cast<IPeakFunction>( totalFunction->getFunction(0)); if (peakFunction) { poldiPeak->setIntensity( UncertainValue(peakFunction->height(), peakFunction->getError(0))); poldiPeak->setQ( UncertainValue(peakFunction->centre(), peakFunction->getError(1))); poldiPeak->setFwhm(UncertainValue(peakFunction->fwhm(), getFwhmWidthRelation(peakFunction) * peakFunction->getError(2))); } } } double PoldiFitPeaks1D::getFwhmWidthRelation(IPeakFunction_sptr peakFunction) const { return peakFunction->fwhm() / peakFunction->getParameter(2); } void PoldiFitPeaks1D::exec() { setPeakFunction(getProperty("PeakFunction")); // Number of points around the peak center to use for the fit m_fwhmMultiples = getProperty("FwhmMultiples"); // try to construct PoldiPeakCollection from provided TableWorkspace TableWorkspace_sptr poldiPeakTable = getProperty("PoldiPeakTable"); m_peaks = getInitializedPeakCollection(poldiPeakTable); g_log.information() << "Peaks to fit: " << m_peaks->peakCount() << '\n'; Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace"); auto fitPlotGroup = boost::make_shared<WorkspaceGroup>(); for (size_t i = 0; i < m_peaks->peakCount(); ++i) { PoldiPeak_sptr currentPeak = m_peaks->peak(i); IFunction_sptr currentProfile = getPeakProfile(currentPeak); IAlgorithm_sptr fit = getFitAlgorithm(dataWorkspace, currentPeak, currentProfile); bool fitSuccess = fit->execute(); if (fitSuccess) { setValuesFromProfileFunction(currentPeak, fit->getProperty("Function")); MatrixWorkspace_sptr fpg = fit->getProperty("OutputWorkspace"); fitPlotGroup->addWorkspace(fpg); } } setProperty("OutputWorkspace", m_peaks->asTableWorkspace()); setProperty("FitPlotsWorkspace", fitPlotGroup); } IAlgorithm_sptr PoldiFitPeaks1D::getFitAlgorithm(const Workspace2D_sptr &dataWorkspace, const PoldiPeak_sptr &peak, const IFunction_sptr &profile) { double width = peak->fwhm(); double extent = std::min(0.05, std::max(0.002, width)) * m_fwhmMultiples; std::pair<double, double> xBorders(peak->q() - extent, peak->q() + extent); IAlgorithm_sptr fitAlgorithm = createChildAlgorithm("Fit", -1, -1, false); fitAlgorithm->setProperty("CreateOutput", true); fitAlgorithm->setProperty("Output", "FitPeaks1D"); fitAlgorithm->setProperty("CalcErrors", true); fitAlgorithm->setProperty("Function", profile); fitAlgorithm->setProperty("InputWorkspace", dataWorkspace); fitAlgorithm->setProperty("WorkspaceIndex", 0); fitAlgorithm->setProperty("StartX", xBorders.first); fitAlgorithm->setProperty("EndX", xBorders.second); return fitAlgorithm; } } // namespace Poldi } // namespace Mantid
gpl-3.0
NathanAhlstrom/CORAL
usage/old/admin/classes/domain/ExternalLogin.php
1138
<?php /* ************************************************************************************************************************** ** CORAL Organizations Module v. 1.0 ** ** Copyright (c) 2010 University of Notre Dame ** ** This file is part of CORAL. ** ** CORAL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ** ** CORAL 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 CORAL. If not, see <http://www.gnu.org/licenses/>. ** ************************************************************************************************************************** */ class ExternalLogin extends DatabaseObject { protected function defineRelationships() {} protected function overridePrimaryKeyName() {} } ?>
gpl-3.0
maxwward/SCOPEBak
askbot/templates/question/answer_controls.html
2748
{#<span class="action-link swap-qa"> <a id="swap-question-with-answer-{{answer.id}}">{% trans %}swap with question{% endtrans %}</a> </span>uncomment if needed#} <span class="action-link"> <a class="permant-link" href="{{ answer.get_absolute_url(question_post=question) }}" title="{% trans %}permanent link{% endtrans %}"> {% trans %}link{% endtrans %} </a> </span> <span id="post-{{answer.id}}-publish" class="action-link" > {% if answer.id in published_answer_ids %} <a class="answer-unpublish" data-answer-id="{{ answer.id }}" >{% trans %}unpublish{% endtrans %}</a> {% else %} <a class="answer-publish" data-answer-id="{{ answer.id}}" >{% trans %}publish{% endtrans %}</a> {% endif %} </span> <span id='post-{{answer.id}}-delete' class="action-link delete-post"> <a class="question-delete" >{% if answer.deleted %}{% trans %}undelete{% endtrans %}{% else %}{% trans %}delete{% endtrans %}{% endif %}</a> </span> {% if answer.offensive_flag_count > 0 %} <span id="answer-offensive-remove-flag-{{ answer.id }}" class="action-link offensive-flag" title="{% trans %}remove offensive flag{% endtrans %}" > <a class="question-flag">{% trans %}remove flag{% endtrans %}</a> </span> <span id="answer-offensive-flag-{{ answer.id }}" class="action-link offensive-flag" title="{% trans %}report as offensive (i.e containing spam, advertising, malicious text, etc.){% endtrans %}" > <a class="question-flag">{% trans %}flag offensive{% endtrans %} ({{ answer.offensive_flag_count }})</a> </span> {% else %} <span id="answer-offensive-flag-{{ answer.id }}" class="action-link offensive-flag" title="{% trans %}report as offensive (i.e containing spam, advertising, malicious text, etc.){% endtrans %}" > <a class="question-flag">{% trans %}flag offensive{% endtrans %}</a> </span> {% endif %} <span id='post-{{answer.id}}-edit' class="action-link"> <a class="question-edit" href="{% url edit_answer answer.id %}">{% trans %}edit{% endtrans %}</a> </span> <span id='post-{{answer.id}}-convert' class="action-link"> <form class="answer-convert" action="{% url answer_to_comment %}" method="POST"> {% csrf_token %} <input type="hidden" name="answer_id" id="id_answer_id" value="{{answer.id}}"/> <input type="submit" name="" value="{% trans %}convert to comment{% endtrans %}"/> </form> </span> <script type="text/javascript"> askbot['functions']['hideConvertAnswerLinks']('{{ answer.id }}'); askbot['functions']['hidePublishAnswerLink']('{{ answer.id }}'); askbot['functions']['renderPostControls']('{{ answer.id }}'); </script>
gpl-3.0
saophaisau/port
Core/SDK Ports/ChallengerSeriesAIO/Plugins/Teemo.cs
12392
using System; using System.Collections.Generic; using System.Linq; using Challenger_Series.Utils; using LeagueSharp; using LeagueSharp.SDK; using SharpDX; using Color = System.Drawing.Color; using Challenger_Series.Utils; using System.Windows.Forms; using LeagueSharp.Data.Enumerations; using LeagueSharp.SDK.Enumerations; using LeagueSharp.SDK.UI; using LeagueSharp.SDK.Utils; using Menu = LeagueSharp.SDK.UI.Menu; using EloBuddy; using LeagueSharp.SDK; namespace Challenger_Series.Plugins { public class Teemo : CSPlugin { public Teemo() { Q = new Spell(SpellSlot.Q, 680); W = new Spell(SpellSlot.W); E = new Spell(SpellSlot.E); R = new Spell(SpellSlot.R, 300); Q.SetTargetted(0.5f, 1500f); R.SetSkillshot(0.5f, 120f, 1000f, false, SkillshotType.SkillshotCircle); InitMenu(); Orbwalker.OnAction += OnAction; DelayedOnUpdate += OnUpdate; Drawing.OnDraw += OnDraw; Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast; Events.OnGapCloser += OnGapCloser; Events.OnInterruptableTarget += OnInterruptableTarget; } public override void OnUpdate(EventArgs args) { if (Q.IsReady()) this.QLogic(); if (W.IsReady()) this.WLogic(); if (R.IsReady()) this.RLogic(); } private void OnGapCloser(object oSender, Events.GapCloserEventArgs args) { /*var sender = args.Sender; if (UseEAntiGapclose) { if (args.IsDirectedToPlayer && args.Sender.Distance(ObjectManager.Player) < 750) { if (E.IsReady()) { E.Cast(sender.ServerPosition); } } }*/ } private void OnInterruptableTarget(object oSender, Events.InterruptableTargetEventArgs args) { /*var sender = args.Sender; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(sender.ServerPosition) < 100) && ObjectManager.Player.Distance(sender) < 550) { W.Cast(sender.ServerPosition); }*/ } private void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { base.OnProcessSpellCast(sender, args); /*if (sender is AIHeroClient && sender.IsEnemy) { if (args.SData.Name == "summonerflash" && args.End.Distance(ObjectManager.Player.ServerPosition) < 650) { var pred = Prediction.GetPrediction((AIHeroClient)args.Target, E); if (!pred.Item3.Any(o => o.IsMinion && !o.IsDead && !o.IsAlly)) { E.Cast(args.End); } } }*/ } public override void OnDraw(EventArgs args) { var drawRange = DrawRange.Value; if (drawRange > 0) { Render.Circle.DrawCircle(ObjectManager.Player.Position, drawRange, Color.Gold); } } private void OnAction(object sender, OrbwalkingActionArgs orbwalkingActionArgs) { if (orbwalkingActionArgs.Type == OrbwalkingType.BeforeAttack) { /*if (orbwalkingActionArgs.Target is Obj_AI_Minion && HasPassive && FocusOnHeadShotting && Orbwalker.ActiveMode == OrbwalkingMode.LaneClear) { var target = orbwalkingActionArgs.Target as Obj_AI_Minion; if (target != null && !target.CharData.BaseSkinName.Contains("MinionSiege") && target.Health > 60) { var tg = (AIHeroClient)TargetSelector.GetTarget(715, DamageType.Physical); if (tg != null && tg.IsHPBarRendered) { Orbwalker.ForceTarget = tg; orbwalkingActionArgs.Process = false; } } }*/ } if (orbwalkingActionArgs.Type == OrbwalkingType.AfterAttack) { Orbwalker.ForceTarget = null; if (E.IsReady() && this.UseECombo) { if (!OnlyUseEOnMelees) { var eTarget = TargetSelector.GetTarget(UseEOnEnemiesCloserThanSlider.Value, DamageType.Physical); if (eTarget != null) { var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 >= (int)HitChance.High) { E.Cast(pred.Item2); } } } else { var eTarget = ValidTargets.FirstOrDefault( e => e.IsMelee && e.Distance(ObjectManager.Player) < UseEOnEnemiesCloserThanSlider.Value && !e.IsZombie); var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 > (int)HitChance.Medium) { E.Cast(pred.Item2); } } } } } private Menu ComboMenu; private MenuBool UseQCombo; private MenuBool UseWChase; private MenuBool UseECombo; private MenuKeyBind UseRCombo; private MenuBool AlwaysQAfterE; private MenuBool FocusOnHeadShotting; private MenuList<string> QHarassMode; private MenuBool UseWInterrupt; private Menu AutoRConfig; private MenuSlider UseEOnEnemiesCloserThanSlider; private MenuBool OnlyUseEOnMelees; private MenuBool UseEAntiGapclose; private MenuSlider DrawRange; public void InitMenu() { ComboMenu = MainMenu.Add(new Menu("teemocombomenu", "Combo Settings: ")); UseQCombo = ComboMenu.Add(new MenuBool("teemoqcombo", "Use Q", true)); UseWChase = ComboMenu.Add(new MenuBool("usewchase", "Use W when chasing")); UseECombo = ComboMenu.Add(new MenuBool("teemorcombo", "Use R", true)); AutoRConfig = MainMenu.Add(new Menu("teemoautor", "R Settings: ")); new Utils.Logic.PositionSaver(AutoRConfig, R); MainMenu.Attach(); } #region Logic void QLogic() { if (Orbwalker.ActiveMode == OrbwalkingMode.Combo) { if (UseQCombo && Q.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(800) == 0 && ObjectManager.Player.CountEnemyHeroesInRange(1100) > 0) { Q.CastIfWillHit(TargetSelector.GetTarget(900, DamageType.Physical), 2); var goodQTarget = ValidTargets.FirstOrDefault( t => t.Distance(ObjectManager.Player) < 950 && t.Health < Q.GetDamage(t) || SquishyTargets.Contains(t.CharData.BaseSkinName)); if (goodQTarget != null) { var pred = Prediction.GetPrediction(goodQTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { Q.Cast(pred.Item2); } } } } if (Orbwalker.ActiveMode != OrbwalkingMode.None && Orbwalker.ActiveMode != OrbwalkingMode.Combo && ObjectManager.Player.CountEnemyHeroesInRange(850) == 0) { var qHarassMode = QHarassMode.SelectedValue; if (qHarassMode != "DISABLED") { var qTarget = TargetSelector.GetTarget(1100, DamageType.Physical); if (qTarget != null) { var pred = Prediction.GetPrediction(qTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { if (qHarassMode == "ALLOWMINIONS") { Q.Cast(pred.Item2); } else if (pred.Item3.Count == 0) { Q.Cast(pred.Item2); } } } } } } void WLogic() { var goodTarget = ValidTargets.FirstOrDefault( e => !e.IsDead && e.HasBuffOfType(BuffType.Knockup) || e.HasBuffOfType(BuffType.Snare) || e.HasBuffOfType(BuffType.Stun) || e.HasBuffOfType(BuffType.Suppression) || e.IsCharmed || e.IsCastingInterruptableSpell() || !e.CanMove); if (goodTarget != null) { var pos = goodTarget.ServerPosition; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(goodTarget.ServerPosition) < 100) && pos.Distance(ObjectManager.Player.ServerPosition) < 820) { W.Cast(goodTarget.ServerPosition); } } foreach (var enemyMinion in ObjectManager.Get<Obj_AI_Base>() .Where( m => m.IsEnemy && m.ServerPosition.Distance(ObjectManager.Player.ServerPosition) < W.Range && m.HasBuff("teleport_target"))) { W.Cast(enemyMinion.ServerPosition); } foreach (var hero in GameObjects.EnemyHeroes.Where(h => h.Distance(ObjectManager.Player) < W.Range)) { var pred = Prediction.GetPrediction(hero, W); if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(pred.Item2) < 100) && (int)pred.Item1 > (int)HitChance.Medium) { W.Cast(pred.Item2); } } } void RLogic() { if (UseRCombo.Active && R.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(900) == 0) { foreach (var rTarget in ValidTargets.Where( e => SquishyTargets.Contains(e.CharData.BaseSkinName) && R.GetDamage(e) > 0.1 * e.MaxHealth || R.GetDamage(e) > e.Health)) { if (rTarget.Distance(ObjectManager.Player) > 1400) { var pred = Prediction.GetPrediction(rTarget, R); if (!pred.Item3.Any(obj => obj is AIHeroClient)) { R.CastOnUnit(rTarget); } break; } R.CastOnUnit(rTarget); } } } #endregion private bool HasPassive => ObjectManager.Player.HasBuff("caitlynheadshot"); private string[] SquishyTargets = { "Ahri", "Anivia", "Annie", "Ashe", "Azir", "Brand", "Caitlyn", "Cassiopeia", "Corki", "Draven", "Ezreal", "Graves", "Jinx", "Kalista", "Karma", "Karthus", "Katarina", "Kennen", "KogMaw", "Kindred", "Leblanc", "Lucian", "Lux", "MissFortune", "Orianna", "Quinn", "Sivir", "Syndra", "Talon", "Teemo", "Tristana", "TwistedFate", "Twitch", "Varus", "Vayne", "Veigar", "Velkoz", "Viktor", "Xerath", "Zed", "Ziggs", "Jhin", "Soraka" }; } }
gpl-3.0
ArneBinder/LanguageAnalyzer
src/main/java/ca/pfv/spmf/test/MainTestSPAM_AGP_FatBitMap_saveToMemory.java
2453
package ca.pfv.spmf.test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPAM_AGP; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.database.SequenceDatabase; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator_FatBitmap; /** * Example of how to use the algorithm SPAM, saving the results in the * main memory * * @author agomariz */ public class MainTestSPAM_AGP_FatBitMap_saveToMemory { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // Load a sequence database double support = 0.5; boolean keepPatterns = true; boolean verbose = false; // if you set the following parameter to true, the sequence ids of the sequences where // each pattern appears will be shown in the result boolean outputSequenceIdentifiers = false; AbstractionCreator abstractionCreator = AbstractionCreator_Qualitative.getInstance(); IdListCreator idListCreator = IdListCreator_FatBitmap.getInstance(); SequenceDatabase sequenceDatabase = new SequenceDatabase(abstractionCreator, idListCreator); sequenceDatabase.loadFile(fileToPath("contextPrefixSpan.txt"), support); System.out.println(sequenceDatabase.toString()); AlgoSPAM_AGP algorithm = new AlgoSPAM_AGP(support); algorithm.runAlgorithm(sequenceDatabase, keepPatterns, verbose, null,outputSequenceIdentifiers); System.out.println("Minimum support (relative) = "+support); System.out.println(algorithm.getNumberOfFrequentPatterns() + " frequent patterns."); System.out.println(algorithm.printStatistics()); } public static String fileToPath(String filename) throws UnsupportedEncodingException { URL url = MainTestSPADE_AGP_FatBitMap_saveToFile.class.getResource(filename); return java.net.URLDecoder.decode(url.getPath(), "UTF-8"); } }
gpl-3.0
guerrierk/dolibarr
htdocs/compta/bank/various_payment/document.php
3783
<?php /* Copyright (C) 2017 Alexandre Spangaro <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * or see http://www.gnu.org/ */ /** * \file htdocs/compta/bank/various_payment/document.php * \ingroup banque * \brief Page of linked files onto various_payment */ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; $langs->load("other"); $langs->load("bank"); $langs->load("companies"); $id = GETPOST('id','int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); // Security check if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'salaries', $id, ''); // Get parameters $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; $object = new PaymentVarious($db); $object->fetch($id, $ref); $upload_dir = $conf->banque->dir_output.'/'.dol_sanitizeFileName($object->id); $modulepart='banque'; /* * Actions */ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; /* * View */ $form = new Form($db); llxHeader("",$langs->trans("VariousPayment")); if ($object->id) { $head=various_payment_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans("VariousPayment"), 0, 'payment'); // Construit liste des fichiers $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); $totalsize=0; foreach($filearray as $key => $file) { $totalsize+=$file['size']; } print '<table class="border" width="100%">'; $linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/various_payment/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>'; // Ref print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td>'; print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); print '</td></tr>'; // Societe //print "<tr><td>".$langs->trans("Company")."</td><td>".$object->client->getNomUrl(1)."</td></tr>"; print '<tr><td>'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>'; print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>'; print '</table>'; print '</div>'; $modulepart = 'banque'; $permission = $user->rights->banque->modifier; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } else { print $langs->trans("ErrorUnknown"); } llxFooter(); $db->close();
gpl-3.0
P3D-Legacy/p3d-legacy
P3D/Pokemon/Items/Balls/FriendBall.vb
445
Namespace Items.Balls <Item(164, "Friend Ball")> Public Class FriendBall Inherits BallItem Public Overrides ReadOnly Property Description As String = "A Pokéball that makes caught Pokémon more friendly." Public Overrides ReadOnly Property PokeDollarPrice As Integer = 150 Public Sub New() _textureRectangle = New Rectangle(192, 144, 24, 24) End Sub End Class End Namespace
gpl-3.0
b3h3moth/L-LP
src/C/Algorithms_and_Data_Structures/algorithms/ricerca/ricerca_sequenziale/ricerca-sequenziale-2.c
1181
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STR 20 int lookup(char *word, char *array[]); int main(int argc, char *argv[]) { char str_input[MAX_STR]; char *flab[] = { "O'Reilly", "Wrox", "Elsevier", "Pearson", "Apogeo", "Sams", NULL }; printf("String: "); /* Stringa da cercare all'interno dell'array */ scanf("%s", str_input); int test = lookup(str_input, flab); if (test >= 0) puts("stringa trovata"); else puts("stringa non trovata"); return(EXIT_SUCCESS); } /* Ricerca sequenziale di parole in un array, detta anche ricerca lineare. L'algoritmo della ricerca sequenziale e' così definito perche' controlla ciascun elemento al fine di verificare la corrispondenza con l'elemento desiderato. Il tempo di esecuzione e' lineare rispetto alla dimensione dei dati, ovvero al mutare del numero dei dati mutera' anche il tempo impiegato per la ricerca. */ int lookup(char *word, char *array[]) { int i; for (i=0; array[i] != NULL; i++) if (strcmp(word, array[i]) == 0) return i; return(-1); }
gpl-3.0
cardmaster/yaddns
src/services/changeip.c
4370
/* * Yaddns - Yet Another ddns client * Copyright (C) 2008 Anthony Viallard <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "../service.h" #include "../request.h" #include "../util.h" #include "../log.h" /* * http://www.changeip.com/clients.asp */ #define DDNS_NAME "changeip" #define DDNS_HOST "nic.changeip.com" #define DDNS_PORT 80 static int ddns_write(const struct cfg_account *cfg, const char const *newwanip, struct request_buff *buff); static int ddns_read(struct request_buff *buff, struct rc_report *report); struct service changeip_service = { .name = DDNS_NAME, .ipserv = DDNS_HOST, .portserv = DDNS_PORT, .make_query = ddns_write, .read_resp = ddns_read }; static int ddns_write(const struct cfg_account *cfg, const char const *newwanip, struct request_buff *buff) { char buf[256]; char *b64_loginpass = NULL; size_t b64_loginpass_size; int n; /* make the update packet */ snprintf(buf, sizeof(buf), "%s:%s", cfgstr_get(&(cfg->username)), cfgstr_get(&(cfg->passwd))); if (util_base64_encode(buf, &b64_loginpass, &b64_loginpass_size) != 0) { /* publish_error_status ?? */ log_error("Unable to encode in base64"); return -1; } n = snprintf(buff->data, sizeof(buff->data), "GET /nic/update?hostname=%s" "&myip=%s" " HTTP/1.0\r\n" "Host: " DDNS_HOST "\r\n" "Authorization: Basic %s\r\n" "User-Agent: " PACKAGE "/" VERSION "\r\n" "Connection: close\r\n" "Pragma: no-cache\r\n\r\n", cfgstr_get(&(cfg->hostname)), newwanip, b64_loginpass); if(n < 0) { log_error("Unable to write data buffer"); return -1; } buff->data_size = (size_t)n; free(b64_loginpass); return 0; } static int ddns_read(struct request_buff *buff, struct rc_report *report) { if(strstr(buff->data, "200 Successful Update")) { report->code = up_success; snprintf(report->proprio_return, sizeof(report->proprio_return), "good"); snprintf(report->proprio_return_info, sizeof(report->proprio_return_info), "Update good and successful, IP updated."); } else if(strstr(buff->data, "401 Access Denied") || strstr(buff->data, "401 Unauthorized")) { report->code = up_account_error; snprintf(report->proprio_return, sizeof(report->proprio_return), "badauth"); snprintf(report->proprio_return_info, sizeof(report->proprio_return_info), "Bad authorization (username or password)."); } else { log_error("Unknown return message received."); report->code = up_unknown_error; snprintf(report->proprio_return, sizeof(report->proprio_return), "unknown"); snprintf(report->proprio_return_info, sizeof(report->proprio_return_info), "Unknown return message received"); } return 0; }
gpl-3.0
karolusw/l2j
game/data/scripts/quests/Q00126_TheNameOfEvil2/32122-3b.html
459
<html><body>Warrior's Grave:<br> The Sirens possess more than simply physical powers; they also possess psychic abilities. In the past, they could impose their wills on others, forcing them to do their bidding. Without Shilen and her mighty Elrokian warriors, this island is doomed...unless you can prevent it.<br> Hear my words!<br> <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h Quest Q00126_TheNameOfEvil2 32122-3a.html">Listen.</Button> </body></html>
gpl-3.0
jayuqar/moodle
user/tests/userlib_test.php
41890
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Unit tests for user/lib.php. * * @package core_user * @category phpunit * @copyright 2013 Rajesh Taneja <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->dirroot.'/user/lib.php'); /** * Unit tests for user lib api. * * @package core_user * @category phpunit * @copyright 2013 Rajesh Taneja <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class core_userliblib_testcase extends advanced_testcase { /** * Test user_get_user_details_courses */ public function test_user_get_user_details_courses() { global $DB; $this->resetAfterTest(); // Create user and modify user profile. $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $course1 = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course1->id); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $this->getDataGenerator()->enrol_user($user1->id, $course1->id); $this->getDataGenerator()->enrol_user($user2->id, $course1->id); role_assign($teacherrole->id, $user1->id, $coursecontext->id); role_assign($teacherrole->id, $user2->id, $coursecontext->id); accesslib_clear_all_caches_for_unit_testing(); // Get user2 details as a user with super system capabilities. $result = user_get_user_details_courses($user2); $this->assertEquals($user2->id, $result['id']); $this->assertEquals(fullname($user2), $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); $this->setUser($user1); // Get user2 details as a user who can only see this user in a course. $result = user_get_user_details_courses($user2); $this->assertEquals($user2->id, $result['id']); $this->assertEquals(fullname($user2), $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); } /** * Test user_update_user. */ public function test_user_update_user() { global $DB; $this->resetAfterTest(); // Create user and modify user profile. $user = $this->getDataGenerator()->create_user(); $user->firstname = 'Test'; $user->password = 'M00dLe@T'; // Update user and capture event. $sink = $this->redirectEvents(); user_update_user($user); $events = $sink->get_events(); $sink->close(); $event = array_pop($events); // Test updated value. $dbuser = $DB->get_record('user', array('id' => $user->id)); $this->assertSame($user->firstname, $dbuser->firstname); $this->assertNotSame('M00dLe@T', $dbuser->password); // Test event. $this->assertInstanceOf('\core\event\user_updated', $event); $this->assertSame($user->id, $event->objectid); $this->assertSame('user_updated', $event->get_legacy_eventname()); $this->assertEventLegacyData($dbuser, $event); $this->assertEquals(context_user::instance($user->id), $event->get_context()); $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, ''); $this->assertEventLegacyLogData($expectedlogdata, $event); // Update user with no password update. $password = $user->password = hash_internal_user_password('M00dLe@T'); user_update_user($user, false); $dbuser = $DB->get_record('user', array('id' => $user->id)); $this->assertSame($password, $dbuser->password); // Verify event is not triggred by user_update_user when needed. $sink = $this->redirectEvents(); user_update_user($user, false, false); $events = $sink->get_events(); $sink->close(); $this->assertCount(0, $events); // With password, there should be 1 event. $sink = $this->redirectEvents(); user_update_user($user, true, false); $events = $sink->get_events(); $sink->close(); $this->assertCount(1, $events); $event = array_pop($events); $this->assertInstanceOf('\core\event\user_password_updated', $event); // Test user data validation. $user->username = 'johndoe123'; $user->auth = 'shibolth'; $user->country = 'WW'; $user->lang = 'xy'; $user->theme = 'somewrongthemename'; $user->timezone = '30.5'; $user->url = 'wwww.somewrong@#$url.com.aus'; $debugmessages = $this->getDebuggingMessages(); user_update_user($user, true, false); $this->assertDebuggingCalledCount(6, $debugmessages); // Now, with valid user data. $user->username = 'johndoe321'; $user->auth = 'shibboleth'; $user->country = 'AU'; $user->lang = 'en'; $user->theme = 'clean'; $user->timezone = 'Australia/Perth'; $user->url = 'www.moodle.org'; user_update_user($user, true, false); $this->assertDebuggingNotCalled(); } /** * Test create_users. */ public function test_create_users() { global $DB; $this->resetAfterTest(); $user = array( 'username' => 'usernametest1', 'password' => 'Moodle2012!', 'idnumber' => 'idnumbertest1', 'firstname' => 'First Name User Test 1', 'lastname' => 'Last Name User Test 1', 'middlename' => 'Middle Name User Test 1', 'lastnamephonetic' => '最後のお名前のテスト一号', 'firstnamephonetic' => 'お名前のテスト一号', 'alternatename' => 'Alternate Name User Test 1', 'email' => '[email protected]', 'description' => 'This is a description for user 1', 'city' => 'Perth', 'country' => 'AU' ); // Create user and capture event. $sink = $this->redirectEvents(); $user['id'] = user_create_user($user); $events = $sink->get_events(); $sink->close(); $event = array_pop($events); // Test user info in DB. $dbuser = $DB->get_record('user', array('id' => $user['id'])); $this->assertEquals($dbuser->username, $user['username']); $this->assertEquals($dbuser->idnumber, $user['idnumber']); $this->assertEquals($dbuser->firstname, $user['firstname']); $this->assertEquals($dbuser->lastname, $user['lastname']); $this->assertEquals($dbuser->email, $user['email']); $this->assertEquals($dbuser->description, $user['description']); $this->assertEquals($dbuser->city, $user['city']); $this->assertEquals($dbuser->country, $user['country']); // Test event. $this->assertInstanceOf('\core\event\user_created', $event); $this->assertEquals($user['id'], $event->objectid); $this->assertEquals('user_created', $event->get_legacy_eventname()); $this->assertEquals(context_user::instance($user['id']), $event->get_context()); $this->assertEventLegacyData($dbuser, $event); $expectedlogdata = array(SITEID, 'user', 'add', '/view.php?id='.$event->objectid, fullname($dbuser)); $this->assertEventLegacyLogData($expectedlogdata, $event); // Verify event is not triggred by user_create_user when needed. $user = array('username' => 'usernametest2'); // Create another user. $sink = $this->redirectEvents(); user_create_user($user, true, false); $events = $sink->get_events(); $sink->close(); $this->assertCount(0, $events); // Test user data validation, first some invalid data. $user['username'] = 'johndoe123'; $user['auth'] = 'shibolth'; $user['country'] = 'WW'; $user['lang'] = 'xy'; $user['theme'] = 'somewrongthemename'; $user['timezone'] = '-30.5'; $user['url'] = 'wwww.somewrong@#$url.com.aus'; $debugmessages = $this->getDebuggingMessages(); $user['id'] = user_create_user($user, true, false); $this->assertDebuggingCalledCount(6, $debugmessages); $dbuser = $DB->get_record('user', array('id' => $user['id'])); $this->assertEquals($dbuser->country, 0); $this->assertEquals($dbuser->lang, 'en'); $this->assertEquals($dbuser->timezone, ''); // Now, with valid user data. $user['username'] = 'johndoe321'; $user['auth'] = 'shibboleth'; $user['country'] = 'AU'; $user['lang'] = 'en'; $user['theme'] = 'clean'; $user['timezone'] = 'Australia/Perth'; $user['url'] = 'www.moodle.org'; user_create_user($user, true, false); $this->assertDebuggingNotCalled(); } /** * Test function user_count_login_failures(). */ public function test_user_count_login_failures() { $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user)); for ($i = 0; $i < 10; $i++) { login_attempt_failed($user); } $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user)); $count = user_count_login_failures($user); // Reset count. $this->assertEquals(10, $count); $this->assertEquals(0, get_user_preferences('login_failed_count_since_success', 0, $user)); for ($i = 0; $i < 10; $i++) { login_attempt_failed($user); } $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user)); $count = user_count_login_failures($user, false); // Do not reset count. $this->assertEquals(10, $count); $this->assertEquals(10, get_user_preferences('login_failed_count_since_success', 0, $user)); } /** * Test function user_add_password_history(). */ public function test_user_add_password_history() { global $DB; $this->resetAfterTest(); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); $DB->delete_records('user_password_history', array()); set_config('passwordreuselimit', 0); user_add_password_history($user1->id, 'pokus'); $this->assertEquals(0, $DB->count_records('user_password_history')); // Test adding and discarding of old. set_config('passwordreuselimit', 3); user_add_password_history($user1->id, 'pokus'); $this->assertEquals(1, $DB->count_records('user_password_history')); $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id))); user_add_password_history($user1->id, 'pokus2'); user_add_password_history($user1->id, 'pokus3'); user_add_password_history($user1->id, 'pokus4'); $this->assertEquals(3, $DB->count_records('user_password_history')); $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id))); user_add_password_history($user2->id, 'pokus1'); $this->assertEquals(4, $DB->count_records('user_password_history')); $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user1->id))); $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user2->id))); user_add_password_history($user2->id, 'pokus2'); user_add_password_history($user2->id, 'pokus3'); $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id))); $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); user_add_password_history($user2->id, 'pokus4'); $this->assertEquals(3, $DB->count_records('user_password_history', array('userid' => $user2->id))); $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); $removed = array_shift($ids); $added = array_pop($newids); $this->assertSame($ids, $newids); $this->assertGreaterThan($removed, $added); // Test disabling prevents changes. set_config('passwordreuselimit', 0); $this->assertEquals(6, $DB->count_records('user_password_history')); $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); user_add_password_history($user2->id, 'pokus5'); user_add_password_history($user3->id, 'pokus1'); $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); $this->assertSame($ids, $newids); $this->assertEquals(6, $DB->count_records('user_password_history')); set_config('passwordreuselimit', -1); $ids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); user_add_password_history($user2->id, 'pokus6'); user_add_password_history($user3->id, 'pokus6'); $newids = array_keys($DB->get_records('user_password_history', array('userid' => $user2->id), 'timecreated ASC, id ASC')); $this->assertSame($ids, $newids); $this->assertEquals(6, $DB->count_records('user_password_history')); } /** * Test function user_add_password_history(). */ public function test_user_is_previously_used_password() { global $DB; $this->resetAfterTest(); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $DB->delete_records('user_password_history', array()); set_config('passwordreuselimit', 0); user_add_password_history($user1->id, 'pokus'); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus')); set_config('passwordreuselimit', 3); user_add_password_history($user2->id, 'pokus1'); user_add_password_history($user2->id, 'pokus2'); user_add_password_history($user1->id, 'pokus1'); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4')); user_add_password_history($user1->id, 'pokus2'); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4')); user_add_password_history($user1->id, 'pokus3'); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4')); user_add_password_history($user1->id, 'pokus4'); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4')); set_config('passwordreuselimit', 2); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4')); set_config('passwordreuselimit', 3); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertTrue(user_is_previously_used_password($user1->id, 'pokus4')); set_config('passwordreuselimit', 0); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus1')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus2')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus3')); $this->assertFalse(user_is_previously_used_password($user1->id, 'pokus4')); } /** * Test that password history is deleted together with user. */ public function test_delete_of_hashes_on_user_delete() { global $DB; $this->resetAfterTest(); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $DB->delete_records('user_password_history', array()); set_config('passwordreuselimit', 3); user_add_password_history($user1->id, 'pokus'); user_add_password_history($user2->id, 'pokus1'); user_add_password_history($user2->id, 'pokus2'); $this->assertEquals(3, $DB->count_records('user_password_history')); $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id))); $this->assertEquals(2, $DB->count_records('user_password_history', array('userid' => $user2->id))); delete_user($user2); $this->assertEquals(1, $DB->count_records('user_password_history')); $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id))); $this->assertEquals(0, $DB->count_records('user_password_history', array('userid' => $user2->id))); } /** * Test user_list_view function */ public function test_user_list_view() { $this->resetAfterTest(); // Course without sections. $course = $this->getDataGenerator()->create_course(); $context = context_course::instance($course->id); $this->setAdminUser(); // Redirect events to the sink, so we can recover them later. $sink = $this->redirectEvents(); user_list_view($course, $context); $events = $sink->get_events(); $this->assertCount(1, $events); $event = reset($events); // Check the event details are correct. $this->assertInstanceOf('\core\event\user_list_viewed', $event); $this->assertEquals($context, $event->get_context()); $this->assertEquals($course->shortname, $event->other['courseshortname']); $this->assertEquals($course->fullname, $event->other['coursefullname']); } /** * Test setting the user menu avatar size. */ public function test_user_menu_custom_avatar_size() { global $PAGE; $this->resetAfterTest(true); $testsize = 100; $PAGE->set_url('/'); $user = $this->getDataGenerator()->create_user(); $opts = user_get_user_navigation_info($user, $PAGE, array('avatarsize' => $testsize)); $avatarhtml = $opts->metadata['useravatar']; $matches = []; preg_match('/(?:.*width=")(\d*)(?:" height=")(\d*)(?:".*\/>)/', $avatarhtml, $matches); $this->assertCount(3, $matches); $this->assertEquals(intval($matches[1]), $testsize); $this->assertEquals(intval($matches[2]), $testsize); } /** * Test user_can_view_profile */ public function test_user_can_view_profile() { global $DB, $CFG; $this->resetAfterTest(); // Create five users. $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $user3 = $this->getDataGenerator()->create_user(); $user4 = $this->getDataGenerator()->create_user(); $user5 = $this->getDataGenerator()->create_user(); $user6 = $this->getDataGenerator()->create_user(array('deleted' => 1)); $user7 = $this->getDataGenerator()->create_user(); $user8 = $this->getDataGenerator()->create_user(); $user8->id = 0; // Visitor. $studentrole = $DB->get_record('role', array('shortname' => 'student')); // Add the course creator role to the course contact and assign a user to that role. $CFG->coursecontact = '2'; $coursecreatorrole = $DB->get_record('role', array('shortname' => 'coursecreator')); $this->getDataGenerator()->role_assign($coursecreatorrole->id, $user7->id); // Create two courses. $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course2->id); // Prepare another course with separate groups and groupmodeforce set to true. $record = new stdClass(); $record->groupmode = 1; $record->groupmodeforce = 1; $course3 = $this->getDataGenerator()->create_course($record); // Enrol users 1 and 2 in first course. $this->getDataGenerator()->enrol_user($user1->id, $course1->id); $this->getDataGenerator()->enrol_user($user2->id, $course1->id); // Enrol users 2 and 3 in second course. $this->getDataGenerator()->enrol_user($user2->id, $course2->id); $this->getDataGenerator()->enrol_user($user3->id, $course2->id); // Enrol users 1, 4, and 5 into course 3. $this->getDataGenerator()->enrol_user($user1->id, $course3->id); $this->getDataGenerator()->enrol_user($user4->id, $course3->id); $this->getDataGenerator()->enrol_user($user5->id, $course3->id); // User 3 should not be able to see user 1, either by passing their own course (course 2) or user 1's course (course 1). $this->setUser($user3); $this->assertFalse(user_can_view_profile($user1, $course2)); $this->assertFalse(user_can_view_profile($user1, $course1)); // Remove capability moodle/user:viewdetails in course 2. assign_capability('moodle/user:viewdetails', CAP_PROHIBIT, $studentrole->id, $coursecontext); $coursecontext->mark_dirty(); // Set current user to user 1. $this->setUser($user1); // User 1 can see User 1's profile. $this->assertTrue(user_can_view_profile($user1)); $tempcfg = $CFG->forceloginforprofiles; $CFG->forceloginforprofiles = 0; // Not forced to log in to view profiles, should be able to see all profiles besides user 6. $users = array($user1, $user2, $user3, $user4, $user5, $user7); foreach ($users as $user) { $this->assertTrue(user_can_view_profile($user)); } // Restore setting. $CFG->forceloginforprofiles = $tempcfg; // User 1 can not see user 6 as they have been deleted. $this->assertFalse(user_can_view_profile($user6)); // User 1 can see User 7 as they are a course contact. $this->assertTrue(user_can_view_profile($user7)); // User 1 is in a course with user 2 and has the right capability - return true. $this->assertTrue(user_can_view_profile($user2)); // User 1 is not in a course with user 3 - return false. $this->assertFalse(user_can_view_profile($user3)); // Set current user to user 2. $this->setUser($user2); // User 2 is in a course with user 3 but does not have the right capability - return false. $this->assertFalse(user_can_view_profile($user3)); // Set user 1 in one group and users 4 and 5 in another group. $group1 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id)); $group2 = $this->getDataGenerator()->create_group(array('courseid' => $course3->id)); groups_add_member($group1->id, $user1->id); groups_add_member($group2->id, $user4->id); groups_add_member($group2->id, $user5->id); $this->setUser($user1); // Check that user 1 can not see user 4. $this->assertFalse(user_can_view_profile($user4)); // Check that user 5 can see user 4. $this->setUser($user5); $this->assertTrue(user_can_view_profile($user4)); // Test the user:viewalldetails cap check using the course creator role which, by default, can't see student profiles. $this->setUser($user7); $this->assertFalse(user_can_view_profile($user4)); assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $coursecreatorrole->id, context_system::instance()->id, true); reload_all_capabilities(); $this->assertTrue(user_can_view_profile($user4)); unassign_capability('moodle/user:viewalldetails', $coursecreatorrole->id, $coursecontext->id); reload_all_capabilities(); $CFG->coursecontact = null; // Visitor (Not a guest user, userid=0). $CFG->forceloginforprofiles = 1; $this->setUser($user8); $this->assertFalse(user_can_view_profile($user1)); $allroles = $DB->get_records_menu('role', array(), 'id', 'archetype, id'); // Let us test with guest user. $this->setGuestUser(); $CFG->forceloginforprofiles = 1; foreach ($users as $user) { $this->assertFalse(user_can_view_profile($user)); } // Even with cap, still guests should not be allowed in. $guestrole = $DB->get_records_menu('role', array('shortname' => 'guest'), 'id', 'archetype, id'); assign_capability('moodle/user:viewdetails', CAP_ALLOW, $guestrole['guest'], context_system::instance()->id, true); reload_all_capabilities(); foreach ($users as $user) { $this->assertFalse(user_can_view_profile($user)); } $CFG->forceloginforprofiles = 0; foreach ($users as $user) { $this->assertTrue(user_can_view_profile($user)); } // Let us test with Visitor user. $this->setUser($user8); $CFG->forceloginforprofiles = 1; foreach ($users as $user) { $this->assertFalse(user_can_view_profile($user)); } $CFG->forceloginforprofiles = 0; foreach ($users as $user) { $this->assertTrue(user_can_view_profile($user)); } // Testing non-shared courses where capabilities are met, using system role overrides. $CFG->forceloginforprofiles = $tempcfg; $course4 = $this->getDataGenerator()->create_course(); $this->getDataGenerator()->enrol_user($user1->id, $course4->id); // Assign a manager role at the system context. $managerrole = $DB->get_record('role', array('shortname' => 'manager')); $user9 = $this->getDataGenerator()->create_user(); $this->getDataGenerator()->role_assign($managerrole->id, $user9->id); // Make sure viewalldetails and viewdetails are overridden to 'prevent' (i.e. can be overridden at a lower context). $systemcontext = context_system::instance(); assign_capability('moodle/user:viewdetails', CAP_PREVENT, $managerrole->id, $systemcontext, true); assign_capability('moodle/user:viewalldetails', CAP_PREVENT, $managerrole->id, $systemcontext, true); $systemcontext->mark_dirty(); // And override these to 'Allow' in a specific course. $course4context = context_course::instance($course4->id); assign_capability('moodle/user:viewalldetails', CAP_ALLOW, $managerrole->id, $course4context, true); assign_capability('moodle/user:viewdetails', CAP_ALLOW, $managerrole->id, $course4context, true); $course4context->mark_dirty(); // The manager now shouldn't have viewdetails in the system or user context. $this->setUser($user9); $user1context = context_user::instance($user1->id); $this->assertFalse(has_capability('moodle/user:viewdetails', $systemcontext)); $this->assertFalse(has_capability('moodle/user:viewdetails', $user1context)); // Confirm that user_can_view_profile() returns true for $user1 when called without $course param. It should find $course1. $this->assertTrue(user_can_view_profile($user1)); // Confirm this also works when restricting scope to just that course. $this->assertTrue(user_can_view_profile($user1, $course4)); } /** * Test user_get_user_details */ public function test_user_get_user_details() { global $DB; $this->resetAfterTest(); // Create user and modify user profile. $teacher = $this->getDataGenerator()->create_user(); $student = $this->getDataGenerator()->create_user(); $studentfullname = fullname($student); $course1 = $this->getDataGenerator()->create_course(); $coursecontext = context_course::instance($course1->id); $teacherrole = $DB->get_record('role', array('shortname' => 'teacher')); $studentrole = $DB->get_record('role', array('shortname' => 'student')); $this->getDataGenerator()->enrol_user($teacher->id, $course1->id); $this->getDataGenerator()->enrol_user($student->id, $course1->id); role_assign($teacherrole->id, $teacher->id, $coursecontext->id); role_assign($studentrole->id, $student->id, $coursecontext->id); accesslib_clear_all_caches_for_unit_testing(); // Get student details as a user with super system capabilities. $result = user_get_user_details($student, $course1); $this->assertEquals($student->id, $result['id']); $this->assertEquals($studentfullname, $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); $this->setUser($teacher); // Get student details as a user who can only see this user in a course. $result = user_get_user_details($student, $course1); $this->assertEquals($student->id, $result['id']); $this->assertEquals($studentfullname, $result['fullname']); $this->assertEquals($course1->id, $result['enrolledcourses'][0]['id']); // Get student details with required fields. $result = user_get_user_details($student, $course1, array('id', 'fullname')); $this->assertCount(2, $result); $this->assertEquals($student->id, $result['id']); $this->assertEquals($studentfullname, $result['fullname']); // Get exception for invalid required fields. $this->expectException('moodle_exception'); $result = user_get_user_details($student, $course1, array('wrongrequiredfield')); } /** * Regression test for MDL-57840. * * Ensure the fields "auth, confirmed, idnumber, lang, theme, timezone and mailformat" are present when * calling user_get_user_details() function. */ public function test_user_get_user_details_missing_fields() { $this->resetAfterTest(true); $this->setAdminUser(); // We need capabilities to view the data. $user = self::getDataGenerator()->create_user([ 'auth' => 'auth_something', 'confirmed' => '0', 'idnumber' => 'someidnumber', 'lang' => 'en_ar', 'theme' => 'mytheme', 'timezone' => '50', 'mailformat' => '0', ]); // Fields that should get by default. $got = user_get_user_details($user); self::assertSame('auth_something', $got['auth']); self::assertSame('0', $got['confirmed']); self::assertSame('someidnumber', $got['idnumber']); self::assertSame('en_ar', $got['lang']); self::assertSame('mytheme', $got['theme']); self::assertSame('50', $got['timezone']); self::assertSame('0', $got['mailformat']); } /** * Test returning the total number of participants. */ public function test_user_get_total_participants() { global $DB; $this->resetAfterTest(); // Create a course. $course = self::getDataGenerator()->create_course(); // Create a teacher. $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); // Create a bunch of students. $student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); // Create a group. $group = self::getDataGenerator()->create_group(array('courseid' => $course->id)); // Enrol the students. self::getDataGenerator()->enrol_user($student1->id, $course->id); self::getDataGenerator()->enrol_user($student2->id, $course->id); self::getDataGenerator()->enrol_user($student3->id, $course->id); // Enrol the teacher. $roleids = $DB->get_records_menu('role', null, '', 'shortname, id'); self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']); // Add the teacher and two of the students to the group. groups_add_member($group->id, $teacher->id); groups_add_member($group->id, $student1->id); groups_add_member($group->id, $student2->id); // Set it so the teacher and two of the students have accessed the courses within the last day, // but only one of the students is in the group. $accesssince = time() - DAYSECS; $lastaccess = new stdClass(); $lastaccess->userid = $teacher->id; $lastaccess->courseid = $course->id; $lastaccess->timeaccess = time() - DAYSECS; $DB->insert_record('user_lastaccess', $lastaccess); $lastaccess->userid = $student1->id; $DB->insert_record('user_lastaccess', $lastaccess); $lastaccess->userid = $student3->id; $DB->insert_record('user_lastaccess', $lastaccess); // Now, when we perform the following search we should only return 1 user. A student who belongs to // the group and has the name 'searchforthis' and has also accessed the course in the last day. $count = user_get_total_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1, 'searchforthis'); $this->assertEquals(1, $count); } /** * Test returning the number of participants on the front page. */ public function test_user_get_total_participants_on_front_page() { $this->resetAfterTest(); // Set it so that only 3 users have accessed the site within the last day. $accesssince = time() - DAYSECS; // Create a bunch of users. $user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); $user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); $user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); // Create a group. $group = self::getDataGenerator()->create_group(array('courseid' => SITEID)); // Add 3 of the users to a group. groups_add_member($group->id, $user1->id); groups_add_member($group->id, $user2->id); groups_add_member($group->id, $user3->id); // Now, when we perform the following search we should only return 2 users. Users who belong to // the group and have the name 'searchforthis' and have also accessed the site in the last day. $count = user_get_total_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis'); $this->assertEquals(2, $count); } /** * Test returning the participants. */ public function test_user_get_participants() { global $DB; $this->resetAfterTest(); // Create a course. $course = self::getDataGenerator()->create_course(); // Create a teacher. $teacher = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); // Create a bunch of students. $student1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $student2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $student3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); // Create a group. $group = self::getDataGenerator()->create_group(array('courseid' => $course->id)); // Enrol the students. self::getDataGenerator()->enrol_user($student1->id, $course->id); self::getDataGenerator()->enrol_user($student2->id, $course->id); self::getDataGenerator()->enrol_user($student3->id, $course->id); // Enrol the teacher. $roleids = $DB->get_records_menu('role', null, '', 'shortname, id'); self::getDataGenerator()->enrol_user($teacher->id, $course->id, $roleids['editingteacher']); // Add the teacher and two of the students to the group. groups_add_member($group->id, $teacher->id); groups_add_member($group->id, $student1->id); groups_add_member($group->id, $student2->id); // Set it so the teacher and two of the students have accessed the course within the last day, but only one of // the students is in the group. $accesssince = time() - DAYSECS; $lastaccess = new stdClass(); $lastaccess->userid = $teacher->id; $lastaccess->courseid = $course->id; $lastaccess->timeaccess = time() - DAYSECS; $DB->insert_record('user_lastaccess', $lastaccess); $lastaccess->userid = $student1->id; $DB->insert_record('user_lastaccess', $lastaccess); $lastaccess->userid = $student3->id; $DB->insert_record('user_lastaccess', $lastaccess); // Now, when we perform the following search we should only return 1 user. A student who belongs to // the group and has the name 'searchforthis' and has also accessed the course in the last day. $userset = user_get_participants($course->id, $group->id, $accesssince + 1, $roleids['student'], 0, -1, 'searchforthis'); $this->assertEquals($student1->id, $userset->current()->id); $this->assertEquals(1, iterator_count($userset)); } /** * Test returning the participants on the front page. */ public function test_user_get_participants_on_front_page() { $this->resetAfterTest(); // Set it so that only 3 users have accessed the site within the last day. $accesssince = time() - DAYSECS; // Create a bunch of users. $user1 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); $user2 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); $user3 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis']); $user4 = self::getDataGenerator()->create_user(['firstname' => 'searchforthis', 'lastaccess' => $accesssince]); // Create a group. $group = self::getDataGenerator()->create_group(array('courseid' => SITEID)); // Add 3 of the users to a group. groups_add_member($group->id, $user1->id); groups_add_member($group->id, $user2->id); groups_add_member($group->id, $user3->id); // Now, when we perform the following search we should only return 2 users. Users who belong to // the group and have the name 'searchforthis' and have also accessed the site in the last day. $userset = user_get_participants(SITEID, $group->id, $accesssince + 1, 0, 0, -1, 'searchforthis', '', array(), 'ORDER BY id ASC'); $this->assertEquals($user1->id, $userset->current()->id); $userset->next(); $this->assertEquals($user2->id, $userset->current()->id); } }
gpl-3.0
ljsimin/gimii
WiiApi/WiiApi/PolozajGlave.cs
3610
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WiimoteLib; namespace WiiApi { /// <summary> /// Klasa koriscena za prikaz polozaja i orijentacije glave u prostoru. Sadrzi samo metode za dobavljanje informacija. /// </summary> public class PolozajGlave { /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> private Point3F polozaj; /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F goreVektor; /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F pogledVektor; /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> private bool uspesno; /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 2 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> public PolozajGlave(bool uspesno, Point3F polozaj) { this.uspesno = uspesno; this.polozaj = polozaj; } /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 3 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> /// <param name="goreVektor">Vektor na gore. </param> /// /// <param name="pogledVektor">Pravac pogleda. </param> public PolozajGlave(bool uspesno, Point3F polozaj, Point3F goreVektor, Point3F pogledVektor) { this.uspesno = uspesno; this.polozaj = polozaj; this.goreVektor = goreVektor; this.pogledVektor = pogledVektor; } /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> public bool Uspesno { get { return uspesno; } } /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> public Point3F Polozaj { get { return polozaj; } } /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F GoreVektor { get { return goreVektor; } } /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F PogledVektor { get { return pogledVektor; } } } }
gpl-3.0
fwahyudi17/ofiskita
system/configa/revslider/js/settings.js
9972
var UniteSettingsRev = new function(){ var arrControls = {}; var colorPicker; var t=this; this.getSettingsObject = function(formID){ var obj = new Object(); var form = document.getElementById(formID); var name,value,type,flagUpdate; //enabling all form items connected to mx var len = form.elements.length; for(var i=0; i<len; i++){ var element = form.elements[i]; if(element.name == "##NAME##[]") continue; //ignore dummy from multi text name = element.name; value = element.value; type = element.type; if(jQuery(element).hasClass("wp-editor-area")) type = "editor"; //trace(name + " " + type); flagUpdate = true; switch(type){ case "checkbox": value = form.elements[i].checked; break; case "radio": if(form.elements[i].checked == false) flagUpdate = false; break; case "editor": value = tinyMCE.get(name).getContent(); break; case "select-multiple": value = jQuery(element).val(); if(value) value = value.toString(); break; } if(flagUpdate == true && name != undefined){ if(name.indexOf('[]') > -1){ name = name.replace('[]', ''); if(typeof obj[name] !== 'object') obj[name] = []; obj[name][Object.keys(obj[name]).length] = value; }else{ obj[name] = value; } } } return(obj); } this.getsdsformvalue = function(formID){ var obj = new Object(); var form = document.getElementById(formID); var name,value,type,flagUpdate; //enabling all form items connected to mx var len = form.elements.length; for(var i=0; i<len; i++){ var element = form.elements[i]; if(element.name == "##NAME##[]") continue; //ignore dummy from multi text name = element.name; value = element.value; type = element.type; if(jQuery(element).hasClass("wp-editor-area")) type = "editor"; //trace(name + " " + type); flagUpdate = true; switch(type){ case "checkbox": value = form.elements[i].checked; break; case "radio": if(form.elements[i].checked == false) flagUpdate = false; break; case "editor": value = tinyMCE.get(name).getContent(); break; case "select-multiple": value = jQuery(element).val(); if(value) value = value.toString(); break; } if(flagUpdate == true && name != undefined){ if(name.indexOf('[]') > -1){ name = name.replace('[]', ''); if(typeof obj[name] !== 'object') obj[name] = []; obj[name][Object.keys(obj[name]).length] = value; }else{ obj[name] = value; } } } return(obj); } /** * on selects change - impiment the hide/show, enabled/disables functionality */ var onSettingChange = function(){ var controlValue = this.value.toLowerCase(); var controlName = this.name; if(!arrControls[this.name]) return(false); jQuery(arrControls[this.name]).each(function(){ var childInput = document.getElementById(this.name); var childRow = document.getElementById(this.name + "_row"); var value = this.value.toLowerCase(); var isChildRadio = (childInput && childInput.tagName == "SPAN" && jQuery(childInput).hasClass("radio_wrapper")); switch(this.type){ case "enable": case "disable": if(childInput){ //disable if(this.type == "enable" && controlValue != this.value || this.type == "disable" && controlValue == this.value){ childRow.className = "disabled"; if(childInput){ childInput.disabled = true; childInput.style.color = ""; } if(isChildRadio) jQuery(childInput).children("input").prop("disabled","disabled").addClass("disabled"); } else{ //enable childRow.className = ""; if(childInput) childInput.disabled = false; if(isChildRadio) jQuery(childInput).children("input").prop("disabled","").removeClass("disabled"); //color the input again if(jQuery(childInput).hasClass("inputColorPicker")) g_picker.linkTo(childInput); } } break; case "show": if(controlValue == this.value) jQuery(childRow).show(); else jQuery(childRow).hide(); break; case "hide": if(controlValue == this.value) jQuery(childRow).hide(); else jQuery(childRow).show(); break; } }); } /** * combine controls to one object, and init control events. */ var initControls = function(){ //combine controls for(key in g_settingsObj){ var obj = g_settingsObj[key]; for(controlKey in obj.controls){ arrControls[controlKey] = obj.controls[controlKey]; } } //init events jQuery(".settings_wrapper select").change(onSettingChange); jQuery(".settings_wrapper input[type='radio']").change(onSettingChange); } //init color picker var initColorPicker = function(){ var colorPickerWrapper = jQuery('#divColorPicker'); colorPicker = jQuery.farbtastic('#divColorPicker'); jQuery(".inputColorPicker").focus(function(){ colorPicker.linkTo(this); colorPickerWrapper.show(); var input = jQuery(this); var offset = input.offset(); var offsetView = jQuery("#viewWrapper").offset(); colorPickerWrapper.css({ "left":offset.left + input.width()+20-offsetView.left, "top":offset.top - colorPickerWrapper.height() + 100-offsetView.top }); if (jQuery(input.data('linkto'))) { var oldval = jQuery(this).val(); jQuery(this).data('int',setInterval(function() { if(input.val() != oldval){ oldval = input.val(); jQuery('#css_preview').css(input.data('linkto'), oldval); jQuery('input[name="css_'+input.data('linkto')+'"]').val(oldval); } } ,200)); } }).blur(function() { clearInterval(jQuery(this).data('int')); }).click(function(){ return(false); //prevent body click }).change(function(){ colorPicker.linkTo(this); colorPicker.setColor(jQuery(this).val()); }); colorPickerWrapper.click(function(){ return(false); //prevent body click }); jQuery("body").click(function(){ colorPickerWrapper.hide(); }); } /** * close all accordion items */ var closeAllAccordionItems = function(formID){ jQuery("#"+formID+" .unite-postbox .inside").slideUp("fast"); jQuery("#"+formID+" .unite-postbox h3").addClass("box_closed"); } /** * init side settings accordion - started from php */ t.initAccordion = function(formID){ var classClosed = "box_closed"; jQuery("#"+formID+" .unite-postbox h3").click(function(){ var handle = jQuery(this); //open if(handle.hasClass(classClosed)){ closeAllAccordionItems(formID); handle.removeClass(classClosed).siblings(".inside").slideDown("fast"); }else{ //close handle.addClass(classClosed).siblings(".inside").slideUp("fast"); } }); } /** * image search */ var initImageSearch = function(){ jQuery(".button-image-select").click(function(){ var settingID = this.id.replace("_button",""); UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){ //update input: jQuery("#"+settingID).val(urlImage); //update preview image: var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,100,70,true); jQuery("#" + settingID + "_button_preview").html('<div style="width:100px;height:70px;background:url(\''+urlShowImage+'\'); background-position:center center; background-size:cover;"></div>'); }); }); jQuery(".button-image-remove").click(function(){ var settingID = this.id.replace("_button_remove",""); jQuery("#"+settingID).val(''); jQuery("#" + settingID + "_button_preview").html(''); }); jQuery(".button-image-select-video").click(function(){ UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){ //update input: jQuery("#input_video_preview").val(urlImage); //update preview image: var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,200,150,true); jQuery("#video-thumbnail-preview").attr('src', urlShowImage); }); }); jQuery(".button-image-remove-video").click(function(){ jQuery("#input_video_preview").val(''); if(jQuery('#video_block_vimeo').css('display') != 'none') jQuery("#button_vimeo_search").trigger("click"); if(jQuery('#video_block_youtube').css('display') != 'none') jQuery("#button_youtube_search").trigger("click"); }); } /** * init the settings function, set the tootips on sidebars. */ var init = function(){ //init tipsy jQuery(".list_settings li .setting_text").tipsy({ gravity:"e", delayIn: 70 }); jQuery(".tipsy_enabled_top").tipsy({ gravity:"s", delayIn: 70 }); jQuery(".button-primary").tipsy({ gravity:"s", delayIn: 70 }); //init controls initControls(); initColorPicker(); initImageSearch(); //init checklist jQuery(".settings_wrapper .input_checklist").each(function(){ var select = jQuery(this); var ominWidth = select.data("minwidth"); if (ominWidth==undefined) ominWidth="none" select.dropdownchecklist({ zIndex:1000, minWidth:ominWidth, onItemClick: function(checkbox,selector) { for (var i=0;i<20;i++) if (checkbox.val()=="notselectable"+i) { //console.log(checkbox.val()); checkbox.attr("checked",false); } } }); select.parent().find('input').each(function() { var option = jQuery(this); for (var i=0;i<20;i++) if (option.val()=="notselectable"+i) option.parent().addClass("dropdowntitleoption"); }) }); } //call "constructor" jQuery(document).ready(function(){ init(); }); } // UniteSettings class end
gpl-3.0
drebes/terraform
website/docs/configuration/syntax-json.html.md
14994
--- layout: "docs" page_title: "JSON Configuration Syntax - Configuration Language" sidebar_current: "docs-config-syntax-json" description: |- In addition to the native syntax that is most commonly used with Terraform, the Terraform language can also be expressed in a JSON-compatible syntax. --- # JSON Configuration Syntax -> **Note:** This page is about Terraform 0.12 and later. The JSON configuration syntax in 0.11 and earlier was never formally documented. For other information about Terraform 0.11 and earlier, see [0.11 Configuration Language](../configuration-0-11/index.html). Most Terraform configurations are written in [the native Terraform language syntax](./syntax.html), which is designed to be easy for humans to read and update. Terraform also supports an alternative syntax that is JSON-compatible. This syntax is useful when generating portions of a configuration programmatically, since existing JSON libraries can be used to prepare the generated configuration files. The JSON syntax is defined in terms of the native syntax. Everything that can be expressed in native syntax can also be expressed in JSON syntax, but some constructs are more complex to represent in JSON due to limitations of the JSON grammar. Terraform expects native syntax for files named with a `.tf` suffix, and JSON syntax for files named with a `.tf.json` suffix. The low-level JSON syntax, just as with the native syntax, is defined in terms of a specification called _HCL_. It is not necessary to know all of the details of HCL syntax or its JSON mapping in order to use Terraform, and so this page summarizes the most important differences between native and JSON syntax. If you are interested, you can find a full definition of HCL's JSON syntax in [its specification](https://github.com/hashicorp/hcl2/blob/master/hcl/json/spec.md). ## JSON File Structure At the root of any JSON-based Terraform configuration is a JSON object. The properties of this object correspond to the top-level block types of the Terraform language. For example: ```json { "variable": { "example": { "default": "hello" } } } ``` Each top-level object property must match the name of one of the expected top-level block types. Block types that expect labels, such as `variable` shown above, are represented by one nested object value for each level of label. `resource` blocks expect two labels, so two levels of nesting are required: ```json { "resource": { "aws_instance": { "example": { "instance_type": "t2.micro", "ami": "ami-abc123" } } } } ``` After any nested objects representing the labels, finally one more nested object represents the body of the block itself. In the above examples, the `default` argument for `variable "example"` and the `instance_type` and `ami` arguments for `resource "aws_instance" "example"` are specified. Taken together, the above two configuration files are equivalent to the following blocks in the native syntax: ```hcl variable "example" { default = "hello" } resource "aws_instance" "example" { instance_type = "t2.micro" ami = "ami-abc123" } ``` Within each top-level block type the rules for mapping to JSON are slightly different (see [Block-type-specific Exceptions][inpage-exceptions] below), but the following general rules apply in most cases: * The JSON object representing the block body contains properties that correspond either to argument names or to nested block type names. * Where a property corresponds to an argument that accepts [arbitrary expressions](./expressions.html) in the native syntax, the property value is mapped to an expression as described under [_Expression Mapping_](#expression-mapping) below. For arguments that do _not_ accept arbitrary expressions, the interpretation of the property value depends on the argument, as described in the [block-type-specific exceptions](#block-type-specific-exceptions) given later in this page. * Where a property name corresponds to an expected nested block type name, the value is interpreted as described under [_Nested Block Mapping_](#nested-block-mapping) below, unless otherwise stated in [the block-type-specific exceptions](#block-type-specific-exceptions) given later in this page. ## Expression Mapping Since JSON grammar is not able to represent all of the Terraform language [expression syntax](./expressions.html), JSON values interpreted as expressions are mapped as follows: | JSON | Terraform Language Interpretation | | ------- | ------------------------------------------------------------------------------------------------------------- | | Boolean | A literal `bool` value. | | Number | A literal `number` value. | | String | Parsed as a [string template](./expressions.html#string-templates) and then evaluated as described below. | | Object | Each property value is mapped per this table, producing an `object(...)` value with suitable attribute types. | | Array | Each element is mapped per this table, producing a `tuple(...)` value with suitable element types. | | Null | A literal `null`. | When a JSON string is encountered in a location where arbitrary expressions are expected, its value is first parsed as a [string template](./expressions.html#string-templates) and then it is evaluated to produce the final result. If the given template consists _only_ of a single interpolation sequence, the result of its expression is taken directly, without first converting it to a string. This allows non-string expressions to be used within the JSON syntax: ```json { "output": { "example": { "value": "${aws_instance.example}" } } } ``` The `output "example"` declared above has the object value representing the given `aws_instance` resource block as its value, rather than a string value. This special behavior does not apply if any literal or control sequences appear in the template; in these other situations, a string value is always produced. ## Nested Block Mapping When a JSON object property is named after a nested block type, the value of this property represents one or more blocks of that type. The value of the property must be either a JSON object or a JSON array. The simplest situation is representing only a single block of the given type when that type expects no labels, as with the `lifecycle` nested block used within `resource` blocks: ```json { "resource": { "aws_instance": { "example": { "lifecycle": { "create_before_destroy": true } } } } } ``` The above is equivalent to the following native syntax configuration: ```hcl resource "aws_instance" "example" { lifecycle { create_before_destroy = true } } ``` When the nested block type requires one or more labels, or when multiple blocks of the same type can be given, the mapping gets a little more complicated. For example, the `provisioner` nested block type used within `resource` blocks expects a label giving the provisioner to use, and the ordering of provisioner blocks is significant to decide the order of operations. The following native syntax example shows a `resource` block with a number of provisioners of different types: ```hcl resource "aws_instance" "example" { # (resource configuration omitted for brevity) provisioner "local-exec" { command = "echo 'Hello World' >example.txt" } provisioner "file" { source = "example.txt" destination = "/tmp/example.txt" } provisioner "remote-exec" { inline = [ "sudo install-something -f /tmp/example.txt", ] } } ``` In order to preserve the order of these blocks, you must use a JSON array as the direct value of the property representing this block type, as in this JSON equivalent of the above: ```json { "resource": { "aws_instance": { "example": { "provisioner": [ { "local-exec": { "command": "echo 'Hello World' >example.txt" } }, { "file": { "source": "example.txt", "destination": "/tmp/example.txt" } }, { "remote-exec": { "inline": ["sudo install-something -f /tmp/example.txt"] } } ] } } } } ``` Each element of the `provisioner` array is an object with a single property whose name represents the label for each `provisioner` block. For block types that expect multiple labels, this pattern of alternating array and object nesting can be used for each additional level. If a nested block type requires labels but the order does _not_ matter, you may omit the array and provide just a single object whose property names correspond to unique block labels. This is allowed as a shorthand for the above for simple cases, but the alternating array and object approach is the most general. We recommend using the most general form if systematically converting from native syntax to JSON, to ensure that the meaning of the configuration is preserved exactly. ### Comment Properties Although we do not recommend hand-editing of JSON syntax configuration files -- this format is primarily intended for programmatic generation and consumption -- a limited form of _comments_ are allowed inside JSON objects that represent block bodies using a special property name: ```json { "resource": { "aws_instance": { "example": { "//": "This instance runs the scheduled tasks for backup", "instance_type": "t2.micro", "ami": "ami-abc123" } } } } ``` In any object that represents a block body, properties named `"//"` are ignored by Terraform entirely. This exception does _not_ apply to objects that are being [interpreted as expressions](#expression-mapping), where this would be interpreted as an object type attribute named `"//"`. This special property name can also be used at the root of a JSON-based configuration file. This can be useful to note which program created the file. ```json { "//": "This file is generated by generate-outputs.py. DO NOT HAND-EDIT!", "output": { "example": { "value": "${aws_instance.example}" } } } ``` ## Block-type-specific Exceptions [inpage-block]: #block-type-specific-exceptions Certain arguments within specific block types are processed in a special way by Terraform, and so their mapping to the JSON syntax does not follow the general rules described above. The following sub-sections describe the special mapping rules that apply to each top-level block type. ### `resource` and `data` blocks Some meta-arguments for the `resource` and `data` block types take direct references to objects, or literal keywords. When represented in JSON, the reference or keyword is given as a JSON string with no additional surrounding spaces or symbols. For example, the `provider` meta-argument takes a `<PROVIDER>.<ALIAS>` reference to a provider configuration, which appears unquoted in the native syntax but must be presented as a string in the JSON syntax: ```json { "resource": { "aws_instance": { "example": { "provider": "aws.foo" } } } } ``` This special processing applies to the following meta-arguments: * `provider`: a single string, as shown above * `depends_on`: an array of strings containing references to named entities, like `["aws_instance.example"]`. * `ignore_changes` within the `lifecycle` block: if set to `all`, a single string `"all"` must be given. Otherwise, an array of JSON strings containing property references must be used, like `["ami"]`. Special processing also applies to the `type` argument of any `connection` blocks, whether directly inside the `resource` block or nested inside `provisioner` blocks: the given string is interpreted literally, and not parsed and evaluated as a string template. ### `variable` blocks All arguments inside `variable` blocks have non-standard mappings to JSON: * `type`: a string containing a type expression, like `"string"` or `"list(string)"`. * `default`: a literal JSON value that can be converted to the given type. Strings within this value are taken literally and _not_ interpreted as string templates. * `description`: a literal JSON string, _not_ interpreted as a template. ```json { "variable": { "example": { "type": "string", "default": "hello" } } } ``` ### `output` blocks The `description` and `sensitive` arguments are interpreted as literal JSON values. The `description` string is not interpreted as a string template. The `value` argument is [interpreted as an expression](#expression-mapping). ```json { "output": { "example": { "value": "${aws_instance.example}" } } } ``` ### `locals` blocks The value of the JSON object property representing the locals block type must be a JSON object whose property names are the local value names to declare: ```json { "locals": { "greeting": "Hello, ${var.name}" } } ``` The value of each of these nested properties is [interpreted as an expression](#expression-mapping). ### `module` blocks The `source` and `version` meta-arguments must be given as literal strings. The values are not interpreted as string templates. The `providers` meta-argument must be given as a JSON object whose properties are the compact provider addresses to expose into the child module and whose values are the provider addresses to use from the current module, both given as literal strings: ```json { "module": { "example": { "source": "hashicorp/consul/azurerm", "version": "= 1.0.0", "providers": { "aws": "aws.usw1" } } } } ``` ### `provider` blocks The `alias` and `version` meta-arguments must be given as literal strings. The values are not interpreted as string templates. ```json { "provider": { "aws": { "alias": "usw1", "region": "us-west-1" } } } ``` ### `terraform` blocks Since no settings within `terraform` blocks accept named object references or function calls, all setting values are taken literally. String values are not interpreted as string templates. Since only one `backend` block is allowed per `terraform` block, the compact block mapping can be used to represent it, with a nested object containing a single property whose name represents the backend type. ```json { "terraform": { "required_version": ">= 0.12.0", "backend": { "s3": { "region": "us-west-2", "bucket": "acme-terraform-states" } } } } ```
mpl-2.0
tyagiarpit/servo
tests/wpt/web-platform-tests/web-animations/keyframe-effect/getComputedTiming-progress.html
9761
<!DOCTYPE html> <meta charset=utf-8> <title>progress of KeyframeEffectReadOnly getComputedTiming() tests</title> <link rel="help" href="https://w3c.github.io/web-animations/#dom-animationeffectreadonly-getcomputedtiming"> <link rel="author" title="Daisuke Akatsuka" href="mailto:[email protected]"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="../testcommon.js"></script> <link rel="stylesheet" href="/resources/testharness.css"> <body> <div id="log"></div> <script> 'use strict'; function executeTests(tests, description) { tests.forEach(function(currentTest) { var testParams = ''; for (var attr in currentTest.input) { testParams += ' ' + attr + ':' + currentTest.input[attr]; } test(function(t) { var div = createDiv(t); var anim = div.animate({ opacity: [ 0, 1 ] }, currentTest.input); assert_equals(anim.effect.getComputedTiming().progress, currentTest.before); anim.currentTime = currentTest.input.delay || 0; assert_equals(anim.effect.getComputedTiming().progress, currentTest.active); if (typeof currentTest.after !== 'undefined') { anim.finish(); assert_equals(anim.effect.getComputedTiming().progress, currentTest.after); } }, description + testParams); }); } async_test(function(t) { var div = createDiv(t); var anim = div.animate({ opacity: [ 0, 1 ] }, { delay: 1 }); assert_equals(anim.effect.getComputedTiming().progress, null); anim.finished.then(t.step_func(function() { assert_equals(anim.effect.getComputedTiming().progress, null); t.done(); })); }, 'Test progress during before and after phase when fill is none'); var gTests_zero_iterations = [ { input: { iterations: 0, iterationStart: 0, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 }, { input: { iterations: 0, iterationStart: 0, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 }, { input: { iterations: 0, iterationStart: 0, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 }, { input: { iterations: 0, iterationStart: 2.5, duration: 0, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: 0, iterationStart: 2.5, duration: 100, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: 0, iterationStart: 2.5, duration: Infinity, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: 0, iterationStart: 3, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 }, { input: { iterations: 0, iterationStart: 3, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 }, { input: { iterations: 0, iterationStart: 3, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0 } ]; var gTests_integer_iterations = [ { input: { iterations: 3, iterationStart: 0, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 1, after: 1 }, { input: { iterations: 3, iterationStart: 0, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 1 }, { input: { iterations: 3, iterationStart: 0, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 }, { input: { iterations: 3, iterationStart: 2.5, duration: 0, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: 3, iterationStart: 2.5, duration: 100, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: 3, iterationStart: 2.5, duration: Infinity, delay: 1, fill: 'both' }, before: 0.5, active: 0.5 }, { input: { iterations: 3, iterationStart: 3, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 1, after: 1 }, { input: { iterations: 3, iterationStart: 3, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 1 }, { input: { iterations: 3, iterationStart: 3, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 } ]; var gTests_fractional_iterations = [ { input: { iterations: 3.5, iterationStart: 0, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 0.5, after: 0.5 }, { input: { iterations: 3.5, iterationStart: 0, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0.5 }, { input: { iterations: 3.5, iterationStart: 0, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 }, { input: { iterations: 3.5, iterationStart: 2.5, duration: 0, delay: 1, fill: 'both' }, before: 0.5, active: 1, after: 1 }, { input: { iterations: 3.5, iterationStart: 2.5, duration: 100, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 1 }, { input: { iterations: 3.5, iterationStart: 2.5, duration: Infinity, delay: 1, fill: 'both' }, before: 0.5, active: 0.5 }, { input: { iterations: 3.5, iterationStart: 3, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 0.5, after: 0.5 }, { input: { iterations: 3.5, iterationStart: 3, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0, after: 0.5 }, { input: { iterations: 3.5, iterationStart: 3, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 } ]; var gTests_infinity_iterations = [ { input: { iterations: Infinity, iterationStart: 0, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 1, after: 1 }, { input: { iterations: Infinity, iterationStart: 0, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0 }, { input: { iterations: Infinity, iterationStart: 0, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 }, { input: { iterations: Infinity, iterationStart: 2.5, duration: 0, delay: 1, fill: 'both' }, before: 0.5, active: 0.5, after: 0.5 }, { input: { iterations: Infinity, iterationStart: 2.5, duration: 100, delay: 1, fill: 'both' }, before: 0.5, active: 0.5 }, { input: { iterations: Infinity, iterationStart: 2.5, duration: Infinity, delay: 1, fill: 'both' }, before: 0.5, active: 0.5 }, { input: { iterations: Infinity, iterationStart: 3, duration: 0, delay: 1, fill: 'both' }, before: 0, active: 1, after: 1 }, { input: { iterations: Infinity, iterationStart: 3, duration: 100, delay: 1, fill: 'both' }, before: 0, active: 0 }, { input: { iterations: Infinity, iterationStart: 3, duration: Infinity, delay: 1, fill: 'both' }, before: 0, active: 0 } ]; executeTests(gTests_zero_iterations, "Test zero iterations:"); executeTests(gTests_integer_iterations, "Test integer iterations:"); executeTests(gTests_fractional_iterations, "Test fractional iterations:"); executeTests(gTests_infinity_iterations, "Test infinity iterations:"); </script> </body>
mpl-2.0
dayglojesus/packer
builder/cloudstack/step_prepare_config.go
5108
package cloudstack import ( "fmt" "io/ioutil" "regexp" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" "github.com/xanzy/go-cloudstack/cloudstack" ) type stepPrepareConfig struct{} func (s *stepPrepareConfig) Run(state multistep.StateBag) multistep.StepAction { client := state.Get("client").(*cloudstack.CloudStackClient) config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) ui.Say("Preparing config...") var err error var errs *packer.MultiError // First get the project and zone UUID's so we can use them in other calls when needed. if config.Project != "" && !isUUID(config.Project) { config.Project, _, err = client.Project.GetProjectID(config.Project) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"project", config.Project, err}) } } if config.UserDataFile != "" { userdata, err := ioutil.ReadFile(config.UserDataFile) if err != nil { errs = packer.MultiErrorAppend(errs, fmt.Errorf("problem reading user data file: %s", err)) } config.UserData = string(userdata) } if !isUUID(config.Zone) { config.Zone, _, err = client.Zone.GetZoneID(config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"zone", config.Zone, err}) } } // Then try to get the remaining UUID's. if config.DiskOffering != "" && !isUUID(config.DiskOffering) { config.DiskOffering, _, err = client.DiskOffering.GetDiskOfferingID(config.DiskOffering) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"disk offering", config.DiskOffering, err}) } } if config.PublicIPAddress != "" && !isUUID(config.PublicIPAddress) { // Save the public IP address before replacing it with it's UUID. config.hostAddress = config.PublicIPAddress p := client.Address.NewListPublicIpAddressesParams() p.SetIpaddress(config.PublicIPAddress) if config.Project != "" { p.SetProjectid(config.Project) } ipAddrs, err := client.Address.ListPublicIpAddresses(p) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, err}) } if err == nil && ipAddrs.Count != 1 { errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, ipAddrs}) } if err == nil && ipAddrs.Count == 1 { config.PublicIPAddress = ipAddrs.PublicIpAddresses[0].Id } } if !isUUID(config.Network) { config.Network, _, err = client.Network.GetNetworkID(config.Network, cloudstack.WithProject(config.Project)) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"network", config.Network, err}) } } if !isUUID(config.ServiceOffering) { config.ServiceOffering, _, err = client.ServiceOffering.GetServiceOfferingID(config.ServiceOffering) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"service offering", config.ServiceOffering, err}) } } if config.SourceISO != "" { if isUUID(config.SourceISO) { config.instanceSource = config.SourceISO } else { config.instanceSource, _, err = client.ISO.GetIsoID(config.SourceISO, "executable", config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"ISO", config.SourceISO, err}) } } } if config.SourceTemplate != "" { if isUUID(config.SourceTemplate) { config.instanceSource = config.SourceTemplate } else { config.instanceSource, _, err = client.Template.GetTemplateID(config.SourceTemplate, "executable", config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"template", config.SourceTemplate, err}) } } } if !isUUID(config.TemplateOS) { p := client.GuestOS.NewListOsTypesParams() p.SetDescription(config.TemplateOS) types, err := client.GuestOS.ListOsTypes(p) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, err}) } if err == nil && types.Count != 1 { errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, types}) } if err == nil && types.Count == 1 { config.TemplateOS = types.OsTypes[0].Id } } // This is needed because nil is not always nil. When returning *packer.MultiError(nil) // as an error interface, that interface will no longer be equal to nil but it will be // an interface with type *packer.MultiError and value nil which is different then a // nil interface. if errs != nil && len(errs.Errors) > 0 { ui.Error(errs.Error()) return multistep.ActionHalt } ui.Message("Config has been prepared!") return multistep.ActionContinue } func (s *stepPrepareConfig) Cleanup(state multistep.StateBag) { // Nothing to cleanup for this step. } type retrieveErr struct { name string value string result interface{} } func (e *retrieveErr) Error() string { if err, ok := e.result.(error); ok { e.result = err.Error() } return fmt.Sprintf("Error retrieving UUID of %s %s: %v", e.name, e.value, e.result) } var uuidRegex = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) func isUUID(uuid string) bool { return uuidRegex.MatchString(uuid) }
mpl-2.0
HatfieldConsultants/Hatfield.EnviroData.DataAcquisition
Source/Hatfield.EnviroData.DataAcquisition.XML/XMLDataSourceLocation.cs
1295
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Hatfield.EnviroData.DataAcquisition.XML { public class XMLDataSourceLocation: IDataSourceLocation { public string _elementName; public string _attributeName; public int _index = 0; public XMLDataSourceLocation(string elementName, string attributeName) { _elementName = elementName; _attributeName = attributeName; } public XMLDataSourceLocation(string elementName, string attributeName, int index) { _elementName = elementName; _attributeName = attributeName; _index = index; } public string AttributeName { get { return _attributeName; } } public string ElementName { get { return _elementName; } } public int Index { get { return _index; } } public override string ToString() { return string.Format("Node: {0}, {1}", _elementName, _attributeName); } } }
mpl-2.0
michaelforfxhelp/fxhelprepo
third_party/libcurl/curl/lib/http_negotiate.c
11517
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "setup.h" #ifdef HAVE_GSSAPI #ifdef HAVE_OLD_GSSMIT #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name #define NCOMPAT 1 #endif #ifndef CURL_DISABLE_HTTP #include "urldata.h" #include "sendf.h" #include "curl_gssapi.h" #include "rawstr.h" #include "curl_base64.h" #include "http_negotiate.h" #include "curl_memory.h" #include "url.h" #ifdef HAVE_SPNEGO # include <spnegohelp.h> # ifdef USE_SSLEAY # ifdef USE_OPENSSL # include <openssl/objects.h> # else # include <objects.h> # endif # else # error "Can't compile SPNEGO support without OpenSSL." # endif #endif #define _MPRINTF_REPLACE /* use our functions only */ #include "../mprintf.h" /* The last #include file should be: */ #include "memdebug.h" static int get_gss_name(struct connectdata *conn, bool proxy, gss_name_t *server) { struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg: &conn->data->state.negotiate; OM_uint32 major_status, minor_status; gss_buffer_desc token = GSS_C_EMPTY_BUFFER; char name[2048]; const char* service; /* GSSAPI implementation by Globus (known as GSI) requires the name to be of form "<service>/<fqdn>" instead of <service>@<fqdn> (ie. slash instead of at-sign). Also GSI servers are often identified as 'host' not 'khttp'. Change following lines if you want to use GSI */ /* IIS uses the <service>@<fqdn> form but uses 'http' as the service name */ if(neg_ctx->gss) service = "KHTTP"; else service = "HTTP"; token.length = strlen(service) + 1 + strlen(proxy ? conn->proxy.name : conn->host.name) + 1; if(token.length + 1 > sizeof(name)) return EMSGSIZE; snprintf(name, sizeof(name), "%s@%s", service, proxy ? conn->proxy.name : conn->host.name); token.value = (void *) name; major_status = gss_import_name(&minor_status, &token, GSS_C_NT_HOSTBASED_SERVICE, server); return GSS_ERROR(major_status) ? -1 : 0; } static void log_gss_error(struct connectdata *conn, OM_uint32 error_status, const char *prefix) { OM_uint32 maj_stat, min_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; char buf[1024]; size_t len; snprintf(buf, sizeof(buf), "%s", prefix); len = strlen(buf); do { maj_stat = gss_display_status(&min_stat, error_status, GSS_C_MECH_CODE, GSS_C_NO_OID, &msg_ctx, &status_string); if(sizeof(buf) > len + status_string.length + 1) { snprintf(buf + len, sizeof(buf) - len, ": %s", (char*) status_string.value); len += status_string.length; } gss_release_buffer(&min_stat, &status_string); } while(!GSS_ERROR(maj_stat) && msg_ctx != 0); infof(conn->data, "%s\n", buf); } /* returning zero (0) means success, everything else is treated as "failure" with no care exactly what the failure was */ int Curl_input_negotiate(struct connectdata *conn, bool proxy, const char *header) { struct SessionHandle *data = conn->data; struct negotiatedata *neg_ctx = proxy?&data->state.proxyneg: &data->state.negotiate; OM_uint32 major_status, minor_status, minor_status2; gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; int ret; size_t len; size_t rawlen = 0; bool gss; const char* protocol; CURLcode error; while(*header && ISSPACE(*header)) header++; if(checkprefix("GSS-Negotiate", header)) { protocol = "GSS-Negotiate"; gss = TRUE; } else if(checkprefix("Negotiate", header)) { protocol = "Negotiate"; gss = FALSE; } else return -1; if(neg_ctx->context) { if(neg_ctx->gss != gss) { return -1; } } else { neg_ctx->protocol = protocol; neg_ctx->gss = gss; } if(neg_ctx->context && neg_ctx->status == GSS_S_COMPLETE) { /* We finished successfully our part of authentication, but server * rejected it (since we're again here). Exit with an error since we * can't invent anything better */ Curl_cleanup_negotiate(data); return -1; } if(neg_ctx->server_name == NULL && (ret = get_gss_name(conn, proxy, &neg_ctx->server_name))) return ret; header += strlen(neg_ctx->protocol); while(*header && ISSPACE(*header)) header++; len = strlen(header); if(len > 0) { error = Curl_base64_decode(header, (unsigned char **)&input_token.value, &rawlen); if(error || rawlen == 0) return -1; input_token.length = rawlen; #ifdef HAVE_SPNEGO /* Handle SPNEGO */ if(checkprefix("Negotiate", header)) { ASN1_OBJECT * object = NULL; unsigned char * spnegoToken = NULL; size_t spnegoTokenLength = 0; unsigned char * mechToken = NULL; size_t mechTokenLength = 0; if(input_token.value == NULL) return CURLE_OUT_OF_MEMORY; spnegoToken = malloc(input_token.length); if(spnegoToken == NULL) return CURLE_OUT_OF_MEMORY; spnegoTokenLength = input_token.length; object = OBJ_txt2obj ("1.2.840.113554.1.2.2", 1); if(!parseSpnegoTargetToken(spnegoToken, spnegoTokenLength, NULL, NULL, &mechToken, &mechTokenLength, NULL, NULL)) { free(spnegoToken); spnegoToken = NULL; infof(data, "Parse SPNEGO Target Token failed\n"); } else { free(input_token.value); input_token.value = malloc(mechTokenLength); if(input_token.value == NULL) return CURLE_OUT_OF_MEMORY; memcpy(input_token.value, mechToken,mechTokenLength); input_token.length = mechTokenLength; free(mechToken); mechToken = NULL; infof(data, "Parse SPNEGO Target Token succeeded\n"); } } #endif } major_status = Curl_gss_init_sec_context(data, &minor_status, &neg_ctx->context, neg_ctx->server_name, GSS_C_NO_CHANNEL_BINDINGS, &input_token, &output_token, NULL); if(input_token.length > 0) gss_release_buffer(&minor_status2, &input_token); neg_ctx->status = major_status; if(GSS_ERROR(major_status)) { /* Curl_cleanup_negotiate(data) ??? */ log_gss_error(conn, minor_status, "gss_init_sec_context() failed: "); return -1; } if(output_token.length == 0) { return -1; } neg_ctx->output_token = output_token; /* conn->bits.close = FALSE; */ return 0; } CURLcode Curl_output_negotiate(struct connectdata *conn, bool proxy) { struct negotiatedata *neg_ctx = proxy?&conn->data->state.proxyneg: &conn->data->state.negotiate; char *encoded = NULL; size_t len = 0; char *userp; CURLcode error; #ifdef HAVE_SPNEGO /* Handle SPNEGO */ if(checkprefix("Negotiate", neg_ctx->protocol)) { ASN1_OBJECT * object = NULL; unsigned char * spnegoToken = NULL; size_t spnegoTokenLength = 0; unsigned char * responseToken = NULL; size_t responseTokenLength = 0; responseToken = malloc(neg_ctx->output_token.length); if(responseToken == NULL) return CURLE_OUT_OF_MEMORY; memcpy(responseToken, neg_ctx->output_token.value, neg_ctx->output_token.length); responseTokenLength = neg_ctx->output_token.length; object=OBJ_txt2obj ("1.2.840.113554.1.2.2", 1); if(!makeSpnegoInitialToken (object, responseToken, responseTokenLength, &spnegoToken, &spnegoTokenLength)) { free(responseToken); responseToken = NULL; infof(conn->data, "Make SPNEGO Initial Token failed\n"); } else { free(responseToken); responseToken = NULL; free(neg_ctx->output_token.value); neg_ctx->output_token.value = malloc(spnegoTokenLength); if(neg_ctx->output_token.value == NULL) { free(spnegoToken); spnegoToken = NULL; return CURLE_OUT_OF_MEMORY; } memcpy(neg_ctx->output_token.value, spnegoToken,spnegoTokenLength); neg_ctx->output_token.length = spnegoTokenLength; free(spnegoToken); spnegoToken = NULL; infof(conn->data, "Make SPNEGO Initial Token succeeded\n"); } } #endif error = Curl_base64_encode(conn->data, neg_ctx->output_token.value, neg_ctx->output_token.length, &encoded, &len); if(error) { Curl_safefree(neg_ctx->output_token.value); neg_ctx->output_token.value = NULL; return error; } if(len == 0) { Curl_safefree(neg_ctx->output_token.value); neg_ctx->output_token.value = NULL; return CURLE_REMOTE_ACCESS_DENIED; } userp = aprintf("%sAuthorization: %s %s\r\n", proxy ? "Proxy-" : "", neg_ctx->protocol, encoded); if(proxy) conn->allocptr.proxyuserpwd = userp; else conn->allocptr.userpwd = userp; free(encoded); Curl_cleanup_negotiate (conn->data); return (userp == NULL) ? CURLE_OUT_OF_MEMORY : CURLE_OK; } static void cleanup(struct negotiatedata *neg_ctx) { OM_uint32 minor_status; if(neg_ctx->context != GSS_C_NO_CONTEXT) gss_delete_sec_context(&minor_status, &neg_ctx->context, GSS_C_NO_BUFFER); if(neg_ctx->output_token.length != 0) gss_release_buffer(&minor_status, &neg_ctx->output_token); if(neg_ctx->server_name != GSS_C_NO_NAME) gss_release_name(&minor_status, &neg_ctx->server_name); memset(neg_ctx, 0, sizeof(*neg_ctx)); } void Curl_cleanup_negotiate(struct SessionHandle *data) { cleanup(&data->state.negotiate); cleanup(&data->state.proxyneg); } #endif #endif
mpl-2.0
jifeon/bem-core
desktop.blocks/page/page.tmpl-specs/50-conditions.html
490
<!DOCTYPE html> <html class="ua_js_no"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>Пример подключения es5-shims для IE</title> <script> (function(e,c){e[c]=e[c].replace(/(ua_js_)no/g,"$1yes");})(document.documentElement,"className"); </script> <!--[if lt IE 9]><script src="//yastatic.net/es5-shims/0.0.1/es5-shims.min.js"></script><![endif]--> </head> <body class="page"></body> </html>
mpl-2.0
pradeepchhetri/terraform
website/source/docs/providers/aws/r/route.html.markdown
2273
--- layout: "aws" page_title: "AWS: aws_route" sidebar_current: "docs-aws-resource-route|" description: |- Provides a resource to create a routing entry in a VPC routing table. --- # aws\_route Provides a resource to create a routing table entry (a route) in a VPC routing table. ~> **NOTE on Route Tables and Routes:** Terraform currently provides both a standalone [Route resource](route.html) and a Route Table resource with routes defined in-line. At this time you cannot use a Route Table with in-line routes in conjunction with any Route resources. Doing so will cause a conflict of rule settings and will overwrite rules. ## Example usage: ``` resource "aws_route" "r" { route_table_id = "rtb-4fbb3ac4" destination_cidr_block = "10.0.1.0/22" vpc_peering_connection_id = "pcx-45ff3dc1" depends_on = ["aws_route_table.testing"] } ``` ## Argument Reference The following arguments are supported: * `route_table_id` - (Required) The ID of the routing table. * `destination_cidr_block` - (Required) The destination CIDR block. * `vpc_peering_connection_id` - (Optional) An ID of a VPC peering connection. * `gateway_id` - (Optional) An ID of a VPC internet gateway or a virtual private gateway. * `nat_gateway_id` - (Optional) An ID of a VPC NAT gateway. * `instance_id` - (Optional) An ID of an EC2 instance. * `network_interface_id` - (Optional) An ID of a network interface. Each route must contain either a `gateway_id`, a `nat_gateway_id`, an `instance_id` or a `vpc_peering_connection_id` or a `network_interface_id`. Note that the default route, mapping the VPC's CIDR block to "local", is created implicitly and cannot be specified. ## Attributes Reference The following attributes are exported: ~> **NOTE:** Only the target type that is specified (one of the above) will be exported as an attribute once the resource is created. * `route_table_id` - The ID of the routing table. * `destination_cidr_block` - The destination CIDR block. * `vpc_peering_connection_id` - An ID of a VPC peering connection. * `gateway_id` - An ID of a VPC internet gateway or a virtual private gateway. * `nat_gateway_id` - An ID of a VPC NAT gateway. * `instance_id` - An ID of a NAT instance. * `network_interface_id` - An ID of a network interface.
mpl-2.0
jcjones/boulder
vendor/github.com/zmap/zlint/v3/lints/cabf_br/lint_sub_cert_aia_missing.go
2127
package cabf_br /* * ZLint Copyright 2021 Regents of the University of Michigan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/v3/lint" "github.com/zmap/zlint/v3/util" ) type subCertAiaMissing struct{} /************************************************************************************************** BRs: 7.1.2.3 authorityInformationAccess With the exception of stapling, which is noted below, this extension MUST be present. It MUST NOT be marked critical, and it MUST contain the HTTP URL of the Issuing CA’s OCSP responder (accessMethod = 1.3.6.1.5.5.7.48.1). It SHOULD also contain the HTTP URL of the Issuing CA’s certificate (accessMethod = 1.3.6.1.5.5.7.48.2). See Section 13.2.1 for details. ***************************************************************************************************/ func init() { lint.RegisterLint(&lint.Lint{ Name: "e_sub_cert_aia_missing", Description: "Subscriber Certificate: authorityInformationAccess MUST be present.", Citation: "BRs: 7.1.2.3", Source: lint.CABFBaselineRequirements, EffectiveDate: util.CABEffectiveDate, Lint: NewSubCertAiaMissing, }) } func NewSubCertAiaMissing() lint.LintInterface { return &subCertAiaMissing{} } func (l *subCertAiaMissing) CheckApplies(c *x509.Certificate) bool { return !util.IsCACert(c) } func (l *subCertAiaMissing) Execute(c *x509.Certificate) *lint.LintResult { if util.IsExtInCert(c, util.AiaOID) { return &lint.LintResult{Status: lint.Pass} } else { return &lint.LintResult{Status: lint.Error} } }
mpl-2.0
maduhu/mycollab
mycollab-mobile/src/main/java/com/esofthead/mycollab/mobile/module/project/view/ProjectLoginPresenter.java
1424
/** * This file is part of mycollab-mobile. * * mycollab-mobile is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * mycollab-mobile 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 mycollab-mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.mobile.module.project.view; import com.esofthead.mycollab.mobile.mvp.AbstractPresenter; import com.esofthead.mycollab.vaadin.mvp.ScreenData; import com.vaadin.addon.touchkit.ui.NavigationManager; import com.vaadin.ui.ComponentContainer; /** * @author MyCollab Ltd. * * @since 4.4.0 * */ public class ProjectLoginPresenter extends AbstractPresenter<ProjectLoginView> { private static final long serialVersionUID = -750325026975907368L; public ProjectLoginPresenter() { super(ProjectLoginView.class); } @Override protected void onGo(ComponentContainer navigationManager, ScreenData<?> data) { ((NavigationManager) navigationManager).navigateTo(view.getWidget()); } }
agpl-3.0
LtRipley36706/ACE
Source/ACE.Server/Network/GameAction/Actions/GameActionUseItem.cs
470
using System; namespace ACE.Server.Network.GameAction.Actions { public static class GameActionUseItem { [GameAction(GameActionType.Use)] public static void Handle(ClientMessage message, Session session) { uint itemGuid = message.Payload.ReadUInt32(); //Console.WriteLine($"{session.Player.Name}.GameAction 0x36 - Use({itemGuid:X8})"); session.Player.HandleActionUseItem(itemGuid); } } }
agpl-3.0
BathnesDevelopment/processmaker-3.1.2.b2-community
workflow/engine/classes/class.reportTables.php
43778
<?php /** * class.reportTables.php * * @package workflow.engine.ProcessMaker * * ProcessMaker Open Source Edition * Copyright (C) 2004 - 2011 Colosa Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email [email protected]. * */ G::LoadClass( 'case' ); /** * ReportTables - Report tables class * * @package workflow.engine.ProcessMaker * @author Julio Cesar Laura Avenda�o * @copyright 2007 COLOSA */ class ReportTables { private $aDef = array ('mysql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' ),'pgsql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' ),'mssql' => array ('number' => 'FLOAT','char' => 'NVARCHAR(255)','text' => 'TEXT','date' => 'CHAR(19)' ) /* Changed DATETIME CHAR(19) for compatibility issues. */ ); //private $sPrefix = 'REP_'; private $sPrefix = ''; /** * Function deleteAllReportVars * This function delete all reports * * @access public * @param string $$sRepTabUid * @return void */ public function deleteAllReportVars ($sRepTabUid = '') { try { $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); ReportVarPeer::doDelete( $oCriteria ); } catch (Exception $oError) { throw ($oError); } } /** * Function prepareQuery * This function removes the table * * @access public * @param string $sTableName Table name * @param string $sConnection Conexion * @return void */ public function dropTable ($sTableName, $sConnection = 'report') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { case 'mysql': $rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`' ); break; case 'mssql': $rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL DROP TABLE [" . $sTableName . "]" ); break; } } catch (Exception $oError) { throw ($oError); } } /** * Function createTable * This Function creates the table * * @access public * @param string $sTableName Table name * @param string $sConnection Connection name * @param string $sType * @param array $aFields * @param string $bDefaultFields * @return void */ public function createTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { case 'mysql': $sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` ('; if ($bDefaultFields) { $sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,"; if ($sType == 'GRID') { $sQuery .= "`ROW` INT NOT NULL,"; } } foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; break; case 'char': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'text': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,"; break; case 'date': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NULL,"; break; } } if ($bDefaultFields) { $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } $sQuery .= ' DEFAULT CHARSET=utf8;'; $rs = $stmt->executeQuery( $sQuery ); break; case 'mssql': $sQuery = 'CREATE TABLE [' . $sTableName . '] ('; if ($bDefaultFields) { $sQuery .= "[APP_UID] VARCHAR(32) NOT NULL DEFAULT '', [APP_NUMBER] INT NOT NULL,"; if ($sType == 'GRID') { $sQuery .= "[ROW] INT NOT NULL,"; } } foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; break; case 'char': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'text': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'date': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NULL,"; break; } } if ($bDefaultFields) { $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } else { $sQuery .= ' '; } $rs = $stmt->executeQuery( $sQuery ); break; } } catch (Exception $oError) { throw ($oError); } } /** * Function populateTable * This Function fills the table * * @access public * @param string $sTableName Table name * @param string $sConnection Connection name * @param string $sType * @param array $aFields * @param string $sProcessUid * @param string $sGrid * @return void */ public function populateTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); if ($sType == 'GRID') { $aAux = explode( '-', $sGrid ); $sGrid = $aAux[0]; } try { switch (DB_ADAPTER) { case 'mysql': //select cases for this Process, ordered by APP_NUMBER $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { $aData = unserialize( $aRow['APP_DATA'] ); //delete previous record from this report table ( previous records in case this is a grid ) $deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'"; $rsDel = $stmt->executeQuery( $deleteSql ); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aData[$aField['sFieldName']] )) { $aData[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? @mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $value = (isset( $aData[$aField['sFieldName']] ) && trim( $aData[$aField['sFieldName']] )) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } else { if (isset( $aData[$sGrid] )) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $value = (isset( $aGridRow[$aField['sFieldName']] ) && trim( $aGridRow[$aField['sFieldName']] )) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } $oDataset->next(); } break; /** * For SQLServer code */ case 'mssql': $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { $aData = unserialize( $aRow['APP_DATA'] ); mysql_query( 'DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'" ); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER]'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aData[$aField['sFieldName']] )) { $aData[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? $aData[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } else { if (isset( $aData[$sGrid] )) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } $oDataset->next(); } break; } } catch (Exception $oError) { throw ($oError); } } /** * Function getTableVars * * @access public * @param string $sRepTabUid * @param boolean $bWhitType * @return void */ public function getTableVars ($sRepTabUid, $bWhitType = false) { try { $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); $oDataset = ReportVarPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); $aVars = array (); $aImportedVars = array (); //This array will help to control if the variable already exist while ($aRow = $oDataset->getRow()) { if ($bWhitType) { if (! in_array( $aRow['REP_VAR_NAME'], $aImportedVars )) { $aImportedVars[] = $aRow['REP_VAR_NAME']; $aVars[] = array ('sFieldName' => $aRow['REP_VAR_NAME'],'sType' => $aRow['REP_VAR_TYPE'] ); } } else { $aVars[] = $aRow['REP_VAR_NAME']; } $oDataset->next(); } return $aVars; } catch (Exception $oError) { throw ($oError); } } /** * Function deleteReportTable * This Function deletes report table * * @access public * @param string $sRepTabUid * @return void */ public function deleteReportTable ($sRepTabUid) { try { $oReportTable = new ReportTable(); $aFields = $oReportTable->load( $sRepTabUid ); if (! (empty( $aFields ))) { $this->dropTable( $aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION'] ); $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); $oDataset = ReportVarPeer::doDelete( $oCriteria ); $oReportTable->remove( $sRepTabUid ); } } catch (Exception $oError) { throw ($oError); } } /** * Function getSplitDate * This function gets the split date * * @access public * @param date $date * @param string $mask * @return array */ public function getSplitDate ($date, $mask) { $sw1 = false; for ($i = 0; $i < 3; $i ++) { $item = substr( $mask, $i * 2, 1 ); switch ($item) { case 'Y': switch ($i) { case 0: $d1 = substr( $date, 0, 4 ); break; case 1: $d1 = substr( $date, 3, 4 ); break; case 2: $d1 = substr( $date, 6, 4 ); break; } $sw1 = true; break; case 'y': switch ($i) { case 0: $d1 = substr( $date, 0, 2 ); break; case 1: $d1 = substr( $date, 3, 2 ); break; case 2: $d1 = substr( $date, 6, 2 ); break; } break; case 'm': switch ($i) { case 0: $d2 = substr( $date, 0, 2 ); break; case 1: $d2 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); break; case 2: $d2 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); break; } break; case 'd': switch ($i) { case 0: $d3 = substr( $date, 0, 2 ); break; case 1: $d3 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); break; case 2: $d3 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); break; } break; } } return Array (isset( $d1 ) ? $d1 : '',isset( $d2 ) ? $d2 : '',isset( $d3 ) ? $d3 : '' ); } /** * Function getFormatDate * This function returns the date formated * * @access public * @param date $sDate * @param date $sMask * @return date */ public function getFormatDate ($sDate, $sMask) { //print $sDate." *** ". $sMask."<BR>"; $dateTime = explode( " ", $sDate ); //To accept the Hour part $aDate = explode( '-', str_replace( "/", "-", $dateTime[0] ) ); $bResult = true; foreach ($aDate as $sDate) { if (! is_numeric( $sDate )) { $bResult = false; break; } } if ($sMask != '') { $aDate = $this->getSplitDate( $dateTime[0], $sMask ); $aDate[0] = ($aDate[0] == '') ? date( 'Y' ) : $aDate[0]; $aDate[1] = ($aDate[1] == '') ? date( 'm' ) : $aDate[1]; $aDate[2] = ($aDate[2] == '') ? date( 'd' ) : $aDate[2]; if (checkdate( $aDate[1], $aDate[2], $aDate[0] )) { } else { return false; } } $sDateC = ''; for ($i = 0; $i < count( $aDate ); $i ++) { $sDateC .= (($i == 0) ? "" : "-") . $aDate[$i]; } return ($sDateC); } /** * Function updateTables * This function updated the Report Tables * * @access public * @param string $sProcessUid * @param string $sApplicationUid * @param string $iApplicationNumber * @param string $aFields * @return void */ public function updateTables ($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) { try { $c = new Criteria('workflow'); $c->addSelectColumn(BpmnProjectPeer::PRJ_UID); $c->add(BpmnProjectPeer::PRJ_UID, $sProcessUid, Criteria::EQUAL); $ds = ProcessPeer::doSelectRS($c); $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); $ds->next(); $row = $ds->getRow(); $isBpmn = isset($row['PRJ_UID']); if (!class_exists('ReportTablePeer')) { require_once 'classes/model/ReportTablePeer.php'; } //get all Active Report Tables $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportTablePeer::PRO_UID, $sProcessUid ); $oCriteria->add( ReportTablePeer::REP_TAB_STATUS, 'ACTIVE' ); $oDataset = ReportTablePeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); $aVars = array (); while ($aRow = $oDataset->getRow()) { $aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME']; $PropelDatabase = $this->chooseDB( $aRow['REP_TAB_CONNECTION'] ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); switch (DB_ADAPTER) { case 'mysql': $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { $sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; $rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC ); $rsExists->next(); $aRow2 = $rsExists->getRow(); if (is_array( $aRow2 )) { $sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET '; foreach ($aTableFields as $aField) { $sQuery .= '`' . $aField['sFieldName'] . '` = '; if(!$isBpmn && !isset($aFields[$aField['sFieldName']])){ foreach($aFields as $row){ if(is_array($row) && isset($row[count($row)])){ $aFields = $row[count($row)]; } } } switch ($aField['sType']) { case 'number': $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } if (! isset( $aFields[$aField['sFieldName'] . '_label'] )) { $aFields[$aField['sFieldName'] . '_label'] = ''; } if(is_array($aFields[$aField['sFieldName']])){ $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']][0] : '') . "',"; }else{ $sQuery .= '\'' . ((isset($aFields[$aField['sFieldName']]))? @mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . '\','; } break; case 'date': $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { $mysqlDate = str_replace( '/', '-', $mysqlDate ); $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); } $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= $value . ","; break; } } $sQuery = substr( $sQuery, 0, - 1 ); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`'; foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { $mysqlDate = str_replace( '/', '-', $mysqlDate ); $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); } $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; } $rs = $stmt->executeQuery( $sQuery ); } else { //remove old rows from database $sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; $rsDelete = $stmt->executeQuery( $sqlDelete ); $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); if (isset( $aFields[$aAux[0]] )) { if (is_array($aFields[$aAux[0]])) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } } break; /** * For SQLServer code */ case 'mssql': $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { $oDataset2 = mssql_query( "SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); if ($aRow2 = mssql_fetch_row( $oDataset2 )) { $sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET '; foreach ($aTableFields as $aField) { $sQuery .= '[' . $aField['sFieldName'] . '] = '; switch ($aField['sType']) { case 'number': $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',"; break; case 'date': $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "',"; break; } } $sQuery = substr( $sQuery, 0, - 1 ); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER]'; foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; } $rs = $stmt->executeQuery( $sQuery ); } else { mysql_query( 'DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); if (isset( $aFields[$aAux[0]] )) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER],[ROW]'; foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } break; } $oDataset->next(); } } catch (Exception $oError) { throw ($oError); } } /** * Function tableExist * Check if table exists * * @access public * @return boolean */ public function tableExist () { /* $bExists = true; $oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS); mysql_select_db(DB_NAME); $oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false); return $bExists; */ $bExists = true; $sDataBase = 'database_' . strtolower( DB_ADAPTER ); if (G::LoadSystemExist( $sDataBase )) { G::LoadSystem( $sDataBase ); $oDataBase = new database(); $bExists = $oDataBase->reportTableExist(); } return $bExists; } /** * Function chooseDB * Choose the database to connect * * @access public * @param string $TabConnectionk * @return string */ public function chooseDB ($TabConnectionk) { $repTabConnection = trim( strtoupper( $TabConnectionk ) ); $PropelDatabase = 'rp'; if ($repTabConnection == '' || $repTabConnection == 'REPORT') { $PropelDatabase = 'rp'; } if ($repTabConnection == 'RBAC') { $PropelDatabase = 'rbac'; } if ($repTabConnection == 'WF') { $PropelDatabase = 'workflow'; } return ($PropelDatabase); } }
agpl-3.0
colosa/processmaker
vendor/league/oauth2-google/src/Provider/Google.php
4424
<?php namespace League\OAuth2\Client\Provider; use League\OAuth2\Client\Exception\HostedDomainException; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use League\OAuth2\Client\Token\AccessToken; use League\OAuth2\Client\Tool\BearerAuthorizationTrait; use Psr\Http\Message\ResponseInterface; class Google extends AbstractProvider { use BearerAuthorizationTrait; /** * @var string If set, this will be sent to google as the "access_type" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $accessType; /** * @var string If set, this will be sent to google as the "hd" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $hostedDomain; /** * @var string If set, this will be sent to google as the "prompt" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $prompt; /** * @var array List of scopes that will be used for authentication. * @link https://developers.google.com/identity/protocols/googlescopes */ protected $scopes = []; public function getBaseAuthorizationUrl() { return 'https://accounts.google.com/o/oauth2/v2/auth'; } public function getBaseAccessTokenUrl(array $params) { return 'https://oauth2.googleapis.com/token'; } public function getResourceOwnerDetailsUrl(AccessToken $token) { return 'https://openidconnect.googleapis.com/v1/userinfo'; } protected function getAuthorizationParameters(array $options) { if (empty($options['hd']) && $this->hostedDomain) { $options['hd'] = $this->hostedDomain; } if (empty($options['access_type']) && $this->accessType) { $options['access_type'] = $this->accessType; } if (empty($options['prompt']) && $this->prompt) { $options['prompt'] = $this->prompt; } // Default scopes MUST be included for OpenID Connect. // Additional scopes MAY be added by constructor or option. $scopes = array_merge($this->getDefaultScopes(), $this->scopes); if (!empty($options['scope'])) { $scopes = array_merge($scopes, $options['scope']); } $options['scope'] = array_unique($scopes); $options = parent::getAuthorizationParameters($options); // The "approval_prompt" MUST be removed as it is not supported by Google, use "prompt" instead: // https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt unset($options['approval_prompt']); return $options; } protected function getDefaultScopes() { // "openid" MUST be the first scope in the list. return [ 'openid', 'email', 'profile', ]; } protected function getScopeSeparator() { return ' '; } protected function checkResponse(ResponseInterface $response, $data) { // @codeCoverageIgnoreStart if (empty($data['error'])) { return; } // @codeCoverageIgnoreEnd $code = 0; $error = $data['error']; if (is_array($error)) { $code = $error['code']; $error = $error['message']; } throw new IdentityProviderException($error, $code, $data); } protected function createResourceOwner(array $response, AccessToken $token) { $user = new GoogleUser($response); $this->assertMatchingDomain($user->getHostedDomain()); return $user; } /** * @throws HostedDomainException If the domain does not match the configured domain. */ protected function assertMatchingDomain($hostedDomain) { if ($this->hostedDomain === null) { // No hosted domain configured. return; } if ($this->hostedDomain === '*' && $hostedDomain) { // Any hosted domain is allowed. return; } if ($this->hostedDomain === $hostedDomain) { // Hosted domain is correct. return; } throw HostedDomainException::notMatchingDomain($this->hostedDomain); } }
agpl-3.0
sanyaade-teachings/mobile-messaging
www/js/models/message.js
4522
define([ 'database', 'backbone' ], function (DB, Backbone) { var MessageModel = Backbone.Model.extend({ defaults: { messageId: 0, sender: '', title: '', content: '', hasAttachment: false, sendDate: new Date(), url: '' }, save: function (attributes) { var deferred = $.Deferred(); var self = this; var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request; if (!attributes) { request = store.add(this.toJSON()); } else { self.set(attributes); request = store.put(this.toJSON(), this.cid); } request.onsuccess = function (e) { if (!attributes) { self.cid = e.target.result; } deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getData: function (cid) { var self = this; var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ]); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.get(cid); request.onsuccess = function (e) { if (request.result) { var data = request.result; self.cid = cid; self.set(data); deferred.resolve(); } else { deferred.reject(); } }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getNext: function (currentKey) { var deferred = $.Deferred(); var range = IDBKeyRange.lowerBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range); request.onsuccess = function (e) { var nextMessage = null; var cursor = e.target.result; if (cursor) { nextMessage = new MessageModel(cursor.value); nextMessage.cid = cursor.primaryKey; } deferred.resolve(nextMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getPrevious: function () { var deferred = $.Deferred(); var range = IDBKeyRange.upperBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range, 'prev'); request.onsuccess = function (e) { var previousMessage = null; var cursor = e.target.result; if (cursor) { previousMessage = new MessageModel(cursor.value); previousMessage.cid = cursor.primaryKey; } deferred.resolve(previousMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, delete: function () { var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.clear(); request.onsuccess = function () { deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); } }); return MessageModel; });
agpl-3.0
sones/sones
Applications/TagExampleWithGraphMappingFramework/Example.cs
29686
/* * sones GraphDB - Community Edition - http://www.sones.com * Copyright (C) 2007-2011 sones GmbH * * This file is part of sones GraphDB Community Edition. * * sones GraphDB is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, version 3 of the License. * * sones GraphDB 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 sones GraphDB. If not, see <http://www.gnu.org/licenses/>. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IdentityModel.Selectors; using sones.GraphDSServer; using System.IdentityModel.Tokens; using System.Diagnostics; using sones.GraphDB; using sones.Library.VersionedPluginManager; using sones.GraphDS.PluginManager; using sones.Library.Commons.Security; using System.Net; using System.Threading; using sones.GraphDB.Manager.Plugin; using System.IO; using System.Globalization; using sones.Library.DiscordianDate; using System.Security.AccessControl; using sones.GraphDSServer.ErrorHandling; using sones.GraphDS.GraphDSRemoteClient; using sones.GraphDS.GraphDSRESTClient; using sones.GraphDB.TypeSystem; using sones.GraphDB.Request; using sones.Library.PropertyHyperGraph; using sones.GraphQL.Result; using sones.Library.Network.HttpServer; namespace TagExampleWithGraphMappingFramework { public class TagExampleWithGraphMappingFramework { #region sones GraphDB Startup private bool quiet = false; private bool shutdown = false; private IGraphDSServer _dsServer; private bool _ctrlCPressed; private IGraphDSClient GraphDSClient; private sones.Library.Commons.Security.SecurityToken SecToken; private long TransToken; public TagExampleWithGraphMappingFramework(String[] myArgs) { Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-us"); if (myArgs.Count() > 0) { foreach (String parameter in myArgs) { if (parameter.ToUpper() == "--Q") quiet = true; } } #region Start RemoteAPI, WebDAV and WebAdmin services, send GraphDS notification IGraphDB GraphDB; GraphDB = new SonesGraphDB(null, true, new CultureInfo("en-us")); #region Configure PlugIns // Plugins are loaded by the GraphDS with their according PluginDefinition and only if they are listed // below - there is no auto-discovery for plugin types in GraphDS (!) #region Query Languages // the GQL Query Language Plugin needs the GraphDB instance as a parameter List<PluginDefinition> QueryLanguages = new List<PluginDefinition>(); Dictionary<string, object> GQL_Parameters = new Dictionary<string, object>(); GQL_Parameters.Add("GraphDB", GraphDB); QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters)); #endregion #region GraphDS Service Plugins List<PluginDefinition> GraphDSServices = new List<PluginDefinition>(); #endregion List<PluginDefinition> UsageDataCollector = new List<PluginDefinition>(); #endregion GraphDSPlugins PluginsAndParameters = new GraphDSPlugins(QueryLanguages); _dsServer = new GraphDS_Server(GraphDB, PluginsAndParameters); #region Start GraphDS Services #region Remote API Service Dictionary<string, object> RemoteAPIParameter = new Dictionary<string, object>(); RemoteAPIParameter.Add("IPAddress", IPAddress.Parse("127.0.0.1")); RemoteAPIParameter.Add("Port", (ushort)9970); _dsServer.StartService("sones.RemoteAPIService", RemoteAPIParameter); #endregion #endregion #endregion #endregion #region Some helping lines... if (!quiet) { Console.WriteLine("This GraphDB Instance offers the following options:"); Console.WriteLine(" * If you want to suppress console output add --Q as a"); Console.WriteLine(" parameter."); Console.WriteLine(); Console.WriteLine(" * the following GraphDS Service Plugins are initialized and started: "); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(" * " + Service.PluginName); } Console.WriteLine(); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(Service.ServiceDescription); Console.WriteLine(); } Console.WriteLine("Enter 'shutdown' to initiate the shutdown of this instance."); } Run(); Console.CancelKeyPress += OnCancelKeyPress; while (!shutdown) { String command = Console.ReadLine(); if (!_ctrlCPressed) { if (command != null) { if (command.ToUpper() == "SHUTDOWN") shutdown = true; } } } Console.WriteLine("Shutting down GraphDS Server"); _dsServer.Shutdown(null); Console.WriteLine("Shutdown complete"); #endregion } #region Cancel KeyPress /// <summary> /// Cancel KeyPress /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public virtual void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; //do not abort Console here. _ctrlCPressed = true; Console.Write("Shutdown GraphDB (y/n)?"); string input; do { input = Console.ReadLine(); } while (input == null); switch (input.ToUpper()) { case "Y": shutdown = true; return; default: shutdown = false; return; } }//method #endregion #region the actual example public void Run() { GraphDSClient = new GraphDS_RemoteClient(new Uri("http://localhost:9970/rpc")); SecToken = GraphDSClient.LogOn(new RemoteUserPasswordCredentials("test", "test")); TransToken = GraphDSClient.BeginTransaction(SecToken); GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create types, create instances and additional work using the GraphDB API GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); Console.WriteLine("Press enter to start example"); Console.ReadLine(); GraphDBRequests(); #endregion //clear the DB (delete all created types) to create them again using the QueryLanguage GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create some types and insert values using the SonesQueryLanguage GraphQLQueries(); #endregion #region make some SELECTS SELECTS(); #endregion Console.WriteLine(); Console.WriteLine("Finished Example. Type a key to finish!"); Console.ReadKey(); } private void GraphDBRequests() { Console.WriteLine("performing DB requests..."); #region define type "Tag" //create a VertexTypePredefinition var Tag_VertexTypePredefinition = new VertexTypePredefinition("Tag"); //create property var PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Tag' named 'Name' and is of type 'String'"); //add property Tag_VertexTypePredefinition.AddProperty(PropertyName); //create outgoing edge to "Website" var OutgoingEdgesTaggedWebsites = new OutgoingEdgePredefinition("TaggedWebsites", "Website") .SetMultiplicityAsMultiEdge() .SetComment(@"This is an outgoing edge on type 'Tag' wich points to the type 'Website' (the AttributeType) and is defined as 'MultiEdge', which means that this edge can contain multiple single edges"); //add outgoing edge Tag_VertexTypePredefinition.AddOutgoingEdge(OutgoingEdgesTaggedWebsites); #endregion #region define type "Website" //create a VertexTypePredefinition var Website_VertexTypePredefinition = new VertexTypePredefinition("Website"); //create properties PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Website' named 'Name' and is of type 'String'"); var PropertyUrl = new PropertyPredefinition("URL", "String") .SetAsMandatory(); //add properties Website_VertexTypePredefinition.AddProperty(PropertyName); Website_VertexTypePredefinition.AddProperty(PropertyUrl); #region create an index on type "Website" on property "Name" //there are three ways to set an index on property "Name" //Beware: Use just one of them! //1. create an index definition and specifie the property- and type name var MyIndex = new IndexPredefinition("MyIndex").SetIndexType("SonesIndex").AddProperty("Name").SetVertexType("Website"); //add index Website_VertexTypePredefinition.AddIndex((IndexPredefinition)MyIndex); //2. on creating the property definition of property "Name" call the SetAsIndexed() method, the GraphDB will create the index //PropertyName = new PropertyPredefinition("Name") // .SetAttributeType("String") // .SetComment("This is a property on type 'Website' with name 'Name' and is of type 'String'") // .SetAsIndexed(); //3. make a create index request, like creating a type //BEWARE: This statement must be execute AFTER the type "Website" is created. //var MyIndex = GraphDSServer.CreateIndex<IIndexDefinition>(SecToken, // TransToken, // new RequestCreateIndex( // new IndexPredefinition("MyIndex") // .SetIndexType("SonesIndex") // .AddProperty("Name") // .SetVertexType("Website")), (Statistics, Index) => Index); #endregion //add IncomingEdge "Tags", the related OutgoingEdge is "TaggedWebsites" on type "Tag" Website_VertexTypePredefinition.AddIncomingEdge(new IncomingEdgePredefinition("Tags", "Tag", "TaggedWebsites")); #endregion #region create types by sending requests //create the types "Tag" and "Website" var DBTypes = GraphDSClient.CreateVertexTypes<IEnumerable<IVertexType>>(SecToken, TransToken, new RequestCreateVertexTypes( new List<VertexTypePredefinition> { Tag_VertexTypePredefinition, Website_VertexTypePredefinition }), (Statistics, VertexTypes) => VertexTypes); /* * BEWARE: The following two operations won't work because the two types "Tag" and "Website" depending on each other, * because one type has an incoming edge to the other and the other one has an incoming edge, * so they cannot be created separate (by using create type), * they have to be created at the same time (by using create types) * * //create the type "Website" * var Website = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Website_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); * * //create the type "Tag" * var Tag = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Tag_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); */ var Tag = DBTypes.Where(type => type.Name == "Tag").FirstOrDefault(); if (Tag != null) Console.WriteLine("Vertex Type 'Tag' created"); var Website = DBTypes.Where(type => type.Name == "Website").FirstOrDefault(); if(Website != null) Console.WriteLine("Vertex Type 'Website' created"); #endregion #region insert some Websites by sending requests var sones = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Sones") .AddStructuredProperty("URL", "http://sones.com/"), (Statistics, Result) => Result); var cnn = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "CNN") .AddStructuredProperty("URL", "http://cnn.com/"), (Statistics, Result) => Result); var xkcd = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "xkcd") .AddStructuredProperty("URL", "http://xkcd.com/"), (Statistics, Result) => Result); var onion = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "onion") .AddStructuredProperty("URL", "http://theonion.com/"), (Statistics, Result) => Result); //adding an unknown property means the property isn't defined before var test = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Test") .AddStructuredProperty("URL", "") .AddUnknownProperty("Unknown", "unknown property"), (Statistics, Result) => Result); if (sones != null) Console.WriteLine("Website 'sones' successfully inserted"); if (cnn != null) Console.WriteLine("Website 'cnn' successfully inserted"); if (xkcd != null) Console.WriteLine("Website 'xkcd' successfully inserted"); if (onion != null) Console.WriteLine("Website 'onion' successfully inserted"); if (test != null) Console.WriteLine("Website 'test' successfully inserted"); #endregion #region insert some Tags by sending requests //insert a "Tag" with an OutgoingEdge to a "Website" include that the GraphDB creates an IncomingEdge on the given Website instances //(because we created an IncomingEdge on type "Website") --> as a consequence we never have to set any IncomingEdge var good = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "good") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, cnn.VertexID) .AddVertexID(Website.ID, xkcd.VertexID)), (Statistics, Result) => Result); var funny = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "funny") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, xkcd.VertexID) .AddVertexID(Website.ID, onion.VertexID)), (Statistics, Result) => Result); if (good != null) Console.WriteLine("Tag 'good' successfully inserted"); if (funny != null) Console.WriteLine("Tag 'funny' successfully inserted"); #endregion #region how to get a type from the DB, properties of the type, instances of a specific type and read out property values //how to get a type from the DB var TagDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Tag.Name), (Statistics, Type) => Type); //how to get a type from the DB var WebsiteDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Website.Name), (Statistics, Type) => Type); //read informations from type var typeName = TagDBType.Name; //are there other types wich extend the type "Tag" var hasChildTypes = TagDBType.HasChildTypes; var hasPropName = TagDBType.HasProperty("Name"); //get the definition of the property "Name" var propName = TagDBType.GetPropertyDefinition("Name"); //how to get all instances of a type from the DB var TagInstances = GraphDSClient.GetVertices(SecToken, TransToken, new RequestGetVertices(TagDBType.Name), (Statistics, Vertices) => Vertices); foreach (var item in TagInstances) { //to get the value of a property of an instance, you need the property ID //(that's why we fetched the type from DB an read out the property definition of property "Name") var name = item.GetPropertyAsString(propName.ID); } Console.WriteLine("API operations finished..."); #endregion } #endregion #region Graph Query Language /// <summary> /// Describes how to send queries using the GraphQL. /// </summary> private void GraphQLQueries() { #region create types //create types at the same time, because of the circular dependencies (Tag has OutgoingEdge to Website, Website has IncomingEdge from Tag) //like shown before, using the GraphQL there are also three different ways to create create an index on property "Name" of type "Website" //1. create an index definition and specifie the property name and index type var Types = GraphDSClient.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (MyIndex INDEXTYPE SonesIndex ON ATTRIBUTES Name)", "sones.gql"); //2. on creating the type with the property "Name", just define the property "Name" under INDICES //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (Name)"); //3. make a create index query //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags)"); //var MyIndex = GraphQL.Query(SecToken, TransToken, "CREATE INDEX MyIndex ON VERTEX TYPE Website (Name) INDEXTYPE SonesIndex"); CheckResult(Types); #endregion #region create instances of type "Website" var cnnResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'CNN', URL = 'http://cnn.com/')", "sones.gql"); CheckResult(cnnResult); var xkcdResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'xkcd', URL = 'http://xkcd.com/')", "sones.gql"); CheckResult(xkcdResult); var onionResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'onion', URL = 'http://theonion.com/')", "sones.gql"); CheckResult(onionResult); //adding an unknown property ("Unknown") means the property isn't defined before var unknown = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'Test', URL = '', Unknown = 'unknown property')", "sones.gql"); CheckResult(onionResult); #endregion #region create instances of type "Tag" var goodResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'good', TaggedWebsites = SETOF(Name = 'CNN', Name = 'xkcd'))", "sones.gql"); CheckResult(goodResult); var funnyResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'funny', TaggedWebsites = SETOF(Name = 'xkcd', Name = 'onion'))", "sones.gql"); CheckResult(funnyResult); #endregion Console.WriteLine("GQL Queries finished..."); } /// <summary> /// Executes some select statements. /// </summary> private void SELECTS() { // find out which tags xkcd is tagged with var _xkcdtags = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Tags WHERE w.Name = 'xkcd' DEPTH 1", "sones.gql"); CheckResult(_xkcdtags); foreach (var _tag in _xkcdtags.Vertices) foreach (var edge in _tag.GetHyperEdge("Tags").GetAllEdges()) Console.WriteLine(edge.GetTargetVertex().GetPropertyAsString("Name")); // List tagged sites names and the count of there tags var _taggedsites = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Name, w.Tags.Count() AS Counter", "sones.gql"); CheckResult(_taggedsites); foreach (var _sites in _taggedsites.Vertices) Console.WriteLine("{0} => {1}", _sites.GetPropertyAsString("Name"), _sites.GetPropertyAsString("Counter")); // find out the URL's of the website of each Tag var _urls = GraphDSClient.Query(SecToken, TransToken, "FROM Tag t SELECT t.Name, t.TaggedWebsites.URL", "sones.gql"); CheckResult(_urls); foreach (var _tag in _urls.Vertices) foreach (var edge in _tag.GetHyperEdge("TaggedWebsites").GetAllEdges()) Console.WriteLine(_tag.GetPropertyAsString("Name") + " - " + edge.GetTargetVertex().GetPropertyAsString("URL")); Console.WriteLine("SELECT operations finished..."); } /// <summary> /// This private method analyses the QueryResult, shows the ResultType and Errors if existing. /// </summary> /// <param name="myQueryResult">The result of a query.</param> private bool CheckResult(IQueryResult myQueryResult) { if (myQueryResult.Error != null) { if (myQueryResult.Error.InnerException != null) Console.WriteLine(myQueryResult.Error.InnerException.Message); else Console.WriteLine(myQueryResult.Error.Message); return false; } else { Console.WriteLine("Query " + myQueryResult.TypeOfResult); return true; } } #endregion } public class sonesGraphDBStarter { static void Main(string[] args) { bool quiet = false; if (args.Count() > 0) { foreach (String parameter in args) { if (parameter.ToUpper() == "--Q") quiet = true; } } if (!quiet) { DiscordianDate ddate = new DiscordianDate(); Console.WriteLine("sones GraphDB version 2.0 - " + ddate.ToString()); Console.WriteLine("(C) sones GmbH 2007-2011 - http://www.sones.com"); Console.WriteLine("-----------------------------------------------"); Console.WriteLine(); Console.WriteLine("Starting up GraphDB..."); } try { var sonesGraphDBStartup = new TagExampleWithGraphMappingFramework(args); } catch (ServiceException e) { if (!quiet) { Console.WriteLine(e.Message); Console.WriteLine("InnerException: " + e.InnerException.ToString()); Console.WriteLine(); Console.WriteLine("Press <return> to exit."); Console.ReadLine(); } } } } }
agpl-3.0
kerr-huang/openss7
src/java/javax/telephony/Connection.java
22953
/* * Copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Please refer to the file "copyright.html" * for further important copyright and licensing information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package javax.telephony; import javax.telephony.capabilities.ConnectionCapabilities; /** * A <CODE>Connection</CODE> represents a link (i&#46e&#46 an association) between * a {@link Call} object and an {@link Address} object. * * <H4>Introduction</H4> * * The purpose of a Connection object is to describe * the relationship between a Call object and an Address object. A Connection * object exists if the Address is a part of the telephone call. Each * Connection has a <EM>state</EM> which describes the particular stage of the * relationship between the Call and Address. These states and their meanings * are described below. Applications use the <CODE>Connection.getCall()</CODE> * and <CODE>Connection.getAddress()</CODE> methods to obtain the Call and * Address associated with this Connection, respectively. * <p> * From one perspective, an application may view a Call only in terms of the * Address/Connection objects which are part of the Call. This is termed a * <EM>logical</EM> view of the Call because it ignores the details provided * by the Terminal and TerminalConnection objects which are also associated * with a Call. In many instances, simple applications (such as an * <EM>outcall</EM> program) may only need to concern itself with the logical * view. In this logical view, a telephone call is views as two or more * endpoint addresses in communication. The Connection object describes the * state of each of these endpoint addresses with respect to the Call. * * <H4>Calls and Addresses</H4> * * Connection objects are immutable in terms of their Call and Address * references. In other words, the Call and Address object references do * not change throughout the lifetime of the Connection object instance. The * same Connection object may not be used in another telephone call. The * existence of a Connection implies that its Address is associated with its * Call in the manner described by the Connection's state. * <p> * Although a Connection's Address and Call references remain valid throughout * the lifetime of the Connection object, the same is not true for the Call * and Address object's references to this Connection. Particularly, when a * Connection moves into the Connection.DISCONNECTED state, it is no longer * listed by the <CODE>Call.getConnections()</CODE> and * <CODE>Address.getConnections()</CODE> methods. Typically, when a Connection * moves into the <CODE>Connection.DISCONNECTED</CODE> state, the application * loses its references to it to facilitate its garbage collection. * * <H4>TerminalConnections</H4> * * Connections objects are containers for zero or more TerminalConnection * objects. Connection objects are containers for zero or more TerminalConnection * objects. Connection objects represent the relationship between the Call and * the Address, whereas TerminalConnection objects represent the relationship * between the Connection and the Terminal. The relationship between the Call and * the Address may be viewed as a logical view of the Call. The relationship * between a Connection and a Terminal represents the physical view of the * Call, i.e. at which Terminal the telephone calls terminates. The * TerminalConnection object specification provides further information. * * <H4>Connection States</H4> * * Below is a description of each Connection state in real-world terms. These * real-world descriptions have no bearing on the specifications of methods, * they only serve to provide a more intuitive understanding of what is going * on. Several methods in this specification state pre-conditions based upon * the state of the Connection. * <p> * <TABLE CELLPADDING=2> * * <TR> * <TD WIDTH="15%"><CODE>Connection.IDLE</CODE></TD> * <TD WIDTH="85%"> * This state is the initial state for all new Connections. Connections which * are in the <CODE>Connection.IDLE</CODE> state are not actively part of a * telephone call, yet their references to the Call and Address objects are * valid. Connections typically do not stay in the <CODE>Connection.IDLE</CODE> * state for long, quickly transitioning to other states. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.DISCONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies it is no longer part of the telephone call, although its * references to Call and Address still remain valid. A Connection in this * state is interpreted as once previously belonging to this telephone call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.INPROGRESS</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Connection, which represents the destination * end of a telephone call, is in the process of contacting the destination * side. Under certain circumstances, the Connection may not progress beyond * this state. Extension packages elaborate further on this state in various * situations. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.ALERTING</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Address is being notified of an incoming call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.CONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies that a Connection and its Address is actively part of a * telephone call. In common terms, two people talking to one another are * represented by two Connections in the <CODE>Connection.CONNECTED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.UNKNOWN</CODE></TD> * <TD WIDTH="85%"> * This state implies that the implementation is unable to determine the * current state of the Connection. Typically, methods are invalid on * Connections which are in this state. Connections may move in and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.FAILED</CODE></TD> * <TD WIDTH="85%"> * This state indicates that a Connection to that end of the call has failed * for some reason. One reason why a Connection would be in the * <CODE>Connection.FAILED</CODE> state is because the party was busy. * </TD> * </TR> * </TABLE> * * <H4>Connection State Transitions</H4> * * With these loose, real-world meanings in the back of one's mind, the * Connection class defines a finite-state diagram which describes the * allowable Connection state transitions. This finite-state diagram must be * guaranteed by the implementation. Each method which causes a change in * a Connection state must be consistent with this state diagram. This finite * state diagram is below: * <P> * Note there is a general left-to-right progression of the state transitions. * A Connection object may transition into and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time (hence, the asterisk * qualifier next to its bidirectional transition arrow). * <p> * <IMG SRC="doc-files/core-connectionstates.gif" ALIGN="center"> * </P> * * <H4>The Connection.disconnect() Method</H4> * * The primary method supported on the core package's Connection interface is * the <CODE>Connection.disconnect()</CODE> method. This method drops an entire * Connection from a telephone call. The result of this method is to move the * Connection object into the <CODE>Connection.DISCONNECTED</CODE> state. See * the specification of the <CODE>Connection.disconnect()</CODE> method on * this page for more detailed information. * * <H4>Listeners and Events</H4> * * All events pertaining to the Connection object are reported via the * <CODE>CallListener</CODE> interface on the Call object associated with this * Connection. In the core package, events are reported to a CallListener when * a new Connection is created and whenever a Connection changes state. * Listeners are added to Call objects via the <CODE>Call.addCallListener()</CODE> * method and more indirectly via the <CODE>Address.addCallListener()</CODE> * and <CODE>Terminal.addCallListener()</CODE> methods. See the specifications * for the Call, Address, and Terminal interfaces for more information. * <p> * The following Connection-related events are defined in the core package. * Each of these events extend the <CODE>ConnectionEvent</CODE> interface (which, in * turn, extends the <CODE>CallEvent</CODE> interface). * <p> * <TABLE CELLPADDING=2> * <TR> * <TD WIDTH="20%"><CODE>ConnectionCreated</CODE></TD> * <TD WIDTH="80%"> * Indicates a new Connection has been created on a Call. * </TD> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionInProgress</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.INPROGRESS</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionAlerting</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.ALERTING</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionConnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.CONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionDisconnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.DISCONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionFailed</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.FAILED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionUnknown</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.UNKNOWN</CODE> * state. * </TD> * </TR> * </TABLE> * <p> * @see javax.telephony.ConnectionEvent * @see javax.telephony.ConnectionListener * @version 04/05/99 1.48 */ public interface Connection { /** * The <CODE>Connection&#46IDLE</CODE> state is the initial state for all new * Connections. Connections which are in the Connection.IDLE state are not * actively part of a telephone call, yet their references to the Call and * Address objects are valid. Connections typically do not stay in the * <CODE>Connection.IDLE</CODE> state for long, quickly transitioning to * other states. */ public static final int IDLE = 0x30; /** * The <CODE>Connection&#46INPROGRESS</CODE> state implies that the Connection, * which represents the destination end of a telephone call, is in the * process of contacting the destination side. Under certain circumstances, * the Connection may not progress beyond this state. Extension packages * elaborate further on this state in various situations. */ public static final int INPROGRESS = 0x31; /** * The <CODE>Connection&#46ALERTING</CODE> state implies that the Address is * being notified of an incoming call. */ public static final int ALERTING = 0x32; /** * The <CODE>Connection&#46CONNECTED</CODE> state implies that a Connection and * its Address is actively part of a telephone call. In common terms, two * people talking to one another are represented by two Connections in the * <CODE>Connection.CONNECTED</CODE> state. */ public static final int CONNECTED = 0x33; /** * The <CODE>Connection&#46DISCONNECTED</CODE> state implies it is no longer * part of the telephone call, although its references to Call and Address * still remain valid. A Connection in the * <CODE>Connection.DISCONNECTED</CODE> state is interpreted as once * previously belonging to this telephone call. */ public static final int DISCONNECTED = 0x34; /** * The <CODE>Connection&#46FAILED</CODE> state indicates that a Connection to * that end of the call has failed for some reason. One reason why a * Connection would be in the <CODE>Connection.FAILED</CODE> state is * because the party was busy. */ public static final int FAILED = 0x35; /** * The <CODE>Connection&#46UNKNOWN</CODE> state implies that the implementation * is unable to determine the current state of the Connection. Typically, * method are invalid on Connections which are in the * <CODE>Connection.UNKNOWN</CODE> state. Connections may move in and out of * this state at any time. */ public static final int UNKNOWN = 0x36; /** * Returns the current state of the Connection. The return value will * be one of states defined above. * <p> * @return The current state of the Connection. */ public int getState(); /** * Returns the Call object associated with this Connection. This Call * reference remains valid throughout the lifetime of the Connection object, * despite the state of the Connection object. This Call reference does not * change once the Connection object has been created. * <p> * @return The call object associated with this Connection. */ public Call getCall(); /** * Returns the Address object associated with this Connection. This Address * object reference remains valid throughout the lifetime of the Connection * object despite the state of the Connection object. This Address reference * does not change once the Connection object has been created. * <p> * @return The Address associated with this Connection. */ public Address getAddress(); /** * Returns an array of TerminalConnection objects associated with this * Connection. TerminalConnection objects represent the relationship between * a Connection and a specific Terminal endpoint. There may be zero * TerminalConnections associated with this Connection. In that case, this * method returns null. Connection objects lose their reference to a * TerminalConnection once the TerminalConnection moves into the * <CODE>TerminalConnection.DROPPED</CODE> state. * <p> * <B>Post-conditions:</B> * <OL> * <LI>Let TerminalConnection tc[] = this.getTerminalConnections() * <LI>tc == null or tc.length >= 1 * <LI>For all i, tc[i].getState() != TerminalConnection.DROPPED * </OL> * @return An array of TerminalConnection objects associated with this * Connection, null if there are no TerminalConnections. */ public TerminalConnection[] getTerminalConnections(); /** * Drops a Connection from an active telephone call. The Connection's Address * is no longer associated with the telephone call. This method does not * necessarily drop the entire telephone call, only the particular * Connection on the telephone call. This method provides the ability to * disconnect a specific party from a telephone call, which is especially * useful in telephone calls consisting of three or more parties. Invoking * this method may result in the entire telephone call being dropped, which * is a permitted outcome of this method. In that case, the appropriate * events are delivered to the application, indicating that more than just * a single Connection has been dropped from the telephone call. * * <H5>Allowable Connection States</H5> * * The Connection object must be in one of several states in order for * this method to be successfully invoked. These allowable states are: * <CODE>Connection.CONNECTED</CODE>, <CODE>Connection.ALERTING</CODE>, * <CODE>Connection.INPROGRESS</CODE>, or <CODE>Connection.FAILED</CODE>. If * the Connection is not in one of these allowable states when this method is * invoked, this method throws InvalidStateException. Having the Connection * in one of the allowable states does not guarantee a successful invocation * of this method. * * <H5>Method Return Conditions</H5> * * This method returns successfully only after the Connection has been * disconnected from the telephone call and has transitioned into the * <CODE>Connection.DISCONNECTED</CODE>. This method may return * unsuccessfully by throwing one of the exceptions listed below. Note that * this method waits (i.e. the invocating thread blocks) until either the * Connection is actually disconnected from the telephone call or an error * is detected and an exception thrown. Also, all of the TerminalConnections * associated with this Connection are moved into the * <CODE>TerminalConnection.DROPPED</CODE> state. As a result, they are no * longer reported via the Connection by the * <CODE>Connection.getTerminalConnections()</CODE> method. * <p> * As a result of this method returning successfully, one or more events * are delivered to the application. These events are listed below: * <p> * <OL> * <LI>A ConnectionDisconnected event for this Connection. * <LI>A TerminalConnectionDropped event for all TerminalConnections associated with * this Connection. * </OL> * * <H5>Dropping Additional Connections</H5> * * Additional Connections may be dropped indirectly as a result of this * method. For example, dropping the destination Connection of a two-party * Call may result in the entire telephone call being dropped. It is up to * the implementation to determine which Connections are dropped as a result * of this method. Implementations should not, however, drop additional * Connections if it does not reflect the natural response of the underlying * telephone hardware. * <p> * Dropping additional Connections implies that their TerminalConnections are * dropped as well. Also, if all of the Connections on a telephone call are * dropped as a result of this method, the Call will move into the * <CODE>Call.INVALID</CODE> state. The following lists additional events * which may be delivered to the application. * <p> * <OL> * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * <B>Pre-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.CONNECTED or Connection.ALERTING * or Connection.INPROGRESS or Connection.FAILED * <LI>Let TerminalConnection tc[] = this.getTerminalConnections (see post- * conditions) * </OL> * <B>Post-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.DISCONNECTED * <LI>For all i, tc[i].getState() == TerminalConnection.DROPPED * <LI>this.getTerminalConnections() == null. * <LI>this is not an element of (this.getCall()).getConnections() * <LI>ConnectionDisconnected is delivered for this Connection. * <LI>TerminalConnectionDropped is delivered for all TerminalConnections associated * with this Connection. * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * @see javax.telephony.ConnectionListener * @see javax.telephony.ConnectionEvent * @exception PrivilegeViolationException The application does not have * the authority or permission to disconnected the Connection. For example, * the Address associated with this Connection may not be controllable in * the Provider's domain. * @exception ResourceUnavailableException An internal resource required * to drop a connection is not available. * @exception MethodNotSupportedException This method is not supported by * the implementation. * @exception InvalidStateException Some object required for the successful * invocation of this method is not in the proper state as given by this * method's pre-conditions. For example, the Provider may not be in the * Provider.IN_SERVICE state or the Connection may not be in one of the * allowable states. */ public void disconnect() throws PrivilegeViolationException, ResourceUnavailableException, MethodNotSupportedException, InvalidStateException; /** * Returns the dynamic capabilities for the instance of the Connection * object. Dynamic capabilities tell the application which actions are * possible at the time this method is invoked based upon the implementations * knowledge of its ability to successfully perform the action. This * determination may be based upon the current state of the call model * or some implementation-specific knowledge. These indications do not * guarantee that a particular method can be successfully invoked, however. * <p> * The dynamic Connection capabilities require no additional arguments. * <p> * @return The dynamic Connection capabilities. */ public ConnectionCapabilities getCapabilities(); /** * Gets the ConnectionCapabilities object with respect to a Terminal and * an Address. If null is passed as a Terminal parameter, the general/ * provider-wide Connection capabilities are returned. * <p> * <STRONG>Note:</STRONG> This method has been replaced in JTAPI v1.2. The * <CODE>Connection.getCapabilities()</CODE> method returns the dynamic * Connection capabilities. This method now should simply invoke the * <CODE>Connection.getCapabilities()</CODE> method. * <p> * @deprecated Since JTAPI v1.2. This method has been replaced by the * Connection.getCapabilities() method. * @param terminal This argument is ignored in JTAPI v1.2 and later. * @param address This argument is ignored in JTAPI v1.2 and later. * @exception InvalidArgumentException This exception is never thrown in * JTAPI v1.2 and later. * @exception PlatformException A platform-specific exception occurred. * @return The dynamic ConnectionCapabilities capabilities. */ public ConnectionCapabilities getConnectionCapabilities(Terminal terminal, Address address) throws InvalidArgumentException, PlatformException; }
agpl-3.0
paulijar/music
js/vendor/jquery-initialize/test.html
1540
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jquery.initialize test</title> <!-- Load MutationObserver and WeakMap polyfill for IE9 and 10 --> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="jquery.initialize.js"></script> </head> <body> <h2>We want every .initialize-me item to have color changed to blue by js - no matter how and when item with this class is added</h2> <div class="wrong-class"> This elem has .wrong-class and will not be initialized </div> <div class="initialize-me"> This class has .initialize-me class so it will be initialized </div> <button id="add-new">Add new item</button> <button id="change-class">Just add .initialize-me to .wrong-class</button> <p>You can even add item with .initialize-me class via browser inspector - proper js will be executed on it just when you finish edition.</p> <script> $(function() { // Deprecated API (does not work with jQuery >= 3.1.1): // $('.initialize-me').initialize(function() { // $(this).css('color', 'blue'); // }); $.initialize('.initialize-me', function() { $(this).css('color', 'blue'); }); $('#add-new').click(function(){ $('<div>').addClass('initialize-me').text('New item that was just appended to body and it’s color is automatically changed to blue without any additional js.').appendTo('body'); }); $('#change-class').click(function(){ $('.wrong-class').addClass('initialize-me'); }); }); </script> </body> </html>
agpl-3.0
nathb2b/mamasound.fr
App/config.js
1324
/* * Copyright (c) 2018. Wise Wild Web * * This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License * Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode * * @author : Nathanael Braun * @contact : [email protected] */ var cfg = require('$super'), p = (APP_PORT != 80) ? (":" + APP_PORT) : "", domain = (__LOCAL__ ? 'mamasound.fr.local' + p : 'mamasound.fr' + p), url = cfg.wwwDomain ? 'www.' + domain : domain; export default { ...require('$super'), PROJECT_NAME : "www.mamasound.fr", PUBLIC_URL : url, ROOT_DOMAIN : domain, API_URL : 'api.' + domain, UPLOAD_URL : 'upload.' + domain, STATIC_URL : 'static.' + domain, STATIC_REDIRECT_URL: __LOCAL__ && 'static.mamasound.fr', OSM_URL: "http://{s}.tile.osm.org/{z}/{x}/{y}.png", DB_URL : "mongodb://localhost:27017/www_mamasound_fr", UPLOAD_DIR : "./uploads/", CACHE_TM : 1000 * 60 * 2, SESSION_CHECK_TM: 1000 * 60 * 1, defaultRootMenuId: "Menu.HyInIUM8.html", htmlRefs: [ { "type": "script", "src" : "https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyA7XcGxipnIMdSSBJHn3tzeJe-fU3ilCak" }, ...(cfg.htmlRefs || []) ] };
agpl-3.0
benjaminsoellner/2015_Data_Analyst_Project_3
Project/audit_quality_map.py
3625
## Note: you must install Levenshtein module # pip install python-Levenshtein # for this Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27 # more info - see: http://stackoverflow.com/questions/18134437/where-can-the-documentation-for-python-levenshtein-be-found-online from pymongo import MongoClient import pymongo import pprint import bson import pandas import Levenshtein EXPECTED_STREET_PATTERN = \ u"^.*(?<![Ss]tra\u00dfe)(?<![Ww]eg)(?<![Aa]llee)(?<![Rr]ing)(?<![Bb]erg)" + \ u"(?<![Pp]ark)(?<![Hh]\u00f6he)(?<![Pp]latz)(?<![Bb]r\u00fccke)(?<![Gg]rund)$" def audit_streets(collection): return list(collection.distinct("name", { "type": "way", "name": {"$regex": EXPECTED_STREET_PATTERN} })) def audit_buildings(db): result = db.eval(''' db.osmnodes.ensureIndex({pos:"2dsphere"}); result = []; db.osmnodes.find( {"building": {"$exists": true}, "address.street": {"$exists": true}, "pos": {"$exists": true}}, {"address.street": "", "pos": ""} ).forEach(function(val, idx) { val.nearby = db.osmnodes.distinct("address.street", {"_id": {"$ne": val._id}, "pos": {"$near": {"$geometry": {"type": "Point", "coordinates": val.pos}, "$maxDistance": 50, "$minDistance": 0}}} ); result.push(val); }) return result; ''') df_list = [] for row in result: street_name = row["address"]["street"] nb_best_dist = None nb_best = "" nb_worst_dist = None nb_worst = "" for nearby_street in row["nearby"]: d = Levenshtein.distance(nearby_street, street_name) if nb_best_dist == None or d < nb_best_dist: nb_best_dist = d nb_best = nearby_street if nb_worst_dist == None or d > nb_worst_dist: nb_worst_dist = d nb_worst = nearby_street df_list += [{ "_id": row["_id"], "street_name": street_name, "num_nearby": len(row["nearby"]), "nb_best": nb_best, "nb_worst": nb_worst, "nb_best_dist": nb_best_dist, "nb_worst_dist": nb_worst_dist }] return pandas.DataFrame(df_list, columns=["_id", "street_name", "num_nearby", "nb_best", "nb_best_dist", "nb_worst", "nb_worst_dist"]) def audit_phone_numbers(collection): return list(collection.aggregate([ {"$match": {"$or": [ {"phone": {"$exists": True}}, {"mobile_phone": {"$exists": True}}, {"address.phone": {"$exists": True}} ]}}, {"$project": { "_id": 1, "phone": {"$ifNull": ["$phone", {"$ifNull": ["$mobile_phone", "$address.phone"]}]} }} ])) def audit_quality_map(mongoServer, mongoPort, csvFilePattern, csvEncoding): client = MongoClient(mongoServer + ":" + mongoPort) db = client.udacity c = client.udacity.osmnodes print print "Auditing way descriptions..." print "These are the 'unusual' street names" r = audit_streets(c) pprint.pprint(r) print print "Auditing streets close to buildings..." r = audit_buildings(db) r.to_csv(csvFilePattern.format("audit_buildings.csv"), encoding=csvEncoding) pprint.pprint(r) print print "Auditing phone numbers..." r = audit_phone_numbers(c) pprint.pprint(r)
agpl-3.0
openss7/openss7
src/perl/ss7view/Message.pm
315643
use constant { RT_UNKNOWN => 0, RT_14BIT_PC => 4, # also RL length in octets RT_24BIT_PC => 7, # also RL length in octets DX_UNKNOWN => 0, DX_HALF_DUPLEX => 1, DX_FULL_DUPLEX => 2, HT_UNKNOWN => 0, HT_BASIC => 3, # also link level header length HT_EXTENDED => 6, # also link level header length MP_UNKNOWN => 0, MP_JAPAN => 1, MP_NATIONAL => 2, MP_INTERNATIONAL => 3, SLL_DIR_RECEIVED => 0, # sent to us by somebody else SLL_DIR_BROADCAST => 1, # broadcast by somebody else SLL_DIR_MULTICAST => 2, # multicast by somebody else SLL_DIR_MONITOR => 3, # sent to somebody else by somebody else SLL_DIR_SENT => 4, # sent by us DLT_ETHERNET => 1, DLT_LINUX_SLL => 113, DLT_MTP2_WITH_PHDR => 139, PPI_M2PA => 5, PPI_M2UA => 2, PPI_M3UA => 3, PPI_SUA => 4, PORT_M2PA => 3565, PORT_M2UA => 2904, PORT_M3UA => 2905, PORT_SUA => 14001, CH_DATA => 0, CH_INIT => 1, CH_INIT_ACK => 2, CH_SACK => 3, CH_BEAT => 4, CH_BEAT_ACK => 5, CH_ABORT => 6, CH_SHUTDOWN => 7, CH_SHUTDOWN_ACK => 8, CH_ERROR => 9, CH_COOKIE_ECHO => 10, CH_COOKIE_ACK => 11, CH_SHUTDOWN_COMPLETE => 14, }; # ------------------------------------- package Decoder; # ------------------------------------- # A Decoder is a context for decoding messages. It contains information that is # not present in each message but is necessary for the decoding of all messages. # This can be used as a base class for other objects. # ------------------------------------- sub add_pdu { my ($self,$pdu,@args) = @_; my $meth = 'add_pdu_'.(split(/::/,ref $pdu))[-1]; return $sub->(@_) if my $sub = $self->can($meth); return unless my $sdu = $pdu->decode($self,@args); return $self->add_pdu($sdu,@args); } # ------------------------------------- package Decoder::Stream; our @ISA = qw(Decoder); # ------------------------------------- # An SCTP Stream decoder must maintain state information to reassemble SCTP data # chunks into messages. # ------------------------------------- #package Decoder::Stream; sub init { my $self = shift; my ($decoder,$chk) = @_; $self->{decoder} = $decoder; # parent decoder $self->{dir} = $chk->{dir}; $self->{stream} = $chk->{stream}; $self->{chunks} = []; $decoder->{streams}->{$self->{dir}}->{$self->{stream}} = $self; } #package Decoder::Stream; sub fini { my $self = shift; delete $decoder->{streams}->{$self->{dir}}->{$self->{stream}} if my $decoder = $self->{decoder}; foreach (qw(decoder stream chunks)) { delete $self->{$_} } } #package Decoder::Stream; sub process_msg { my ($self,$chunks) = @_; my $decoder = $self->{decoder}; if (my $msg = Message::ULP->new($decoder,$chunks)) { $decoder->add_pdu($msg); } } #package Decoder::Stream; sub add_chk { my $self = shift; my ($chk,$oos) = @_; return if $chk->{flags} & 0x4; my $beg = (($chunk->{flags} & 0x2) != 0); my $end = (($chunk->{flags} & 0x1) != 0); if ($beg) { $self->{chunks} = []; $self->{ssn} = $chunk->{ssn}; if ($end) { $self->process_msg([$chunk]); } else { push @{$self->{chunks}},$chunk; } ($self->{beg},$self->{end}) = ($beg,$end); return; } if ($oos or $self->{ssn} != $chunk->{ssn}) { $self->{chunks} = []; return; } if ($end) { push @{$self->{chunks}}, $chunk; $self->process_msg($self->{chunks}); $self->{chunks} = []; } } # ------------------------------------- package Decoder::SCTP; our @ISA = qw(Decoder); # ------------------------------------- # An SCTP decoder must maintain state information to reassembled SCTP data # chunks into messages # ------------------------------------- #package Decoder::SCTP; sub init { my $self = shift; my $type = ref $self; my $pkt = pop; $self->{ppi} = $pkt->{ppi}; $self->{sport} = $pkt->{sport}; $self->{dport} = $pkt->{dport}; $self->{vtag} = $pkt->{vtag}; $self->{acks} = {0=>undef,1=>undef}; # cumm. acks $self->{tsns} = {0=>{}, 1=>{}, }; # data chunks $self->{streams} = {0=>{}, 1=>{}, }; # streams $self->{chunks} = {0=>[], 1=>[], }; # reassembled messages } #package Decoder::SCTP; sub fini { my $self = shift; foreach (qw(acks tsns streams chunks ulps)) { delete $self->{$_} } foreach (qw(ppi sport dport vtag)) { delete $self->{$_} } } #package Decoder::SCTP; sub add_chk { my ($self,$pdu,@args) = @_; my $meth = 'add_chk_'.(split(/::/,ref $pdu))[-1]; $sub->(@_) if my $sub = $self->can($meth); } #package Decoder::SCTP; sub tst_chk { my ($self,$pdu,@args) = @_; my $meth = 'tst_chk_'.(split(/::/,ref $pdu))[-1]; $sub->(@_) if my $sub = $self->can($meth); } #package Decoder::SCTP; sub add_pdu_SCTP { my ($self,$pdu) = (shift,shift); foreach (@{$pdu->{chunks}}) { $self->add_chk($_,@_); } } #package Decoder::SCTP; sub tst_pdu_SCTP { my ($self,$pdu) = (shift,shift); foreach (@{$pdu->{chunks}}) { return 1 if $self->tst_chk($pdu,$_,@_); } } #package Decoder::SCTP; sub add_chk_DATA { my ($self,$chk) = (shift,shift); my $dir = $chk->{dir}; $self->{acks}->{$dir} = $chk->{tsn} unless exists $self->{acks}->{$dir}; my $cumm = $self->{acks}->{$dir}; my $num = $chk->{tsn} - $cumm; return if $num <= 0; # duplicated or cleared TSN return if exists $self->{tsns}->{$dir}->{$num}; # duplicate not cleared TSN $self->{tsns}->{$dir}->{$num} = $chk; } #package Decoder::SCTP; sub add_chk_ack { my ($self,$chk) = @_; my $dir = $chk->{dir}^0x1; $self->{acks}->{$dir} = $chk->{cumm} unless exists $self->{acks}->{$dir}; my $cumm = $self->{acks}->{$dir}; my $ack = $chk->{cumm} - $cumm; return if $ack <= 0; # doesn't ack anything my $seq = undef; foreach my $num (sort {$a<=>$b} keys %{$self->{tsns}->{$dir}}) { $seq = $num unless defined $seq; my $c = delete $self->{tsns}->{$dir}->{$num}; if ($num <= $ack) { my $oos = ($seq != $num); # clear chunks numbered less than or equal to $ack my $stream = Decoder::Stream->new($self,$c,$dir) unless $stream = $self->{streams}->{$dir}->{$c->{stream}}; $stream->add_chk($c,$dir,$oos); } else { # renumber chunks in tsn queue to $num - $ack $self->{tsns}->{$dir}->{$num-$ack} = $c; } } } #package Decoder::SCTP; sub add_chk_SACK { return shift->add_chk_ack(@_); } #package Decoder::SCTP; sub add_chk_SHUTDOWN { return shift->add_chk_ack(@_); } #package Decoder::SCTP; sub tst_chk_DATA { my ($self,$pdu,$chk) = @_; unless (exists $self->{acks}->{0} or exists $self->{acks}->{1}) { # no data or ack chunk received yet, assume forward direction $pdu->{dir} = 0; return 1; } my $found = undef; for (my $dir = 0;$dir<2;$dir++) { next unless exists $self->{acks}->{$dir}; my $cumm = $self->{acks}->{$dir}; my $num = $chk->{tsn} - $cumm; # TSN would certainly have been filled in by fast-retransmit next if -30 > $num or $num > 30; # both match, cannot tell return if defined $found; $found = $dir; } if (defined $found) { $pdu->{dir} = $found; return 1; } } #package Decoder::SCTP; sub tst_chk_ack { my ($self,$pdu,$chk) = @_; unless (exists $self->{acks}->{0} or exists $self->{acks}->{1}) { # no data or ack chunk received yet, assume reverse direction $pdu->{dir} = 1; return 1; } my $found = undef; for (my $dir = 1;$dir>= 0;$dir--) { next unless exists $self->{acks}->{$dir}; my $cumm = $self->{acks}->{$dir}; my $ack = $chk->{cumm} - $cumm; # Cumm acks must be fairly close together next if -30 > $num or $num > 30; # both match, cannot tell return if defined $found; $found = $dir; } if (defined $found) { $pdu->{dir} = $found ^ 0x1; return 1; } } #package Decoder::SCTP; sub tst_chk_SACK { return shift->tst_chk_ack(@_); } #package Decoder::SCTP; sub tst_chk_SHUTDOWN { return shift->tst_chk_ack(@_); } # ------------------------------------- package Decoder::SCTP::M2PA; our @ISA = qw(Decoder::SCTP); package Decoder::SCTP::M2UA; our @ISA = qw(Decoder::SCTP); package Decoder::SCTP::M3UA; our @ISA = qw(Decoder::SCTP); package Decoder::SCTP::SUA; our @ISA = qw(Decoder::SCTP); # ------------------------------------- # ------------------------------------- package Frame; # ------------------------------------- #package Frame; sub testit { return 1; } #package Frame; sub try { my $self = {}; my $type = shift; bless $self,$type; my $pdu = shift; $self->{pdu} = $pdu; $self->{hdr} = $pdu->{hdr}; $self->{buf} = $pdu->{buf}; $self->{beg} = $pdu->{doff}; $self->{off} = $pdu->{doff}; $self->{end} = $pdu->{dend}; return $self->testit(@_); } #package Frame; sub detect { return; } #package Frame; sub unpack { my $self = shift; my ($decoder,$stop) = @_; my $type = 'Frame::Pcap'; bless $self,$type; return $self->unpack(@_) unless $stop and $self->isa($stop); return 0; } #package Frame; sub new { my $self = {}; my $type = shift; bless $self,$type; my $pdu = shift; $self->{pdu} = $pdu; $self->{hdr} = $pdu->{hdr}; $self->{buf} = $pdu->{buf}; $self->{beg} = $pdu->{doff}; $self->{off} = $pdu->{doff}; $self->{end} = $pdu->{dend}; return $self->unpack(@_); } #package Frame; sub decode { return undef; } #package Frame; sub dissect { my $self = shift; my ($decoder,$stop) = @_; my ($type,$ret) = (ref $self,undef); my @layers = (); bless $self,'Frame::Pcap'; while ($ret = $self->dissect(@_) and ref $self ne $type) { push @layers, $ret; last if $stop and $self->isa($stop); $type = ref $self; } return \@layers; } #package Frame; sub pbits { my ($val,$msk) = @_; my $s=' '; my $len = length($msk); my @v = unpack('C*',$val); my @m = unpack('C*',$msk); for (my $l=0;$l<$len;$l++,$s=' '.$s) { my ($bv,$bm) = (pop @v,pop @m); for (my $b=0;$b<8;$b++,$bm>>=1,$bv>>=1) { if ($bm&0x1) { if ($bv&0x1) { $s='1'.$s; } else { $s='0'.$s; } } else { $s='-'.$s; } } } return $s; } #package Frame; sub bytes { my ($val,$msk,$len) = @_; my $s=' '; for (my $l=0;$l<$len;$l++,$s=' '.$s) { for (my $b=0;$b<8;$b++,$msk>>=1) { if ($msk&0x1) { if ($val&0x1) { $s='1'.$s; } else { $s='0'.$s; } $val>>=1; } else { $s='-'.$s; } } } return $s; } #package Frame; sub spare { my ($val,$msk,$len) = @_; my $s = ' '; for (my $l=0;$l<$len;$l++,$s=' '.$s) { for (my $b=0;$b<8;$b++,$msk>>=1) { if ($msk&0x1) { if ($val&0x1) { $s='1'.$s; } else { $s='X'.$s; } $val>>=1; } else { $s='-'.$s; } } } return $s; } # ------------------------------------- package Frame::Pcap; our @ISA = qw(Frame); # ------------------------------------- sub new { my ($type,$src,$dlt,$buf,$hdr) = @_; my $self = { src=>$src, dlt=>$dlt, buf=>$buf, hdr=>$hdr, beg=>0, off=>0, end=>$hdr->{caplen}, }; bless $self,$type; return $self; } use constant { DLT_TYPES=>{ &::DLT_ETHERNET=>'Ethernet', &::DLT_LINUX_SLL=>'LinuxSLL', &::DLT_MTP2_WITH_PHDR=>'Mtp2WithPhdr', }, }; sub unpack { my $self = shift; my $type = DLT_TYPES->{$self->{dlt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self->upack(@_); } use constant { DLT_NAMES=>{ &::DLT_ETHERNET=>'DLT_ETHERNET', &::DLT_LINUX_SLL=>'DLT_LINUX_SLL', &::DLT_MTP2_WITH_PHDR=>'DLT_MTP2_WITH_PHDR', }, }; sub dissect { my $self = shift; my $name = DLT_NAMES->{$self->{dlt}}; return 'PCAP Header', [ [ undef, undef, 'Data Link Type', $name ], [ undef, undef, 'Package Length', $self->{hdr}->{len}], [ undef, undef, 'Capture Length', $self->{hdr}->{caplen}], [ undef, undef, 'Seconds', $self->{hdr}->{tv_sec} ], [ undef, undef, 'Microseconds', $self->{hdr}->{tv_usec} ], ], @_; } # ------------------------------------- package Frame::Pcap::Ethernet; our @ISA = qw(Frame::Pcap); # ------------------------------------- sub unpack { my $self = shift; return unless $self->{off} + 14 <= $self->{end}; $self->{dhwa} = substr(${$self->{buf}},$self->{off},6); $self->{off} += 6; $self->{shwa} = substr(${$self->{buf}},$self->{off},6); $self->{off} += 6; $self->{etyp} = unpack('n',substr(${$self->{buf}},$self->{off},2)); $self->{off} += 2; $self->{elen} = $self->{etyp}; $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; return $self; } sub decode { return new Frame::IEEE802(@_); } sub dissect { my $self = shift; my $off = $self->{beg}; return $self->SUPER::dissect('Ethernet header', [ [$off+ 0,Frame::pbits($self->{dhwa},$mask),'Dest Eth Addr',undef ], [$off+ 6,Frame::pbits($self->{shwa},$mask),'Srce Eth Addr',undef ], [$off+12,Frame::bytes($self->{etyp},0xffff,2),'Etype/Len',$self->{etyp}], ], @_,); } # ------------------------------------- package Frame::Pcap::LinuxSLL; our @ISA = qw(Frame::Pcap); # ------------------------------------- sub unpack { my $self = shift; return unless $self->{off} + 16 <= $self->{end}; ( $self->{from}, $self->{arph}, $self->{llen}, ) = unpack('nnn',substr(${$self->{buf}},$self->{off},6)); $self->{off} += 6; my $len = $self->{llen}; $len = 8 unless $self->{llen} <= 8; $self->{shwa} = substr(${$self->{buf}},$self->{off},$len); $self->{off} += 8; $self->{etyp} = unpack('n',substr(${$self->{buf}},$self->{off},2)); $self->{off} += 2; $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; return $self; } sub decode { return new Frame::IEEE802(@_); } sub dissect { my $self = shift; my $off = $self->{beg}; return unless $self->unpack(@_); my $len = $self->{llen}; $len = 8 unless $self->{llen} <= 8; my $mask = substr(pack('NN',0xffffffff,0xffffffff),0,$len); my $from = { ::SLL_DIR_RECEIVED => 'SLL_DIR_RECEIVED', ::SLL_DIR_BROADCAST => 'SLL_DIR_BROADCAST', ::SLL_DIR_MULTICAST => 'SLL_DIR_MULTICAST', ::SLL_DIR_MONITOR => 'SLL_DIR_MONITOR', ::SLL_DIR_SENT => 'SLL_DIR_SENT', }->{$self->{from}}; return $self->SUPER::dissect('Linux Cooked Header', [ [$off + 0, Frame::bytes($self->{from},0xffff,2),'From',$from], [$off + 2, Frame::bytes($self->{arph},0xffff,2),'Arp Hardware', sprintf('0x%04X',$self->{arph})], [$off + 4, Frame::bytes($self->{llen},0xffff,2),'Addr Length',$self->{llen}], [$off + 6, Frame::pbits($self->{shwa},$mask), 'Srce Addr',undef], [$off + 14, Frame::bytes($self->{etyp},0xffff,2),'Ethertype',sprintf('0x%04X',$self->{etype})], ],@_); } # ------------------------------------- package Frame::Pcap::Mtp2WithPhdr; our @ISA = qw(Frame::Pcap); # ------------------------------------- sub unpack { my $self = shift; return unless $self->{off} + 4 <= $self->{end}; ( $self->{way}, $self->{xsn}, $self->{ppa}, ) = unpack('CCn',substr(${$self->{buf}},$self->{off},4)); $self->{off} += 4; $self->{dir} = (($self->{way} ^ 0x1) ^ 0x1); $self->{card} = ($self->{ppa} >> 7) & 0x3; $self->{span} = ($self->{ppa} >> 5) & 0x3; $self->{slot} = ($self->{ppa} >> 0) & 0x1f; $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; return $self; } sub decode { return new Message::MTP2(@_); } sub dissect { my $self = shift; my $off = 0; return $self->SUPER::dissect('MTP2 Pseudo-header', [ [$off+ 0,Frame::bytes($self->{way},0xff000000,4),'Way',$way], [$off+ 0,Frame::bytes($self->{xsn},0x00ff0000,4),'Annex A',$xsn], [$off+ 0,Frame::bytes($self->{ppa},0x0000ffff,4),'PPA', "$self->{card}:$self->{span}:$self->{slot}"], ],@_); } # ------------------------------------- package Frame::IEEE802; our @ISA = qw(Frame); # ------------------------------------- use constant { ETHER_TYPES=>{ 0x0800=>'IP', 0x0806=>'ARP', 0x8100=>'TPID', 0x88cc=>'LLDP', }, }; sub unpack { my $self = shift; my $pdu = $self->{pdu}; $self->{etyp} = $pdu->{etyp}; $self->{shwa} = $pdu->{shwa}; $self->{dhwa} = $pdu->{dhwa} if $pdu->{dhwa}; my $type = ETHER_TYPES->{$self->{etyp}}; if ($type eq 'TPID') { # priority/VLAN tagged frame return unless $self->{off} + 4 <= $self->{end}; ( $self->{tci}, $self->{etyp}, ) = unpack('nn',substr(${$self->{buf}},$self->{off},4)); $self->{off}+=4; $self->{upri} = ($self->{tci} >> 13) & 0x7; $self->{cfi} = ($self->{tci} >> 12) & 0x1; $self->{vlan} = ($self->{tci} >> 0) & 0x0fff; $type = ETHER_TYPES->{$self->{etyp}}; $type = undef if $type eq 'TPID'; } unless ($type) { bless $self,ref($self).'::LLC'; return $self->unpack(@_); } $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{beg}; if (exists $self->{vlan}) { return 'IEEE 802.1P Tag', [ [$off+0,Frame::bytes($self->{upri},0xe000,2),'User Priority',$self->{upri}], [$off+0,Frame::bytes($self->{cfi}, 0x1000,2),'CFI',$self->{cfi}], [$off+0,Frame::bytes($self->{vlan},0x0fff,2),'VLAN',$self->{vlan}], ],@_; } } # ------------------------------------- package Frame::IEEE802::IP; our @ISA = qw(Frame::IEEE802); # ------------------------------------- sub unpack { return $self } sub decode { return new Frame::IP(@_); } # ------------------------------------- package Frame::IEEE802::ARP; our @ISA = qw(Frame::IEEE802); # ------------------------------------- sub unpack { return $self } sub decode { return new Frame::ARP(@_); } # ------------------------------------- package Frame::IEEE802::LLDP; our @ISA = qw(Frame::IEEE802); # ------------------------------------- sub unpack { return $self } sub decode { return new Frame::LLDP(@_); } # ------------------------------------- package Frame::IEEE802::LLC; our @ISA = qw(Frame::IEEE802); # ------------------------------------- use constant { SNAP_HDR =>pack('CCC',0xaa,0xaa,0x03), NLPID_HDR =>pack('CCC',0xfe,0xfe,0x03), } sub unpack { my $self = shift; $self->{llc} = substr(${$self->{buf}},$self->{off},3); $self->{off} += 3; ( $self->{dsap}, $self->{ssap}, $self->{ctrl}, ) = unpack('CCC',$self->{llc}); if ($self->{llc} eq SNAP_HDR) { bless $self,ref($self).'::SNAP'; return $self->unpack(@_); } if ($self->{llc} eq NLPID_HDR) { bless $self,ref($self).'::NLPID'; return $self->unpack(@_); } return; } sub dissect { my $self = shift; my $off = $self->{beg}; my $dsap = sprintf('0x%02X',$self->{dsap}); my $ssap = sprintf('0x%02X',$self->{ssap}); return $self->SUPER::dissect('LLC Header', [ [$off+0,Frame::bytes($self->{dsap},0xff,1),'DSAP',$dsap], [$off+1,Frame::bytes($self->{ssap},0xff,1),'SSAP',$ssap], [$off+2,Frame::bytes($self->{ctrl},0xff,1),'Control','UI'], @_, ]); } # ------------------------------------- package Frame::IEEE802::LLC::SNAP; our @ISA = qw(Frame::IEEE802::LLC); # ------------------------------------- use constant { ETHER_TYPES=>{ 0x0800=>'IP', 0x0806=>'ARP', 0x88cc=>'LLDP', }, SNAP_OUI =>pack('CCC',0x00,0x80,0xc2), RFC1402_OUI =>pack('CCC',0x00,0x00,0x00), }; sub unpack { my $self = shift; $self->{snap} = $self->{llc}; $self->{oui} = substr(${$self->{buf}},$self->{off},3); $self->{off} += 3; return unless $self->{oui} eq SNAP_OUI or $self->{oui} eq RFC1402_OUI; $self->{etyp} = unpack('n',substr(${$self->{buf}},$self->{off},2)); $self->{off} += 2; $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; my $type = ETHER_TYPES->{$self->{etyp}}; return unless $type; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{beg} + 3; my $mask = pack('C*',0xff,0xff,0xff); my $oui = sprintf('%02X-%02X-%02X',unpack('C*',$self->{oui})); my $etyp = sprintf('%s(%04X)',ETHER_TYPES->{$self->{etyp}},$self->{etyp}); return $self->SUPER::dissect( [$off+0,Frame::pbits($self->{oui},$mask),'OUI',$oui], [$off+3,Frame::bytes($self->{etype},0xffff,2),'Ethertype',$etyp], @_); } # ------------------------------------- package Frame::IEEE802::LLC::SNAP::IP; our @ISA = qw(Frame::IEEE802::LLC::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::IP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::SNAP::ARP; our @ISA = qw(Frame::IEEE802::LLC::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::ARP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::SNAP::LLDP; our @ISA = qw(Frame::IEEE802::LLC::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::LLDP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID; our @ISA = qw(Frame::IEEE802::LLC); # ------------------------------------- use constant { NLPID_TYPES=>{ 0x80=>'SNAP', 0xCC=>'IP', }, }; sub unpack { my $self = shift; $self->{i802} = $self->{llc}; $self->{nlpid} = unpack('C',substr(${$self->{buf}},$self->{off},1)); $self->{off} += 1; my $type = NLPID_TYPES->{$self->{nlpid}}; return unless $type; if ($type eq 'SNAP') { bless $self,ref($self)."::$type"; return $self->unpack(@_); } elsif ($type eq 'IP') { $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; bless $self,ref($self)."::$type"; return $self; } } sub dissect { my $self = shift; my $off = $self->{beg} + 3; my $nlpid = sprintf('%s(%02X)',NLPID_TYPES->{$self->{nlpid}}, $self->{nlpid}); return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{nlpid},0xff,1),'NLPID',$nlpid], @_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID::IP; our @ISA = qw(Frame::IEEE802::LLC::NLPID); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::IP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID::SNAP; our @ISA = qw(Frame); # ------------------------------------- use constant { ETHER_TYPES=>{ 0x0800=>'IP', 0x0806=>'ARP', 0x88cc=>'LLDP', }, SNAP_OUI =>pack('CCC',0x00,0x80,0xc2), RFC1402_OUI =>pack('CCC',0x00,0x00,0x00), }; sub unpack { my $self = shift; $self->{oui} = substr(${$self->{buf}},$self->{off},3); $self->{off} += 3; return unless $self->{oui} eq SNAP_OUI or $self->{oui} eq RFC1402_OUI; $self->{etyp} = unpack('n',substr(${$self->{buf}},$self->{off},2)); $self->{off} += 2; my $type = ETHER_TYPES->{$etyp}; return unless $type; $self->{doff} = $self->{off}; $self->{dend} = $self->{end}; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{beg} + 4; my $oui = sprintf('%02X-%02X-%02X',unpack('C*',$self->{oui})); my $etyp = sprintf('%s(%04X)',ETHER_TYPES->{$self->{etyp}},$self->{etyp}); return $self->SUPER::dissect( [$off+0,Frame::pbits($self->{oui},$mask),'OUI',$oui], [$off+3,Frame::bytes($self->{etype},0xffff,2),'Ethertype',$etyp], @_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID::SNAP::IP; our @ISA = qw(Frame::IEEE802::LLC::NLPID::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::IP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID::SNAP::LLDP; our @ISA = qw(Frame::IEEE802::LLC::NLPID::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::LLDP(@_); } # ------------------------------------- package Frame::IEEE802::LLC::NLPID::SNAP::ARP; our @ISA = qw(Frame::IEEE802::LLC::NLPID::SNAP); # ------------------------------------- sub unpack { return shift } sub decode { return new Frame::ARP(@_); } # ------------------------------------- package Frame::ARP; our @ISA = qw(Frame); # ------------------------------------- sub unpack { my $self = shift; my $pdu = $self->{pdu}; $self->{shwa} = $pdu->{shwa}; $self->{dhwa} = $pdu->{dhwa} if $pdu->{dhwa}; return unless $self->{off} + 28 <= $self->{end}; ( $self->{arphrd}, $self->{arppro}, $self->{arphln}, $self->{arppln}, $self->{arpop}, ) = unpack('nnccn',substr($$self->{buf},$self->{off},8)); $self->{off} += 8; return unless $self->{arpop} == 1 or $self->{arpop} == 2; return unless $self->{arphdr} == 1; return unless $self->{arphln} == 6; return unless $self->{arppln} == 4; return unless $self->{arppro} == 0x0800; $self->{arpsha} = substr($$self->{buf},$self->{off},6); $self->{off} += 6; $self->{arpspa} = unpack('N',substr($$self->{buf},$self->{off},4)); $self->{off} += 4; $self->{arptha} = substr($$self->{buf},$self->{off},6); $self->{off} += 6; $self->{arptpa} = unpack('N',substr($$self->{buf},$self->{off},4)); $self->{off} += 4; return $self; } use constant { ARPOP_TYPE=>{ 0x1=>'Request', 0x2=>'Reply', }, }; sub dissect { my $self = shift; my $off = $self->{beg}; my $arpspa = sprintf('%d.%d.%d.%d', ($self->{arpspa}>>24)&0xff, ($self->{arpspa}>>16)&0xff, ($self->{arpspa}>> 8)&0xff, ($self->{arpspa}>> 0)&0xff); my $arptpa = sprintf('%d.%d.%d.%d', ($self->{arptpa}>>24)&0xff, ($self->{arptpa}>>16)&0xff, ($self->{arptpa}>> 8)&0xff, ($self->{arptpa}>> 0)&0xff); my $arpsha = sprintf('%02x:%02x:%02x:%02x:%02x:%02x', unpack('C*',$self->{arpsha})); my $arptha = sprintf('%02x:%02x:%02x:%02x:%02x:%02x', unpack('C*',$self->{arptha})); my $arpop = ARPOP_TYPE->{$self->{arpop}}."($self->{arpop})"; my $mask = pack('C*',0xff,0xff,0xff,0xff,0xff,0xff); return 'ARP', [ [$off+ 0,Frame::bytes($self->{arphrd},0xffff,2),'ar$hrd','Ethernet(1)',], [$off+ 2,Frame::bytes($self->{arppro},0xffff,2),'ar$pro','IP(0x0800)',], [$off+ 4,Frame::bytes($self->{arphln},0xff,1),'ar$hln',$self->{arphln},], [$off+ 5,Frame::bytes($self->{arppln},0xff,1),'ar$pln',$self->{arppln},], [$off+ 6,Frame::bytes($self->{arpop},0xffff,2),'ar$op',$arpop], [$off+ 8,Frame::pbits($self->{arpsha},$mask),'ar$sha',$arpsha], [$off+14,Frame::bytes($self->{arpspa},0xffffffff,4),$arpspa], [$off+18,Frame::pbits($self->{arptha},$mask),'ar$tha',$arptha], [$off+24,Frame::bytes($self->{arptpa},0xffffffff,4),$arptpa], ]; } # ------------------------------------- package Frame::LLDP; our @ISA = qw(Frame); # ------------------------------------- use constant { TAG_TYPE=>{ 0=>'End of LLDPDU', 1=>'Chassis ID', 2=>'Port ID', 3=>'Time To Live', 4=>'Port Description', 5=>'System Name', 6=>'System Description', 8=>'System Capabilities', 9=>'Management Address', 127=>'Organizationally Specific TLV', }, CHASSIS_ID_TYPE=>{ 1=>'Chassis component', 2=>'Interface alias', 3=>'Port component', 4=>'MAC address', 5=>'Network address', 6=>'Interface name', 7=>'Locally assigned', }, PORT_ID_TYPE=>{ 1=>'Interface alias', 2=>'Port component', 3=>'MAC address', 4=>'Network address', 5=>'Interface name', 6=>'Agent circuit ID', 7=>'Locally assigned', }, TAG_OUI=>{ 0x0080c2=>'IEEE 802.1', 0x00120f=>'IEEE 802.3', 0x0012bb=>'TIA', }, TAG_SUBTYPE=>{ 0x0080c201=>'Port VLAN ID', 0x0080c202=>'Port and Protocol VLAN ID', 0x0080c203=>'VLAN Name', 0x0080c204=>'Protocol Identity', 0x00120f01=>'MAC/PHY Configuration/Status', 0x00120f02=>'Power Via MDI', 0x00120f03=>'Link Aggregation', 0x00120f04=>'Maximum Frame Size', 0x0012bb01=>'Media Capabilities', 0x0012bb02=>'Network Policy', 0x0012bb03=>'Location Identification', 0x0012bb04=>'Extended Power-via-MDI', 0x0012bb05=>'Inventory - Hardware Revision', 0x0012bb06=>'Inventory - Firmware Revision', 0x0012bb07=>'Inventory - Software Revision', 0x0012bb08=>'Inventory - Serial Number', 0x0012bb09=>'Inventory - Manufacturer Name', 0x0012bb0a=>'Inventory - Model Name', 0x0012bb0b=>'Inventory - Asset ID', }, TIA_APP_TYPE=>{ 1=>'Voice', 2=>'Voice Signalling', 3=>'Guest Voice', 4=>'Guest Voice Signalling', 5=>'Softphone Voice', 6=>'Video Conferencing', 7=>'Streaming Video', 8=>'Video Signalling', }, TIA_LOC_TYPE=>{ 0=>'Invalid', 1=>'Coordiante-based LCI', # RFC 3825 lat,long,alt 2=>'Civic Address LCI', # draft-ietf-geopriv-dhcp-civil-05 3=>'ECS ELIN', # 10-digits in NA }, }; sub unpack { my $self = shift; my $pdu = $self->{pdu}; $self->{shwa} = $pdu->{shwa}; $self->{dhwa} = $pdu->{dhwa} if $pdu->{dhwa}; return unless $self->{off} + 2 <= $self->{end}; my ($tl,$tag,$len); $tl = unpack('n',substr($$self->{buf},$self->{off},2)); $self->{off} += 2; ($tag,$len) = (($tl>>9)&0x7f,($tl>>0)&0x1ff); return unless $tag == 1; # Chassis ID return unless $len >= 1; return unless $self->{off} + $len <= $self->{end}; $self->{chidtype} = unpack('C',substr($$self->{buf},$self->{off},1)); $self->{off} += 1; return unless exists CHASSIS_ID_TYPE->{$self->{chidtype}}; $self->{chid} = substr($$self->{buf},$self->{off},$len-1); $self->{off} += $len - 1; $tl = unpack('n',substr($$self->{buf},$self->{off},2)); $self->{off} += 2; ($tag,$len) = (($tl>>9)&0x7f,($tl>>0)&0x1ff); return unless $tag == 2; # Port ID return unless $len >= 1; return unless $self->{off} + $len <= $self->{end}; $self->{ptidtype} = unpack('C',substr($$self->{buf},$self->{off},1)); $self->{off} += 1; return unless exists PORT_ID_TYPE->{$self->{ptidtype}}; $self->{ptid} = substr($$self->{buf},$self->{off},$len-1); $self->{off} += $len - 1; $tl = unpack('n',substr($$self->{buf},$self->{off},2)); $self->{off} += 2; ($tag,$len) = (($tl>>9)&0x7f,($tl>>0)&0x1ff); return unless $tag == 3; # Time to live return unless $len == 2; return unless $self->{off} + $len <= $self->{end}; $self->{ttl} = unpack('n',substr($$self->{buf},$self->{off},2)); $self->{off} += 2; for (;;) { $tl = unpack('n',substr($$self->{buf},$self->{off},2)); $self->{off} += 2; ($tag,$len) = (($tl>>9)&0x7f,($tl>>0)&0x1ff); last if $tag == 0; return unless $self->{off} + $len <= $self->{end}; } } # ------------------------------------- package Frame::IP; our @ISA = qw(Frame); # ------------------------------------- use constant { IP_PROTOS=>{ 132=>'SCTP', }, }; sub unpack { my $self = shift; my $byte; ( $byte, $self->{dsn}, $self->{dlen}, $self->{ipid}, $self->{frag}, $self->{frago}, $self->{ttl}, $self->{ipproto}, $self->{ipcsum}, $self->{saddr}, $self->{daddr}, ) = unpack('CCnnCCCCnNN',substr(${$self->{buf}},$self->{off},20)); $self->{ipvers} = ($byte & 0xf0) >> 4; return if $self->{ipvers} != 4; $self->{iplen} = ($byte & 0x0f) << 2; return if $self->{iplen} < 20; $self->{doff} = $self->{off} + $self->{iplen}; $self->{dend} = $self->{doff} + $self->{dlen}; my $type = IP_PROTOS->{$self->{ipproto}}; return unless $type; return $self; } sub decode { return new Frame::SCTP(@_); } sub dissect { my $self = shift; my $off = $self->{beg}; my $saddr = sprintf('%d.%d.%d.%d', ($self->{saddr}>>24)&0xff, ($self->{saddr}>>16)&0xff, ($self->{saddr}>> 8)&0xff, ($self->{saddr}>> 0)&0xff); my $daddr = sprintf('%d.%d.%d.%d', ($self->{daddr}>>24)&0xff, ($self->{daddr}>>16)&0xff, ($self->{daddr}>> 8)&0xff, ($self->{daddr}>> 0)&0xff); my $ipproto = sprintf('%s(%d)',IP_PROTOS->{$self->{ipproto},$self->{ipproto}); return 'IP Header', [ [$off + 0, Frame::bytes($self->{ipvers},0xf0,1),'IP Version',$self->{ipvers}], [$off + 0, Frame::bytes($self->{iplen},0x0f,1),'Header Length',$self->{iplen}<<2], [$off + 1, Frame::bytes($self->{dsn},0xff,1),'DSN',undef], [$off + 2, Frame::bytes($self->{plen},0xffff,2),'Length',$self->{plen}], [$off + 4, Frame::bytes($self->{ipid},0xffff,2),'Id',sprintf('0x%04X',$self->{ipid})], [$off + 6, Frame::bytes($self->{frag},0xff,1),'Frag',undef], [$off + 7, Frame::bytes($self->{frago},0xff,1),'Frag Offset',$self->{frago}], [$off + 8, Frame::bytes($self->{ttl},0xff,1),'Time to live',$self->{ttl}], [$off + 9, Frame::bytes($self->{ipproto},0xff,1),'Protocol',$ipproto], [$off + 10, Frame::bytes($self->{ipcsum},0xffff,2),'Checksum',sprintf('0x%04X',$self->{ipcsum})], [$off + 12, Frame::bytes($self->{saddr},0xffffffff,4),'Srce Addr',$saddr], [$off + 16, Frame::bytes($self->{daddr},0xffffffff,4),'Dest Addr',$daddr], @_, ]; } # ------------------------------------- package Chunk; our @ISA = qw(Frame); # ------------------------------------- use constant { CHUNK_TYPES=>{ ::CH_DATA => 'DATA', ::CH_INIT => 'INIT', ::CH_INIT_ACK => 'INIT_ACK', ::CH_SACK => 'SACK', ::CH_BEAT => 'BEAT', ::CH_BEAT_ACK => 'BEAT_ACK', ::CH_ABORT => 'ABORT', ::CH_SHUTDOWN => 'SHUTDOWN', ::CH_SHUTDOWN_ACK => 'SHUTDOWN_ACK', ::CH_ERROR => 'ERROR', ::CH_COOKIE_ECHO => 'COOKIE_ECHO', ::CH_COOKIE_ACK => 'COOKIE_ACK', ::CH_SHUTDOWN_COMPLETE => 'SHUTDOWN_COMPLETE', } }; sub new { my $type = shift; my $self = {}; bless $self,$type; my $pdu = shift; ( $self->{type}, $self->{flags}, $self->{clen}, ) = unpack('CCn',substr($$pdu->{buf},$pdu->{off},4)); $self->{pdu} = $pdu; $self->{dir} = $pdu->{dir}; $self->{hdr} = $pdu->{hdr}; $self->{buf} = $pdu->{buf}; my $doff = $pdu->{off} + 4; my $dend = $pdu->{off} + $self->{clen}; $self->{off} = $doff; $self->{beg} = $doff; $self->{end} = $dend; $pdu->{off} += ($self->{clen}+3)&(~0x3); return unless exists CHUNK_TYPES->{$self->{type}}; my $type = CHUNK_TYPES->{$self->{type}}; bless $self,ref($self)."::$type"; return $self->unpack(@_); } sub dissect { my $self = shift; my $off = $self->{off}; my $type = CHUNK_TYPES->{$self->{type}}; return "$type Chunk", [ [$off+ 0, Frame::bytes($self->{type}, 0xff000000,1),'Type', $type ], [$off+ 0, Frame::bytes($self->{flags},0x00ff0000,1),'Flags', sprintf('0x%02X',$self->{flags}) ], [$off+ 0, Frame::bytes($self->{clen}, 0x0000ffff,2),'Length', $self->{clen} ], @_, ]; } # ------------------------------------- package Chunk::DATA; our @ISA = qw(Chunk); # ------------------------------------- use constant { PPI_TYPES=>{ 0=>'Unspecified', 2=>'M2UA', 3=>'M3UA', 4=>'SUA', 5=>'M2PA' } }; sub unpack { my $self = shift; ( $self->{tsn}, $self->{stream}, $self->{ssn}, $self->{ppi}, ) = unpack('NnnN',substr(${$self->{buf}},$self->{off},12)); $self->{off} += 12; $self->{pdu}->{ppi} = $self->{ppi}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $ppi = $self->{ppi}; $ppi = PPI_TYPES->{$ppi}."($ppi)" if exists PPI_TYPES->{$ppi}; return $self->SUPER::dissect( [$off+ 4,Frame::bytes($self->{tsn}, 0xffffffff,4),'TSN', sprintf('0x%08X',$self->{tsn})], [$off+ 8,Frame::bytes($self->{stream},0xffff0000,4),'Stream',$self->{stream}], [$off+ 8,Frame::bytes($self->{ssn}, 0x0000ffff,4),'SSN', $self->{ssn}], [$off+12,Frame::bytes($self->{ppi}, 0xffffffff,4),'PPI', $ppi], @_); } # ------------------------------------- package Chunk::SACK; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; ( $self->{cumm}, $self->{arwnd}, $self->{nacks}, $self->{ndups}, ) = unpack('NNnn',substr(${$self->{buf}},$self->{off},12)); $self->{off} += 12; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( [$off+ 4,Frame::bytes($self->{cumm}, 0xffffffff,4),'Cumm Ack',sprintf('0x%08X',$self->{cumm})], [$off+ 8,Frame::bytes($self->{arwnd},0xffffffff,4),'Ad Recv Win',$self->{arwnd}], [$off+12,Frame::bytes($self->{nacks},0xffff0000,4),'Gap Acks',$self->{nacks}], [$off+12,Frame::bytes($self->{ndups},0x0000ffff,4),'Duplicates',$self->{dups}], #TODO: dissect the gap acks @_); } # ------------------------------------- package Chunk::SHUTDOWN; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; my ($network,$pkt) = @_; $self->{cumm} = unpack('N',substr(${$self->{buf}},$self->{off},4)); $self->{off} += 4; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( [$off+ 4,Frame::bytes($self->{cumm}, 0xffffffff,4),'Cumm Ack',sprintf('0x%08X',$self->{cumm})], @_); } # ------------------------------------- package Chunk::INIT; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::INIT_ACK; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::BEAT; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::BEAT_ACK; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::ABORT; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::SHUTDOWN_ACK; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::ERROR; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::COOKIE_ECHO; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::COOKIE_ACK; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- package Chunk::SHUTDOWN_COMPLETE; our @ISA = qw(Chunk); # ------------------------------------- sub unpack { my $self = shift; $self->{data} = substr(${$self->{buf}},$self->{off},$self->{end}-$self->{off}); return $self; } # ------------------------------------- # ------------------------------------- package Frame::SCTP; our @ISA = qw(Frame); # ------------------------------------- use constant { SIGTRAN_PORTS=>{ &::PORT_M2PA => [ 'M2PA', ::PPI_M2PA ], &::PORT_M2UA => [ 'M2UA', ::PPI_M2UA ], &::PORT_M3UA => [ 'M3UA', ::PPI_M3UA ], &::PORT_SUA => [ 'SUA', ::PPI_SUA ], }, PPIS=>{ &::PPI_M2UA => 'M2UA', &::PPI_M3UA => 'M3UA', &::PPI_SUA => 'SUA', &::PPI_M2PA => 'M2PA', }, }; sub unpack { my $self = shift; ( $self->{sport}, $self->{dport}, $self->{vtag}, $self->{sctpcsum}, ) = unpack('nnNN',substr(${$self->{buf}},$self->{off},12)); $self->{off} += 12; $self->{chunks} = []; while ($self->{end} >= $self->{off} + 4) { my $chunk = new Chunk($self,@_); push @{$self->{chunks}}, $chunk if $chunk; } return $self; } sub testit { my $self = shift; return -1 unless $self->unpack(@_); my ($decoder) = @_; my $type = PPIS->{$self->{ppi}} if exists $self->{ppi} and exists PPIS->{$self->{ppi}}; if (!defined $type) { return -1 if exists $self->{ppi} and $self->{ppi} != 0; if (exists SIGTRAN_PORTS->{$self->{sport}}) { $type = SIGTRAN_PORTS->{$self->{sport}}->[0]; $self->{ppi} = SIGTRAN_PORTS->{$self->{sport}}->{1]; } if (exists SIGTRAN_PORTS->{$self->{dport}}) { $type = SIGTRAN_PORTS->{$self->{dport}}->[0]; $self->{ppi} = SIGTRAN_PORTS->{$self->{dport}}->{1]; } return unless defined $type; } $decoder->setppi($self->{ppi}); return 1; } sub hmmm { my $sub = ref($self); $sub =~ s/::/_/g; my $decoder = shift; $sub = $decoder->can($sub); return unless $sub; return $sub->($decoder,$self); my $assoc; if (defined $type) { $type = 'Association::'.$type; $assoc = $type->get(@_,$self); } else { $type = 'Association'; $assoc = $type->find(@_,$self); unless ($assoc) { warn "$self: cannot determine payload type"; return undef; } $self->{ppi} = $assoc->{ppi}; $type = ref $assoc; } my ($network) = @_; my $dir = exists $assoc->objb->{ips}->{$self->{saddr}} ? 1 : 0; $assoc->add_pkt($network,$self,$dir); if ($self->{shwa}) { Etherlink->get($network,$self->{shwa},$self->{dhwa},$self)->add_pkt($network,$self,0); Flow->get($network,$self->{shwa},$self->{saddr},$self)->add_pkt($network,$self,0); } if ($self->{dhwa}) { Etherlink->get($network,$self->{dhwa},$self->{shwa},$self)->add_pkt($network,$self,1); Flow->get($network,$self->{dhwa},$self->{daddr},$self)->add_pkt($network,$self,1); } return 1; } sub dissect { my $self = shift; my $off = $self->{sctp}->{off}; my $len = $self->{sctp}->{end} - $off; my $sport = $self->{sport}; $sport = SIGTRAN_PORTS->{$self->{sport}}->[0]."($sport)" if exists SIGTRAN_PORTS->{$self->{sport}}; my $dport = $self->{dport}; $dport = SIGTRAN_PORTS->{$self->{dport}}->[0]."($dport)" if exists SIGTRAN_PORTS->{$self->{dport}}; my @fields = ('SCTP Packet Header', [ [ $off + 0, Frame::bytes($self->{sport},0xffff0000,4), 'Srce Port', $sport ], [ $off + 0, Frame::bytes($self->{dport},0x0000ffff,4), 'Dest Port', $dport ], [ $off + 4, Frame::bytes($self->{vtag},0xffffffff,4), 'Verification Tag', sprintf('0x%08X',$self->{vtag})], [ $off + 8, Frame::bytes($self->{sctpcsum},0xffffffff,4), 'Checksum', sprintf('0x%08X',$self->{sctpcsum})], ]); foreach (@{$self->{chunks}}) { push @fields,$_->dissect(); } return @fields; } # ------------------------------------- package Message; our @ISA = qw(Frame); # ------------------------------------- sub mt { my $self = shift; my $type = ref $self; my @fields = split(/::/,$type); return $fields[2]; } sub unpack_MF { my ($self,$parm,$off,$len,$sub) = @_; return unless $off + $len <= $self->{end}; return unless $sub = $self->can("unpack_PT_$parm"); return $sub->($self,$off,$len); } sub unpack_MV { my ($self,$parm,$off,$ptr,$len,$sub) = @_; return unless $off < $self->{end}; $ptr = unpack('C',substr($$self->{buf},$off,1)) + $off; return unless $ptr < $self->{end}; $len = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; return unless $ptr + $len <= $self->{end}; return unless $sub = $self->can("unpack_PT_$parm"); return $sub->($self,$ptr,$len); } sub unpack_OP { my ($self,$off,$ptr,$sub) = @_; return unless $off < $self->{end}; $ptr = unpack('C',substr($$self->{buf},$off,1)); return 1 unless $ptr; # empty list $ptr += $off; return unless $ptr < $self->{end}; return unless $sub = $self->can('unpack_oparms'); return $sub->($self,$ptr); } # ------------------------------------- package Message::ULP; our @ISA = qw(Message); # ------------------------------------- #package Message::ULP; sub new { my $type = shift; my $self = {}; bless $self,$type; my ($decoder,$chks) = @_; my $pdu = $chks->[0]; $self->{pdus} = $chks; $self->{dat} = ''; $self->{pdu} = $pdu; $self->{hdr} = $pdu->{hdr}; $self->{buf} = \$self->{dat}; $self->{beg} = 0; $self->{off} = 0; $self->{end} = 0; $self->{dir} = $pdu->{dir}; $self->{stream} = $pdu->{stream}; $self->{ppi} = $decoder->{ppi}; foreach (@$chks) { $self->{dat} .= substr($$chk->{buf},$chk->{doff},$chk->{dlen}); $self->{end} += $chk->{dlen}; } $self->{li} = $self->{end}; return $self->unpack(@_); } use constant { SIGTRAN_TYPES=>{ 0=>['MGMT',{ 1=>'ERR', 2=>'NTFY', }], 1=>['XFER',{ 1=>'DATA', }], 2=>['SSNM',{ 1=>'DUNA', 2=>'DAVA', 3=>'DAUD', 4=>'SCON', 5=>'DUPU', 6=>'DRST', }], 3=>['ASPSM',{ 1=>'ASPUP_REQ', 2=>'ASPDN_REQ', 3=>'HBEAT_REQ', 4=>'ASPUP_ACK', 5=>'ASPDN_ACK', 6=>'HBEAT_ACK', }], 4=>['ASPTM',{ 1=>'ASPAC_REQ', 2=>'ASPIA_REQ', 3=>'ASPAC_ACK', 4=>'ASPIA_ACK', }], 5=>['QPTM',{ 1=>'Data_Request', 2=>'Data_Indication', 3=>'Unit_Data_Request', 4=>'Unit_Data_Indication', 5=>'Establish_Request', 6=>'Establish_Confirm', 7=>'Establish_Indication', 8=>'Release_Request', 9=>'Release_Confirm', 10=>'Release_Indication', }], 6=>['MAUP',{ 1=>'Data', 2=>'Establish_Request', 3=>'Establish_Confirm', 4=>'Release_Request', 5=>'Release_Confirm', 6=>'Release_Indication', 7=>'State_Request', 8=>'State_Confirm', 9=>'State_Indication', 10=>'Data_Retrieval_Request', 11=>'Data_Retrieval_Confirm', 12=>'Data_Retrieval_Indication', 13=>'Data_Retrieval_Complete_Indication', 14=>'Congestion_Indication', 15=>'Data_Acknowledge', }], 7=>['CL',{ 1=>'CLDT', 2=>'CLDR', }], 8=>['CO',{ 1=>'CORE', 2=>'COAK', 3=>'COREF', 4=>'RELRE', 5=>'RELCO', 6=>'RESCO', 7=>'RESRE', 8=>'CODT', 9=>'CODA', 10=>'COERR', 11=>'COIT', }], 9=>['RKM',{ 1=>'REG_REQ', 2=>'REG_RSP', 3=>'DEREG_REQ', 4=>'DEREG_RSP', }], 10=>['IIM',{ 1=>'REG_REQ', 2=>'REG_RSP', 3=>'DEREG_REQ', 4=>'DEREG_RSP', }], 11=>['M2PA',{ 1=>'DATA', 2=>'STATUS', }], }, }; sub unpack { my $self = shift; return if $self->{end} < $self->{off} + 8; ( $self->{vers}, $self->{resv}, $self->{clas}, $self->{type}, $self->{mlen}, ) = unpack('CCCCN',substr(${$self->{buf}},$self->{off},8)); return if $self->{end} < $self->{off} + $self->{mlen}; $self->{end} = $self->{off} + (($self->{mlen}+3)&(~0x3)); $self->{off} += 8; return if $self->{vers} != 1; return unless exists SIGTRAN_TYPES->{$self->{clas}}; my $clas = SIGTRAN_TYPES->{$self->{clas}}->[0]; return unless exists SIGTRAN_TYPES->{$self->{clas}}->[1]->{$self->{type}}; my $type = SIGTRAN_TYPES->{$self->{clas}}->[1]->{$self->{type}}; bless $self,ref($self)."::$clas\::$type"; return $self->unpack(@_); } use constant { PPI_TYPES=>{ 0=>'Unspecified', 2=>'M2UA', 3=>'M3UA', 4=>'SUA', 5=>'M2PA' } }; sub dissect { my $self = shift; my $off = 0; my $prot = PPI_TYPES->{$self->{ppi}}; my $clas = SIGTRAN_TYPES->{$self->{clas}}->[0]; my $type = SIGTRAN_TYPES->{$self->{clas}}->[1]->{$self->{type}}; return [ "$prot Header $clas\:$type", [$off + 0,Frame::bytes($self->{vers},0xff000000,1),'Version',"$prot($self->{vers})"], [$off + 0,Frame::bytes($self->{resv},0x00ff0000,1),'Reserved',$self->{resv}], [$off + 0,Frame::bytes($self->{clas},0x0000ff00,1),'Class',"$clas($self->{clas})"], [$off + 0,Frame::bytes($self->{type},0x000000ff,1),'Type',"$type($self->{type})"], [$off + 4,Frame::bytes($self->{mlen},0xffffffff,4),'Length',$self->{mlen}], ]; } use constant { ULP_PT_IIID =>0x0001, ULP_PT_TIID =>0x0003, ULP_PT_INFO =>0x0004, ULP_PT_RC =>0x0006, ULP_PT_DIAG =>0x0007, ULP_PT_RIID =>0x0008, ULP_PT_HBDATA =>0x0009, ULP_PT_TMODE =>0x000b, ULP_PT_ECODE =>0x000c, ULP_PT_STATUS =>0x000d, ULP_PT_ASPID =>0x0011, ULP_PT_APC =>0x0012, ULP_PT_CID =>0x0013, ULP_PT_RRESULT =>0x0014, ULP_PT_DRESULT =>0x0015, ULP_PT_RSTATUS =>0x0016, ULP_PT_DSTATUS =>0x0017, ULP_PT_KEYID =>0x0018, SUA_PT_HOPC =>0x0101, SUA_PT_SA =>0x0102, SUA_PT_DA =>0x0103, SUA_PT_SRN =>0x0104, SUA_PT_DRN =>0x0105, SUA_PT_CAUSE =>0x0106, SUA_PT_SEQNO =>0x0107, SUA_PT_RSEQNO =>0x0108, SUA_PT_ASPCAP =>0x0109, SUA_PT_CREDIT =>0x010a, SUA_PT_DATA =>0x010b, SUA_PT_UCAUSE =>0x010c, SUA_PT_NA =>0x010d, SUA_PT_RKEY =>0x010e, SUA_PT_DRNLAB =>0x010f, SUA_PT_TIDLAB =>0x0110, SUA_PT_RANGE =>0x0111, SUA_PT_SMI =>0x0112, SUA_PT_IMP =>0x0113, SUA_PT_PRIO =>0x0114, SUA_PT_PCLASS =>0x0115, SUA_PT_SEQCTL =>0x0116, SUA_PT_SEGM =>0x0117, SUA_PT_CONG =>0x0118, SUA_PT_GTI =>0x8001, SUA_PT_PC =>0x8002, SUA_PT_SSN =>0x8003, SUA_PT_IPV4 =>0x8004, SUA_PT_HOST =>0x8005, SUA_PT_IPV6 =>0x8006, M3UA_PT_NA =>0x0200, M3UA_PT_UCAUSE =>0x0204, M3UA_PT_CONG =>0x0205, M3UA_PT_CDEST =>0x0206, M3UA_PT_RKEY =>0x0207, M3UA_PT_RRESULT =>0x0208, M3UA_PT_DRESULT =>0x0209, M3UA_PT_KEYID =>0x020a, M3UA_PT_DPC =>0x020b, M3UA_PT_SI =>0x020c, M3UA_PT_OPCLIST =>0x020e, M3UA_PT_DATA =>0x0210, M3UA_PT_RSTATUS =>0x0212, M3UA_PT_DSTATUS =>0x0213, M2UA_PT_PDATA1 =>0x0300, M2UA_PT_PDATA2 =>0x0301, M2UA_PT_STATE =>0x0302, M2UA_PT_EVENT =>0x0303, M2UA_PT_CONGEST =>0x0304, M2UA_PT_DISCARD =>0x0305, M2UA_PT_ACTION =>0x0306, M2UA_PT_SEQNUM =>0x0307, M2UA_PT_RTVRES =>0x0308, M2UA_PT_LKEY =>0x0309, M2UA_PT_KEYID =>0x030a, M2UA_PT_SDTI =>0x030b, M2UA_PT_SDLI =>0x030c, M2UA_PT_RRESULT =>0x030d, M2UA_PT_RSTATUS =>0x030e, M2UA_PT_DRESULT =>0x030f, M2UA_PT_DSTATUS =>0x0310, }; sub unpack_ULP_UCAUS { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; ($self->{$lab}->{caus},$self->{$lab}->{user}) = unpack('nn',${$self->{buf}},$off,4); } sub unpack_ULP_LABEL { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; ($self->{$lab}->{beg},$self->{$lab}->{end},$self->{$lab}->{val}) = unpack('CCn',${$self->{buf}},$off,4); } sub unpack_ULP_PDATA { my ($self,$off,$end,$len,$lab) = @_; $self->{$lab} = substr(${$self->{buf}},$off,$len); } sub unpack_ULP_U8BIT { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; $self->{$lab} = unpack('N',${$self->{buf}},$off,4) & 0xff; } sub unpack_ULP_32BIT { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; $self->{$lab} = unpack('N',${$self->{buf}},$off,4); } sub unpack_ULP_32LST { my ($self,$off,$end,$len,$lab) = @_; while ($end >= $off + 4) { my $val = unpack('N',substr(${$self->{buf}},$off,4)); push @{$self->{$lab.'s'}},$val if $val; $off += 4; } } sub unpack_ULP_PCODE { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; $self->{$lab} = unpack('N',substr($$self->{buf},$off,4)) & 0xffffff; } sub unpack_ULP_PCLST { my ($self,$off,$end,$len,$lab) = @_; while ($end >= $off + 4) { my $val = unpack('N',substr($$self->{buf},$off,4)); my $spc = ($val >> 0) & 0xffffff; my $msk = ($val >> 24) & 0xff; push @{$self->{$lab.'s'}},[$msk,$val]; $off += 4; } } sub unpack_ULP_STRNG { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; $self->{$lab} = substr(${$self->{buf}},$off,$len); } sub unpack_ULP_CMPND { my ($self,$off,$end,$len,$lab) = @_; my $cmpnd = { off=>0, end=>$len, dat=>substr(${$self->{buf}},$off,$len) }; return unless Message::ULP::unpack_parms($cmpnd,@_); push @{$self->{$lab.'s'}}, $cmpnd; } sub unpack_ULP_ADDR { my ($self,$off,$end,$len,$lab) = @_; my $addr = { off=>4, end=>$len, dat=>substr(${$self->{buf}},$off,$len) }; ( $addr->{ri}, $addr->{ai}, ) = unpack('nn',substr(${$self->{buf}},$off,4)); return unless Message::ULP::unpack_parms($addr,@_); $self->{$lab} = $addr; } sub unpack_ULP_PT_IIID { my ($self,$off,$end,$len,$lab) = @_; while ($end >= $off + 4) { $self->{ctx} = substr(${$self->{buf}},$off,4); $self->{$lab} = unpack('N',$self->{ctx}); push @{$self->{ctxs}}, $self->{ctx}; push @{$self->{$lab.'s'}}, $self->{$lab}; $off += 4; } } sub unpack_ULP_PT_TIID { my ($self,$off,$end,$len,$lab) = @_; $self->{ctx} = substr(${$self->{buf}},$off,$len); $self->{$lab} = $self->{ctx}; push @{$self->{ctxs}}, $self->{ctx}; push @{$self->{$lab.'s'}}, $self->{$lab}; } sub unpack_ULP_PT_INFO { return shift->Message::ULP::unpack_ULP_PDATA(@_) } sub unpack_ULP_PT_RC { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; while ($end >= $off + 4) { $self->{ctx} = substr(${$self->{buf}},$off,4); $self->{$lab} = unpack('N',$self->{ctx}); push @{$self->{ctxs}}, $self->{ctx}; push @{$self->{$lab.'s'}}, $self->{$lab}; $off += 4; } } sub unpack_ULP_PT_DIAG { return shift->Message::ULP::unpack_ULP_PDATA(@_) } sub unpack_ULP_PT_RIID { my ($self,$off,$end,$len,$lab) = @_; while ($end >= $off + 8) { my ($beg,$fin) = unpack('NN',substr(${$self->{buf}},$off,8)); for (my $i = $beg; $i <= $fin; $i++) { $self->{ctx} = pack('N',$i); $self->{$lab} = $i; push @{$self->{ctxs}}, $self->{ctx}; push @{$self->{$lab.'s'}}, $self->{$lab}; } $off += 8; } } sub unpack_ULP_PT_HBDATA { return shift->Message::ULP::unpack_ULP_PDATA(@_) } sub unpack_ULP_PT_TMODE { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_ECODE { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_STATUS { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; ( $self->{$lab}->{type}, $self->{$lab}->{info}, ) = unpack('nn',${$self->{buf}},$off,4); } sub unpack_ULP_PT_ASPID { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_APC { return shift->Message::ULP::unpack_ULP_PCLST(@_) } sub unpack_ULP_PT_CID { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_RRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_ULP_PT_DRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_ULP_PT_RSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_DSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_ULP_PT_KEYID { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_HOPC { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_SA { return shift->Message::ULP::unpack_ULP_ADDR(@_) } sub unpack_SUA_PT_DA { return shift->Message::ULP::unpack_ULP_ADDR(@_) } sub unpack_SUA_PT_SRN { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_DRN { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_CAUSE { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; ( $self->{$lab}->{type}, $self->{$lab}->{valu}, ) = unpack('nn',${$self->{buf}},$off,4); } sub unpack_SUA_PT_SEQNO { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; my $val = unpack('N',substr(${$self->{buf}},$off,4)); $self->{$lab}->{rseqno} = ($val >> 9)&0x7f; $self->{$lab}->{sseqno} = ($val >> 0)&0xff; $self->{$lab}->{m} = ($val >> 8)&0x01; } sub unpack_SUA_PT_RSEQNO { return shift->Message::ULP::unpack_ULP_U8BIT(@_) } sub unpack_SUA_PT_ASPCAP { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; ($self->{$lab}->{spare},$self->{$lab}->{iwf},$self->{$lab}->{iw}) = unpack('nCC',substr(${$self->{buf}},$off,4)); } sub unpack_SUA_PT_CREDIT { return shift->Message::ULP::unpack_ULP_U8BIT(@_) } sub unpack_SUA_PT_DATA { my ($self,$off,$end,$len,$lab) = @_; $self->{doff} = $off; $self->{dlen} = $len; $self->{dend} = $off + $len; } sub unpack_SUA_PT_UCAUSE { return shift->Message::ULP::unpack_ULP_UCAUS(@_) } sub unpack_SUA_PT_NA { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_RKEY { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_SUA_PT_DRNLAB { return shift->Message::ULP::unpack_ULP_LABEL(@_) } sub unpack_SUA_PT_TIDLAB { return shift->Message::ULP::unpack_ULP_LABEL(@_) } sub unpack_SUA_PT_RANGE { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_SUA_PT_SMI { return shift->Message::ULP::unpack_ULP_U8BIT(@_) } sub unpack_SUA_PT_IMP { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_PRIO { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_PCLASS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_SEQCTL { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_SEGM { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 4; $self->{$lab}->{fr} = unpack('C',substr(${$self->{buf}},$off,1)); $self->{$lab}->{segref} = unpack('N',substr(${$self->{buf}},$off,4)) & 0xffffff; } sub unpack_SUA_PT_CONG { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_GTI { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 8; ( $self->{gti}, $self->{num}, $self->{tt}, $self->{np}, $self->{nai}, ) = unpack('NCCCC',substr(${$self->{buf}},$off,8)); $self->{digs} = substr(${$self->{buf}},$off+8,$len-8); } sub unpack_SUA_PT_PC { return shift->Message::ULP::unpack_ULP_PCODE(@_) } sub unpack_SUA_PT_SSN { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_IPV4 { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_SUA_PT_HOST { return shift->Message::ULP::unpack_ULP_STRNG(@_) } sub unpack_SUA_PT_IPV6 { return shift->Message::ULP::unpack_ULP_STRNG(@_) } sub unpack_M3UA_PT_NA { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M3UA_PT_UCAUSE { return shift->Message::ULP::unpack_ULP_UCAUS(@_) } sub unpack_M3UA_PT_CONG { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M3UA_PT_CDEST { return shift->Message::ULP::unpack_ULP_PCODE(@_) } sub unpack_M3UA_PT_RKEY { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M3UA_PT_RRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M3UA_PT_DRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M3UA_PT_KEYID { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M3UA_PT_DPC { return shift->Message::ULP::unpack_ULP_PCODE(@_) } sub unpack_M3UA_PT_SI { my ($self,$off,$end,$len,$lab) = @_; while ($end > $off) { my $val = unpack('C',substr(${$self->{buf}},$off,1)); push @{$self->{$lab.'s'}},$val if $val; $off++; } } sub unpack_M3UA_PT_OPCLIST { return shift->Message::ULP::unpack_ULP_32LST(@_) } sub unpack_M3UA_PT_DATA { my ($self,$off,$end,$len,$lab) = @_; return unless $len >= 12; ( $self->{opc}, $self->{dpc}, $self->{si}, $self->{ni}, $self->{mp}, $self->{sls}, ) = unpack('NNCCCC',substr(${$self->{buf}},$off,12)); $self->{doff} = $off + 12; $self->{dlen} = $len - 12; $self->{dend} = $off + $len; $self->{li} = $self->{dlen}; } sub unpack_M3UA_PT_RSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M3UA_PT_DSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_PDATA1 { my ($self,$off,$end,$len,$lab) = @_; $self->{doff} = $off; $self->{dlen} = $len; $self->{dend} = $off + $len; $self->{li} = $self->{dlen}; } sub unpack_M2UA_PT_PDATA2 { my ($self,$off,$end,$len,$lab) = @_; $self->{doff} = $off + 1; $self->{dlen} = $len - 1; $self->{dend} = $off + $len; $self->{li} = $self->{dlen}; $self->{li0} = unpack('C',substr(${$self->{buf}},$off,1)) >> 6; $self->{mp} = $self->{li0}; $self->{rt} = ::RT_24BIT_PC; $self->{pr} = ::MP_JAPAN; } sub unpack_M2UA_PT_STATE { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_EVENT { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_CONGEST { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_DISCARD { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_ACTION { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_SEQNUM { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_RTVRES { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_LKEY { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M2UA_PT_KEYID { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_SDTI { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_SDLI { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_RRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M2UA_PT_RSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } sub unpack_M2UA_PT_DRESULT { return shift->Message::ULP::unpack_ULP_CMPND(@_) } sub unpack_M2UA_PT_DSTATUS { return shift->Message::ULP::unpack_ULP_32BIT(@_) } use constant { ULP_PARMS_UNPACK=>{ &ULP_PT_IIID => [\&Message::ULP::unpack_ULP_PT_IIID, 'iiid' ], &ULP_PT_TIID => [\&Message::ULP::unpack_ULP_PT_TIID, 'tiid' ], &ULP_PT_INFO => [\&Message::ULP::unpack_ULP_PT_INFO, 'info' ], &ULP_PT_RC => [\&Message::ULP::unpack_ULP_PT_RC, 'rc' ], &ULP_PT_DIAG => [\&Message::ULP::unpack_ULP_PT_DIAG, 'diag' ], &ULP_PT_RIID => [\&Message::ULP::unpack_ULP_PT_RIID, 'riid' ], &ULP_PT_HBDATA => [\&Message::ULP::unpack_ULP_PT_HBDATA, 'hbdata' ], &ULP_PT_TMODE => [\&Message::ULP::unpack_ULP_PT_TMODE, 'tmode' ], &ULP_PT_ECODE => [\&Message::ULP::unpack_ULP_PT_ECODE, 'ecode' ], &ULP_PT_STATUS => [\&Message::ULP::unpack_ULP_PT_STATUS, 'status' ], &ULP_PT_ASPID => [\&Message::ULP::unpack_ULP_PT_ASPID, 'aspid' ], &ULP_PT_APC => [\&Message::ULP::unpack_ULP_PT_APC, 'apc' ], &ULP_PT_CID => [\&Message::ULP::unpack_ULP_PT_CID, 'cid' ], &ULP_PT_RRESULT => [\&Message::ULP::unpack_ULP_PT_RRESULT, 'rresult'], &ULP_PT_DRESULT => [\&Message::ULP::unpack_ULP_PT_DRESULT, 'dresult'], &ULP_PT_RSTATUS => [\&Message::ULP::unpack_ULP_PT_RSTATUS, 'rstatus'], &ULP_PT_DSTATUS => [\&Message::ULP::unpack_ULP_PT_DSTATUS, 'dstatus'], &ULP_PT_KEYID => [\&Message::ULP::unpack_ULP_PT_KEYID, 'keyid' ], &SUA_PT_HOPC => [\&Message::ULP::unpack_SUA_PT_HOPC, 'hopc' ], &SUA_PT_SA => [\&Message::ULP::unpack_SUA_PT_SA, 'sa' ], &SUA_PT_DA => [\&Message::ULP::unpack_SUA_PT_DA, 'da' ], &SUA_PT_SRN => [\&Message::ULP::unpack_SUA_PT_SRN, 'srn' ], &SUA_PT_DRN => [\&Message::ULP::unpack_SUA_PT_DRN, 'drn' ], &SUA_PT_CAUSE => [\&Message::ULP::unpack_SUA_PT_CAUSE, 'cause' ], &SUA_PT_SEQNO => [\&Message::ULP::unpack_SUA_PT_SEQNO, 'seqno' ], &SUA_PT_RSEQNO => [\&Message::ULP::unpack_SUA_PT_RSEQNO, 'rseqno' ], &SUA_PT_ASPCAP => [\&Message::ULP::unpack_SUA_PT_ASPCAP, 'aspcap' ], &SUA_PT_CREDIT => [\&Message::ULP::unpack_SUA_PT_CREDIT, 'credit' ], &SUA_PT_DATA => [\&Message::ULP::unpack_SUA_PT_DATA, 'data' ], &SUA_PT_UCAUSE => [\&Message::ULP::unpack_SUA_PT_UCAUSE, 'ucause' ], &SUA_PT_NA => [\&Message::ULP::unpack_SUA_PT_NA, 'na' ], &SUA_PT_RKEY => [\&Message::ULP::unpack_SUA_PT_RKEY, 'rkey' ], &SUA_PT_DRNLAB => [\&Message::ULP::unpack_SUA_PT_DRNLAB, 'drnlab' ], &SUA_PT_TIDLAB => [\&Message::ULP::unpack_SUA_PT_TIDLAB, 'tidlab' ], &SUA_PT_RANGE => [\&Message::ULP::unpack_SUA_PT_RANGE, 'range' ], &SUA_PT_SMI => [\&Message::ULP::unpack_SUA_PT_SMI, 'smi' ], &SUA_PT_IMP => [\&Message::ULP::unpack_SUA_PT_IMP, 'imp' ], &SUA_PT_PRIO => [\&Message::ULP::unpack_SUA_PT_PRIO, 'prio' ], &SUA_PT_PCLASS => [\&Message::ULP::unpack_SUA_PT_PCLASS, 'pclass' ], &SUA_PT_SEQCTL => [\&Message::ULP::unpack_SUA_PT_SEQCTL, 'seqctl' ], &SUA_PT_SEGM => [\&Message::ULP::unpack_SUA_PT_SEGM, 'segm' ], &SUA_PT_CONG => [\&Message::ULP::unpack_SUA_PT_CONG, 'cong' ], &SUA_PT_GTI => [\&Message::ULP::unpack_SUA_PT_GTI, 'gti' ], &SUA_PT_PC => [\&Message::ULP::unpack_SUA_PT_PC, 'pc' ], &SUA_PT_SSN => [\&Message::ULP::unpack_SUA_PT_SSN, 'ssn' ], &SUA_PT_IPV4 => [\&Message::ULP::unpack_SUA_PT_IPV4, 'ipv4' ], &SUA_PT_HOST => [\&Message::ULP::unpack_SUA_PT_HOST, 'host' ], &SUA_PT_IPV6 => [\&Message::ULP::unpack_SUA_PT_IPV6, 'ipv6' ], &M3UA_PT_NA => [\&Message::ULP::unpack_M3UA_PT_NA, 'na' ], &M3UA_PT_UCAUSE => [\&Message::ULP::unpack_M3UA_PT_UCAUSE, 'ucause' ], &M3UA_PT_CONG => [\&Message::ULP::unpack_M3UA_PT_CONG, 'cong' ], &M3UA_PT_CDEST => [\&Message::ULP::unpack_M3UA_PT_CDEST, 'cdest' ], &M3UA_PT_RKEY => [\&Message::ULP::unpack_M3UA_PT_RKEY, 'rkey' ], &M3UA_PT_RRESULT=> [\&Message::ULP::unpack_M3UA_PT_RRESULT,'rresult'], &M3UA_PT_DRESULT=> [\&Message::ULP::unpack_M3UA_PT_DRESULT,'dresult'], &M3UA_PT_KEYID => [\&Message::ULP::unpack_M3UA_PT_KEYID, 'keyid' ], &M3UA_PT_DPC => [\&Message::ULP::unpack_M3UA_PT_DPC, 'dpc' ], &M3UA_PT_SI => [\&Message::ULP::unpack_M3UA_PT_SI, 'si' ], &M3UA_PT_OPCLIST=> [\&Message::ULP::unpack_M3UA_PT_OPCLIST,'opclist'], &M3UA_PT_DATA => [\&Message::ULP::unpack_M3UA_PT_DATA, 'data' ], &M3UA_PT_RSTATUS=> [\&Message::ULP::unpack_M3UA_PT_RSTATUS,'rstatus'], &M3UA_PT_DSTATUS=> [\&Message::ULP::unpack_M3UA_PT_DSTATUS,'dstatus'], &M2UA_PT_PDATA1 => [\&Message::ULP::unpack_M2UA_PT_PDATA1, 'pdata1' ], &M2UA_PT_PDATA2 => [\&Message::ULP::unpack_M2UA_PT_PDATA2, 'pdata2' ], &M2UA_PT_STATE => [\&Message::ULP::unpack_M2UA_PT_STATE, 'state' ], &M2UA_PT_EVENT => [\&Message::ULP::unpack_M2UA_PT_EVENT, 'event' ], &M2UA_PT_CONGEST=> [\&Message::ULP::unpack_M2UA_PT_CONGEST,'congest'], &M2UA_PT_DISCARD=> [\&Message::ULP::unpack_M2UA_PT_DISCARD,'discard'], &M2UA_PT_ACTION => [\&Message::ULP::unpack_M2UA_PT_ACTION, 'action' ], &M2UA_PT_SEQNUM => [\&Message::ULP::unpack_M2UA_PT_SEQNUM, 'seqnum' ], &M2UA_PT_RTVRES => [\&Message::ULP::unpack_M2UA_PT_RTVRES, 'rtvres' ], &M2UA_PT_LKEY => [\&Message::ULP::unpack_M2UA_PT_LKEY, 'lkey' ], &M2UA_PT_KEYID => [\&Message::ULP::unpack_M2UA_PT_KEYID, 'keyid' ], &M2UA_PT_SDTI => [\&Message::ULP::unpack_M2UA_PT_SDTI, 'sdti' ], &M2UA_PT_SDLI => [\&Message::ULP::unpack_M2UA_PT_SDLI, 'sdli' ], &M2UA_PT_RRESULT=> [\&Message::ULP::unpack_M2UA_PT_RRESULT,'rresult'], &M2UA_PT_RSTATUS=> [\&Message::ULP::unpack_M2UA_PT_RSTATUS,'rstatus'], &M2UA_PT_DRESULT=> [\&Message::ULP::unpack_M2UA_PT_DRESULT,'dresult'], &M2UA_PT_DSTATUS=> [\&Message::ULP::unpack_M2UA_PT_DSTATUS,'dstatus'], }, }; sub unpack_parms { my $self = shift; while ($self->{off} + 4 <= $self->{end}) { my ($tag,$len) = unpack('nn',substr(${$self->{buf}},$self->{off},4)); my $off = $self->{off} + 4; my $end = $self->{off} + (($len+3)&(~0x3)); return if $end > $self->{end}; return unless $len >= 4; if (exists ULP_PARMS_UNPACK->{$tag}) { my @args = @{ULP_PARMS_UNPACK->{$tag}}; my $sub = shift @args; $sub->($self,$off,$end,$len-4,@args,@_); } $self->{off} = $end; } return if $self->{len} < $self->{off}; return 1; } sub dissect_ULP_PT_IIID { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end >= $off + 4) { my $val = unpack('N',${$self->{buf}},$off,4); push @fields, [$off,Frame::bytes($val,0xffffffff,4),'Int IID',$val]; } return \@fields; } sub dissect_ULP_PT_TIID { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','Text IID',Frame::ptext(substr(${$self->{buf}},$off,$len))], ]; } sub dissect_ULP_PT_INFO { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','INFO',Frame::ptext(substr(${$self->{buf}},$off,$len))], ]; } sub dissect_ULP_PT_RC { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end >= $off + 4) { my $val = unpack('N',${$self->{buf}},$off,4); push @fields, [$off,Frame::bytes($val,0xffffffff,4),'RC',$val]; } return \@fields; } sub dissect_ULP_PT_DIAG { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','DIAG',Frame::ptext(substr(${$self->{buf}},$off,$len))], ]; } sub dissect_ULP_PT_RIID { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end >= $off + 8) { my ($beg,$fin) = unpack('NN',substr(${$self->{buf}},$off,8)); push @fields, [$off+0,Frame::bytes($beg,0xffffffff,4),'IID Start',$beg], [$off+4,Frame::bytes($fin,0xffffffff,4),'IID Stop',$fin]; } return \@fields; } sub dissect_ULP_PT_HBDATA { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','HBDATA',Frame::pdata(substr(${$self->{buf}},$off,$len))], ]; } use constant { TMODE_TYPE=>{ 1=>'Override', 2=>'Loadshare', 3=>'Broadcast' } }; sub dissect_ULP_PT_TMODE { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $tmode = $val; $tmode = TMODE_TYPE->{$val}."($val)" if exists TMODE_TYPE->{$val}; return [ [$off,Frame::bytes($val,0xffffffff,4),'TMODE',$tmode] ]; } use constant { ECODE_TYPE=>{ 0x01=>'Invalid Version', 0x02=>'Invalid Interface Identifier', 0x03=>'Unsupported Message Class', 0x04=>'Unsupported Message Type', 0x05=>'Unsupported Traffic Mode Type', 0x06=>'Unexpected Message', 0x07=>'Protocol Error', 0x08=>'Unsupported Interface Identifier Type', 0x09=>'Invalid Stream Identifier', # 0x0a=>'Unassigned TEI', # IUA # 0x0b=>'Unrecognized SAPI', # IUA # 0x0c=>'Invalid TEI, SAPI Combination', # IUA 0x0d=>'Refused - Management Blocking', 0x0e=>'ASP Identifier Required', 0x0f=>'Invalid ASP Identifier', 0x10=>'ASP Active for Interface Identifiers', 0x11=>'Invalid Parameter Value', 0x12=>'Parameter Field Error', 0x13=>'Unexpected Parameter', 0x14=>'Destination Status Unknown', 0x15=>'Invalid Network Appearance', 0x16=>'Missing Parameter', # 0x17=>'', # 0x18=>'', 0x19=>'Invalid Routing Context', 0x1a=>'No Configured AS for ASP', 0x1b=>'Subsystem Status Unknown', 0x1c=>'Invalid Loadsharing Label', # 0x1c=>'Channel Number out of range', # DUA # 0x1d=>'Channel Number not configured', # DUA } }; sub dissect_ULP_PT_ECODE { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $ecode = $val; $ecode = "$val ('".ECODE_TYPE->{$val}."')" if exists ECODE_TYPE->{$val}; return [ [$off,Frame::bytes($val,0xffffffff,4),'ECODE',$ecode] ]; } use constant { STATUS_TYPES=>{ 1=>'AS-State_Change', 2=>'Other', }, STATUS_INFOS=>{ 0x00010001=>'Reserved', 0x00010002=>'AS-INACTIVE', 0x00010003=>'AS-ACTIVE', 0x00010004=>'AS-PENDING', 0x00020001=>'Insufficient ASPs Active in AS', 0x00020002=>'Alternate ASP Active', 0x00020003=>'ASP Failure', }, }; sub dissect_ULP_PT_STATUS { my ($self,$off,$end,$len) = @_; my ($val1,$val2) = unpack('nn',${$self->{buf}},$off,4); my $val0 = unpack('N',${$self->{buf}},$off,4); my $stype = $val1; $stype = $style." ('".STATUS_TYPES->{$val1}."')" if exists STATUS_TYPES->{$val1}; my $sinfo = $val2; $sinfo = $sinfo." ('".STATUS_INFOS->{$val0}."')" if exists STATUS_INFOS->{$val0}; return [ [$off,Frame::bytes($val1,0xffff0000,4),'Status Type',$stype], [$off,Frame::bytes($val2,0x0000ffff,4),'Status Info',$sinfo], ]; } sub dissect_ULP_PT_ASPID { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'ASPID',$val] ]; } sub dissect_ULP_PT_APC { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end >= $off + 4) { my $spa = unpack('C',substr(${$self->{buf}},$off,1)); my $val = unpack('N',substr(${$self->{buf}},$off,4)) & 0xffffff; my $apc = $val; if ($val&(~0x3fff)) { $apc = (($apc>>16)&0xff).'-'.(($apc>>8)&0xff).'-'.(($apc>>0)&0xff); push @fields, [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::bytes($val,0x00ffffff,4),'APC', $apc]; } else { $apc = (($apc>>11)&0x07).'-'.(($apc>>3)&0xff).'-'.(($apc>>0)&0x07); my $apc0 = ($apc >> 14) & 0x3ff; push @fields, [$off,Frame::spare($spa, 0xff000000,4),'Spare', $spa], [$off,Frame::spare($apc0,0x00ffc000,4),'Unused',$apc0], [$off,Frame::bytes($val, 0x00003fff,4),'APC', $apc]; } } return \@fields; } sub dissect_ULP_PT_CID { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'CORID',$val] ]; } sub dissect_ULP_PT_RRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_ULP_PT_DRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_ULP_PT_RSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Reg Status',$val] ]; } sub dissect_ULP_PT_DSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Dereg Status',$val] ]; } sub dissect_ULP_PT_KEYID { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Key ID',$val] ]; } sub dissect_SUA_PT_HOPC { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Hop Counter',$val] ]; } sub dissect_SUA_PT_SA { my ($self,$off,$end,$len) = @_; my ($val1,$val2) = unpack('nn',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val1,0xffff0000,4),'RI',$val1], [$off,Frame::bytes($val2,0x0000ffff,4),'AI',$val2], @{Message::ULP::dissect_parms($self,$off+4,$end,$len-4)}, ]; } sub dissect_SUA_PT_DA { my ($self,$off,$end,$len) = @_; my ($val1,$val2) = unpack('nn',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val1,0xffff0000,4),'RI',$val1], [$off,Frame::bytes($val2,0x0000ffff,4),'AI',$val2], @{Message::ULP::dissect_parms($self,$off+4,$end,$len-4)}, ]; } sub dissect_SUA_PT_SRN { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'SRN',$val] ]; } sub dissect_SUA_PT_DRN { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'DRN',$val] ]; } sub dissect_SUA_PT_CAUSE { my ($self,$off,$end,$len) = @_; my ($val1,$val2) = unpack('nn',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val1,0xffff0000,4),'Cause Type',$val1], [$off,Frame::bytes($val2,0x0000ffff,4),'Cause Value',$val2], ]; } sub dissect_SUA_PT_SEQNO { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); my $spare = ($val >> 16); my $rseqno = ($val >> 9)&0x7f; my $sseqno = ($val >> 0)&0xff; my $m = ($val >> 8)&0x01; return [ [$off,Frame::spare($spare, 0xffff0000,4),'Spare',$spare], [$off,Frame::bytes($rseqno,0x0000fe00,4),'Recv Seq No',$rseqno], [$off,Frame::bytes($m, 0x00000100,4),'M',$m], [$off,Frame::bytes($sseqno,0x000000ff,4),'Send Seq No',$sseqno], ]; } sub dissect_SUA_PT_RSEQNO { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); my $spare = $val >> 8; my $rseqno = $val & 0xff; return [ [$off,Frame::spare($spare, 0xffffff00,4),'Spare',$spare], [$off,Frame::bytes($rseqno,0x000000ff,4),'Recv Seq No',$rseqno], ]; } sub dissect_SUA_PT_ASPCAP { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); $iw = ($val >> 0) & 0xff; $iwf = ($val >> 8) & 0xff; $spa = ($val >>16); return [ [$off,Frame::spare($spa,0xffff0000,4),'Spare',$spa], [$off,Frame::bytes($iwf,0x0000ff00,4),'I/W Flags',$iwf], [$off,Frame::bytes($iw, 0x000000ff,4),'I/W',$iw], ]; } sub dissect_SUA_PT_CREDIT { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spare = $val >> 8; my $credit = $val & 0xff; return [ [$off,Frame::spare($spare, 0xffffff00,4),'Spare',$spare], [$off,Frame::bytes($credit,0x000000ff,4),'Credit',$credit], ]; } sub dissect_SUA_PT_DATA { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','Data',Frame::pdata(substr(${$self->{buf}},$off,$len))] ]; } sub dissect_SUA_PT_UCAUSE { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $caus = ($val >> 16) & 0xffff; my $user = ($val >> 0) & 0xffff; return [ [$off,Frame::bytes($caus,0xffff0000,4),'Cause',$caus], [$off,Frame::bytes($user,0x0000ffff,4),'User',$user], ]; } sub dissect_SUA_PT_NA { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'NA',$val] ]; } sub dissect_SUA_PT_RKEY { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_SUA_PT_DRNLAB { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $b = ($val >> 24) & 0xff; my $e = ($val >> 16) & 0xff; my $v = ($val >> 0) & 0xffff; return [ [$off,Frame::bytes($b,0xff000000,4),'DRN Begin',$b], [$off,Frame::bytes($e,0x00ff0000,4),'DRN End',$e], [$off,Frame::bytes($v,0x0000ffff,4),'DRN Value',$v], ]; } sub dissect_SUA_PT_TIDLAB { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $b = ($val >> 24) & 0xff; my $e = ($val >> 16) & 0xff; my $v = ($val >> 0) & 0xffff; return [ [$off,Frame::bytes($b,0xff000000,4),'TID Begin',$b], [$off,Frame::bytes($e,0x00ff0000,4),'TID End',$e], [$off,Frame::bytes($v,0x0000ffff,4),'TID Value',$v], ]; } sub dissect_SUA_PT_RANGE { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_SUA_PT_SMI { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = ($val >> 8); my $smi = $val & 0xff; return [ [$off,Frame::spare($spa,0xffffff00,4),'Spare',$spa], [$off,Frame::bytes($smi,0x000000ff,4),'SMI',$smi], ]; } sub dissect_SUA_PT_IMP { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = ($val >> 8); my $imp = $val & 0xff; return [ [$off,Frame::spare($spa,0xffffff00,4),'Spare',$spa], [$off,Frame::bytes($imp,0x000000ff,4),'Importance',$imp], ]; } sub dissect_SUA_PT_PRIO { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Priority',$val], ]; } sub dissect_SUA_PT_PCLASS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = ($val >> 8); my $pcl = $val & 0xff; return [ [$off,Frame::spare($spa,0xffffff00,4),'Spare',$spa], [$off,Frame::bytes($pcl,0x000000ff,4),'Protocol Class',$pcl], ]; } sub dissect_SUA_PT_SEQCTL { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Seq Control',$val], ]; } sub dissect_SUA_PT_SEGM { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $fr = ($val >> 24) & 0xff; my $sr = $val & 0xffffff; return [ [$off,Frame::bytes($fr,0xff000000,4),'Fragment',$fr], [$off,Frame::bytes($sr,0x00ffffff,4),'Segment Reference',$sr], ]; } sub dissect_SUA_PT_CONG { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Cong Level',$val], ]; } sub dissect_SUA_PT_GTI { my ($self,$off,$end,$len) = @_; my ($gti, $num, $tt, $np, $nai) = unpack('NCCCC',substr(${$self->{buf}},$off,8)); my $digs = substr(${$self->{buf}},$off+8,$len-8); return [ [$off+0,Frame::bytes($gti,0xffffffff,4),'GTI',$gti], [$off+4,Frame::bytes($num,0xff000000,4),'Num Digits',$num], [$off+4,Frame::bytes($tt, 0x00ff0000,4),'Transl Type',$tt], [$off+4,Frame::bytes($np, 0x0000ff00,4),'Numb Plan',$np], [$off+4,Frame::bytes($nai,0x000000ff,4),'Nat Addr Ind',$nai], [$off+8,' ******** ','Digits',Frame::pdigs(substr(${$self->{buf}},$off+8,$len-8),$num)], ]; } sub dissect_SUA_PT_PC { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = $val >> 24; my $pc = $val & 0xffffff; if ($pc&(~0x3fff)) { $pc = (($pc>>16)&0xff).'-'.(($pc>>8)&0xff).'-'.(($pc>>0)&0xff); return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::bytes($val,0x00ffffff,4),'Point Code',$pc], ]; } else { $pc = (($pc>>11)&0x07).'-'.(($pc>>3)&0xff).'-'.(($pc>>0)&0x07); my $pc0 = ($val >> 14) & 0x3ff; return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::spare($pc0,0x00ffc000,4),'Unused',$pc0], [$off,Frame::bytes($val,0x00003fff,4),'Point Code',$pc], ]; } } sub dissect_SUA_PT_SSN { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = $val >> 8; my $ssn = $val & 0xff; return [ [$off,Frame::spare($spa,0xffffff00,4),'Spare',$spa], [$off,Frame::bytes($ssn,0x000000ff,4),'SSN',$ssn], ]; } sub dissect_SUA_PT_IPV4 { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $ipa = (($val>>24)&0xff).'.'.(($val>>16)&0xff).'.'.(($val>>8)&0xff).'.'.(($val>>0)&0xff); return [ [$off,Frame::bytes($val,0xffffffff,4),'IPv4 Addr',$ipa] ]; } sub dissect_SUA_PT_HOST { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','Hostname',Frame::ptext(substr(${$self->{buf}},$off,$len))] ]; } sub dissect_SUA_PT_IPV6 { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','IPv6 Addr',Frame::pdata(substr(${$self->{buf}},$off,$len))] ]; } sub dissect_M3UA_PT_NA { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'NA',$val] ]; } sub dissect_M3UA_PT_UCAUSE { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $caus = ($val >> 16) & 0xffff; my $user = ($val >> 0) & 0xffff; return [ [$off,Frame::bytes($caus,0xffff0000,4),'Cause',$caus], [$off,Frame::bytes($user,0x0000ffff,4),'User',$user], ]; } sub dissect_M3UA_PT_CONG { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Cong Level',$val] ]; } sub dissect_M3UA_PT_CDEST { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = $val >> 24; my $dpc = $val & 0xffffff; if ($dpc&(~0x3fff)) { $dpc = (($dpc>>16)&0xff).'-'.(($dpc>>8)&0xff).'-'.(($dpc>>0)&0xff); return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::bytes($val,0x00ffffff,4),'Dest PC',$dpc], ]; } else { $dpc = (($dpc>>11)&0x07).'-'.(($dpc>>3)&0xff).'-'.(($dpc>>0)&0x07); my $pc0 = ($val >> 14) & 0x3ff; return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::spare($pc0,0x00ffc000,4),'Unused',$pc0], [$off,Frame::bytes($val,0x00003fff,4),'Dest PC',$dpc], ]; } } sub dissect_M3UA_PT_RKEY { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_M3UA_PT_RRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_M3UA_PT_DRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms($self,$off,$end,$len); } sub dissect_M3UA_PT_KEYID { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); return [ [$off,Frame::bytes($val,0xffffffff,4),'Key ID',$val] ]; } sub dissect_M3UA_PT_DPC { my ($self,$off,$end,$len) = @_; my $val = unpack('N',${$self->{buf}},$off,4); my $spa = $val >> 24; my $dpc = $val & 0xffffff; if ($dpc&(~0x3fff)) { $dpc = (($dpc>>16)&0xff).'-'.(($dpc>>8)&0xff).'-'.(($dpc>>0)&0xff); return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::bytes($val,0x00ffffff,4),'DPC',$dpc], ]; } else { $dpc = (($dpc>>11)&0x07).'-'.(($dpc>>3)&0xff).'-'.(($dpc>>0)&0x07); my $pc0 = ($val >> 14) & 0x3ff; return [ [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::spare($pc0,0x00ffc000,4),'Unused',$pc0], [$off,Frame::bytes($val,0x00003fff,4),'DPC',$dpc], ]; } } sub dissect_M3UA_PT_SI { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end > $off) { my $val = unpack('C',substr(${$self->{buf}},$off,1)); if ($val) { push @fields, [$off,Field::bytes($val,0xff,1),'SI',$val]; } else { push @fields, [$off,Field::spare($val,0xff,1),'Spare',$val]; } } return \@fields; } sub dissect_M3UA_PT_OPCLIST { my ($self,$off,$end,$len) = @_; my @fields = (); while ($end >= $off + 4) { my $spa = unpack('C',substr(${$self->{buf}},$off,1)); my $val = unpack('N',substr(${$self->{buf}},$off,4)) & 0xffffff; my $opc = $val; if ($val&(~0x3fff)) { $opc = (($opc>>16)&0xff).'-'.(($opc>>8)&0xff).'-'.(($opc>>0)&0xff); push @fields, [$off,Frame::spare($spa,0xff000000,4),'Spare',$spa], [$off,Frame::bytes($val,0x00ffffff,4),'OPC', $opc]; } else { $opc = (($opc>>11)&0x07).'-'.(($opc>>3)&0xff).'-'.(($opc>>0)&0x07); my $opc0 = ($opc >> 14) & 0x3ff; push @fields, [$off,Frame::spare($spa, 0xff000000,4),'Spare', $spa ], [$off,Frame::spare($opc0,0x00ffc000,4),'Unused',$opc0], [$off,Frame::bytes($val, 0x00003fff,4),'OPC', $opc ]; } } return \@fields; } sub dissect_M3UA_PT_DATA { my ($self,$off,$end,$len) = @_; my ($opc, $dpc, $si, $ni, $mp, $sls) = unpack('NNCCCC',substr(${$self->{buf}},$off,12)); my ($osp, $dsp) = (($opc>>24)&0xff,(($dpc>>24)&0xff)); $opc &= 0xffffff; $dpc &= 0xffffff; my @fields = (); if (($opc|$dpc)&(~0x3fff)) { my $OPC = (($opc>>16)&0xff).'-'.(($opc>>8)&0xff).'-'.(($opc>>0)&0xff); my $DPC = (($dpc>>16)&0xff).'-'.(($dpc>>8)&0xff).'-'.(($dpc>>0)&0xff); push @fields, [$off+ 0,Frame::spare($osp,0xff000000,4),'Spare',$osp], [$off+ 0,Frame::bytes($opc,0x00ffffff,4),'OPC',$OPC], [$off+ 4,Frame::spare($dsp,0xff000000,4),'Spare',$dsp], [$off+ 4,Frame::bytes($dpc,0x00ffffff,4),'DPC',$DPC]; } else { my ($op0,$dp0) = (($opc>>14)&0x3ff,($dpc>>24)&0x3ff); $opc &= 0x3fff; $dpc &= 0x3fff; my $OPC = (($opc>>11)&0x07).'-'.(($opc>>3)&0xff).'-'.(($opc>>0)&0x07); my $DPC = (($dpc>>11)&0x07).'-'.(($dpc>>3)&0xff).'-'.(($dpc>>0)&0x07); push @fields, [$off+ 0,Frame::spare($osp,0xff000000,4),'Spare',$osp], [$off+ 0,Frame::spare($os0,0x00ffc000,4),'Unused',$os0], [$off+ 0,Frame::bytes($opc,0x00003fff,4),'OPC',$OPC], [$off+ 4,Frame::spare($dsp,0xff000000,4),'Spare',$dsp], [$off+ 4,Frame::spare($ds0,0x00ffc000,4),'Unused',$ds0], [$off+ 4,Frame::bytes($dpc,0x00003fff,4),'DPC',$DPC]; } push @fields, [$off+ 8,Frame::bytes($si, 0xff000000,4),'SI',$si], [$off+ 8,Frame::bytes($ni, 0x00ff0000,4),'NI',$ni], [$off+ 8,Frame::bytes($mp, 0x0000ff00,4),'MP',$mp], [$off+ 8,Frame::bytes($sls,0x000000ff,4),'SLS',$sls], [$off+12,' ******** ','Data',Frame::pdata(substr(${$self->{buf}},$off+12,$len-12))]; return \@fields; } sub dissect_M3UA_PT_RSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Reg Status',$val] ]; } sub dissect_M3UA_PT_DSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Dereg Status',$val] ]; } sub dissect_M2UA_PT_PDATA1 { my ($self,$off,$end,$len) = @_; return [ [$off,' ******** ','Data',Frame::pdata(substr(${$self->{buf}},$off,$len))] ]; } sub dissect_M2UA_PT_PDATA2 { my ($self,$off,$end,$len) = @_; my $li0 = unpack('C',substr(${$self->{buf}},$off,1)); my $spa = $li0 & 0x3f; $li0 >>= 6; return [ [$off,Frame::bytes($li0,0xc0,1),'MP',$li0], [$off,Frame::spare($spa,0x3f,1),'Spare',$spa], [$off,' ******** ','Data',Frame::pdata(substr(${$self->{buf}},$off+1,$len-1))], ]; } sub dissect_M2UA_PT_STATE { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'State',$val] ]; } sub dissect_M2UA_PT_EVENT { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Event',$val] ]; } sub dissect_M2UA_PT_CONGEST { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Congest level',$val] ]; } sub dissect_M2UA_PT_DISCARD { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Discard level',$val] ]; } sub dissect_M2UA_PT_ACTION { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Action',$val] ]; } sub dissect_M2UA_PT_SEQNUM { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Seq Numb',$val] ]; } sub dissect_M2UA_PT_RTVRES { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Retrieve Result',$val] ]; } sub dissect_M2UA_PT_LKEY { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms(@_); } sub dissect_M2UA_PT_KEYID { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Key ID',$val] ]; } sub dissect_M2UA_PT_SDTI { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); my $spar = $val >> 16; my $sdti = $val & 0xffff; return [ [$off,Frame::spare($spar,0xffff0000,4),'Spare',$spar], [$off,Frame::bytes($sdti,0x0000ffff,4),'SDTI', $sdti], ]; } sub dissect_M2UA_PT_SDLI { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); my $spar = $val >> 16; my $sdli = $val & 0xffff; return [ [$off,Frame::spare($spar,0xffff0000,4),'Spare',$spar], [$off,Frame::bytes($sdli,0x0000ffff,4),'SDLI', $sdli], ]; } sub dissect_M2UA_PT_RRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms(@_); } sub dissect_M2UA_PT_RSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Reg Status',$val] ]; } sub dissect_M2UA_PT_DRESULT { my ($self,$off,$end,$len) = @_; return Message::ULP::dissect_parms(@_); } sub dissect_M2UA_PT_DSTATUS { my ($self,$off,$end,$len) = @_; my $val = unpack('N',substr(${$self->{buf}},$off,4)); return [ [$off,Frame::bytes($val,0xffffffff,4),'Dereg Status',$val] ]; } use constant { ULP_PARMS_DISSECT=>{ &ULP_PT_IIID => [\&Message::ULP::dissect_ULP_PT_IIID, 'IIID', 'Integer interface identifier'], &ULP_PT_TIID => [\&Message::ULP::dissect_ULP_PT_TIID, 'TIID', 'Text interface identifier'], &ULP_PT_INFO => [\&Message::ULP::dissect_ULP_PT_INFO, 'INFO', 'Information'], &ULP_PT_RC => [\&Message::ULP::dissect_ULP_PT_RC, 'RC', 'Routing context'], &ULP_PT_DIAG => [\&Message::ULP::dissect_ULP_PT_DIAG, 'DIAG', 'Diagnostic'], &ULP_PT_RIID => [\&Message::ULP::dissect_ULP_PT_RIID, 'RIID', 'Integer interface identifier range'], &ULP_PT_HBDATA => [\&Message::ULP::dissect_ULP_PT_HBDATA, 'HB Data', 'Heartbeat data'], &ULP_PT_TMODE => [\&Message::ULP::dissect_ULP_PT_TMODE, 'TMODE', 'Traffic mode type'], &ULP_PT_ECODE => [\&Message::ULP::dissect_ULP_PT_ECODE, 'ECODE', 'Error code'], &ULP_PT_STATUS => [\&Message::ULP::dissect_ULP_PT_STATUS, 'Status', 'Notification Status'], &ULP_PT_ASPID => [\&Message::ULP::dissect_ULP_PT_ASPID, 'ASP Id', 'ASP identifier'], &ULP_PT_APC => [\&Message::ULP::dissect_ULP_PT_APC, 'APC', 'Affected point code'], &ULP_PT_CID => [\&Message::ULP::dissect_ULP_PT_CID, 'Corr Id', 'Correlation identifier'], &ULP_PT_RRESULT => [\&Message::ULP::dissect_ULP_PT_RRESULT, 'Result', 'Registration result'], &ULP_PT_DRESULT => [\&Message::ULP::dissect_ULP_PT_DRESULT, 'Result', 'Deregistration result'], &ULP_PT_RSTATUS => [\&Message::ULP::dissect_ULP_PT_RSTATUS, 'Status', 'Registration status'], &ULP_PT_DSTATUS => [\&Message::ULP::dissect_ULP_PT_DSTATUS, 'Status', 'Deregistration status'], &ULP_PT_KEYID => [\&Message::ULP::dissect_ULP_PT_KEYID, 'Key Id', 'Local key identifier'], &SUA_PT_HOPC => [\&Message::ULP::dissect_SUA_PT_HOPC, 'HOPC', 'Hop counter'], &SUA_PT_SA => [\&Message::ULP::dissect_SUA_PT_SA, 'SA', 'Source address'], &SUA_PT_DA => [\&Message::ULP::dissect_SUA_PT_DA, 'DA', 'Destination address'], &SUA_PT_SRN => [\&Message::ULP::dissect_SUA_PT_SRN, 'SRN', 'Source reference number'], &SUA_PT_DRN => [\&Message::ULP::dissect_SUA_PT_DRN, 'DRN', 'Destinration reference number'], &SUA_PT_CAUSE => [\&Message::ULP::dissect_SUA_PT_CAUSE, 'Cause', 'SCCP cause'], &SUA_PT_SEQNO => [\&Message::ULP::dissect_SUA_PT_SEQNO, 'SEQNO', 'Sequence number'], &SUA_PT_RSEQNO => [\&Message::ULP::dissect_SUA_PT_RSEQNO, 'RSEQNO', 'Receive sequence number'], &SUA_PT_ASPCAP => [\&Message::ULP::dissect_SUA_PT_ASPCAP, 'ASPCAP', 'ASP capabilities'], &SUA_PT_CREDIT => [\&Message::ULP::dissect_SUA_PT_CREDIT, 'Credit', 'Credit'], &SUA_PT_DATA => [\&Message::ULP::dissect_SUA_PT_DATA, 'Data', 'SCCP-user data'], &SUA_PT_UCAUSE => [\&Message::ULP::dissect_SUA_PT_UCAUSE, 'UCAUSE', 'User/cause'], &SUA_PT_NA => [\&Message::ULP::dissect_SUA_PT_NA, 'NA', 'Network appearance'], &SUA_PT_RKEY => [\&Message::ULP::dissect_SUA_PT_RKEY, 'RK', 'Routing key'], &SUA_PT_DRNLAB => [\&Message::ULP::dissect_SUA_PT_DRNLAB, 'DRN Label', 'Destination reference number label'], &SUA_PT_TIDLAB => [\&Message::ULP::dissect_SUA_PT_TIDLAB, 'TID Label', 'Transaction identifier label'], &SUA_PT_RANGE => [\&Message::ULP::dissect_SUA_PT_RANGE, 'Range', 'Address range'], &SUA_PT_SMI => [\&Message::ULP::dissect_SUA_PT_SMI, 'SMI', 'System multiplicity indicator'], &SUA_PT_IMP => [\&Message::ULP::dissect_SUA_PT_IMP, 'IMP', 'Importance'], &SUA_PT_PRIO => [\&Message::ULP::dissect_SUA_PT_PRIO, 'PRIO', 'Priority'], &SUA_PT_PCLASS => [\&Message::ULP::dissect_SUA_PT_PCLASS, 'PCLASS', 'Protocol class'], &SUA_PT_SEQCTL => [\&Message::ULP::dissect_SUA_PT_SEQCTL, 'SEQCTL', 'Sequence control'], &SUA_PT_SEGM => [\&Message::ULP::dissect_SUA_PT_SEGM, 'SEGM', 'Segmentation'], &SUA_PT_CONG => [\&Message::ULP::dissect_SUA_PT_CONG, 'CONG', 'Congestion level'], &SUA_PT_GTI => [\&Message::ULP::dissect_SUA_PT_GTI, 'GTI', 'Global title indicator'], &SUA_PT_PC => [\&Message::ULP::dissect_SUA_PT_PC, 'PC', 'Point code'], &SUA_PT_SSN => [\&Message::ULP::dissect_SUA_PT_SSN, 'SSN', 'Subsystem number'], &SUA_PT_IPV4 => [\&Message::ULP::dissect_SUA_PT_IPV4, 'IPv4', 'Internet Protocol version 4 address'], &SUA_PT_HOST => [\&Message::ULP::dissect_SUA_PT_HOST, 'Host', 'Host name'], &SUA_PT_IPV6 => [\&Message::ULP::dissect_SUA_PT_IPV6, 'IPV6', 'Internet Protocol version 6 address'], &M3UA_PT_NA => [\&Message::ULP::dissect_M3UA_PT_NA, 'NA', 'Network appearance'], &M3UA_PT_UCAUSE => [\&Message::ULP::dissect_M3UA_PT_UCAUSE, 'UCAUSE', 'User/cause'], &M3UA_PT_CONG => [\&Message::ULP::dissect_M3UA_PT_CONG, 'CONG', 'Congestion level'], &M3UA_PT_CDEST => [\&Message::ULP::dissect_M3UA_PT_CDEST, 'CDEST', 'Concerned destination'], &M3UA_PT_RKEY => [\&Message::ULP::dissect_M3UA_PT_RKEY, 'RK', 'Routing key'], &M3UA_PT_RRESULT=> [\&Message::ULP::dissect_M3UA_PT_RRESULT, 'Result', 'Registration result'], &M3UA_PT_DRESULT=> [\&Message::ULP::dissect_M3UA_PT_DRESULT, 'Result', 'Deregistration result'], &M3UA_PT_KEYID => [\&Message::ULP::dissect_M3UA_PT_KEYID, 'Key Id', 'Local key identifier'], &M3UA_PT_DPC => [\&Message::ULP::dissect_M3UA_PT_DPC, 'DPC', 'Destination point code'], &M3UA_PT_SI => [\&Message::ULP::dissect_M3UA_PT_SI, 'SI', 'Service indicators'], &M3UA_PT_OPCLIST=> [\&Message::ULP::dissect_M3UA_PT_OPCLIST, 'OPC List', 'Originating point code list'], &M3UA_PT_DATA => [\&Message::ULP::dissect_M3UA_PT_DATA, 'Data', 'MTP-user Data'], &M3UA_PT_RSTATUS=> [\&Message::ULP::dissect_M3UA_PT_RSTATUS, 'Status', 'Registration status'], &M3UA_PT_DSTATUS=> [\&Message::ULP::dissect_M3UA_PT_DSTATUS, 'Status', 'Deregistration status'], &M2UA_PT_PDATA1 => [\&Message::ULP::dissect_M2UA_PT_PDATA1, 'Prot Data 1', 'Protocol data 1'], &M2UA_PT_PDATA2 => [\&Message::ULP::dissect_M2UA_PT_PDATA2, 'Prot Data 2', 'Protocol data 2 (TTC)'], &M2UA_PT_STATE => [\&Message::ULP::dissect_M2UA_PT_STATE, 'State', 'State'], &M2UA_PT_EVENT => [\&Message::ULP::dissect_M2UA_PT_EVENT, 'Event', 'Event'], &M2UA_PT_CONGEST=> [\&Message::ULP::dissect_M2UA_PT_CONGEST, 'Congest', 'Congest level'], &M2UA_PT_DISCARD=> [\&Message::ULP::dissect_M2UA_PT_DISCARD, 'Discard', 'Discard level'], &M2UA_PT_ACTION => [\&Message::ULP::dissect_M2UA_PT_ACTION, 'Action', 'Action'], &M2UA_PT_SEQNUM => [\&Message::ULP::dissect_M2UA_PT_SEQNUM, 'Seqnum', 'Sequence number'], &M2UA_PT_RTVRES => [\&Message::ULP::dissect_M2UA_PT_RTVRES, 'Result', 'Retrieval result'], &M2UA_PT_LKEY => [\&Message::ULP::dissect_M2UA_PT_LKEY, 'LK', 'Link key'], &M2UA_PT_KEYID => [\&Message::ULP::dissect_M2UA_PT_KEYID, 'Key Id', 'Local key identifier'], &M2UA_PT_SDTI => [\&Message::ULP::dissect_M2UA_PT_SDTI, 'SDTI', 'Signalling terminal identifier'], &M2UA_PT_SDLI => [\&Message::ULP::dissect_M2UA_PT_SDLI, 'SDLI', 'Signalling data link identifier'], &M2UA_PT_RRESULT=> [\&Message::ULP::dissect_M2UA_PT_RRESULT, 'Result', 'Registration result'], &M2UA_PT_RSTATUS=> [\&Message::ULP::dissect_M2UA_PT_RSTATUS, 'Status', 'Resgistration status'], &M2UA_PT_DRESULT=> [\&Message::ULP::dissect_M2UA_PT_DRESULT, 'Result', 'Deregistration result'], &M2UA_PT_DSTATUS=> [\&Message::ULP::dissect_M2UA_PT_DSTATUS, 'Status', 'Deregistration status'], }, }; sub dissect_parms { my ($self,$off,$end,$mlen) = @_; my @parms = (); while ($off + 4 <= $end) { my ($tag,$len) = unpack('nn',substr(${$self->{buf}},$off,4)); my $pt = ULP_PARM_TYPES->{$tag}.'('.sprintf('0x%04X',$tag).')'; push @parms, "Parameter $pt", [$off+0,Frame::bytes($tag,0xffff0000,4),'Tag',$pt], [$off+0,Frame::bytes($len,0x0000ffff,4),'Length',$len]; my $sub = ULP_PARMS_DISSECT->{$tag} if exists ULP_PARMS_DISSECT->{$tag}; if (defined $sub) { push @parms, @{$sub->($self,$off+4,$off+(($len+3)&(~0x3)),$len-4)}; } else { push @parms, [$off+4,' ******** ','Data',Frame::pdata(substr(${$self->{buf}},$off+4,$len-4))]; } } return \@parms; } # ------------------------------------- package Message::M2PA; our @ISA = qw(Message::ULP); # ------------------------------------- sub unpack { my $self = shift; return if $self->{mlen} < 16; return if $self->{end} < $self->{off} + 8; $self->{m2pa}->{off} = $self->{off}; $self->{m2pa}->{end} = $self->{end}; ( $self->{bsn}, $self->{fsn}, ) = unpack('NN',substr(${$self->{buf}},$self->{off},8)); $self->{off} += 8; $self->{bsn} &= 0x00ffffff; $self->{fsn} &= 0x00ffffff; $self->{li} = $self->{mlen} - 16; return $self; } sub dissect { my $self = shift; my $off = $self->{m2pa}->{off}; return [ @{$self->SUPER::dissect(@_)}, [$off+0,Frame::bytes($self->{bsn}, 0x00ffffff,4),'BSN',$self->{bsn}], [$off+4,Frame::bytes($self->{fsn}, 0x00ffffff,4),'FSN',$self->{fsn}], ]; } # ------------------------------------- package Message::M2PA::ACK; our @ISA = qw(Message::M2PA); # ------------------------------------- # ------------------------------------- package Message::M2PA::DATA; our @ISA = qw(Message::M2PA); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_header(@_); $self->{li0} = unpack('C',substr(${$self->{buf}},$self->{off},1)) >> 6; if ($self->{li0} == 0) { bless $self,'Message::M2PA::ACK'; return $self; } $self->{off}++; $self->{li}--; $self->{doff} = $self->{off}; $self->{dlen} = $self->{li}; $self->{dend} = $self->{off} + $self->{li}; return $self; } sub testit { my $self = shift; return -1 unless $self->unpack(@_); my ($decoder) = @_; $decoder->{ht} = ::HT_EXTENDED; if ($decoder->{pr} == ::MP_UNKNOWN) { if ($self->{li0} != 0) { $decoder->setpr(::MP_JAPAN); $decoder->setrt(::RT_24BIT_PC); } } return 1; } sub decode { return new Message::MTP3(@_); } sub detect { return try Message::MTP3(@_); } sub dissect { my $self = shift; my $off = $self->{m2pa}->{off} + 8; my $li00 = unpack('C',substr(${$self->{buf}},$off,1)) & 0x3f; return [ @{$self->SUPER::dissect(@_)}, [$off+0,Frame::spare($li00,0x3f,1),'Spare',$li00], [$off+0,Frame::bytes($self->{li0},0xc0,1),'LI Spare Bits',$self->{li0}], ]; } # ------------------------------------- package Message::M2PA::STATUS; our @ISA = qw(Message::M2PA); # ------------------------------------- use constant { M2PA_STATUS_TYPES=>{ 1=>'ALIGNMENT', 2=>'PROVING_NORMAL', 3=>'PROVING_EMERGENCY', 4=>'IN_SERVICE', 5=>'PROCESSOR_OUTAGE', 6=>'PROCESSOR_OUTAGE_ENDED', 7=>'BUSY', 8=>'BUSY_ENDED', 9=>'OUT_OF_SERVICE', }, }; sub unpack { my $self = shift; return unless $self->SUPER::unpack(@_); return unless $self->{end} >= $self->{off} + 4; $self->{stat} = unpack('N',substr(${$self->{buf}},$self->{off},4)); $self->{off} += 4; $self->{li} -= 4; return unless exists M2PA_STATUS_TYPES->{$self->{stat}}; $self->{filler} = substr(${$self->{buf}},$self->{off},$self->{li}); bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{m2pa}->{off} + 8; my $stat = $self->{stat}; $stat = M2PA_STATUS_TYPES->{$stat}."($stat)"; return [ @{$self->SUPER::dissect(@_)}, [$off+0,Frame::bytes($self->{stat},0xffffffff),'Status',$stat], ]; } # ------------------------------------- package Message::M2PA::ALIGNMENT; our @ISA = qw(Message::M2PA); package Message::M2PA::PROVING_NORMAL; our @ISA = qw(Message::M2PA); package Message::M2PA::PROVING_EMERGENCY; our @ISA = qw(Message::M2PA); package Message::M2PA::IN_SERVICE; our @ISA = qw(Message::M2PA); package Message::M2PA::PROCESSOR_OUTAGE; our @ISA = qw(Message::M2PA); package Message::M2PA::PROCESSOR_OUTAGE_ENDED; our @ISA = qw(Message::M2PA); package Message::M2PA::BUSY; our @ISA = qw(Message::M2PA); package Message::M2PA::BUSY_ENDED; our @ISA = qw(Message::M2PA); package Message::M2PA::OUT_OF_SERVICE; our @ISA = qw(Message::M2PA); # ------------------------------------- # ------------------------------------- package Message::M2UA; our @ISA = qw(Message::ULP); package Message::M2UA::MAUP; our @ISA = qw(Message::M2UA); # ------------------------------------- package Message::M2UA::MAUP::Data; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{doff}; return $self; } sub decode { return new Message::MTP3(@_); } sub detect { return try Message::MTP3(@_); } # ------------------------------------- package Message::M2UA::MAUP::Data_Acknowledge; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{cid}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::State_Request; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{state}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::State_Confirm; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{state}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::State_Indication; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{event}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::Congestion_Indication; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{congest}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::Data_Retrieval_Request; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{action}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::Data_Retrieval_Confirm; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{action} and exists $self->{result}; return $self; } # ------------------------------------- package Message::M2UA::MAUP::Data_Retrieval_Indication; our @ISA = qw(Message::M2UA::MAUP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_parms(@_); return unless exists $self->{doff}; return $self; } sub decode { return new Message::MTP3(@_); } sub detect { return try Message::MTP3(@_); } # ------------------------------------- package Message::M2UA::MGMT; our @ISA = qw(Message::M2UA); # ------------------------------------- package Message::M2UA::MGMT::ERR; our @ISA = qw(Message::M2UA::MGMT); package Message::M2UA::MGMT::NTFY; our @ISA = qw(Message::M2UA::MGMT); # ------------------------------------- # ------------------------------------- package Message::M2UA::ASPSM; our @ISA = qw(Message::M2UA); # ------------------------------------- package Message::M2UA::ASPSM::ASPUP_REQ; our @ISA = qw(Message::M2UA::ASPSM); package Message::M2UA::ASPSM::ASPUP_ACK; our @ISA = qw(Message::M2UA::ASPSM); package Message::M2UA::ASPSM::ASPDN_REQ; our @ISA = qw(Message::M2UA::ASPSM); package Message::M2UA::ASPSM::ASPDN_ACK; our @ISA = qw(Message::M2UA::ASPSM); package Message::M2UA::ASPSM::HBEAT_REQ; our @ISA = qw(Message::M2UA::ASPSM); package Message::M2UA::ASPSM::HBEAT_ACK; our @ISA = qw(Message::M2UA::ASPSM); # ------------------------------------- # ------------------------------------- package Message::M2UA::ASPTM; our @ISA = qw(Message::M2UA); # ------------------------------------- package Message::M2UA::ASPTM::ASPAC_REQ; our @ISA = qw(Message::M2UA::ASPTM); package Message::M2UA::ASPTM::ASPAC_ACK; our @ISA = qw(Message::M2UA::ASPTM); package Message::M2UA::ASPTM::ASPIA_REQ; our @ISA = qw(Message::M2UA::ASPTM); package Message::M2UA::ASPTM::ASPIA_ACK; our @ISA = qw(Message::M2UA::ASPTM); # ------------------------------------- # ------------------------------------- package Message::M2UA::IIM; our @ISA = qw(Message::M2UA); # ------------------------------------- package Message::M2UA::IIM::REG_REQ; our @ISA = qw(Message::M2UA::IIM); package Message::M2UA::IIM::REG_RSP; our @ISA = qw(Message::M2UA::IIM); package Message::M2UA::IIM::DEREG_REQ; our @ISA = qw(Message::M2UA::IIM); package Message::M2UA::IIM::DEREG_RSP; our @ISA = qw(Message::M2UA::IIM); # ------------------------------------- # ------------------------------------- package Message::M3UA; our @ISA = qw(Message::ULP); # ------------------------------------- sub unpack { my $self = shift; return unless $self->SUPER::unpack_parms(@_); return $self; } # ------------------------------------- package Message::M3UA::XFER; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::XFER::DATA; our @ISA = qw(Message::M3UA::XFER); # ------------------------------------- use constant { SI_VALUES=>{ 0=>'SNMM', 1=>'SNTM', 2=>'SNSM', 3=>'SCCP', 4=>'TUP', 5=>'ISUP' } }; sub decode { my $self = shift; my $type = SI_VALUES->{$self->{si}} if exists SI_VALUES->{$self->{si}}; $type = 'USER' unless defined $type; my $prot = (($self->{dpc}|$self->{opc})&(~0x3fff)) ? 'ANSI' : 'ITUT'; return new Message::$prot::$type($self,@_); } # ------------------------------------- package Message::M3UA::SSNM; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::SSNM::DUNA; our @ISA = qw(Message::M3UA::SSNM); package Message::M3UA::SSNM::DAVA; our @ISA = qw(Message::M3UA::SSNM); package Message::M3UA::SSNM::DAUD; our @ISA = qw(Message::M3UA::SSNM); package Message::M3UA::SSNM::SCON; our @ISA = qw(Message::M3UA::SSNM); package Message::M3UA::SSNM::DUPU; our @ISA = qw(Message::M3UA::SSNM); package Message::M3UA::SSNM::DRST; our @ISA = qw(Message::M3UA::SSNM); # ------------------------------------- # ------------------------------------- package Message::M3UA::MGMT; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::MGMT::ERR; our @ISA = qw(Message::M3UA::MGMT); package Message::M3UA::MGMT::NTFY; our @ISA = qw(Message::M3UA::MGMT); # ------------------------------------- # ------------------------------------- package Message::M3UA::ASPSM; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::ASPSM::ASPUP; our @ISA = qw(Message::M3UA::ASPSM); package Message::M3UA::ASPSM::ASPDN; our @ISA = qw(Message::M3UA::ASPSM); package Message::M3UA::ASPSM::HBEAT; our @ISA = qw(Message::M3UA::ASPSM); # ------------------------------------- package Message::M3UA::ASPSM::ASPUP_REQ; our @ISA = qw(Message::M3UA::ASPSM::ASPUP); package Message::M3UA::ASPSM::ASPDN_REQ; our @ISA = qw(Message::M3UA::ASPSM::ASPDN); package Message::M3UA::ASPSM::HBEAT_REQ; our @ISA = qw(Message::M3UA::ASPSM::HBEAT); package Message::M3UA::ASPSM::ASPUP_ACK; our @ISA = qw(Message::M3UA::ASPSM::ASPUP); package Message::M3UA::ASPSM::ASPDN_ACK; our @ISA = qw(Message::M3UA::ASPSM::ASPDN); package Message::M3UA::ASPSM::HBEAT_ACK; our @ISA = qw(Message::M3UA::ASPSM::HBEAT); # ------------------------------------- # ------------------------------------- package Message::M3UA::ASPTM; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::ASPTM::ASPAC_REQ; our @ISA = qw(Message::M3UA::ASPTM); package Message::M3UA::ASPTM::ASPIA_REQ; our @ISA = qw(Message::M3UA::ASPTM); package Message::M3UA::ASPTM::ASPAC_ACK; our @ISA = qw(Message::M3UA::ASPTM); package Message::M3UA::ASPTM::ASPIA_ACK; our @ISA = qw(Message::M3UA::ASPTM); # ------------------------------------- # ------------------------------------- package Message::M3UA::RKM; our @ISA = qw(Message::M3UA); # ------------------------------------- package Message::M3UA::RKM::REG_REQ; our @ISA = qw(Message::M3UA::RKM); package Message::M3UA::RKM::REG_RSP; our @ISA = qw(Message::M3UA::RKM); package Message::M3UA::RKM::DEREG_REQ; our @ISA = qw(Message::M3UA::RKM); package Message::M3UA::RKM::DEREG_RSP; our @ISA = qw(Message::M3UA::RKM); # ------------------------------------- # ------------------------------------- package Message::SUA; our @ISA = qw(Message::ULP); # ------------------------------------- sub unpack { my $self = shift; $self->{sua}->{off} = $self->{off}; $self->{sua}->{end} = $self->{end}; return unless $self->SUPER::unpack_parms(@_); return $self; } sub decode { return undef unless exists $self->{doff}; return new Message::SCCP::USER(shift,@_); } # ------------------------------------- package Message::SUA::CLDT; our @ISA = qw(Message::SUA); package Message::SUA::CLDR; our @ISA = qw(Message::SUA); # ------------------------------------- package Message::SUA::CORE; our @ISA = qw(Message::SUA); package Message::SUA::COAK; our @ISA = qw(Message::SUA); package Message::SUA::COREF; our @ISA = qw(Message::SUA); package Message::SUA::RELRE; our @ISA = qw(Message::SUA); package Message::SUA::RELCO; our @ISA = qw(Message::SUA); package Message::SUA::RESCO; our @ISA = qw(Message::SUA); package Message::SUA::RESRE; our @ISA = qw(Message::SUA); package Message::SUA::CODT; our @ISA = qw(Message::SUA); package Message::SUA::CODA; our @ISA = qw(Message::SUA); package Message::SUA::COERR; our @ISA = qw(Message::SUA); package Message::SUA::COIT; our @ISA = qw(Message::SUA); # ------------------------------------- # ------------------------------------- package Message::MTP2; our @ISA = qw(Message); # ------------------------------------- use constant { LI_TYPES=>{ 0=>'FISU', 1=>'LSSU', 2=>'LSSU', 3=>'MSU', }, }; sub unpack { my $self = shift; my ($decoder) = @_; if (($self->{ht} = $decoder->{ht}) == ::HT_BASIC) { ( $self->{bsn}, $self->{fsn}, $self->{li}, ) = unpack('CCC',substr(${$self->{buf}},$self->{off},3)); $self->{bib} = ($self->{bsn} >> 7) & 0x01; $self->{bsn} &= 0x7f; $self->{fib} = ($self->{fsn} >> 7) & 0x01; $self->{fsn} &= 0x7f; $self->{li0} = ($self->{li} >> 6} & 0x03; $self->{li} &= 0x3f; $self->{off} += 3; } elsif ($self->{ht} == ::HT_EXTENDED) { ( $self->{bsn}, $self->{fsn}, $self->{li}, ) = unpack('vvv',substr(${$self->{buf}},$self->{off},6)); $self->{bib} = ($self->{bsn} >> 15) & 0x01; $self->{bsn} &= 0x0fff; $self->{fib} = ($self->{fsn} >> 15) & 0x01; $self->{fsn} &= 0x0fff; $self->{li0} = ($self->{li} >> 14) & 0x03; $self->{li} &= 0x01ff; $self->{off} += 6; } else { return; } my $len = $self->{end} - $self->{off}; if (($self->{li} != $len) && ($len <= 63 || $self->{li} != 63)) { print STDERR "W: $self: bad length indicator $self->{li} != $$len\n"; } if ($self->{li0} != 0) { $decoder->setrt(::RT_24BIT_PC) if $decoder->{rt} == ::RT_UNKNOWN; $decoder->setpr(::MP_JAPAN) if $decoder->{pr} == ::MP_UNKNOWN; } my $li = $self->{li}; $li = 3 if $li > 3; my $type = LI_TYPES->[$self->{li}]; bless $self,ref($self)."::$type"; return $self->unpack(@_); } sub testit { my $self = shift; my ($decoder) = @_; my $len = $self->{end} - $self->{off}; if (3 <= $len && $len <= 5) { $decoder->setht(::HT_BASIC); return 1; } elsif (6 <= $len && $len <= 8) { $decoder->setht(::HT_EXTENDED); return 1; } } sub dissect { my $self = shift; my $off = $self->{beg}; if ($self->{ht} == ::HT_EXTENDED) { my $bsn0 = (unpack('v',substr(${$self->{buf}},$off+0,2)) >> 12) & 0x7; my $fsn0 = (unpack('v',substr(${$self->{buf}},$off+2,2)) >> 12) & 0x7; my $li0 = (unpack('v',substr(${$self->{buf}},$off+4,2)) >> 9) & 0x1f; my $li = $self->{li}; $li = 3 if $li > 3; $li = LI_TYPES->{$li}."($self->{li})"; return 'MTP Level 2 Extended Header', [ [$off+ 0,Frame::bytes($self->{bsn},0x0fff,2),'BSN',$self->{bsn}], [$off+ 0,Frame::spare($bsn0, 0x7000,2),'Spare',$bsn0], [$off+ 0,Frame::bytes($self->{bib},0x8000,2),'BIB',$self->{bib}], [$off+ 2,Frame::bytes($self->{fsn},0x0fff,2),'FSN',$self->{fsn}], [$off+ 2,Frame::spare($fsn0, 0x7000,2),'Spare',$fsn0], [$off+ 2,Frame::bytes($self->{fib},0x8000,2),'FIB',$self->{fib}], [$off+ 4,Frame::bytes($self->{li}, 0x01ff,2),'LI',$li], [$off+ 4,Frame::spare($li0, 0x3e00,2),'Spare',$li0], [$off+ 4,Frame::bytes($self->{li0},0xc000,2),'LI0',$self->{li0}], ],@_; } elsif ($self->{ht} == ::HT_BASIC) { my $li = $self->{li}; $li = 3 if $li > 3; $li = LI_TYPES->{$li}."($self->{li})"; return 'MTP Level 2 Basic Header', [ [$off+ 0,Frame::bytes($self->{bsn},0x7f,1),'BSN',$self->{bsn}], [$off+ 0,Frame::bytes($self->{bib},0x80,1),'BIB',$self->{bib}], [$off+ 1,Frame::bytes($self->{fsn},0x7f,1),'FSN',$self->{fsn}], [$off+ 1,Frame::bytes($self->{fib},0x80,1),'FIB',$self->{fib}], [$off+ 2,Frame::bytes($self->{li}, 0x3f,1),'LI', $li} ], [$off+ 2,Frame::bytes($self->{li0},0xc0,1),'LI0',$self->{li0}], ],@_; } else { return 'Unknown MTP Level 2 Header Type', [ [$off,' ******** ','DATA',Frame::pdata(substr($$self->{buf},$self->{off},$self->{end}-$self->{off})], ],@_; } } # ------------------------------------- package Message::MTP2::FISU; our @ISA = qw(Message::MTP2); # ------------------------------------- package Message::MTP2::LSSU; our @ISA = qw(Message::MTP2); # ------------------------------------- use constant { LSSU_TYPES=>{ 'SIO', 'SIN', 'SIE', 'SIOS', 'SIPO', 'SIB' } }; sub unpack { my $self = shift; $self->{stat} = unpack('C',substr(${$self->{buf}},$self->{off},1)) & 0x7; $self->{off}++; return unless exists LSSU_TYPES->[$self->{stat}]; my $type = LSSU_TYPES->[$self->{stat}]; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{beg} + $self->{ht}; my $stat = $self->{stat}; $stat = LSSU_TYPES->[$stat]."($stat)"; my ($mask,$stat0,$mask0); my $li = $self->{li}; if ($li == 1) { $mask = 0x07; $stat0 = unpack('C',substr(${$self->{buf}},$off,1)) >> 3; $mask0 = 0xf8; } else { $mask = 0x0007; $stat0 = unpack('v',substr(${$self->{buf}},$off,2)) >> 3; $mask0 = 0xfff8; } return $self->SUPER::dissect(@_), "Link Status $stat", [ [$off+0,Frame::bytes($self->{stat},$mask, $li),'Status',$stat], [$off+0,Frame::spare($stat0, $mask0,$li),'Spare',$stat0], ]; }; package Message::MTP2::LSSU::SIO; our @ISA = qw(Message::MTP2::LSSU); package Message::MTP2::LSSU::SIN; our @ISA = qw(Message::MTP2::LSSU); package Message::MTP2::LSSU::SIE; our @ISA = qw(Message::MTP2::LSSU); package Message::MTP2::LSSU::SIOS; our @ISA = qw(Message::MTP2::LSSU); package Message::MTP2::LSSU::SIPO; our @ISA = qw(Message::MTP2::LSSU); package Message::MTP2::LSSU::SIB; our @ISA = qw(Message::MTP2::LSSU); # ------------------------------------- package Message::MTP2::MSU; our @ISA = qw(Message::MTP2); # ------------------------------------- sub unpack { return shift } sub decode { return new Message::MTP3(@_); } sub detect { return try Message::MTP3(@_); } # ------------------------------------- package Message::MTP3; our @ISA = qw(Message); # ------------------------------------- use constant { SI_VALUES=>{ 0=>'SNMM', 1=>'SNTM', 2=>'SNSM', 3=>'SCCP', 4=>'TUP', 5=>'ISUP', }, }; #package Message::MTP3; sub unpack { my $self = shift; { my ($decoder) = @_; $self->{ht} = $decoder->{ht}; $self->{rt} = $decoder->{rt}; $self->{pr} = $decoder->{pr}; } $self->{si} = unpack('C',substr(${$self->{buf}},$self->{off},1)); $self->{ni} = ($self->{si} >> 6) & 0x03; $self->{mp} = ($self->{si} >> 4) & 0x03; $self->{si} &= 0x0f; my $type = (exists SI_VALUES->{$self->{si}}) ? SI_VALUES->{$self->{si}} : 'USER'; $self->{mp} = $self->{li0} if $self->{pr} == ::MP_JAPAN; $self->{mp} = 0 if $self->{pr} == ::MP_INTERNATIONAL; $self->{off}++; my $flav; if ($self->{ni} < 2 or $self->{rt} == ::RT_14BIT_PC) { return unless $self->{li} >= 6; $self->{dpc} = (unpack('v',substr(${$self->{buf}},$self->{off}+0,2)) >> 0) & 0x3fff; $self->{opc} = (unpack('V',substr(${$self->{buf}},$self->{off}+1,4)) >> 2) & 0x3fff; $self->{sls} = (unpack('C',substr(${$self->{buf}},$self->{off}+3,1)) >> 4) & 0x0f; $self->{off} += 4; $flav = 'ITUT'; } elsif ($self->{rt} == ::RT_24BIT_PC) { return unless $self->{li} >= 9; $self->{dpc} = unpack('V',substr(${$self->{buf}},$self->{off}+0,4)) & 0x00ffffff; $self->{opc} = unpack('V',substr(${$self->{buf}},$self->{off}+3,4)) & 0x00ffffff; $self->{sls} = unpack('C',substr(${$self->{buf}},$self->{off}+6,1)); $self->{off} += 7; $flav = 'ANSI'; } else { return -1; } bless $self,"Message::$flav::$type"; return $self->unpack(@_); } #package Message::MTP3; use constant { NI_VALUES=>{ 0=>'International', 1=>'International reserved', 2=>'National', 3=>'National reserved', }, }; #package Message::MTP3; sub dissect { my $self = shift; my $off = $self->{beg}; my $si = $self->{si}; $si = SI_VALUES->{$si}."($si)" if exists SI_VALUES->{$si}; my $ni = $self->{ni}; $ni = NI_VALUES->{$ni}."($ni)"; if ($self->{ni} < 2 or $self->{rt} == ::RT_14BIT_PC) { my $dpc = $self->{dpc}; $dpc = (($dpc>>11)&0x7).'-'.(($dpc>>3)&0xff).'-'.(($dpc>>0)&0x7); my $opc = $self->{opc}; $opc = (($opc>>11)&0x7).'-'.(($opc>>3)&0xff).'-'.(($opc>>0)&0x7); my $sls = $self->{sls}; return "ITU-T $si Message", [ [$off+0,Frame::bytes($self->{si},0x0f,1),'SI',$si], 'ITU-T Routing Label', [ [$off+0,Frame::bytes($self->{mp},0x30,1),'MP',$self->{mp}], [$off+0,Frame::bytes($self->{ni},0xc0,1),'NI',$ni], [$off+1,Frame::bytes($self->{dpc},0x00003fff,4),'DPC',$dpc], [$off+1,Frame::bytes($self->{opc},0x0fffc000,4),'OPC',$opc], [$off+1,Frame::bytes($self->{sls},0xf0000000,4),'SLS',$sls], ], ],@_; } elsif ($self->{rt} == ::RT_24BIT_PC) { my $dpc = $self->{dpc}; $dpc = (($dpc>>16)&0xff).'-'.(($dpc>>8)&0xff).'-'.(($dpc>>0)&0xff); my $opc = $self->{opc}; $opc = (($opc>>16)&0xff).'-'.(($opc>>8)&0xff).'-'.(($opc>>0)&0xff); my $sls = $self->{sls}; return "ANSI $si Message", [ [$off+0,Frame::bytes($self->{si},0x0f,1),'SI',$si], 'ANSI Routing Label', [ [$off+0,Frame::bytes($self->{mp},0x30,1),'MP',$self->{mp}], [$off+0,Frame::bytes($self->{ni},0xc0,1),'NI',$ni], [$off+1,Frame::bytes($self->{dpc},0xffffff,3),'DPC',$dpc], [$off+4,Frame::bytes($self->{opc},0xffffff,3),'OPC',$opc], [$off+7,Frame::bytes($self->{sls},0xff,1),'SLS',$sls], ], ],@_; } else { return "Unknown RL for $si Message", [ [$off,' ******** ','DATA',Frame::pdata(substr($$self->{buf},$self->{beg},$self->{end}-$self->{beg}], ],@_; } } #package Message::MTP3; sub testit { my $self = shift; my ($decoder) = @_; $self->{si} = unpack('C',substr(${$self->{buf}},$self->{off},1)); $self->{ni} = ($self->{si} >> 6) & 0x03; $self->{mp} = ($self->{si} >> 4) & 0x03; $self->{si} &= 0x0f; unless (exists SI_VALUES->{$self->{si}}) { warn "$self: no message type for si=$self->{si}"; } if ($self->{ni} == 0) { $decoder->setrt(::RT_14BIT_PC); $decoder->setpr(::MP_INTERNATIONAL); } if ($decoder->{pr} == ::MP_UNKNOWN) { $decoder->setpr(::MP_NATIONAL) if $self->{mp} != 0; } elsif ($decoder->{pr} == ::MP_JAPAN) { $self->{mp} = $self->{li0}; } elsif ($decoder->{pr} == ::MP_INTERNATIONAL) { $self->{mp} = 0; } if ($self->{li} < ::HT_EXTENDED) { warn "$self: too short for RL, li = $self->{li}"; return -1; } if ($self->{li} < 9 || ($self->{si} == 5 && $self->{li} < 11)) { $decoder->setrt(::RT_14BIT_PC); } if ($decoder->{rt} == ::RT_UNKNOWN) { my @b = (unpack('C*', substr(${$self->{buf}}, $self->{off}, 11))); my $ret = $self->_checkRoutingLabelType(\@b); return if $ret <= 0; } return 1; } #package Message::MTP3; use constant { PT_YES => 1, PT_MAYBE => 0, PT_NO => -1 }; #package Message::MTP3; sub _checkRoutingLabelType { my $self = shift; if ($self->{si} == 0) { return $self->_checkSnmm(@_); } elsif ($self->{si} == 1) { return $self->_checkSntm(@_); } elsif ($self->{si} == 2) { return $self->_checkSnsm(@_); } elsif ($self->{si} == 3) { return $self->_checkSccp(@_); } elsif ($self->{si} == 5) { return $self->_checkIsup(@_); } return 0; } #package Message::MTP3; sub _checkSnmm { my $self = shift; my $ansi = $self->_checkAnsiSnmm(@_); my $itut = $self->_checkItutSnmm(@_); if ($ansi == PT_YES) { return 0 if $itut == PT_YES; $self->{rt} = ::RT_24BIT_PC; return 1; } elsif ($ansi == PT_MAYBE) { return 0 if $itut == PT_MAYBE; if ($itut == PT_YES) { $self->{rt} = ::RT_14BIT_PC; } else { $self->{rt} = ::RT_24BIT_PC; } return 1; } else { return -1 if $itut == PT_NO; $self->{rt} = ::RT_14BIT_PC; return 1; } } #package Message::MTP3; sub _checkItutSnmm { my ($self,$b) = @_; my $mt = (($b->[5] & 0x0f) << 4) | ($b->[5] >> 4); if ($self->{li} == 6) { return PT_YES if $mt == 0x17 || $mt == 0x27 || $mt == 0x13 || $mt == 0x28 || $mt == 0x38 || $mt == 0x48 || $mt == 0x12 || $mt == 0x22 || $mt == 0x16 || $mt == 0x26 || $mt == 0x36 || $mt == 0x46 || $mt == 0x56 || $mt == 0x66 || $mt == 0x76 || $mt == 0x86; return PT_NO; } if ($self->{li} == 7) { return PT_YES if $mt == 0x11 || $mt == 0x21 || $mt == 0x51 || $mt == 0x61; return PT_NO; } if ($self->{li} == 8) { return PT_YES if $mt == 0x23 || $mt == 0x14 || $mt == 0x24 || $mt == 0x34 || $mt == 0x44 || $mt == 0x54 || $mt == 0x64 || $mt == 0x15 || $mt == 0x25 || $mt == 0x35 || $mt == 0x45; return PT_NO; } if ($self->{li} == 9) { return PT_YES if $mt == 0x1a || $mt == 0x2a || $mt == 0x3a; return PT_NO; } return PT_NO; } #package Message::MTP3; sub _checkAnsiSnmm { my ($self,$b) = @_; my $mt = (($b->[8] & 0x0f) << 4) | ($b->[8] >> 4); return PT_NO if $self->{li} < 9; if ($self->{li} == 9) { return PT_YES if $mt == 0x17 || $mt == 0x27 || $mt == 0x13; return PT_NO; } if ($self->{li} == 10) { return PT_YES if $mt == 0x28 || $mt == 0x38 || $mt == 0x38 || $mt == 0x48 || $mt == 0x12 || $mt == 0x22 || $mt == 0x16 || $mt == 0x26 || $mt == 0x36 || $mt == 0x46 || $mt == 0x56 || $mt == 0x66 || $mt == 0x76 || $mt == 0x86; return PT_NO; } if ($self->{li} == 11) { return PT_YES if $mt == 0x11 || $mt == 0x21 || $mt == 0x51 || $mt == 0x61; return PT_NO; } if ($self->{li} == 12) { return PT_YES if $mt == 0x14 || $mt == 0x24 || $mt == 0x34 || $mt == 0x44 || $mt == 0x54 || $mt == 0x64 || $mt == 0x15 || $mt == 0x25 || $mt == 0x35 || $mt == 0x45 || $mt == 0x18; return PT_NO; } if ($self->{li} == 13) { return PT_YES if $mt == 0x23 || $mt == 0x1a || $mt == 0x2a || $mt == 0x3a; return PT_NO; } return PT_NO; } #package Message::MTP3; sub _checkSntm { my $self = shift; my $ansi = $self->_checkAnsiSntm(@_); my $itut = $self->checkItutSntm(@_); if ($ansi == PT_YES) { return 0 if $itut == PT_YES; $self->{rt} = ::RT_24BIT_PC; return 1; } elsif ($ansi == PT_MAYBE) { return 0 if $itut == PT_MAYBE; if ($itut == PT_YES) { $self->{rt} = ::RT_14BIT_PC; } else { $self->{rt} = ::RT_24BIT_PC; } return 1; } else { return -1 if $itut == PT_NO; $self->{rt} = ::RT_14BIT_PC; return 1; } } #package Message::MTP3; sub _checkItutSntm { my ($self,$b) = @_; my $mt = (($b->[5] & 0x0f) << 4) | ($b->[5] >> 4); return PT_NO if 7 > $self->{li} || $self->{li} > 22; return PT_NO if $mt != 0x11 && $mt != 0x12; if (($b->[6] >> 4) == $self->{li} - 7) { return PT_YES if 7 <= $self->{li} && $self->{li} <= 9; return PT_MAYBE; } return PT_NO; } #package Message::MTP3; sub _checkAnsiSntm { my ($self,$b) = @_; my $mt = (($b->[8] & 0x0f) << 4) | ($b->[8] >> 4); return PT_NO if 10 > $self->{li} || $self->{li} > 25; return PT_NO if $mt != 0x11 && $mt != 0x12; if (($b->[9] >> 4) == $self->{li} - 10) { return PT_YES if 23 <= $self->{li} && $self->{li} <= 25; return PT_MAYBE; } return PT_NO; } #package Message::MTP3; sub _checkSnsm { my $self = shift; my $ansi = $self->_checkAnsiSnsm(@_); my $itut = $self->_checkItutSntm(@_); if ($ansi == PT_YES) { return 0 if $itut == PT_YES; $self->{rt} = ::RT_24BIT_PC; return 1; } elsif ($ansi == PT_MAYBE) { return 0 if $itut == PT_MAYBE; if ($itut == PT_YES) { $self->{rt} = ::RT_14BIT_PC; } else { $self->{rt} = ::RT_24BIT_PC; } return 1; } else { return -1 if $itut == PT_NO; $self->{rt} = ::RT_14BIT_PC; return 1; } } #package Message::MTP3; sub _checkItutSnsm { return PT_NO; } #package Message::MTP3; sub _checkAnsiSnsm { my $self = shift; return $self->_checkAnsiSntm(@_); } #package Message::MTP3; sub _checkSccp { my $self = shift; my $ansi = $self->_checkAnsiSccp(@_); my $itut = $self->_checkItutSccp(@_); if ($ansi == PT_YES) { return 0 if $itut == PT_YES; $self->{rt} = ::RT_24BIT_PC; return 1; } elsif ($ansi == PT_MAYBE) { return 0 if $itut == PT_MAYBE; if ($itut == PT_YES) { $self->{rt} = ::RT_14BIT_PC; } else { $self->{rt} = ::RT_24BIT_PC; } return 1; } else { return -1 if $itut == PT_NO; $self->{rt} = ::RT_14BIT_PC; return 1; } } #package Message::MTP3; sub _checkItutSccp { my ($self,$b) = @_; my $mt = $b->[5]; return PT_MAYBE if 0x01 <= $mt && $mt <= 0x14; return PT_NO; } #package Message::MTP3; sub _checkAnsiSccp { my ($self,$b) = @_; my $mt = $b->[8]; return PT_MAYBE if 0x01 <= $mt && $mt <= 0x14; return PT_NO; } #package Message::MTP3; sub _checkIsup { my $self = shift; my $ansi = $self->_checkAnsiIsup(@_); my $itut = $self->_checkItutIsup(@_); if ($ansi == PT_YES) { return 0 if $itut == PT_YES; $self->{rt} = ::RT_24BIT_PC; return 1; } elsif ($ansi == PT_MAYBE) { return 0 if $itut == PT_MAYBE; if ($itut == PT_YES) { $self->{rt} = ::RT_14BIT_PC; } else { $self->{rt} = ::RT_24BIT_PC; } return 1; } else { return -1 if $itut == PT_NO; $self->{rt} = ::RT_14BIT_PC; return 1; } } #package Message::MTP3; sub _checkItutIsup { my ($self,$b) = @_; my $mt = $b->[7]; return PT_NO if $self->{li} < 8; if ($mt == 0x11 || $mt == 0x12 || $mt == 0x13 || $mt == 0x14 || $mt == 0x15 || $mt == 0x16 || $mt == 0x24 || $mt == 0x2e || $mt == 0x30 || $mt == 0x31) { return PT_NO if $self->{li} != 8; return PT_YES; } if ($mt == 0x05) { return PT_NO if $self->{li} != 9; return PT_YES; } if ($mt == 0x10 || $mt == 0x27 || $mt == 0x08 || $mt == 0x09 || $mt == 0x34 || $mt == 0x33 || $mt == 0x35 || $mt == 0x36 || $mt == 0x37 || $mt == 0x38 || $mt == 0x32) { return PT_NO if $self->{li} < 9; if ($self->{li} > 9) { return PT_NO if $b->[8] == 0; return PT_YES if $self->{li} < 11; return PT_MAYBE; } return PT_NO if $b->[8] != 0; return PT_YES; } if ($mt == 0x03 || $mt == 0x04 || $mt == 0x06 || $mt == 0x0d || $mt == 0x0e || $mt == 0x1c || $mt == 0x1d || $mt == 0x1e || $mt == 0x1f || $mt == 0x20 || $mt == 0x2c) { return PT_NO if $self->{li} < 10; if ($self->{li} > 10) { return PT_NO if $b->[8] == 0; return PT_MAYBE; } return PT_NO if $b->[8] != 0; return PT_YES; } if ($mt == 0x01) { return PT_NO if $self->{li} < 18; return PT_MAYBE; } if ($mt == 0x21 || $mt == 0x2b) { return PT_NO if $self->{li} < 14; return PT_MAYBE; } if ($mt == 0x02 || $mt == 0x0c || $mt == 0x2f) { return PT_NO if $self->{li} < 13; return PT_MAYBE; } if ($mt == 0x17 || $mt == 0x2d || $mt == 0x18 || $mt == 0x1a || $mt == 0x19 || $mt == 0x1b) { return PT_NO if $self->{li} < 12; return PT_MAYBE; } if ($mt == 0x07) { return PT_NO if $self->{li} < 11; if ($self->{li} > 11) { return PT_NO if $b->[10] == 0; return PT_MAYBE; } return PT_NO if $b->[10] != 0; return PT_YES; } if ($mt == 0x29 || $mt == 0x2a) { return PT_NO if $self->{li} < 11; return PT_MAYBE; } if ($mt == 0x28) { return PT_MAYBE; } if ($mt == 0x22 || $mt == 0x23 || $mt == 0xe9 || $mt == 0xea || $mt == 0xeb || $mt == 0xec || $mt == 0xed || $mt == 0xf8 || $mt == 0xfc || $mt == 0xfd || $mt == 0xfe || $mt == 0xff || $mt == 0x25 || $mt == 0x26) { return PT_NO; } return PT_NO; } #package Message::MTP3; sub _checkAnsiIsup { my ($self,$b) = @_; my $mt = $b->[10]; return PT_NO if $self->{li} < 11; if ($mt == 0x10 || $mt == 0x11 || $mt == 0x12 || $mt == 0x13 || $mt == 0x14 || $mt == 0x15 || $mt == 0x16 || $mt == 0x24 || $mt == 0x2e || $mt == 0xe9 || $mt == 0xec) { return PT_NO if $self->{li} != 11; return PT_MAYBE; } if ($mt == 0xed) { return PT_NO if $self->{li} < 12; if ($self->{li} > 12) { return PT_NO if $b->[11] == 0; return PT_MAYBE; } return PT_NO if $b->[11] != 0; return PT_MAYBE; } if ($mt == 0x05 || $mt == 0xea) { return PT_NO if $self->{li} != 12; return PT_MAYBE; } if (exists ISUP_TYPES->{$mt}) { return PT_MAYBE; } return PT_MAYBE; } # ------------------------------------- package Message::ITUT::MTP3; our @ISA = qw(Message::MTP3); # ------------------------------------- use constant { SI_VALUES=>{ 0=>'SNMM', 1=>'SNTM', 2=>'SNSM', 3=>'SCCP', 4=>'TUP', 5=>'ISUP', }, NI_VALUES=>{ 0=>'International', 1=>'International reserved', 2=>'National', 3=>'National reserved', }, }; sub dissect { my $off = $self->{beg}; my $si = $self->{si}; $si = SI_VALUES->{$si}."($si)" if exists SI_VALUES->{$si}; my $ni = $self->{ni}; $ni = NI_VALUES->{$ni}."($ni)"; my $dpc = $self->{dpc}; $dpc = (($dpc>>11)&0x7).'-'.(($dpc>>3)&0xff).'-'.(($dpc>>0)&0x7); my $opc = $self->{opc}; $opc = (($opc>>11)&0x7).'-'.(($opc>>3)&0xff).'-'.(($opc>>0)&0x7); my $sls = $self->{sls}; return "ITU-T $si Message", [ [$off+0,Frame::bytes($self->{si},0x0f,1),'SI',$si], 'ITU-T Routing Label', [ [$off+0,Frame::bytes($self->{mp},0x30,1),'MP',$self->{mp}], [$off+0,Frame::bytes($self->{ni},0xc0,1),'NI',$ni], [$off+1,Frame::bytes($self->{dpc},0x00003fff,4),'DPC',$dpc], [$off+1,Frame::bytes($self->{opc},0x0fffc000,4),'OPC',$opc], [$off+1,Frame::bytes($self->{sls},0xf0000000,4),'SLS',$sls], ], @_, ]; } # ------------------------------------- package Message::ANSI::MTP3; our @ISA = qw(Message::MTP3); # ------------------------------------- use constant { SI_VALUES=>{ 0=>'SNMM', 1=>'SNTM', 2=>'SNSM', 3=>'SCCP', 4=>'TUP', 5=>'ISUP', }, NI_VALUES=>{ 0=>'International', 1=>'International reserved', 2=>'National', 3=>'National reserved', }, }; sub dissect { my $off = $self->{beg}; my $si = $self->{si}; $si = SI_VALUES->{$si}."($si)" if exists SI_VALUES->{$si}; my $ni = $self->{ni}; $ni = NI_VALUES->{$ni}."($ni)"; my $dpc = $self->{dpc}; $dpc = (($dpc>>16)&0xff).'-'.(($dpc>>8)&0xff).'-'.(($dpc>>0)&0xff); my $opc = $self->{opc}; $opc = (($opc>>16)&0xff).'-'.(($opc>>8)&0xff).'-'.(($opc>>0)&0xff); my $sls = $self->{sls}; return "ANSI $si Message", [ [$off+0,Frame::bytes($self->{si},0x0f,1),'SI',$si], 'ANSI Routing Label', [ [$off+0,Frame::bytes($self->{mp},0x30,1),'MP',$self->{mp}], [$off+0,Frame::bytes($self->{ni},0xc0,1),'NI',$ni], [$off+1,Frame::bytes($self->{dpc},0xffffff,3),'DPC',$dpc], [$off+4,Frame::bytes($self->{opc},0xffffff,3),'OPC',$opc], [$off+7,Frame::bytes($self->{sls},0xff,1),'SLS',$sls], ]; @_, ]; } # ------------------------------------- # ------------------------------------- package Message::MTP3::MGMT; our @ISA = qw(Message::MTP3); # ------------------------------------- sub dissect { my $self = shift; return $self->Message::MTP3::dissect(@_) if exists $self->{mtp3}; return $self->Message::M3UA::XFER::DATA::dissect(@_) if exists $self->{m3ua}; } # ------------------------------------- package Message::SNMM; our @ISA = qw(Message::MTP3::MGMT); # ------------------------------------- use constant { SNMM_TYPES=>{ 0x11 => 'COO', 0x12 => 'COA', 0x15 => 'CBD', 0x16 => 'CBA', 0x21 => 'ECO', 0x22 => 'ECA', 0x31 => 'RCT', 0x32 => 'TFC', 0x41 => 'TFP', 0x42 => 'TCP', 0x43 => 'TFR', 0x44 => 'TCR', 0x45 => 'TFA', 0x46 => 'TCA', 0x51 => 'RST', 0x52 => 'RSR', 0x53 => 'RCP', 0x54 => 'RCR', 0x61 => 'LIN', 0x62 => 'LUN', 0x63 => 'LIA', 0x64 => 'LUA', 0x65 => 'LID', 0x66 => 'LFU', 0x67 => 'LLT', 0x68 => 'LRT', 0x71 => 'TRA', 0x72 => 'TRW', 0x81 => 'DLC', 0x82 => 'CSS', 0x83 => 'CNS', 0x84 => 'CNP', 0xa1 => 'UPU', 0xa2 => 'UPA', 0xa3 => 'UPT', }, }; sub unpack { my $self = shift; $self->{snmm}->{off} = $self->{off}; $self->{snmm}->{end} = $self->{end}; $self->{mt} = unpack('C',substr(${$self->{buf}},$self->{off},1)); $self->{off} += 1; $self->{h0} = ($self->{mt}>>0)&0xf; $self->{h1} = ($self->{mt}>>4)&0xf; $self->{mt} = ($self->{h0}<<4)|$self->{h1}; my $type = SNMM_TYPES->{$self->{mt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self->unpack(@_); } sub dissect { my $self = shift; my $off = $self->{beg}; my $mt = $self->{mt}; $mt = SNMM_TYPES->{$mt}.sprintf('(%02x)',$mt); return "$mt Message", [ [$off+0,Frame::bytes($self->{h0},0x0f,1),'H0',sprintf('0x%1X',$self->{h0})], [$off+0,Frame::bytes($self->{h1},0xf0,1),'H1',sprintf('0x%1X',$self->{h1})], @_, ]; } # ------------------------------------- package Message::ITUT::SNMM; our @ISA = qw(Message::SNMM); package Message::ANSI::SNMM; our @ISA = qw(Message::SNMM); # ------------------------------------- # ------------------------------------- package Message::ITUT::SNMM::COM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{fsnl} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{fsnl} &= 0x7f; $self->{slc} = $self->{sls}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $fsnl0 = unpack('C',substr(${$self->{buf}},$off,1)) >> 7 return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{fsnl},0x7f,1),'FSNL',$self->{fsnl}], [$off+0,Frame::spare($fsnl0,0x80,1),'Spare',$fsnl0], ); } package Message::ITUT::SNMM::COO; our @ISA = qw(Message::ITUT::SNMM::COM); package Message::ITUT::SNMM::COA; our @ISA = qw(Message::ITUT::SNMM::COM); # ------------------------------------- package Message::ANSI::SNMM::COM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{fsnl} = unpack('v',substr(${$self->{buf}},$off,2)); $off+=2; $self->{slc} = $self->{fsnl} & 0x0f; $self->{fsnl} >>= 4; $self->{fsnl} &= 0x7f; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $fsnl0 = unpack('C',substr(${$self->{buf}},$off+1))>>3; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{slc}, 0x000f,2),'SLC', $self->{slc}], [$off+0,Frame::bytes($self->{fsnl},0x07f0,2),'FSNL',$self->{fsnl}], [$off+0,Frame::spare($fsnl0, 0xf800,2),'Spare',$fsnl0], ); } package Message::ANSI::SNMM::COO; our @ISA = qw(Message::ANSI::SNMM::COM); package Message::ANSI::SNMM::COA; our @ISA = qw(Message::ANSI::SNMM::COM); # ------------------------------------- package Message::ITUT::SNMM::CBM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{cbc} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{slc} = $self->{sls}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{cbc},0xff,1),'CBC',$self->{cbc}], ); } package Message::ITUT::SNMM::CBD; our @ISA = qw(Message::ITUT::SNMM::CBM); package Message::ITUT::SNMM::CBA; our @ISA = qw(Message::ITUT::SNMM::CBM); # ------------------------------------- package Message::ANSI::SNMM::CBM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{cbc} = unpack('v',substr(${$self->{buf}},$off,2)); $off+=2; $self->{slc} = $self->{cbc} & 0x0f; $self->{cbc} >>= 4; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{slc},0x000f,2),'SLC',$self->{slc}], [$off+0,Frame::bytes($self->{cbc},0xfff0,2),'CBC',$self->{cbc}], ); } package Message::ANSI::SNMM::CBD; our @ISA = qw(Message::ANSI::SNMM::CBM); package Message::ANSI::SNMM::CBA; our @ISA = qw(Message::ANSI::SNMM::CBM); # ------------------------------------- package Message::ITUT::SNMM::SLM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; $self->{slc} = $self->{sls}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect(); } package Message::ITUT::SNMM::ECO; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::ECA; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LIN; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LUN; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LIA; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LUA; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LID; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LFU; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LLT; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::LRT; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::CSS; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::CNS; our @ISA = qw(Message::ITUT::SNMM::SLM); package Message::ITUT::SNMM::CNP; our @ISA = qw(Message::ITUT::SNMM::SLM); # ------------------------------------- package Message::ANSI::SNMM::SLM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{slc} = unpack('C',substr(${$self->{buf}},$off,1)) & 0x0f; $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $slc0 = unpack('C',substr(${$self->{buf}},$off,1))>>4; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{slc},0x0f,1),'SLC',$self->{slc}], [$off+0,Frame::spare($slc0, 0xf0,1),'Spare',$slc0], ); } package Message::ANSI::SNMM::ECO; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::ECA; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LIN; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LUN; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LIA; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LUA; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LID; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LFU; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LLT; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::LRT; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::CSS; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::CNS; our @ISA = qw(Message::ANSI::SNMM::SLM); package Message::ANSI::SNMM::CNP; our @ISA = qw(Message::ANSI::SNMM::SLM); # ------------------------------------- package Message::SNMM::SIF; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect(); } # ------------------------------------- package Message::ITUT::SNMM::SIF; our @ISA = qw(Message::SNMM::SIF); package Message::ITUT::SNMM::RCT; our @ISA = qw(Message::ITUT::SNMM::SIF); package Message::ITUT::SNMM::TRA; our @ISA = qw(Message::ITUT::SNMM::SIF); package Message::ITUT::SNMM::TRW; our @ISA = qw(Message::ITUT::SNMM::SIF); package Message::ANSI::SNMM::SIF; our @ISA = qw(Message::SNMM::SIF); package Message::ANSI::SNMM::RCT; our @ISA = qw(Message::ANSI::SNMM::SIF); package Message::ANSI::SNMM::TRA; our @ISA = qw(Message::ANSI::SNMM::SIF); package Message::ANSI::SNMM::TRW; our @ISA = qw(Message::ANSI::SNMM::SIF); # ------------------------------------- package Message::ITUT::SNMM::TFC; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('v',substr(${$self->{buf}},$off,2)); $off+=2; $self->{stat} = ($self->{dest} >> 14) & 0x3; $self->{dest} &= 0x3fff; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>11)&0x7).'-'.(($dest>>3)&0xff).'-'.(($dest>>0)&0x7); return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x3fff,2),'DEST',$dest], [$off+0,Frame::bytes($self->{stat},0xc000,2),'STAT',$self->{stat}], ); } #package Message::ITUT::SNMM::TFC; our @ISA = qw(Message::ITUT::SNMM); # ------------------------------------- package Message::ANSI::SNMM::TFC; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('V',substr(${$self->{buf}},$off,4)); $off+=4; $self->{stat} = ($self->{dest} >> 24) & 0x3; $self->{dest} &= 0x00ffffff; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>16)&0xff).'-'.(($dest>>8)&0xff).'-'.(($dest>>0)&0xff); my $stat0 = unpack('C',substr(${$self->{buf}},$off+3,1))>>2; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x00ffffff,4),'DEST',$dest], [$off+0,Frame::bytes($self->{stat},0x03000000,4),'STAT',$self->{stat}], [$off+0,Frame::spare($stat0, 0xfc000000,4),'Spare',$stat0], ); } #package Message::ANSI::SNMM::TFC; our @ISA = qw(Message::ANSI::SNMM); # ------------------------------------- package Message::ITUT::SNMM::TFM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('v',substr(${$self->{buf}},$off,2)) & 0x3fff; $off+=2; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>11)&0x7).'-'.(($dest>>3)&0xff).'-'.(($dest>>0)&0x7); my $dest0 = unpack('C',substr(${$self->{buf}},$off+1,1))>>6; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x3fff,2),'DEST',$dest], [$off+0,Frame::bytes($dest0, 0xc000,2),'Spare',$dest0], ); } package Message::ITUT::SNMM::TFP; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::TCP; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::TFR; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::TCR; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::TFA; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::TCA; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::RST; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::RSR; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::RCP; our @ISA = qw(Message::ITUT::SNMM::TFM); package Message::ITUT::SNMM::RCR; our @ISA = qw(Message::ITUT::SNMM::TFM); # ------------------------------------- package Message::ANSI::SNMM::TFM; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('V',substr(${$self->{buf}}.pack('C',0),$off,4)) & 0x00ffffff; $off+=4; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>16)&0xff).'-'.(($dest>>8)&0xff).'-'.(($dest>>0)&0xff); return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x00ffffff,4),'DEST',$dest], ); } package Message::ANSI::SNMM::TFP; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::TCP; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::TFR; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::TCR; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::TFA; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::TCA; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::RST; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::RSR; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::RCP; our @ISA = qw(Message::ANSI::SNMM::TFM); package Message::ANSI::SNMM::RCR; our @ISA = qw(Message::ANSI::SNMM::TFM); # ------------------------------------- package Message::ITUT::SNMM::DLC; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{sdli} = unpack('v',substr(${$self->{buf}},$off,2)) & 0x0fff; $off+=2; $self->{slc} = $self->{sls}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $sdli0 = unpack('C',substr(${$self->{buf}},$off+1,1)) >> 4; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{sdli},0x0fff,2),'SDLI',$self->{sdli}], [$off+0,Frame::spare($sdli0, 0xf000,2),'Spare',$sdli0], ); } #package Message::ITUT::SNMM::DLC; our @ISA = qw(Message::ITUT::SNMM); # ------------------------------------- package Message::ANSI::SNMM::DLC; our @ISA = qw(Message::SNMM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{sdli} = unpack('V',substr(${$self->{buf}}.pack('C',0),$off,4)); $off+=4; $self->{slc} = $self->{sdli} & 0x0f; $self->{sdli} >>= 4; $self->{sdli} &= 0x3fff; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $sdli0 = unpack('C',substr(${$self->{buf}},$off+2,1)) >> 2; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{slc}, 0x00000f,3),'SLC', $self->{slc}], [$off+0,Frame::bytes($self->{sdli},0x03fff0,3),'SDLI',$self->{sdli}], [$off+0,Frame::spare($sdli0, 0xfc0000,3),'Spare',$sdli0], ); } #package Message::ANSI::SNMM::DLC; our @ISA = qw(Message::ANSI::SNMM); # ------------------------------------- package Message::ITUT::SNMM::UPM; our @ISA = qw(Message::SNMM); # ------------------------------------- use constant { UPI_VALUES=>[ 'Spare', 'Spare', 'Spare', 'SCCP', 'TUP', 'ISUP', 'DUP', 'Spare', 'MTUP', 'B-ISUP', 'S-ISUP', 'Spare', 'Spare', 'Spare', 'Spare', 'Spare', ], }; sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('v',substr(${$self->{buf}},$off,2)) & 0x3fff; $off+=2; $self->{upi} = unpack('C',substr(${$self->{buf}},$off,1)) & 0x0f; $off+=1; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>11)&0x7).'-'.(($dest>>3)&0xff).'-'.(($dest>>0)&0x7); my $dest0 = unpack('C',substr(${$self->{buf}},$off+1,1))>>6; my $upi = $self->{upi}; $upi = UPI_VALUES->[$upi]."($upi)"; my $upi0 = unpack('C',substr(${$self->{buf}},$off+2,1))>>4; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x003fff,3),'DEST',$dest], [$off+0,Frame::spare($dest0, 0x00c000,3),'Spare',$dest0], [$off+0,Frame::bytes($self->{upi}, 0x0f0000,3),'UPI',$upi], [$off+0,Frame::spare($upi0, 0xf00000,3),'Spare',$upi0], ); } package Message::ITUT::SNMM::UPU; our @ISA = qw(Message::ITUT::SNMM::UPM); package Message::ITUT::SNMM::UPA; our @ISA = qw(Message::ITUT::SNMM::UPM); package Message::ITUT::SNMM::UPT; our @ISA = qw(Message::ITUT::SNMM::UPM); # ------------------------------------- package Message::ANSI::SNMM::UPM; our @ISA = qw(Message::SNMM); # ------------------------------------- use constant { UPI_VALUES=>[ 'Spare', 'Spare', 'Spare', 'SCCP', 'TUP', 'ISUP', 'DUP', 'Spare', 'MTUP', 'B-ISUP', 'S-ISUP', 'Spare', 'Spare', 'Spare', 'Spare', 'Spare', ], }; sub unpack { my $self = shift; my $off = $self->{off}; $self->{dest} = unpack('V',substr(${$self->{buf}},$off,4)); $off+=4; $self->{upi} = ($self->{dest} >> 24) & 0x0f; $self->{dest} &= 0x00ffffff; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $dest = $self->{dest}; $dest = (($dest>>16)&0xff).'-'.(($dest>>8)&0xff).'-'.(($dest>>0)&0xff); my $upi = $self->{upi}; $upi = UPI_VALUES->[$upi]."($upi)"; my $upi0 = unpack('C',substr(${$self->{buf}},$off+3,1))>>4; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{dest},0x00ffffff,4),'DEST',$dest], [$off+0,Frame::bytes($self->{upi}, 0x0f000000,4),'UPI',$upi], [$off+0,Frame::spare($upi0, 0xf0000000,4),'Spare',$upi0], ); } package Message::ANSI::SNMM::UPU; our @ISA = qw(Message::ANSI::SNMM::UPM); package Message::ANSI::SNMM::UPA; our @ISA = qw(Message::ANSI::SNMM::UPM); package Message::ANSI::SNMM::UPT; our @ISA = qw(Message::ANSI::SNMM::UPM); # ------------------------------------- # ------------------------------------- package Message::SNTM; our @ISA = qw(Message::MTP3::MGMT); # ------------------------------------- use constant { SNTM_TYPES=>{ 0x11 => 'SLTM', 0x12 => 'SLTA', }, }; sub unpack { my $self = shift; my $off = $self->{off}; $self->{mt} = unpack('C',substr(${$self->{buf}},$off,1)); $off+=1; $self->{h0} = ($self->{mt}>>0)&0xf; $self->{h1} = ($self->{mt}>>4)&0xf; $self->{mt} = ($self->{h0}<<4)|$self->{h1}; my $type = SNTM_TYPES->{$self->{mt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $mt = $self->{mt}; $mt = SNTM_TYPES->{$mt}.sprintf('(%02x)',$mt); return [ @{$self->SUPER::dissect(@_)}, "$mt Message", [$off+0,Frame::bytes($self->{h0},0x0f,1),'H0',sprintf('0x%1X',$self->{h0})], [$off+0,Frame::bytes($self->{h1},0xf0,1),'H1',sprintf('0x%1X',$self->{h1})], ]; } # ------------------------------------- package Message::ITUT::SNTM; our @ISA = qw(Message::SNTM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{tli} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{slc} = $self->{sls}; $self->{tli} >>= 4; $self->{tli} &= 0x0f; $self->{tdata} = substr(${$self->{buf}},$self->{off},$self->{tli}); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return [ @{$self->SUPER::dissect(@_)}, [$off+1,Frame::bytes($self->{tli},0xf0,1),'TLI',$self->{tli}], #TODO: print data ]; } # ------------------------------------- package Message::ITUT::SNTM::SLTM; our @ISA = qw(Message::ITUT::SNTM); package Message::ITUT::SNTM::SLTA; our @ISA = qw(Message::ITUT::SNTM); # ------------------------------------- # ------------------------------------- package Message::ANSI::SNTM; our @ISA = qw(Message::SNTM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{tli} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{slc} = $self->{tli} & 0x0f; $self->{tli} >>= 4; $self->{tli} &= 0x0f; $self->{tdata} = substr(${$self->{buf}},$self->{off},$self->{tli}); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return [ @{$self->SUPER::dissect(@_)}, [$off+1,Frame::bytes($self->{slc},0x0f,1),'SLC',$self->{slc}], [$off+1,Frame::bytes($self->{tli},0xf0,1),'TLI',$self->{tli}], #TODO: print data ]; } # ------------------------------------- package Message::ANSI::SNTM::SLTM; our @ISA = qw(Message::ANSI::SNTM); package Message::ANSI::SNTM::SLTA; our @ISA = qw(Message::ANSI::SNTM); # ------------------------------------- # ------------------------------------- package Message::SNSM; our @ISA = qw(Message::MTP3::MGMT); # ------------------------------------- use constant { SNSM_TYPES=>{ 0x11 => 'SLTM', 0x12 => 'SLTA', }, }; sub unpack { my $self = shift; my $off = $self->{off}; $self->{mt} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{h0} = ($self->{mt}>>0)&0xf; $self->{h1} = ($self->{mt}>>4)&0xf; $self->{mt} = ($self->{h0}<<4)|$self->{h1}; my $type = SNSM_TYPES->{$self->{mt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $mt = $self->{mt}; $mt = SNSM_TYPES->{$mt}.sprintf('(%02x)',$mt); return [ @{$self->SUPER::dissect(@_)}, "$mt Message", [$off+0,Frame::bytes($self->{h0},0x0f,1),'H0',sprintf('0x%1X',$self->{h0})], [$off+0,Frame::bytes($self->{h1},0xf0,1),'H1',sprintf('0x%1X',$self->{h1})], ]; } # ------------------------------------- package Message::ITUT::SNSM; our @ISA = qw(Message::SNSM); # ------------------------------------- sub unpack { my $self = shift; # doesn't exists for ITU return $self; } # ------------------------------------- package Message::ITUT::SNSM::SLTM; our @ISA = qw(Message::ITUT::SNSM); package Message::ITUT::SNSM::SLTA; our @ISA = qw(Message::ITUT::SNSM); # ------------------------------------- # ------------------------------------- package Message::ANSI::SNSM; our @ISA = qw(Message::SNSM); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; $self->{tli} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $self->{slc} = $self->{tli} & 0x0f; $self->{tli} >>= 4; $self->{tli} &= 0x0f; $self->{tdata} = substr(${$self->{buf}},$off,$self->{tli}); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( [$off+0,Frame::bytes($self->{slc},0x0f,1),'SLC',$self->{slc}], [$off+0,Frame::bytes($self->{tli},0xf0,1),'TLI',$self->{tli}], [$off+1,' ******** ','TDATA',Frame::pdata($self->{tdata})], ); } # ------------------------------------- package Message::ANSI::SNSM::SLTM; our @ISA = qw(Message::ANSI::SNSM); package Message::ANSI::SNSM::SLTA; our @ISA = qw(Message::ANSI::SNSM); # ------------------------------------- # ------------------------------------- package Message::SCCP; our @ISA = qw(Message); # ------------------------------------- use constant { SCCP_MSG_TYPE=>{ 0x01 => 'CR', 0x02 => 'CC', 0x03 => 'CREF', 0x04 => 'RLSD', 0x05 => 'RLC', 0x06 => 'DT1', 0x07 => 'DT2', 0x08 => 'AK', 0x09 => 'UDT', 0x0a => 'UDTS', 0x0b => 'ED', 0x0c => 'EA', 0x0d => 'RSR', 0x0e => 'RSC', 0x0f => 'ERR', 0x10 => 'IT', 0x11 => 'XUDT', 0x12 => 'XUDTS', 0x13 => 'LUDT', 0x14 => 'LUDTS', }, }; sub unpack { my $self = shift; my $off = $self->{off}; $self->{mt} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; my $type = SCCP_MSG_TYPE->{$self->{mt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; my $layers; if (exists $self->{mtp3}) { $layers = $self->SUPER::dissect(@_); } else { # if (exists $self->{m3ua}) { $layers = $self->Message::M3UA::XFER::DATA::dissect(@_); } my $mt = $self->{mt}; $mt = SCCP_MSG_TYPE->{$mt}."($mt)"; return [ @{$layers}, "$mt Message", [$off+0,Frame::bytes($self->{mt},0xff,1),'MT',$mt], ]; } use constant { SCCP_PT_EOP => 0, # 0000 0000 End of optional parameters SCCP_PT_DLR => 1, # 0000 0001 Destination local reference SCCP_PT_SLR => 2, # 0000 0010 Source local reference SCCP_PT_CDPA => 3, # 0000 0011 Called party address SCCP_PT_CGPA => 4, # 0000 0100 Calling party address SCCP_PT_PCLS => 5, # 0000 0101 Protocol class SCCP_PT_SEG => 6, # 0000 0110 Segmenting/reassembling SCCP_PT_RSN => 7, # 0000 0111 Receive sequence number SCCP_PT_SEQ => 8, # 0000 1000 Sequencing/segmenting SCCP_PT_CRED => 9, # 0000 1001 Credit SCCP_PT_RELC => 10, # 0000 1010 Release cause SCCP_PT_RETC => 11, # 0000 1011 Return cause (formerly diagnostic) SCCP_PT_RESC => 12, # 0000 1100 Reset cause SCCP_PT_ERRC => 13, # 0000 1101 Error cause SCCP_PT_REFC => 14, # 0000 1110 Refusal cause SCCP_PT_DATA => 15, # 0000 1111 Data SCCP_PT_SGMT => 16, # 0001 0000 Segmentation SCCP_PT_HOPC => 17, # 0001 0001 SCCP hop counter SCCP_PT_IMP => 18, # 0001 0010 Importance (not ANSI) SCCP_PT_LDATA => 19, # 0001 0011 Long data SCCP_PT_MTI =>248, # 1111 1000 Message type interworking SCCP_PT_INS =>249, # 1111 1001 Intermediate network selection SCCP_PT_ISNI =>250, # 1111 1010 Intermediate signalling network identification SCCP_PARM_TYPE=>{ &SCCP_PT_EOP => 'EOP', &SCCP_PT_DLR => 'DLR', &SCCP_PT_SLR => 'SLR', &SCCP_PT_CDPA => 'CDPA', &SCCP_PT_CGPA => 'CGPA', &SCCP_PT_PCLS => 'PCLS', &SCCP_PT_SEG => 'SEG', &SCCP_PT_RSN => 'RSN', &SCCP_PT_SEQ => 'SEQ', &SCCP_PT_CRED => 'CRED', &SCCP_PT_RELC => 'RELC', &SCCP_PT_RETC => 'RETC', &SCCP_PT_RESC => 'RESC', &SCCP_PT_ERRC => 'ERRC', &SCCP_PT_REFC => 'REFC', &SCCP_PT_DATA => 'DATA', &SCCP_PT_SGMT => 'SGMT', &SCCP_PT_HOPC => 'HOPC', &SCCP_PT_IMP => 'IMP', &SCCP_PT_LDATA => 'LDATA', &SCCP_PT_MTI => 'MTI', &SCCP_PT_INS => 'INS', &SCCP_PT_ISNI => 'ISNI', } }; sub unpack_SCCP_ADDR { my ($self,$off,$end,$len,$lab) = @_; return unless $off < $end; $self->{$lab} = {}; $lab = $self->{$lab}; my $ai = $lab->{ai} = unpack('C',substr(${$self->{buf}},$off,1)); $off++; $lab->{ni} = ($ai >> 7) & 0x01; $lab->{ri} = ($ai >> 6) & 0x01; $lab->{gti} = ($ai >> 2) & 0x0f; $lab->{ssi} = ($ai >> 1) & 0x01; $lab->{pci} = ($ai >> 0) & 0x01; if ($lab->{ni} == 0) { if ($lab->{pci}) { return unless $off + 2 <= $end; $lab->{pc} = unpack('v',substr(${$self->{buf}},$off,2)) & 0x3fff; $off += 2; } $lab->{ssn} = 0; if ($lab->{ssi}) { return unless $off + 1 <= $end; $lab->{ssn} = unpack('C',substr(${$self->{buf}},$off,1)); $off += 1; } if ($lab->{gti}) { if (1 > $lab->{gti} or $lab->{gti} > 4) { return 1; } elsif ($lab->{gti} == 1) { return unless $off + 1 <= $end; my $nai = unpack('C',substr(${$self->{buf}},$off,1)); $off += 1; $lab->{oe} = ($nai >> 7) & 0x01; $lab->{nai} = ($nai >> 0) & 0x7f; $lab->{es} = 2 if $lab->{oe} == 0; $lab->{es} = 1 if $lab->{oe} == 1; } elsif ($lab->{gti} == 2) { return unless $off + 1 <= $end; $lab->{tt} = unpack('C',substr(${$self->{buf}},$off,1)); $off += 1; } elsif ($lab->{gti} == 3) { return unless $off + 2 <= $end; my $ne; ($lab->{tt},$ne) = unpack('CC',substr(${$self->{buf}},$off,2)); $off += 2; $lab->{np} = ($ne>>4) & 0x0f; $lab->{es} = ($ne>>0) & 0x0f; } elsif ($lab->{gti} == 4) { return unless $off + 3 <= $end; my ($ne,$nai); ($lab->{tt},$ne,$nai) = unpack('CCC',substr(${$self->{buf}},$off,3)); $off += 3; $lab->{np} = ($ne >>4) & 0x0f; $lab->{es} = ($ne >>0) & 0x0f; $lab->{oe} = ($nai>>7) & 0x01; # should always be zero $lab->{nai} = ($nai>>0) & 0x7f; } } } else { $lab->{ssn} = 0; if ($lab->{ssi}) { return unless $off + 1 <= $end; $lab->{ssn} = unpack('C',substr(${$self->{buf}},$off,1)); $off += 1; } if ($lab->{pci}) { return unless $off + 3 <= $end; $lab->{pc} = unpack('V',substr(${$self->{buf}},$off-1,4)) & 0xffffff; $off += 3; } if ($lab->{gti}) { if (1 > $lab->{gti} or $lab->{gti} > 2) { return 1; } elsif ($lab->{gti} == 1) { return unless $off + 2 <= $end; my $ne; ($lab->{tt},$ne) = unpack('CC',substr(${$self->{buf}},$off,2)); $off += 2; $lab->{np} = ($ne>>4) & 0x0f; $lab->{es} = ($ne>>0) & 0x0f; } elsif ($lab->{gti} == 2) { return unless $off + 1 <= $end; $lab->{tt} = unpack('C',substr(${$self->{buf}},$off,1)); $off += 1; } } } if ($lab->{gti}) { if ($lab->{es} == 1 or $lab->{es} == 2) { $lab->{add} = ''; foreach (unpack('C*',substr(${$self->{buf}},$off,$end-$off))) { $lab->{add}.=sprintf('%1X',($_>>0)&0x0f); $lab->{add}.=sprintf('%1X',($_>>4)&0x0f); } $lab->{add} = substr($lab->{add},0,length($lab->{add})-1) if $lab->{es} == 1; } else { $lab->{add} = substr(${$self->{buf}},$off,$end-$off); } } return 1; } sub unpack_SCCP_LOCR { my ($self,$off,$end,$len,$lab) = @_; return unless $len == 3; $self->{$lab} = unpack('V',substr(${$self->{buf}},$off-1,$len+1)) & 0xffffff; return 1; } sub unpack_SCCP_1OCT { my ($self,$off,$end,$len,$lab) = @_; $self->{$lab} = unpack('C',substr(${$self->{buf}},$off,1)); return 1; } sub unpack_PT_EOP { my ($self,$off,$end,$len,$lab) = @_; return 2; } sub unpack_PT_DLR { return shift->Message::SCCP::unpack_SCCP_LOCR(@_) } sub unpack_PT_SLR { return shift->Message::SCCP::unpack_SCCP_LOCR(@_) } sub unpack_PT_CDPA { return shift->Message::SCCP::unpack_SCCP_ADDR(@_) } sub unpack_PT_CGPA { return shift->Message::SCCP::unpack_SCCP_ADDR(@_) } sub unpack_PT_PCLS { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_SEG { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_RSN { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_SEQ { my ($self,$off,$end,$len,$lab) = @_; $self->{$lab} = {}; $lab = $self->{$lab}; ($lab->{ps},$lab->{pr}) = unpack('CC',substr(${$self->{buf}},$off,2)); $lab->{m} = $lab->{pr} & 0x1; $lab->{pr} &= 0xfe; $lab->{ps} &= 0xfe; return 1; } sub unpack_PT_CRED { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_RELC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_RETC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_RESC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_ERRC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_REFC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_DATA { my ($self,$off,$end,$len,$lab) = @_; return unless $len <= 252; $self->{doff} = $off; $self->{dlen} = $len; $self->{dend} = $off + $len; return 1; } sub unpack_PT_SGMT { my ($self,$off,$end,$len,$lab) = @_; return unless $off + 4 <= $end; $self->{$lab} = {}; $lab = $self->{$lab}; my $val = unpack('V',substr(${$self->{buf}},$off,4)); $lab->{rems} = ($val >> 0) & 0x0f; $lab->{isdo} = ($val >> 6) & 0x01; $lab->{flag} = ($val >> 7) & 0x01; $lab->{lref} = ($val >> 8) & 0xffffff; return 1; } sub unpack_PT_HOPC { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_IMP { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_LDATA { my ($self,$off,$end,$len,$lab) = @_; return unless $le <= 3904; $self->{doff} = $off; $self->{dlen} = $len; $self->{dend} = $off + $len; return 1; } sub unpack_PT_MTI { return shift->Message::SCCP::unpack_SCCP_1OCT(@_) } sub unpack_PT_INS { my ($self,$off,$end,$len,$lab) = @_; $self->{$lab} = substr(${$self->{buf}},$off,$len); # just binary copy for now return 1; } sub unpack_PT_ISNI { my ($self,$off,$end,$len,$lab) = @_; $self->{$lab} = substr(${$self->{buf}},$off,$len); # just binary copy for now return 1; } sub unpack_oparms { my ($self,$ptr,$tag,$len,$parm,$sub) = @_; for (;;) { return unless $ptr < $self->{end}; $tag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; return 1 if $tag == 0; return unless exists SCCP_PARM_TYPE->{$tag}; $parm = SCCP_PARM_TYPE->{$tag}; return unless $ptr < $self->{end}; $len = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; return if $len == 0; return unless $ptr + $len <= $self->{end}; return unless $sub = $self->can("unpack_PT_$parm"); return unless $sub->($self,$ptr,$len); $ptr += $len; } } sub dissect_PT_EOP { my ($self,$off,$end,$len) = @_; return; } sub dissect_PT_DLR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SLR { my ($self,$off,$end,$len) = @_; } use constant { ITUT_GTI_TYPES=>{ 0x0=>'no global title included', 0x1=>'global title includes nature of address indicator only', 0x2=>'global title includes translation type only', 0x3=>'global title includes translation type, numbering plan and encoding scheme', 0x4=>'global title includes translation type, numbering plan, encoding scheme and nature of address indicator', }, ANSI_GTI_TYPES=>{ 0x0=>'no global title included', 0x1=>'global title includes translation type, numbering plan and encoding scheme', 0x2=>'global title includes translation type only', }, RI_TYPES=>{ 0x0=>'Route on global title', 0x1=>'Route on subsystem number', }, SSN_TYPES=>{ 0x00=>'SSN not known/not used', 0x01=>'SCCP management', 0x02=>'Reserved for ITU-T allocation', 0x03=>'ISDN user part', 0x04=>'Operation, maintenance and administration part (OMAP)', 0x05=>'Mobile application part (MAP)', 0x06=>'Home location register (HLR)', 0x07=>'Visitor location register (VLR)', 0x08=>'Mobile switching center (MSC)', 0x09=>'Equipment identifier centre (EIC)', 0x0a=>'Authentication center (AUC)', 0x0b=>'Reserved for ITU-T for ISDN supplementary services/MOSMS', 0x0c=>'Reserved for international use', 0x0d=>'Reserved for ITU-T for broadband ISDN edge-to-edge applications', 0x0e=>'Reserved for ITU-T for TC test responder', 0x0f=>'Reserved for international use', 0x1f=>'Reserved for international use', 0x20=>'Spare', 0xc0=>'Enhanced 911 location testing (E911)', 0xc1=>'Enhanced 911 testing (E911)', 0xeb=>'Voicemail (message waiting)', 0xf7=>'Local number portability (LNP)', 0xf8=>'Local number portability (LNP)', 0xfa=>'LNP Wireline and Wireless/One-way outgoing CMS', 0xfb=>'CLASS/Call Management services', 0xfc=>'PVN/Billed Number Screening', 0xfd=>'LIDB Query (GR-945-CORE)/Automated Calling Card Services', 0xfe=>'800 Number Translation/800 Plus/Toll Free services', 0xff=>'Reserved for expansion', }, NAI_TYPES=>{ 0x00=>'unknown', 0x01=>'subscriber number', 0x02=>'reserved for national use', 0x03=>'national significant number', 0x04=>'international number', }, OE_TYPES=>{ 0x0=>'even number of address signals', 0x1=>'odd number of address signals', }, NP_TYPES=>{ 0x0=>'unknown', 0x1=>'ISDN/telephony numbering plan (ITU-T E.163/164)', 0x2=>'generic numbering plan', 0x3=>'data numbering plan (ITU-T X.121)', 0x4=>'telex numbering plan (ITU-T F.69)', 0x5=>'maritime mobile numbering plan (ITU-T E.210/211)', 0x6=>'land mobile numbering plan (ITU-T E.212)', 0x7=>'ISDN/mobile numbering plan (ITU-T E.214)', }, ES_TYPES=>{ 0x0=>'unknown', 0x1=>'BCD, odd number of digits', 0x2=>'BCD, even number of digits', 0x3=>'national specific', }, RELC_TYPES=>{ 0x00=>'end user originated', 0x01=>'end user busy', 0x02=>'end user failure', 0x03=>'SCCP user originated', 0x04=>'remote procedure error', 0x05=>'inconsistent connection data', 0x06=>'access failure', 0x07=>'access congestion', 0x08=>'subsystem failure', 0x09=>'subsystem congestion', 0x0a=>'MTP failure', 0x0b=>'network congestion', 0x0c=>'expiration of reset timer', 0x0d=>'expiration of receive inactivity timer', 0x0e=>'reserved', 0x0f=>'unqualified', 0x10=>'SCCP failure (ITU-T only)', }, RETC_TYPES=>{ 0x00=>'no translation for an address of such nature', 0x01=>'no translation for this specific address', 0x02=>'subsystem congestion', 0x03=>'subsystem failure', 0x04=>'unequipped user', 0x05=>'MTP failure', 0x06=>'network congestion', 0x07=>'unqualified', 0x08=>'error in message transport', 0x09=>'error in local processing', 0x0a=>'destination cannot perform reassembly', 0x0b=>'SCCP failure (ITU-T only)', 0x0c=>'SCCP hop counter violation', 0x0d=>'segmentation not supported', 0x0e=>'segmentation failure', 0xf7=>'message change failure', 0xf8=>'invalid INS routing request', 0xf9=>'invalid INSI routing request', 0xfa=>'unauthorized message', 0xfb=>'message incompatibility', 0xfc=>'cannot perform ISNI constrained routing', 0xfd=>'redundant ISNI constrained routing information', 0xfe=>'unable to perform ISNI identification', }, RESC_TYPES=>{ 0x00=>'end user originated', 0x01=>'SCCP user originated', 0x02=>'message out of order - incorrect P(S)', 0x03=>'message out of order - incorrect P(R)', 0x04=>'remote procedure error - message out of window', 0x05=>'remote procedure error - incorrect P(S) after (re)init', 0x06=>'remote procedure error - general', 0x07=>'remote end user operational', 0x08=>'network operational', 0x09=>'access operational', 0x0a=>'network congestion', 0x0b=>'not obtainable (reserved)', 0x0c=>'unqualified', }, ERRC_TYPES=>{ 0x00=>'LRN mismatch - unassigned destination LRN', 0x01=>'LRN mismatch - inconsistent source LRN', 0x02=>'point code mismatch', 0x03=>'service class mismatch', 0x04=>'unqualified', }, REFC_TYPES=>{ 0x00=>'end user originated', 0x01=>'end user congestion', 0x02=>'end user failure', 0x03=>'SCCP user originated', 0x04=>'destination address unknown', 0x05=>'destination inaccessible', 0x06=>'network resource - QoS not available/non-transient', 0x07=>'network resource - QoS not available/transient', 0x08=>'access failure', 0x09=>'access congestion', 0x0a=>'subsytem failure', 0x0b=>'subsystem congestion', 0x0c=>'expiration of the connection establishment timer', 0x0d=>'incompatible user data', 0x0e=>'reserved', 0x0f=>'unqualified', 0x10=>'SCCP hop counter violation', 0x11=>'SCCP faliure (ITU-T only)', 0x12=>'no translation for an address of such nature', 0x13=>'unequipped user', }, ADIGIT_TYPES=>['0','1','2','3','4','5','6','7','8','9','a','*','#','d','e','ST'], ANSI_TT_VALUES=>{ 0x00=>'reserved', 0x01=>'identification cards', 0x02=>'reserved - 14 digit calling card (note 1)', 0x03=>'cellular nationwide roaming service/OTA provisioning and IS41 roaming', 0x04=>'global title = point code', 0x05=>'calling name delivery', 0x06=>'reserved - cal management (note 1)', 0x07=>'message waiting', 0x08=>'SCP assisted call processing', 0x09=>'national and international cellulsar/PCS roaming', 0x0a=>'PCS call delivery/network entity addressing/LNP wireline', 0x0b=>'internetwork NP query/response (NP Q/R)/wireless LNP', 0x0c=>'wireless MIN-based short message service/MOSMS', 0x0d=>'wireless IMSI-based short message service', 0x0e=>'mobile subscriber addressing/wireless services impacted by number portability', 0x0f=>'package data interworking', 0x10=>'cellular/PCS interworking', 0x11=>'mobile subscriber message center addressing', 0x12=>'internetwork applications', 0x13=>'internetwork applications', 0x14=>'internetwork applications', 0x15=>'internetwork applications', 0x16=>'internetwork applications', 0x17=>'internetwork applications', 0x18=>'internetwork applications', 0x19=>'internetwork applications', 0x1a=>'internetwork applications', 0x1b=>'internetwork applications', 0x1c=>'14 digit telecommunication calling cards - post 10-digit (NP) GTT (loop code) (note 3)', 0x1d=>'calling name delivery post-10-digit (NP) GTT (loop code) (note 3)', 0x1e=>'call management post-10-digit (NP) GTT (loop code) (note 3)', 0x1f=>'message waiting post-10-digit (NP) GTT (loop code) (note 3)', 0x77=>'E911 (another E911 assigment)', 0x8c=>'GSM Voice roaming MSISDN to HLR', 0xbf=>'E911', 0xc0=>'E911 location testing', 0xc1=>'E911 testing', 0xc2=>'E911 testing', 0xd3=>'IN type Wireline LNP query', 0xf9=>'network specific applications', 0xfa=>'network specific applications', 0xfb=>'network specific applications/call management', 0xfc=>'network specific applications', 0xfd=>'network specific applications/14 digit calling card/LIDB GR-945-CORE', 0xfe=>'800 service', 0xff=>'reserved', }, }; sub dissect_PT_CDPA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CGPA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PCLS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SEG { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RSN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SEQ { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CRED { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RELC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RETC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RESC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ERRC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_REFC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_DATA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SGMT { my ($self,$off,$end,$len) = @_; } sub dissect_PT_HOPC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_IMP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_LDATA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_MTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_INS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ISNI { my ($self,$off,$end,$len) = @_; } use constant { SCCP_PARMS_DISSECT=>{ &SCCP_PT_EOP => [\&Message::SCCP::dissect_PT_EOP, 'EOP', 'End of optional parameters'], &SCCP_PT_DLR => [\&Message::SCCP::dissect_PT_DLR, 'DLR', 'Destination local reference'], &SCCP_PT_SLR => [\&Message::SCCP::dissect_PT_SLR, 'SLR', 'Source local reference'], &SCCP_PT_CDPA => [\&Message::SCCP::dissect_PT_CDPA, 'CDPA', 'Called party address'], &SCCP_PT_CGPA => [\&Message::SCCP::dissect_PT_CGPA, 'CGPA', 'Calling party address'], &SCCP_PT_PCLS => [\&Message::SCCP::dissect_PT_PCLS, 'PCLS', 'Protocol class'], &SCCP_PT_SEG => [\&Message::SCCP::dissect_PT_SEG, 'SEG', 'Segmenting/reassembling'], &SCCP_PT_RSN => [\&Message::SCCP::dissect_PT_RSN, 'RSN', 'Receive sequence number'], &SCCP_PT_SEQ => [\&Message::SCCP::dissect_PT_SEQ, 'SEQ', 'Sequencing/segmenting'], &SCCP_PT_CRED => [\&Message::SCCP::dissect_PT_CRED, 'CRED', 'Credit'], &SCCP_PT_RELC => [\&Message::SCCP::dissect_PT_RELC, 'RELC', 'Release cause'], &SCCP_PT_RETC => [\&Message::SCCP::dissect_PT_RETC, 'RETC', 'Return cause (formerly diagnostic)'], &SCCP_PT_RESC => [\&Message::SCCP::dissect_PT_RESC, 'RESC', 'Reset cause'], &SCCP_PT_ERRC => [\&Message::SCCP::dissect_PT_ERRC, 'ERRC', 'Error cause'], &SCCP_PT_REFC => [\&Message::SCCP::dissect_PT_REFC, 'REFC', 'Refusal cause'], &SCCP_PT_DATA => [\&Message::SCCP::dissect_PT_DATA, 'DATA', 'Data'], &SCCP_PT_SGMT => [\&Message::SCCP::dissect_PT_SGMT, 'SGMT', 'Segmentation'], &SCCP_PT_HOPC => [\&Message::SCCP::dissect_PT_HOPC, 'HOPC', 'SCCP hop counter'], &SCCP_PT_IMP => [\&Message::SCCP::dissect_PT_IMP, 'IMP', 'Importance (not ANSI)'], &SCCP_PT_LDATA => [\&Message::SCCP::dissect_PT_LDATA, 'LDATA','Long data'], &SCCP_PT_MTI => [\&Message::SCCP::dissect_PT_MTI, 'MTI', 'Message type interworking'], &SCCP_PT_INS => [\&Message::SCCP::dissect_PT_INS, 'INS', 'Intermediate network selection'], &SCCP_PT_ISNI => [\&Message::SCCP::dissect_PT_ISNI, 'ISNI', 'Intermediate signalling network identification'], } }; sub dissect_oparms { my ($self,$off,$end) = @_; my @oparms = (); for (;$off < $end;$off++) { my @fields = (); my $ptr = unpack('C',substr(${$self->{buf}},$off,1)); push @fields, [$off,Frame::bytes($ptr,0xff,1),'Pointer',$ptr]; my $poff = $off + $ptr; return unless $poff <= $end; my $ptag = unpack('C',substr(${$self->{buf}},$poff,1)); my $parm; if (exists SCCP_PARMS_DISSECT->{$ptag}) { my @args = @{SCCP_PARMS_DISSECT->{$ptag}}; my $sub = shift @args; $parm = sprintf '%s(%d) - %s', $args[0], $ptag, $args[1]; push @fields, [$poff,Frame::bytes($ptag,0xff,1),'Tag',$parm], $poff++; my ($plen,$pend) = (undef,$poff); if ($ptag) { $plen = unpack('C',substr(${$self->{buf}},$poff,1)); push @fields, [$poff,Frame::bytes($plen,0xff,1),'Length',$plen]; $poff++; $pend = $poff + $plen; } return unless $pend <= $self->{end}; push @fields, @{$sub->($self,$poff,$pend,$plen,@args,@_)}; } else { $parm = "Unknown($ptag) - Unknown parameter tag"; push @fields, [$poff,Frame::bytes($ptag,0xff,1),'Tag',$parm]; $poff++; my $plen = unpack('C',substr(${$self->{buf}},$poff,1)); push @fields, [$poff,Frame::bytes($plen,0xff,1),'Length',$plen]; $poff++; my $pend = $poff + $plen; return unless $pend <= $self->{end}; push @fields, [$poff,' ******** ','Parameter',Frame::pdata(substr(${$self->{buf}},$poff,$plen))]; } push @oparms, "Parameter $parm", \@fields; } return [ 'Optional Parameters', \@oparms ]; } # ------------------------------------- package Message::ITUT::SCCP; our @ISA = qw(Message::SCCP); package Message::ANSI::SCCP; our @ISA = qw(Message::SCCP); # ------------------------------------- package Message::SCCP::CR; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(SLR) F(PCLS) V(CDPA) O(CRED CGPA DATA HOPC EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self, 'SLR', $off, 3); $off += 3; return unless Message::unpack_MF($self, 'PCLS',$off, 1); $off += 1; return unless Message::unpack_MV($self, 'CDPA',$off ); $off += 1; return unless Message::unpack_OP($self, $off ); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self, 'SLR', $off+0, 3), Message::dissect_MF($self, 'PCLS',$off+3, 1), Message::dissect_MV($self, 'CDPA',$off+4 ), Mesasge::dissect_OP($self, $off+5 ), ); } package Message::ITUT::SCCP::CR; our @ISA = qw(Message::SCCP::CR Message::ITUT::SCCP); package Message::ANSI::SCCP::CR; our @ISA = qw(Message::SCCP::CR Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::CC; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) F(PCLS) O(CRED CDPA DATA EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self, 'DLR', $off, 3); $off += 3; return unless Message::unpack_MF($self, 'SLR', $off, 3); $off += 3; return unless Message::unpack_MF($self, 'PCLS',$off, 1); $off += 1; return unless Message::unpack_OP($self, $off ); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self, 'DLR', $off+0, 3), Message::dissect_MF($self, 'SLR', $off+3, 3), Message::dissect_MF($self, 'PCLS',$off+6, 1), message::dissect_OP($self, $off+7 ), ); } package Message::ITUT::SCCP::CC; our @ISA = qw(Message::SCCP::CC Message::ITUT::SCCP); package Message::ANSI::SCCP::CC; our @ISA = qw(Message::SCCP::CC Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::CREF; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(REFC) O(CDPA DATA EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'REFC',$off,1); $off+=1; return unless Message::unpack_OP($self, $off ); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'REFC',$off+3,1), Message::dissect_OP($self, $off ), ); } package Message::ITUT::SCCP::CREF; our @ISA = qw(Message::SCCP::CREF Message::ITUT::SCCP); package Message::ANSI::SCCP::CREF; our @ISA = qw(Message::SCCP::CREF Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::RLSD; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) F(RELC) O(DATA EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'SLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'RELC',$off,1); $off+=1; return unless Message::unpack_OP($self, $off ); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'SLR', $off+3,3), Message::dissect_MF($self,'RELC',$off+6,1), Message::dissect_OP($self, $off ), ); } package Message::ITUT::SCCP::RLSD; our @ISA = qw(Message::SCCP::RLSD Message::ITUT::SCCP); package Message::ANSI::SCCP::RLSD; our @ISA = qw(Message::SCCP::RLSD Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::RLC; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR',$off,3); $off+=3; return unless Message::unpack_MF($self,'SLR',$off,3); $off+=3; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR',$off+0,3), Message::dissect_MF($self,'SLR',$off+3,3), ); } package Message::ITUT::SCCP::RLC; our @ISA = qw(Message::SCCP::RLC Message::ITUT::SCCP); package Message::ANSI::SCCP::RLC; our @ISA = qw(Message::SCCP::RLC Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::DT1; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SEG) V(DATA) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'SEG', $off,1); $off+=1; return unless Message::unpack_MV($self,'DATA',$off ); $off+=1; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'SEG', $off+3,1), Message::dissect_MV($self,'DATA',$off+4 ), ); } package Message::ITUT::SCCP::DT1; our @ISA = qw(Message::SCCP::DT1 Message::ITUT::SCCP); package Message::ANSI::SCCP::DT1; our @ISA = qw(Message::SCCP::DT1 Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::DT2; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SEQ) V(DATA) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'SEQ', $off,2); $off+=2; return unless Message::unpack_MV($self,'DATA',$off ); $off+=1; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'SEQ', $off+3,1), Message::dissect_MV($self,'DATA',$off+4 ), ); } package Message::ITUT::SCCP::DT2; our @ISA = qw(Message::SCCP::DT2 Message::ITUT::SCCP); package Message::ANSI::SCCP::DT2; our @ISA = qw(Message::SCCP::DT2 Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::AK; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(RSN) F(CRED) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'RSN', $off,1); $off+=1; return unless Message::unpack_MF($self,'CRED',$off,1); $off+=1; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'RSN', $off+3,1), Message::dissect_MF($self,'CRED',$off+4,1), ); } package Message::ITUT::SCCP::AK; our @ISA = qw(Message::SCCP::AK Message::ITUT::SCCP); package Message::ANSI::SCCP::AK; our @ISA = qw(Message::SCCP::AK Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::UDT; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(PCLS) V(CDPA) V(CGPA) V(DATA) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'PCLS',$off,1); $off++; return unless Message::unpack_MV($self,'CDPA',$off ); $off++; return unless Message::unpack_MV($self,'CGPA',$off ); $off++; return unless Message::unpack_MV($self,'DATA',$off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'PCLS',$off+0,1), Message::dissect_MV($self,'CDPA',$off+1 ), Message::dissect_MV($self,'CGPA',$off+2 ), Message::dissect_MV($self,'DATA',$off+3 ), ); } package Message::ITUT::SCCP::UDT; our @ISA = qw(Message::SCCP::UDT Message::ITUT::SCCP); package Message::ANSI::SCCP::UDT; our @ISA = qw(Message::SCCP::UDT Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::UDTS; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(RETC) V(CDPA) V(CGPA) V(DATA) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'RETC',$off,1); $off++; return unless Message::unpack_MV($self,'CDPA',$off ); $off++; return unless Message::unpack_MV($self,'CGPA',$off ); $off++; return unless Message::unpack_MV($self,'DATA',$off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'RETC',$off+0,1), Message::dissect_MV($self,'CDPA',$off+1 ), Message::dissect_MV($self,'CGPA',$off+2 ), Message::dissect_MV($self,'DATA',$off+3 ), ); } package Message::ITUT::SCCP::UDTS; our @ISA = qw(Message::SCCP::UDTS Message::ITUT::SCCP); package Message::ANSI::SCCP::UDTS; our @ISA = qw(Message::SCCP::UDTS Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::ED; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) V(DATA) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MV($self,'DATA',$off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MV($self,'DATA',$off+3 ), ); } package Message::ITUT::SCCP::ED; our @ISA = qw(Message::SCCP::ED Message::ITUT::SCCP); package Message::ANSI::SCCP::ED; our @ISA = qw(Message::SCCP::ED Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::EA; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR',$off,3); $off+=3; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR',$off,3), ); } package Message::ITUT::SCCP::EA; our @ISA = qw(Message::SCCP::EA Message::ITUT::SCCP); package Message::ANSI::SCCP::EA; our @ISA = qw(Message::SCCP::EA Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::RSR; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) F(RESC) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'SLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'RESC',$off,1); $off+=1; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'SLR', $off+3,3), Message::dissect_MF($self,'RESC',$off+6,1), ); } package Message::ITUT::SCCP::RSR; our @ISA = qw(Message::SCCP::RSR Message::ITUT::SCCP); package Message::ANSI::SCCP::RSR; our @ISA = qw(Message::SCCP::RSR Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::RSC; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR',$off,3); $off+=3; return unless Message::unpack_MF($self,'SLR',$off,3); $off+=3; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR',$off+0,3), Mesasge::dissect_MF($self,'SLR',$off+3,3), ); } package Message::ITUT::SCCP::RSC; our @ISA = qw(Message::SCCP::RSC Message::ITUT::SCCP); package Message::ANSI::SCCP::RSC; our @ISA = qw(Message::SCCP::RSC Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::ERR; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(ERRC) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'ERRC',$off,1); $off++; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'ERRC',$off+3,1), ); } package Message::ITUT::SCCP::ERR; our @ISA = qw(Message::SCCP::ERR Message::ITUT::SCCP); package Message::ANSI::SCCP::ERR; our @ISA = qw(Message::SCCP::ERR Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::IT; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(DLR) F(SLR) F(PCLS) F(SEQ) F(CRED) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'DLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'SLR', $off,3); $off+=3; return unless Message::unpack_MF($self,'PCLS',$off,1); $off+=1; return unless Message::unpack_MF($self,'SEQ', $off,2); $off+=2; return unless Message::unpack_MF($self,'CRED',$off,1); $off+=1; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'DLR', $off+0,3), Message::dissect_MF($self,'SLR', $off+3,3), Message::dissect_MF($self,'PCLS',$off+6,1), Message::dissect_MF($self,'SEQ', $off+7,2), Message::dissect_MF($self,'CRED',$off+9,1), ); } package Message::ITUT::SCCP::IT; our @ISA = qw(Message::SCCP::IT Message::ITUT::SCCP); package Message::ANSI::SCCP::IT; our @ISA = qw(Message::SCCP::IT Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::XUDT; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(PCLS) F(HOPC) V(CDPA) V(CGPA) V(DATA) O(SEG ISNI INS EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'PCLS',$off,1); $off++; return unless Message::unpack_MF($self,'HOPC',$off,1); $off++; return unless Message::unpack_MV($self,'CDPA',$off ); $off++; return unless Message::unpack_MV($self,'CGPA',$off ); $off++; return unless Message::unpack_MV($self,'DATA',$off ); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'PCLS',$off+0,1), Message::dissect_MF($self,'HOPC',$off+1,1), Message::dissect_MV($self,'CDPA',$off+2 ), Message::dissect_MV($self,'CGPA',$off+3 ), Message::dissect_MV($self,'DATA',$off+4 ), Message::dissect_oP($self, $off+5 ), ); my $off = $self->{sccp}->{off} + 1; return [ @{$self->SUPER::dissect(@_)}, ]; } package Message::ITUT::SCCP::XUDT; our @ISA = qw(Message::SCCP::XUDT Message::ITUT::SCCP); package Message::ANSI::SCCP::XUDT; our @ISA = qw(Message::SCCP::XUDT Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::XUDTS; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(RETC) F(HOPC) V(CDPA) V(CGPA) V(DATA) O(SGMT ISNI INS EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'RETC',$off,1); $off++; return unless Message::unpack_MF($self,'HOPC',$off,1); $off++; return unless Message::unpack_MV($self,'CDPA',$off ); $off++; return unless Message::unpack_MV($self,'CGPA',$off ); $off++; return unless Message::unpack_MV($self,'DATA',$off ); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'RETC',$off+0,1), Message::dissect_MF($self,'HOPC',$off+1,1), Message::dissect_MV($self,'CDPA',$off+2 ), Message::dissect_MV($self,'CGPA',$off+3 ), Message::dissect_MV($self,'DATA',$off+4 ), Message::dissect_OP($self, $off+5 ), ); } package Message::ITUT::SCCP::XUDTS; our @ISA = qw(Message::SCCP::XUDTS Message::ITUT::SCCP); package Message::ANSI::SCCP::XUDTS; our @ISA = qw(Message::SCCP::XUDTS Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::LUDT; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(PCLS) F(HOPC) V(CDPA) V(CGPA) V(LDATA) O(SGMT ISNI INS EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'PCLS', $off,1); $off++; return unless Message::unpack_MF($self,'HOPC', $off,1); $off++; return unless Message::unpack_MV($self,'CDPA', $off ); $off++; return unless Message::unpack_MV($self,'CGPA', $off ); $off++; return unless Message::unpack_MV($self,'LDATA',$off ); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'PCLS', $off+0,1), Message::dissect_MF($self,'HOPC', $off+1,1), Message::dissect_MV($self,'CDPA', $off+2 ), Message::dissect_MV($self,'CGPA', $off+3 ), Message::dissect_MV($self,'LDATA',$off+4 ), ); } package Message::ITUT::SCCP::LUDT; our @ISA = qw(Message::SCCP::LUDT Message::ITUT::SCCP); package Message::ANSI::SCCP::LUDT; our @ISA = qw(Message::SCCP::LUDT Message::ANSI::SCCP); # ------------------------------------- package Message::SCCP::LUDTS; our @ISA = qw(Message::SCCP); # ------------------------------------- # F(MT) F(RETC) F(HOPC) V(CDPA) V(CGPA) V(LDATA) O(SGMT ISNI INS EOP) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'RETC', $off,1); $off++; return unless Message::unpack_MF($self,'HOPC', $off,1); $off++; return unless Message::unpack_MV($self,'CDPA', $off ); $off++; return unless Message::unpack_MV($self,'CGPA', $off ); $off++; return unless Message::unpack_MV($self,'LDATA',$off ); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'RETC', $off+0,1), Message::dissect_MF($self,'HOPC', $off+1,1), Message::dissect_MV($self,'CDPA', $off+2 ), Message::dissect_MV($self,'CGPA', $off+3 ), Message::dissect_MV($self,'LDATA',$off+4 ), Message::dissect_OP($self, $off+5 ), ); } package Message::ITUT::SCCP::LUDTS; our @ISA = qw(Message::SCCP::LUDTS Message::ITUT::SCCP); package Message::ANSI::SCCP::LUDTS; our @ISA = qw(Message::SCCP::LUDTS Message::ANSI::SCCP); # ------------------------------------- # ------------------------------------- package Message::ITUT::SCCP::SCMG; our @ISA = qw( Message::ITUT::SCCP::UDT Message::ITUT::SCCP:UDTS Message::ITUT::SCCP::XUDT Message::ITUT::SCCP:XUDTS Message::ITUT::SCCP::LUDT Message::ITUT::SCCP:LUDTS ); # ------------------------------------- # F(MT) F(ASSN) F(APC) F(SMI) for SSC only F(SCL) # ------------------------------------- sub new { my $type = shift; my $parent = shift; my $self = {}; bless $self,$type; $self->{parent} = $parent; $self->{hdr} = $parent->{hdr}; $self->{buf} = $parent->{buf}; $self->{beg} = $parent->{off}; $self->{end} = $parent->{end}; return $self->unpack($self->{beg},$self->{end},@_); } use constant { SCMG_TYPES=>{ 0x01=>['SSA','Subsystem available'], 0x02=>['SSP','Subsystem prohibited'], 0x03=>['SST','Subsystem status test'], 0x04=>['SOR','Subsystem out-of-service request'], 0x05=>['SOG','Subsystem out-of-service grant'], 0x06=>['SSC','SCCP/Subsystem congestion'], }, SMI_TYPES=>[ 'affected subsystem multiplicity unknown', 'affected subsystem is solitary', 'affected subsystem is duplicated', 'spare', ] }; sub unpack { my ($self,$off,$end) = (shift,shift,shift); ( $self->{fi}, $self->{assn}, $self->{apc}, $self->{smi}, $self->{scl}, ) = unpack('CCvCC',substr(${$self->{buf}},$off,6)); $self->{smi} &= 0x03; $self->{scl} &= 0x0f if $self->{fi} == 6; return unless exists SCMG_TYPES->{$self->{fi}}; my $type = SCMG_TYPES->{$self->{fi}}->[0]; bless $self,ref($self)."$type"; return $self; } use constant { SCCP_MT_CR =>0x01, SCCP_MT_CC =>0x02, SCCP_MT_CREF =>0x03, SCCP_MT_RLSD =>0x04, SCCP_MT_RLC =>0x05, SCCP_MT_DT1 =>0x06, SCCP_MT_DT2 =>0x07, SCCP_MT_AK =>0x08, SCCP_MT_UDT =>0x09, SCCP_MT_UDTS =>0x0a, SCCP_MT_ED =>0x0b, SCCP_MT_EA =>0x0c, SCCP_MT_RSR =>0x0d, SCCP_MT_RSC =>0x0e, SCCP_MT_ERR =>0x0f, SCCP_MT_IT =>0x10, SCCP_MT_XUDT =>0x11, SCCP_MT_XUDTS =>0x12, SCCP_MT_LUDT =>0x13, SCCP_MT_LUDTS =>0x14, }; sub dissect { my $self = shift; my $parent = $self->{parent}->dissect(@_); my $off = $self->{scmg}->{off}; my ($mt,$desc) = (@{SCMG_TYPES->{$self->{fi}}}); my $smi = SMI_TYPES->[$self->{smi}]; my $apc = $self->{apc}; $apc = (($apc>>11)&0x07).'-'.(($apc>>3)&0xff).'-'.(($apc>>0)&0x07); my @fields = ( [$off+0,Frame::bytes($self->{fi},0xff,1),'FI',"$mt - $desc"], [$off+1,Frame::bytes($self->{assn},0xff,1),'ASSN',$self->{assn}], [$off+2,Frame::bytes($self->{apc},0x3fff,2),'APC',$apc], [$off+4,Frame::bytes($self->{smi},0xff,1),'SMI',$smi], ); push @fields, [$off+5,Frame::bytes($self->{scl},0xff,1),'SCL',$self->{scl}] if $mt eq 'SSC'; return [ @{$parent}, "SCMG Message $mt $desc", \@fields ]; } # ------------------------------------- package Message::ANSI::SCCP::SCMG; our @ISA = qw( Message::ANSI::SCCP::UDT Message::ANSI::SCCP:UDTS Message::ANSI::SCCP::XUDT Message::ANSI::SCCP:XUDTS Message::ANSI::SCCP::LUDT Message::ANSI::SCCP:LUDTS ); # ------------------------------------- # F(MT) F(ASSN) F(APC) F(SMI) for SSC only F(SCL) # ------------------------------------- use constant { SCMG_TYPES=>{ 0x01=>['SSA','Subsystem available'], 0x02=>['SSP','Subsystem prohibited'], 0x03=>['SST','Subsystem status test'], 0x04=>['SOR','Subsystem out-of-service request'], 0x05=>['SOG','Subsystem out-of-service grant'], 0xfd=>['SBR','Subsystem backup routing'], 0xfe=>['SNR','Subsystem normal routing'], 0xff=>['SRC','Subsystem routing status test'], }, SMI_TYPES=>[ 'affected subsystem multiplicity unknown', 'affected subsystem is solitary', 'affected subsystem is duplicated', 'spare', ] }; sub unpack { my $self = shift; $self->{scmg}->{off} = $self->{off}; $self->{scmg}->{end} = $self->{end}; ( $self->{fi}, $self->{assn}, $self->{apc}, ) = unpack('CCV',substr(${$self->{buf}},$self->{off},6)); $self->{smi} = ($self->{apc} >> 24) & 0xff; $self->{apc} = ($self->{apc} >> 0) & 0xffffff; $self->{smi} &= 0x03; $self->{scl} &= 0x0f if $self->{fi} == 6; return unless exists SCMG_TYPES->{$self->{fi}}; my $type = SCMG_TYPES->{$self->{fi}}->[0]; bless $self,ref($self)."$type"; return $self; } sub dissect { my $self = shift; my $parent = $self->{parent}->dissect(@_); my $off = $self->{scmg}->{off}; my ($mt,$desc) = (@{SCMG_TYPES->{$self->{fi}}}); my $smi = SMI_TYPES->[$self->{smi}]; my $apc = $self->{apc}; $apc = (($apc>>16)&0xff).'-'.(($apc>>8)&0xff).'-'.(($apc>>0)&0xff); my @fields = ( [$off+0,Frame::bytes($self->{fi},0xff,1),'FI',"$mt - $desc"], [$off+1,Frame::bytes($self->{assn},0xff,1),'ASSN',$self->{assn}], [$off+2,Frame::bytes($self->{apc},0xffffff,3),'APC',$apc], [$off+5,Frame::bytes($self->{smi},0xff,1),'SMI',$smi], ); push @fields, [$off+6,Frame::bytes($self->{scl},0xff,1),'SCL',$self->{scl}] if $mt eq 'SSC'; return [ @{$parent}, "SCMG Message $mt $desc", \@fields ]; } # ------------------------------------- package Message::ITUT::SCCP::SCMG::SSA; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SSA; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ITUT::SCCP::SCMG::SSP; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SSP; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ITUT::SCCP::SCMG::SST; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SST; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ITUT::SCCP::SCMG::SOR; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SOR; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ITUT::SCCP::SCMG::SOG; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SOG; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ITUT::SCCP::SCMG::SSC; our @ISA = qw(Message::ITUT::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SBR; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SNR; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- package Message::ANSI::SCCP::SCMG::SRT; our @ISA = qw(Message::ANSI::SCCP::SCMG); # ------------------------------------- # ------------------------------------- package Message::USER; our @ISA = qw(Message::MTP3); # ------------------------------------- sub unpack { my $self = shift; my ($network,$datalink) = @_; $self->{mt} = unpack('C',substr(${$self->{buf}},$self->{off},1)); return $self; } sub dissect { my $self = shift; return $self->Message::MTP3::dissect(@_) if exists $self->{mtp3}; return $self->Message::M3UA::XFER::DATA::dissect(@_) if exists $self->{m3ua}; } # ------------------------------------- package Message::ISUP; our @ISA = qw(Message::MTP3); # ------------------------------------- use constant { ISUP_MT_IAM => 0x01, # 0000 0001 Initial address ISUP_MT_SAM => 0x02, # 0000 0010 Subsequent address message ISUP_MT_INR => 0x03, # 0000 0011 Information request (national use) ISUP_MT_INF => 0x04, # 0000 0100 Information response (national use) ISUP_MT_COT => 0x05, # 0000 0101 Continuity ISUP_MT_ACM => 0x06, # 0000 0110 Address complete ISUP_MT_CON => 0x07, # 0000 0111 Connect ISUP_MT_FOT => 0x08, # 0000 1000 Forward transfer ISUP_MT_ANM => 0x09, # 0000 1001 Answer #ISUP_MT_FIXME => 0x0a, # 0000 1010 Reserved (Red book) #ISUP_MT_FIXME => 0x0b, # 0000 1011 Reserved (Red book) ISUP_MT_REL => 0x0c, # 0000 1100 Release ISUP_MT_SUS => 0x0d, # 0000 1101 Suspend ISUP_MT_RES => 0x0e, # 0000 1110 Resume #ISUP_MT_FIXME => 0x0f, # 0000 1111 Reserved (Red book) ISUP_MT_RLC => 0x10, # 0001 0000 Release complete ISUP_MT_CCR => 0x11, # 0001 0001 Continuity check request ISUP_MT_RSC => 0x12, # 0001 0010 Reset circuit ISUP_MT_BLO => 0x13, # 0001 0011 Blocking ISUP_MT_UBL => 0x14, # 0001 0100 Unblocking ISUP_MT_BLA => 0x15, # 0001 0101 Blocking acknowledgement ISUP_MT_UBA => 0x16, # 0001 0110 Unblocking acknowledgement ISUP_MT_GRS => 0x17, # 0001 0111 Circuit group reset ISUP_MT_CGB => 0x18, # 0001 1000 Circuit group blocking ISUP_MT_CGU => 0x19, # 0001 1001 Circuit group unblocking ISUP_MT_CGBA => 0x1a, # 0001 1010 Circuit group blocking acknowledgement ISUP_MT_CGUA => 0x1b, # 0001 1011 Circuit group ublocking acknowledgement ISUP_MT_CMR => 0x1c, # 0001 1100 Call modification request ISUP_MT_CMC => 0x1d, # 0001 1101 Call modification complete ISUP_MT_CMRJ => 0x1e, # 0001 1110 Call modification reject ISUP_MT_FAR => 0x1f, # 0001 1111 Facility request ISUP_MT_FAA => 0x20, # 0010 0000 Facility accepted ISUP_MT_FRJ => 0x21, # 0010 0001 Facility reject ISUP_MT_FAD => 0x22, # 0010 0010 Facility deactivate ISUP_MT_FAI => 0x23, # 0010 0011 Facility information ISUP_MT_LPA => 0x24, # 0010 0100 Loop back acknowledgement (national) ISUP_MT_CSVQ => 0x25, # 0010 0101 Reserved (Red book) ISUP_MT_CSVR => 0x26, # 0010 0110 Reserved (Red book) ISUP_MT_DRS => 0x27, # 0010 0111 Delayed release (Reserved (Blue Book)) ISUP_MT_PAM => 0x28, # 0010 1000 Pass along message (national) ISUP_MT_GRA => 0x29, # 0010 1001 Circuit group reset acknowledgement ISUP_MT_CQM => 0x2a, # 0010 1010 Circuit group query (national) ISUP_MT_CQR => 0x2b, # 0010 1011 Circuit group query response (national) ISUP_MT_CPG => 0x2c, # 0010 1100 Call progress ISUP_MT_USR => 0x2d, # 0010 1101 User to user information ISUP_MT_UCIC => 0x2e, # 0010 1110 Unequipped CIC (national) ISUP_MT_CFN => 0x2f, # 0010 1111 Confusion ISUP_MT_OLM => 0x30, # 0011 0000 Overload (national) ISUP_MT_CRG => 0x31, # 0011 0001 Charge information (national) ISUP_MT_NRM => 0x32, # 0011 0010 Network resource managment ISUP_MT_FAC => 0x33, # 0011 0011 Facility ISUP_MT_UPT => 0x34, # 0011 0100 User part test ISUP_MT_UPA => 0x35, # 0011 0101 User part available ISUP_MT_IDR => 0x36, # 0011 0110 Identification request ISUP_MT_IRS => 0x37, # 0011 0111 Identification response ISUP_MT_SGM => 0x38, # 0011 1000 Segmentation #ISUP_MT_FIXME => 0x39, # 0011 1001 Reserved (B-ISUP) #ISUP_MT_FIXME => 0x3a, # 0011 1010 Reserved (B-ISUP) #ISUP_MT_FIXME => 0x3b, # 0011 1011 Reserved (B-ISUP) #ISUP_MT_FIXME => 0x3c, # 0011 1100 Reserved (B-ISUP) #ISUP_MT_FIXME => 0x3d, # 0011 1101 Reserved (B-ISUP) #ISUP_MT_FIXME => 0x3e, # 0011 1110 #ISUP_MT_FIXME => 0x3f, # 0011 1111 ISUP_MT_LPR => 0x40, # 0100 0000 Loop preservation ISUP_MT_APT => 0x41, # 0100 0001 Application transport ISUP_MT_PRI => 0x42, # 0100 0010 Pre-releation information ISUP_MT_SDN => 0x43, # 0100 0011 Subsequent directory number (national) # ISUP_MT_CRA => 0xe9, # 1110 1001 Circuit reservation acknowledgment ISUP_MT_CRM => 0xea, # 1110 1010 Circuit reservation ISUP_MT_CVR => 0xeb, # 1110 1011 Circuit validation response ISUP_MT_CVT => 0xec, # 1110 1100 Circuit validation test ISUP_MT_EXM => 0xed, # 1110 1101 Exit message # ISUP_MT_NON => 0xf8, # 1111 1000 National notification (Spain) # # 1111 1001 # # 1111 1010 # # 1111 1011 ISUP_MT_LLM => 0xfc, # 1111 1100 National malicioius call (Spain) ISUP_MT_CAK => 0xfd, # 1111 1101 Charge acknowledgement (Singapore) ISUP_MT_TCM => 0xfe, # 1111 1110 Tariff charge (Signapore) ISUP_MT_MCP => 0xff, # 1111 1111 Malicious call print (Singapore) }; use constant { ISUP_TYPES=>{ &ISUP_MT_IAM => 'IAM', # 0000 0001 Initial address &ISUP_MT_SAM => 'SAM', # 0000 0010 Subsequent address message &ISUP_MT_INR => 'INR', # 0000 0011 Information request (national use) &ISUP_MT_INF => 'INF', # 0000 0100 Information response (national use) &ISUP_MT_COT => 'COT', # 0000 0101 Continuity &ISUP_MT_ACM => 'ACM', # 0000 0110 Address complete &ISUP_MT_CON => 'CON', # 0000 0111 Connect &ISUP_MT_FOT => 'FOT', # 0000 1000 Forward transfer &ISUP_MT_ANM => 'ANM', # 0000 1001 Answer #0x0a => '???', # 0000 1010 Reserved (Red book) #0x0b => '???', # 0000 1011 Reserved (Red book) &ISUP_MT_REL => 'REL', # 0000 1100 Release &ISUP_MT_SUS => 'SUS', # 0000 1101 Suspend &ISUP_MT_RES => 'RES', # 0000 1110 Resume #0x0f => '???', # 0000 1111 Reserved (Red book) &ISUP_MT_RLC => 'RLC', # 0001 0000 Release complete &ISUP_MT_CCR => 'CCR', # 0001 0001 Continuity check request &ISUP_MT_RSC => 'RSC', # 0001 0010 Reset circuit &ISUP_MT_BLO => 'BLO', # 0001 0011 Blocking &ISUP_MT_UBL => 'UBL', # 0001 0100 Unblocking &ISUP_MT_BLA => 'BLA', # 0001 0101 Blocking acknowledgement &ISUP_MT_UBA => 'UBA', # 0001 0110 Unblocking acknowledgement &ISUP_MT_GRS => 'GRS', # 0001 0111 Circuit group reset &ISUP_MT_CGB => 'CGB', # 0001 1000 Circuit group blocking &ISUP_MT_CGU => 'CGU', # 0001 1001 Circuit group unblocking &ISUP_MT_CGBA => 'CGBA', # 0001 1010 Circuit group blocking acknowledgement &ISUP_MT_CGUA => 'CGUA', # 0001 1011 Circuit group ublocking acknowledgement &ISUP_MT_CMR => 'CMR', # 0001 1100 Call modification request (Reserved (Blue book)) &ISUP_MT_CMC => 'CMC', # 0001 1101 Call modification complete (Reserved (Blue book)) &ISUP_MT_CMRJ => 'CMRJ', # 0001 1110 Call modification reject (Reserved (Blue book)) &ISUP_MT_FAR => 'FAR' # 0001 1111 Facility request, &ISUP_MT_FAA => 'FAA', # 0010 0000 Facility accepted &ISUP_MT_FRJ => 'FRJ', # 0010 0001 Facility reject &ISUP_MT_FAD => 'FAD', # 0010 0010 Facility deactivate (Reserved (Red book)) &ISUP_MT_FAI => 'FAI', # 0010 0011 Facility information (Reserved (Red book)) &ISUP_MT_LPA => 'LPA', # 0010 0100 Loop back acknowledgement (national) &ISUP_MT_CSVQ => 'CSVQ', # 0010 0101 Reserved (Red book) &ISUP_MT_CSVR => 'CSVR', # 0010 0110 Reserved (Red book) &ISUP_MT_DRS => 'DRS', # 0010 0111 Delayed release (Reserved (Blue book)) &ISUP_MT_PAM => 'PAM', # 0010 1000 Pass along message (national) &ISUP_MT_GRA => 'GRA', # 0010 1001 Circuit group reset acknowledgement &ISUP_MT_CQM => 'CQM', # 0010 1010 Circuit group query (national) &ISUP_MT_CQR => 'CQR', # 0010 1011 Circuit group query response (national) &ISUP_MT_CPG => 'CPG', # 0010 1100 Call progress &ISUP_MT_USR => 'USR', # 0010 1101 User to user information &ISUP_MT_UCIC => 'UCIC', # 0010 1110 Unequipped CIC (national) &ISUP_MT_CFN => 'CFN', # 0010 1111 Confusion &ISUP_MT_OLM => 'OLM', # 0011 0000 Overload (national) &ISUP_MT_CRG => 'CRG', # 0011 0001 Charge information (national) &ISUP_MT_NRM => 'NRM', # 0011 0010 Network resource managment &ISUP_MT_FAC => 'FAC', # 0011 0011 Facility &ISUP_MT_UPT => 'UPT', # 0011 0100 User part test &ISUP_MT_UPA => 'UPA', # 0011 0101 User part available &ISUP_MT_IDR => 'IDR', # 0011 0110 Identification request &ISUP_MT_IRS => 'IRS', # 0011 0111 Identification response &ISUP_MT_SGM => 'SGM', # 0011 1000 Segmentation #0x39 => '???', # 0011 1001 Reserved (B-ISUP) #0x3a => '???', # 0011 1010 Reserved (B-ISUP) #0x3b => '???', # 0011 1011 Reserved (B-ISUP) #0x3c => '???', # 0011 1100 Reserved (B-ISUP) #0x3d => '???', # 0011 1101 Reserved (B-ISUP) #0x3e => '???', # 0011 1110 #0x3f => '???', # 0011 1111 &ISUP_MT_LPR => 'LPR', # 0100 0000 Loop preservation &ISUP_MT_ATP => 'ATP', # 0100 0001 Application transport &ISUP_MT_PRI => 'PRI', # 0100 0010 Pre-releation information &ISUP_MT_SDN => 'SDN', # 0100 0011 Subsequent directory number (national) # &ISUP_MT_CRA => 'CRA', # 1110 1001 Circuit reservation acknowledgment &ISUP_MT_CRM => 'CRM', # 1110 1010 Circuit reservation &ISUP_MT_CVR => 'CVR', # 1110 1011 Circuit validation response &ISUP_MT_CVT => 'CVT', # 1110 1100 Circuit validation test &ISUP_MT_EXM => 'EXM', # 1110 1101 Exit message # &ISUP_MT_NON => 'NON', # 1111 1000 National notification (Spain) # # 1111 1001 # # 1111 1010 # # 1111 1011 &ISUP_MT_LLM => 'LLM', # 1111 1100 National malicioius call (Spain), &ISUP_MT_CAK => 'CAK', # 1111 1101 Charge acknowledgement (Singapore) &ISUP_MT_TCM => 'TCM', # 1111 1110 Tariff charge (Signapore) &ISUP_MT_MCP => 'MCP', # 1111 1111 Malicious call print (Singapore) }, }; sub unpack { my $self = shift; $self->{isup}->{off} = $self->{off}; $self->{isup}->{end} = $self->{end}; ( $self->{cic}, $self->{mt}, ) = unpack('vC',substr(${$self->{buf}},$self->{off},3)); my $type = ISUP_TYPES->{$self->{mt}}; return unless defined $type; bless $self,ref($self)."::$type"; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off}; my $layers; if (exists $self->{mtp3}) { $layers = $self->SUPER::dissect(@_); } else { # if (exists $self->{m3ua}) { $layers = $self->Message::M3UA::XFER::DATA::dissect(@_); } my $mt = $self->{mt}; $mt = ISUP_TYPES->{$mt}."($mt)"; return [ @{$layers}, "$mt Message", [$off+0,Frame::bytes($self->{cic},0x00ffff,3),'CIC',$self->{cic}], [$off+0,Frame::bytes($self->{mt},0xff0000,3),'MT',$mt], ]; } use constant { ISUP_PT_EOP => 0, # 0000 0000 End of optional parameters ISUP_PT_CLRF => 1, # 0000 0001 Call reference @ ISUP_PT_TMR => 2, # 0000 0010 Transmission medium requirement (!A) ISUP_PT_ATP => 3, # 0000 0011 Access transport ISUP_PT_CDPN => 4, # 0000 0100 Called party number ISUP_PT_SUBN => 5, # 0000 0101 Subsequent number (!A) ISUP_PT_NCI => 6, # 0000 0110 Nature of connection indicators ISUP_PT_FCI => 7, # 0000 0111 Forward call indicators ISUP_PT_OFCI => 8, # 0000 1000 Optional forward call indicators ISUP_PT_CPC => 9, # 0000 1001 Calling party's category ISUP_PT_CGPN => 10, # 0000 1010 Calling party number ISUP_PT_RDGN => 11, # 0000 1011 Redirecting number ISUP_PT_RDNN => 12, # 0000 1100 Redirection number ISUP_PT_CONR => 13, # 0000 1101 Connection request ISUP_PT_INRI => 14, # 0000 1110 Information request indicators (N) ISUP_PT_INFI => 15, # 0000 1111 Information indicators (N) @ ISUP_PT_COTI => 16, # 0001 0000 Continuity indicators ISUP_PT_BCI => 17, # 0001 0001 Backward call indicators ISUP_PT_CAUS => 18, # 0001 0010 Cause indicators ISUP_PT_RDI => 19, # 0001 0011 Redirection information # # 0001 0100 Reserved (Q.763 1984, Red Book) ISUP_PT_CGI => 21, # 0001 0101 Circuit group supervision message type ISUP_PT_RS => 22, # 0001 0110 Range and status ISUP_PT_CMI => 23, # 0001 0111 Call modification indicators (Blue Book) (!A) ISUP_PT_FACI => 24, # 0001 1000 Facility indicator (!A) ISUP_PT_FAII => 25, # 0001 1001 Facility information indicators (Bellcore) (!A) ISUP_PT_CUGI => 26, # 0001 1010 Closed user group interlock code (!A) ISUP_PT_INDEX => 27, # 0001 1011 Index (Bellcore) (!A) ISUP_PT_CUGC => 28, # 0001 1100 Closed user group check response indicators (!A) ISUP_PT_USI => 29, # 0001 1101 User service information ISUP_PT_SPC => 30, # 0001 1110 Signalling point code (N) (!A) (Bellcore) @ # # 0001 1111 Reserved (Q.763 1984, Red Book) ISUP_PT_UUI => 32, # 0010 0000 User-to-user information ISUP_PT_CONN => 33, # 0010 0001 Connected number (!A) ISUP_PT_SRIS => 34, # 0010 0010 Suspend/resume indicators ISUP_PT_TNS => 35, # 0010 0011 Transit network selection (N) @ ISUP_PT_EVNT => 36, # 0010 0100 Event information indicators ISUP_PT_CAM => 37, # 0010 0101 Circuit assignment map ISUP_PT_CSI => 38, # 0010 0110 Circuit state indicator @ ISUP_PT_ACL => 39, # 0010 0111 Automatic congestion level ISUP_PT_OCDN => 40, # 0010 1000 Original called number ISUP_PT_OBCI => 41, # 0010 1001 Optional backward call indicators ISUP_PT_UUIND => 42, # 0010 1010 User-to-user indicators ISUP_PT_ISPC => 43, # 0010 1011 Origination ISC point code (X) ISUP_PT_GNOT => 44, # 0010 1100 Generic notification (X) ISUP_PT_CHI => 45, # 0010 1101 Call history information (X) ISUP_PT_ADI => 46, # 0010 1110 Access delivery information (X) ISUP_PT_NSF => 47, # 0010 1111 Network specific facility (N) @ ISUP_PT_USIP => 48, # 0011 0000 User service information prime ISUP_PT_PROP => 49, # 0011 0001 Propagation delay counter (X) ISUP_PT_ROPS => 50, # 0011 0010 Remote operations (N) @ ISUP_PT_SA => 51, # 0011 0011 Service activation @ ISUP_PT_UTI => 52, # 0011 0100 User teleservice information (X) ISUP_PT_TMU => 53, # 0011 0101 Transmission medium used ISUP_PT_CDI => 54, # 0011 0110 Call diversion information (X) ISUP_PT_ECI => 55, # 0011 0111 Echo control information (X) ISUP_PT_MCI => 56, # 0011 1000 Message compatibility information ISUP_PT_PCI => 57, # 0011 1001 Parameter compatibility information ISUP_PT_MLPP => 58, # 0011 1010 MLPP precedence (Precedence ANSI) ISUP_PT_MCIQ => 59, # 0011 1011 MCID request indicators (X) ISUP_PT_MCIR => 60, # 0011 1100 MCID response indicators (X) ISUP_PT_HOPC => 61, # 0011 1101 Hop counter (reserved) ISUP_PT_TMRP => 62, # 0011 1110 Transmission medium requirement prime (X) ISUP_PT_LN => 63, # 0011 1111 Location number (X) ISUP_PT_RDNR => 64, # 0100 0000 Redirection number restriction (X) ISUP_PT_FREEP => 65, # 0100 0001 Freephone indicators/Reserved (Q.763 1992, White Book) (X) ISUP_PT_GREF => 66, # 0100 0010 Generic reference/Reserved (Q.763 1992, White Book) (X) ISUP_PT_CTR => 67, # 0100 0011 Call transfer reference (Q.763) (X) ISUP_PT_LPI => 68, # 0100 0100 Loop prevention indicators (Q.763) (X) ISUP_PT_CTN => 69, # 0100 0101 Call transfer number (Q.763) (X) # # 0100 0110 Reserved (B-ISUP) # # 0100 0111 Reserved (B-ISUP) # # 0100 1000 Reserved (B-ISUP) # # 0100 1001 Reserved (B-ISUP) # # 0100 1010 Reserved (B-ISUP) ISUP_PT_CCSS => 75, # 0100 1011 CCSS (Q.763) (X) ISUP_PT_FGVSN => 76, # 0100 1100 Forward GVNS (Q.763) (X) ISUP_PT_BGVNS => 77, # 0100 1101 Backward GVNS (Q.763) (X) ISUP_PT_RDCAP => 78, # 0100 1110 Redirect capability (N) (ANSI/GR-246-CORE) # # 0100 1111 Reserved (B-ISUP) # # 0101 0000 Reserved (B-ISUP) # # 0101 0001 Reserved (B-ISUP) # # 0101 0010 Reserved (B-ISUP) # # 0101 0011 Reserved (B-ISUP) # # 0101 0100 Reserved (B-ISUP) # # 0101 0101 Reserved (B-ISUP) # # 0101 0110 Reserved (B-ISUP) # # 0101 0111 Reserved (B-ISUP) # # 0101 1000 Reserved (B-ISUP) # # 0101 1001 Reserved (B-ISUP) # # 0101 1010 Reserved (B-ISUP) ISUP_PT_NMC => 91, # 0101 1011 Network management controls (ANSI/GR-246-CORE) # # 0101 1100 Reserved (B-ISUP) # # 0101 1101 Reserved (B-ISUP) # # 0101 1110 Reserved (B-ISUP) # # 0101 1111 Reserved (B-ISUP) # # 0110 0000 Reserved (B-ISUP) # # 0110 0001 Reserved (B-ISUP) # # 0110 0010 Reserved (B-ISUP) # # 0110 0011 Reserved (B-ISUP) # # 0110 0100 Reserved (B-ISUP) # # 0110 0100 Reserved (B-ISUP) ISUP_PT_CID =>101, # 0110 0101 Correlation id (Q.763) (X) ISUP_PT_SCFID =>102, # 0110 0110 SCF id (Q.763) (X) # # 0110 0111 Reserved (B-ISUP) # # 0110 1000 Reserved (B-ISUP) # # 0110 1001 Reserved (B-ISUP) # # 0110 1010 Reserved (B-ISUP) # # 0110 1011 Reserved (B-ISUP) # # 0110 1100 Reserved (B-ISUP) # # 0110 1101 Reserved (B-ISUP) ISUP_PT_CDTI =>110, # 0110 1110 Call diversion treatment indicators (Q.763) (X) ISUP_PT_CINN =>111, # 0110 1111 Called IN number (Q.763) (X) ISUP_PT_CTRI =>112, # 0111 0000 Call offering treatment indicators (Q.763) (X) ISUP_PT_CHPI =>113, # 0111 0001 Charged party identification (Q.763) (X) ISUP_PT_CTI =>114, # 0111 0010 Conference treatment indicators (Q.763) (X) ISUP_PT_DISP =>115, # 0111 0011 Display information (Q.763) (X) ISUP_PT_UAI =>116, # 0111 0100 UID action indicators (Q.763) (X) ISUP_PT_UCI =>117, # 0111 0101 UID capability indicators (Q.763) (X) # # 0111 0110 Reserved (B-ISUP) ISUP_PT_RC =>119, # 0111 0111 Redirect counter (N) (ANSI/GR-246-CORE)/Reserved (B-ISUP) ISUP_PT_AT =>120, # 0111 1000 Application transport (Q.763)/Reserved (B-ISUP) (X) ISUP_PT_CCR =>121, # 0111 1001 Collect call request (Q.763)/Reserved (B-ISUP) (X) ISUP_PT_CPI =>122, # 0111 1010 CCNR possible indicator (Q.763)/Reserved (B-ISUP) (X) ISUP_PT_PVTCA =>123, # 0111 1011 Pivot capability (ANSI/Q.763)/Reserved (B-ISUP) ISUP_PT_PVTRI =>124, # 0111 1100 Pivot routing indicators (ANSI/Q.763)/Reserved (B-ISUP) ISUP_PT_CDDN =>125, # 0111 1101 Called directory number (Q.763)/Reserved (B-ISUP) (X) # # 0111 1110 Reserved (B-ISUP) ISUP_PT_OCDIN =>127, # 0111 1111 Original called IN number (Q.763) (X) # # 1000 0000 ISUP_PT_GL =>129, # 1000 0001 Calling geodetic location (ANSI/GR-246-CORE) ISUP_PT_HTRI =>130, # 1000 0010 HTR information (Q.763) (X) # # 1000 0011 ISUP_PT_NRN =>132, # 1000 0100 Network routing number (N) (Q.763) (X) ISUP_PT_QORC =>133, # 1000 0101 Query on release capability (O) (Q.763) (X) ISUP_PT_PVTS =>134, # 1000 0110 Pivot status (N) (ANSI/Q.763) (!A) ISUP_PT_PVTC =>135, # 1000 0111 Pivot counter (ANSI/Q.763) (!A) ISUP_PT_PVTFI =>136, # 1000 1000 Pivot routing forward information (ANSI/Q.763) (!A) ISUP_PT_PVTBI =>137, # 1000 1001 Pivot routing backward information (ANSI/Q.763) (!A) ISUP_PT_RDS =>138, # 1000 1010 Redirect status (N) ISUP_PT_RDFI =>139, # 1000 1011 Redirect forward information (N) ISUP_PT_RDBI =>140, # 1000 1100 Redirect backward information (N) ISUP_PT_NPFI =>141, # 1000 1101 Number portability forward information (O) (X) # # 1000 1110 # # 1000 1111 Reserved (B-ISUP) # # 1001 0000 Reserved (B-ISUP) # # 1001 0001 Reserved (B-ISUP) # # 1001 0010 Reserved (B-ISUP) # # 1001 0011 Reserved (B-ISUP) # # 1001 0100 Reserved (B-ISUP) # # 1001 0101 Reserved (B-ISUP) # # 1001 0110 Reserved (B-ISUP) ISUP_PT_ARR =>140, # 1001 0110 Automatic re-routing # # 1001 0111 Reserved (B-ISUP) # # 1001 1000 Reserved (B-ISUP) # ISUP_PT_IEPS =>166, # 1010 0110 Internation Emergency Prefrerence Scheme call info (Q.763/Amd.4/01/2006) ISUP_PT_VEDI =>168, # 1010 1000 Voice Enhancement Device Information (Q.763/Amd.5/09/2006) # ISUP_PT_GNUM =>192, # 1100 0000 Generic number (Q.763)/Generic address (ANSI/GR-246-CORE) ISUP_PT_GDIG =>193, # 1100 0001 Generic digits (N) ISUP_PT_OSI =>194, # 1100 0010 Operator services information (ANSI/GR-246-CORE) ISUP_PT_EGRESS =>195, # 1100 0011 Egress (ANSI/GR-246-CORE) ISUP_PT_JUR =>196, # 1100 0100 Jurisdiction (ANSI/GR-246-CORE) ISUP_PT_CIDC =>197, # 1100 0101 Carrier identification (ANSI/GR-246-CORE) ISUP_PT_BGROUP =>198, # 1100 0110 Business group (ANSI/GR-246-CORE) ISUP_PT_GNAM =>199, # 1100 0111 Generic name (ANSI/GR-246-CORE) # ISUP_PT_NOTI =>225, # 1110 0001 Notification indicator (ANSI/GR-246-CORE) ISUP_PT_CSPI =>226, # 1110 0010 Carrier service provider identification (ANSI) ISUP_PT_TRNSRQ =>227, # 1110 0011 Transaction request (ANSI/GR-246-CORE) ISUP_PT_LSPI =>228, # 1110 0100 Local service provider identification (ANSI) ISUP_PT_CGCI =>229, # 1110 0101 Circuit group characteristic indicator (ANSI/GR-246-CORE) ISUP_PT_CVRI =>230, # 1110 0110 Circuit validation response indicator (ANSI/GR-246-CORE) ISUP_PT_OTGN =>231, # 1110 0111 Outgoing trunk group number (ANSI/GR-246-CORE) ISUP_PT_CIN =>232, # 1110 1000 Circuit identification name (ANSI/GR-246-CORE) ISUP_PT_CLLI =>233, # 1110 1001 Common language location identification (ANSI/GR-246-CORE) ISUP_PT_OLI =>234, # 1110 1010 Originating line information (ANSI/GR-246-CORE) ISUP_PT_CHGN =>235, # 1110 1011 Charge number (ANSI/GR-246-CORE) ISUP_PT_SVCD =>236, # 1110 1100 Service code indicator (ANSI/GR-246-CORE) ISUP_PT_SPR =>237, # 1110 1101 Special processing request (ANSI/GR-246-CORE) ISUP_PT_CSEL =>238, # 1110 1110 Carrier selection information (ANSI/GR-246-CORE) ISUP_PT_NT =>239, # 1110 1111 Network transport (ANSI/GR-246-CORE) # 1111 0000 # 1111 0001 # 1111 0010 ISUP_PT_ORI =>243, # 1111 0011 Outgoing route identification (Spain) ISUP_PT_IRI =>244, # 1111 0100 Incoming route identification (Spain) # 1111 0101 # 1111 0110 # 1111 0111 ISUP_PT_RATE =>248, # 1111 1000 Rate (Spain) ISUP_PT_IIC =>249, # 1111 1001 Identifier of incoming circuit (Spain) # 1111 1010 # 1111 1011 # 1111 1100 ISUP_PT_TOI =>253, # 1111 1101 Trunk offering information (Singapore) ISUP_PT_TON =>253, # 1111 1101 Type of notification (Spain) ISUP_PT_CRI =>254, # 1111 1110 Charge rate information (Singapore) ISUP_PT_ICCI =>255, # 1111 1111 Call charge information (Signapore) }; sub unpack_PT_EOP { my ($self,$off,$end,$len) = @_; return; } sub unpack_PT_CLRF { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TMR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ATP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CDPN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SUBN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_FCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OFCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CPC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CGPN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDGN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDNN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CONR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_INRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_INFI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_COTI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_BCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CAUS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CGI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CMI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_FACI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_FAII { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CUGI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_INDEX { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CUGC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_USI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SPC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_UUI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CONN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SRIS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TNS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_EVNT { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CAM { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CSI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ACL { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OCDN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OBCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_UUIND { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ISPC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GNOT { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CHI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ADI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NSF { my ($self,$off,$end,$len) = @_; } sub unpack_PT_USIP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PROP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ROPS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SA { my ($self,$off,$end,$len) = @_; } sub unpack_PT_UTI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TMU { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CDI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ECI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_MCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_MLPP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_MCIQ { my ($self,$off,$end,$len) = @_; } sub unpack_PT_MCIR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_HOPC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TMRP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_LN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDNR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_FREEP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GREF { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CTR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_LPI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CTN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CCSS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_FGVSN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_BGVNS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDCAP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NMC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CID { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SCFID { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CDTI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CINN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CTRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CHPI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CTI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_DISP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_UAI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_UCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_AT { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CCR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CPI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTCA { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CDDN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OCDIN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GL { my ($self,$off,$end,$len) = @_; } sub unpack_PT_HTRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NRN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_QORC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTFI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_PVTBI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDFI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RDBI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NPFI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GNUM { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GDIG { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OSI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_EGRESS { my ($self,$off,$end,$len) = @_; } sub unpack_PT_JUR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CIDC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_BGROUP { my ($self,$off,$end,$len) = @_; } sub unpack_PT_GNAM { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NOTI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CSPI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TRNSRQ { my ($self,$off,$end,$len) = @_; } sub unpack_PT_LSPI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CGCI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CVRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OTGN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CIN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CLLI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_OLI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CHGN { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SVCD { my ($self,$off,$end,$len) = @_; } sub unpack_PT_SPR { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CSEL { my ($self,$off,$end,$len) = @_; } sub unpack_PT_NT { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ORI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_IRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_RATE { my ($self,$off,$end,$len) = @_; } sub unpack_PT_IIC { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TOI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_TON { my ($self,$off,$end,$len) = @_; } sub unpack_PT_CRI { my ($self,$off,$end,$len) = @_; } sub unpack_PT_ICCI { my ($self,$off,$end,$len) = @_; } use constant { ISUP_PARM_TYPE=>{ &ISUP_PT_EOP => 'EOP', &ISUP_PT_CLRF => 'CLRF', &ISUP_PT_TMR => 'TMR', &ISUP_PT_ATP => 'ATP', &ISUP_PT_CDPN => 'CDPN', &ISUP_PT_SUBN => 'SUBN', &ISUP_PT_NCI => 'NCI', &ISUP_PT_FCI => 'FCI', &ISUP_PT_OFCI => 'OFCI', &ISUP_PT_CPC => 'CPC', &ISUP_PT_CGPN => 'CGPN', &ISUP_PT_RDGN => 'RDGN', &ISUP_PT_RDNN => 'RDNN', &ISUP_PT_CONR => 'CONR', &ISUP_PT_INRI => 'INRI', &ISUP_PT_INFI => 'INFI', &ISUP_PT_COTI => 'COTI', &ISUP_PT_BCI => 'BCI', &ISUP_PT_CAUS => 'CAUS', &ISUP_PT_RDI => 'RDI', &ISUP_PT_CGI => 'CGI', &ISUP_PT_RS => 'RS', &ISUP_PT_CMI => 'CMI', &ISUP_PT_FACI => 'FACI', &ISUP_PT_FAII => 'FAII', &ISUP_PT_CUGI => 'CUGI', &ISUP_PT_INDEX => 'INDEX', &ISUP_PT_CUGC => 'CUGC', &ISUP_PT_USI => 'USI', &ISUP_PT_SPC => 'SPC', &ISUP_PT_UUI => 'UUI', &ISUP_PT_CONN => 'CONN', &ISUP_PT_SRIS => 'SRIS', &ISUP_PT_TNS => 'TNS', &ISUP_PT_EVNT => 'EVNT', &ISUP_PT_CAM => 'CAM', &ISUP_PT_CSI => 'CSI', &ISUP_PT_ACL => 'ACL', &ISUP_PT_OCDN => 'OCDN', &ISUP_PT_OBCI => 'OBCI', &ISUP_PT_UUIND => 'UUIND', &ISUP_PT_ISPC => 'ISPC', &ISUP_PT_GNOT => 'GNOT', &ISUP_PT_CHI => 'CHI', &ISUP_PT_ADI => 'ADI', &ISUP_PT_NSF => 'NSF', &ISUP_PT_USIP => 'USIP', &ISUP_PT_PROP => 'PROP', &ISUP_PT_ROPS => 'ROPS', &ISUP_PT_SA => 'SA', &ISUP_PT_UTI => 'UTI', &ISUP_PT_TMU => 'TMU', &ISUP_PT_CDI => 'CDI', &ISUP_PT_ECI => 'ECI', &ISUP_PT_MCI => 'MCI', &ISUP_PT_PCI => 'PCI', &ISUP_PT_MLPP => 'MLPP', &ISUP_PT_MCIQ => 'MCIQ', &ISUP_PT_MCIR => 'MCIR', &ISUP_PT_HOPC => 'HOPC', &ISUP_PT_TMRP => 'TMRP', &ISUP_PT_LN => 'LN', &ISUP_PT_RDNR => 'RDNR', &ISUP_PT_FREEP => 'FREEP', &ISUP_PT_GREF => 'GREF', &ISUP_PT_CTR => 'CTR', &ISUP_PT_LPI => 'LPI', &ISUP_PT_CTN => 'CTN', &ISUP_PT_CCSS => 'CCSS', &ISUP_PT_FGVSN => 'FGVSN', &ISUP_PT_BGVNS => 'BGVNS', &ISUP_PT_RDCAP => 'RDCAP', &ISUP_PT_NMC => 'NMC', &ISUP_PT_CID => 'CID', &ISUP_PT_SCFID => 'SCFID', &ISUP_PT_CDTI => 'CDTI', &ISUP_PT_CINN => 'CINN', &ISUP_PT_CTRI => 'CTRI', &ISUP_PT_CHPI => 'CHPI', &ISUP_PT_CTI => 'CTI', &ISUP_PT_DISP => 'DISP', &ISUP_PT_UAI => 'UAI', &ISUP_PT_UCI => 'UCI', &ISUP_PT_RC => 'RC', &ISUP_PT_AT => 'AT', &ISUP_PT_CCR => 'CCR', &ISUP_PT_CPI => 'CPI', &ISUP_PT_PVTCA => 'PVTCA', &ISUP_PT_PVTRI => 'PVTRI', &ISUP_PT_CDDN => 'CDDN', &ISUP_PT_OCDIN => 'OCDIN', &ISUP_PT_GL => 'GL', &ISUP_PT_HTRI => 'HTRI', &ISUP_PT_NRN => 'NRN', &ISUP_PT_QORC => 'QORC', &ISUP_PT_PVTS => 'PVTS', &ISUP_PT_PVTC => 'PVTC', &ISUP_PT_PVTFI => 'PVTFI', &ISUP_PT_PVTBI => 'PVTBI', &ISUP_PT_RDS => 'RDS', &ISUP_PT_RDFI => 'RDFI', &ISUP_PT_RDBI => 'RDBI', &ISUP_PT_NPFI => 'NPFI', &ISUP_PT_GNUM => 'GNUM', &ISUP_PT_GDIG => 'GDIG', &ISUP_PT_OSI => 'OSI', &ISUP_PT_EGRESS => 'EGRESS', &ISUP_PT_JUR => 'JUR', &ISUP_PT_CIDC => 'CIDC', &ISUP_PT_BGROUP => 'BGROUP', &ISUP_PT_GNAM => 'GNAM', &ISUP_PT_NOTI => 'NOTI', &ISUP_PT_CSPI => 'CSPI', &ISUP_PT_TRNSRQ => 'TRNSRQ', &ISUP_PT_LSPI => 'LSPI', &ISUP_PT_CGCI => 'CGCI', &ISUP_PT_CVRI => 'CVRI', &ISUP_PT_OTGN => 'OTGN', &ISUP_PT_CIN => 'CIN', &ISUP_PT_CLLI => 'CLLI', &ISUP_PT_OLI => 'OLI', &ISUP_PT_CHGN => 'CHGN', &ISUP_PT_SVCD => 'SVCD', &ISUP_PT_SPR => 'SPR', &ISUP_PT_CSEL => 'CSEL', &ISUP_PT_NT => 'NT', &ISUP_PT_ORI => 'ORI', &ISUP_PT_IRI => 'IRI', &ISUP_PT_RATE => 'RATE', &ISUP_PT_IIC => 'IIC', &ISUP_PT_TOI => 'TOI', &ISUP_PT_TON => 'TON', &ISUP_PT_CRI => 'CRI', &ISUP_PT_ICCI => 'ICCI', }, }; sub unpack_oparms { my ($self,$ptr,$tag,$len,$parm,$sub) = @_; for (;;) { return unless $ptr < $self->{end}; $tag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; return 1 if $tag == 0; return unless exists ISUP_PARM_TYPE->{$tag}; $parm = ISUP_PARM_TYPE->{$tag}; return unless $ptr < $self->{end}; $len = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; return if $len == 0; return unless $ptr + $len <= $self->{end}; return unless $sub = $self->can("unpack_PT_$parm"); return unless $sub->($self,$ptr,$len); $ptr += $len; } } sub dissect_PT_EOP { my ($self,$off,$end,$len) = @_; return; } sub dissect_PT_CLRF { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TMR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ATP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CDPN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SUBN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_FCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OFCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CPC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CGPN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDGN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDNN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CONR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_INRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_INFI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_COTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_BCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CAUS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CGI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CMI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_FACI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_FAII { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CUGI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_INDEX { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CUGC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_USI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SPC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_UUI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CONN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SRIS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TNS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_EVNT { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CAM { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CSI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ACL { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OCDN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OBCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_UUIND { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ISPC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GNOT { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CHI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ADI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NSF { my ($self,$off,$end,$len) = @_; } sub dissect_PT_USIP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PROP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ROPS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_UTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TMU { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CDI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ECI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_MCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_MLPP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_MCIQ { my ($self,$off,$end,$len) = @_; } sub dissect_PT_MCIR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_HOPC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TMRP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_LN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDNR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_FREEP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GREF { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CTR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_LPI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CTN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CCSS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_FGVSN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_BGVNS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDCAP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NMC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CID { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SCFID { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CDTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CINN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CTRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CHPI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_DISP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_UAI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_UCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_AT { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CCR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CPI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTCA { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CDDN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OCDIN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GL { my ($self,$off,$end,$len) = @_; } sub dissect_PT_HTRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NRN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_QORC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTFI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_PVTBI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDFI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RDBI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NPFI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GNUM { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GDIG { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OSI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_EGRESS { my ($self,$off,$end,$len) = @_; } sub dissect_PT_JUR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CIDC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_BGROUP { my ($self,$off,$end,$len) = @_; } sub dissect_PT_GNAM { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NOTI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CSPI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TRNSRQ { my ($self,$off,$end,$len) = @_; } sub dissect_PT_LSPI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CGCI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CVRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OTGN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CIN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CLLI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_OLI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CHGN { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SVCD { my ($self,$off,$end,$len) = @_; } sub dissect_PT_SPR { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CSEL { my ($self,$off,$end,$len) = @_; } sub dissect_PT_NT { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ORI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_IRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_RATE { my ($self,$off,$end,$len) = @_; } sub dissect_PT_IIC { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TOI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_TON { my ($self,$off,$end,$len) = @_; } sub dissect_PT_CRI { my ($self,$off,$end,$len) = @_; } sub dissect_PT_ICCI { my ($self,$off,$end,$len) = @_; } use constant { ISUP_PARMS_DISSECT=>{ &ISUP_PT_EOP => [\&Message::ISUP::dissect_PT_EOP, 'EOP', 'End of optional parameters'], &ISUP_PT_CLRF => [\&Message::ISUP::dissect_PT_CLRF, 'CLRF', 'Call reference @'], &ISUP_PT_TMR => [\&Message::ISUP::dissect_PT_TMR, 'TMR', 'Transmission medium requirement (not ANSI)'], &ISUP_PT_ATP => [\&Message::ISUP::dissect_PT_ATP, 'ATP', 'Access transport'], &ISUP_PT_CDPN => [\&Message::ISUP::dissect_PT_CDPN, 'CDPN', 'Called party number'], &ISUP_PT_SUBN => [\&Message::ISUP::dissect_PT_SUBN, 'SUBN', 'Subsequent number (not ANSI)'], &ISUP_PT_NCI => [\&Message::ISUP::dissect_PT_NCI, 'NCI', 'Nature of connection indicators'], &ISUP_PT_FCI => [\&Message::ISUP::dissect_PT_FCI, 'FCI', 'Forward call indicators'], &ISUP_PT_OFCI => [\&Message::ISUP::dissect_PT_OFCI, 'OFCI', 'Optional forward call indicators'], &ISUP_PT_CPC => [\&Message::ISUP::dissect_PT_CPC, 'CPC', 'Calling party\'s category'], &ISUP_PT_CGPN => [\&Message::ISUP::dissect_PT_CGPN, 'CGPN', 'Calling party number'], &ISUP_PT_RDGN => [\&Message::ISUP::dissect_PT_RDGN, 'RDGN', 'Redirecting number'], &ISUP_PT_RDNN => [\&Message::ISUP::dissect_PT_RDNN, 'RDNN', 'Redirection number'], &ISUP_PT_CONR => [\&Message::ISUP::dissect_PT_CONR, 'CONR', 'Connection request'], &ISUP_PT_INRI => [\&Message::ISUP::dissect_PT_INRI, 'INRI', 'Information request indicators (Nat use)'], &ISUP_PT_INFI => [\&Message::ISUP::dissect_PT_INFI, 'INFI', 'Information indicators (Nat use) @'], &ISUP_PT_COTI => [\&Message::ISUP::dissect_PT_COTI, 'COTI', 'Continuity indicators'], &ISUP_PT_BCI => [\&Message::ISUP::dissect_PT_BCI, 'BCI', 'Backward call indicators'], &ISUP_PT_CAUS => [\&Message::ISUP::dissect_PT_CAUS, 'CAUS', 'Cause indicators'], &ISUP_PT_RDI => [\&Message::ISUP::dissect_PT_RDI, 'RDI', 'Redirection information'], &ISUP_PT_CGI => [\&Message::ISUP::dissect_PT_CGI, 'CGI', 'Circuit group supervision message type'], &ISUP_PT_RS => [\&Message::ISUP::dissect_PT_RS, 'RS', 'Range and status'], &ISUP_PT_CMI => [\&Message::ISUP::dissect_PT_CMI, 'CMI', 'Call modification indicators (Blue Book) (not ANSI)'], &ISUP_PT_FACI => [\&Message::ISUP::dissect_PT_FACI, 'FACI', 'Facility indicator (not ANSI)'], &ISUP_PT_FAII => [\&Message::ISUP::dissect_PT_FAII, 'FAII', 'Facility information indicators (Bellcore) (not ANSI)'], &ISUP_PT_CUGI => [\&Message::ISUP::dissect_PT_CUGI, 'CUGI', 'Closed user group interlock code (not ANSI)'], &ISUP_PT_INDEX => [\&Message::ISUP::dissect_PT_INDEX, 'INDEX', 'Index (Bellcore) (not ANSI)'], &ISUP_PT_CUGC => [\&Message::ISUP::dissect_PT_CUGC, 'CUGC', 'Closed user group check response indicators (not ANSI)'], &ISUP_PT_USI => [\&Message::ISUP::dissect_PT_USI, 'USI', 'User service information'], &ISUP_PT_SPC => [\&Message::ISUP::dissect_PT_SPC, 'SPC', 'Signalling point code (Nat use) (not ANSI) (Bellcore) @'], &ISUP_PT_UUI => [\&Message::ISUP::dissect_PT_UUI, 'UUI', 'User-to-user information'], &ISUP_PT_CONN => [\&Message::ISUP::dissect_PT_CONN, 'CONN', 'Connected number (not ANSI)'], &ISUP_PT_SRIS => [\&Message::ISUP::dissect_PT_SRIS, 'SRIS', 'Suspend/resume indicators'], &ISUP_PT_TNS => [\&Message::ISUP::dissect_PT_TNS, 'TNS', 'Transit network selection (Nat use) @'], &ISUP_PT_EVNT => [\&Message::ISUP::dissect_PT_EVNT, 'EVNT', 'Event information indicators'], &ISUP_PT_CAM => [\&Message::ISUP::dissect_PT_CAM, 'CAM', 'Circuit assignment map'], &ISUP_PT_CSI => [\&Message::ISUP::dissect_PT_CSI, 'CSI', 'Circuit state indicator @'], &ISUP_PT_ACL => [\&Message::ISUP::dissect_PT_ACL, 'ACL', 'Automatic congestion level'], &ISUP_PT_OCDN => [\&Message::ISUP::dissect_PT_OCDN, 'OCDN', 'Original called number'], &ISUP_PT_OBCI => [\&Message::ISUP::dissect_PT_OBCI, 'OBCI', 'Optional backward call indicators'], &ISUP_PT_UUIND => [\&Message::ISUP::dissect_PT_UUIND, 'UUIND', 'User-to-user indicators'], &ISUP_PT_ISPC => [\&Message::ISUP::dissect_PT_ISPC, 'ISPC', 'Origination ISC point code (not ANSI)'], &ISUP_PT_GNOT => [\&Message::ISUP::dissect_PT_GNOT, 'GNOT', 'Generic notification (not ANSI)'], &ISUP_PT_CHI => [\&Message::ISUP::dissect_PT_CHI, 'CHI', 'Call history information (not ANSI)'], &ISUP_PT_ADI => [\&Message::ISUP::dissect_PT_ADI, 'ADI', 'Access delivery information (not ANSI)'], &ISUP_PT_NSF => [\&Message::ISUP::dissect_PT_NSF, 'NSF', 'Network specific facility (Nat use) @'], &ISUP_PT_USIP => [\&Message::ISUP::dissect_PT_USIP, 'USIP', 'User service information prime'], &ISUP_PT_PROP => [\&Message::ISUP::dissect_PT_PROP, 'PROP', 'Propagation delay counter (not ANSI)'], &ISUP_PT_ROPS => [\&Message::ISUP::dissect_PT_ROPS, 'ROPS', 'Remote operations (Nat use) @'], &ISUP_PT_SA => [\&Message::ISUP::dissect_PT_SA, 'SA', 'Service activation @'], &ISUP_PT_UTI => [\&Message::ISUP::dissect_PT_UTI, 'UTI', 'User teleservice information (not ANSI)'], &ISUP_PT_TMU => [\&Message::ISUP::dissect_PT_TMU, 'TMU', 'Transmission medium used'], &ISUP_PT_CDI => [\&Message::ISUP::dissect_PT_CDI, 'CDI', 'Call diversion information (not ANSI)'], &ISUP_PT_ECI => [\&Message::ISUP::dissect_PT_ECI, 'ECI', 'Echo control information (not ANSI)'], &ISUP_PT_MCI => [\&Message::ISUP::dissect_PT_MCI, 'MCI', 'Message compatibility information'], &ISUP_PT_PCI => [\&Message::ISUP::dissect_PT_PCI, 'PCI', 'Parameter compatibility information'], &ISUP_PT_MLPP => [\&Message::ISUP::dissect_PT_MLPP, 'MLPP', 'MLPP precedence (Precedence ANSI)'], &ISUP_PT_MCIQ => [\&Message::ISUP::dissect_PT_MCIQ, 'MCIQ', 'MCID request indicators (not ANSI)'], &ISUP_PT_MCIR => [\&Message::ISUP::dissect_PT_MCIR, 'MCIR', 'MCID response indicators (not ANSI)'], &ISUP_PT_HOPC => [\&Message::ISUP::dissect_PT_HOPC, 'HOPC', 'Hop counter (reserved)'], &ISUP_PT_TMRP => [\&Message::ISUP::dissect_PT_TMRP, 'TMRP', 'Transmission medium requirement prime (not ANSI)'], &ISUP_PT_LN => [\&Message::ISUP::dissect_PT_LN, 'LN', 'Location number (not ANSI)'], &ISUP_PT_RDNR => [\&Message::ISUP::dissect_PT_RDNR, 'RDNR', 'Redirection number restriction (not ANSI)'], &ISUP_PT_FREEP => [\&Message::ISUP::dissect_PT_FREEP, 'FREEP', 'Freephone indicators/Reserved (Q.763 1992, White Book) (not ANSI)'], &ISUP_PT_GREF => [\&Message::ISUP::dissect_PT_GREF, 'GREF', 'Generic reference/Reserved (Q.763 1992, White Book) (not ANSI)'], &ISUP_PT_CTR => [\&Message::ISUP::dissect_PT_CTR, 'CTR', 'Call transfer reference (Q.763) (not ANSI)'], &ISUP_PT_LPI => [\&Message::ISUP::dissect_PT_LPI, 'LPI', 'Loop prevention indicators (Q.763) (not ANSI)'], &ISUP_PT_CTN => [\&Message::ISUP::dissect_PT_CTN, 'CTN', 'Call transfer number (Q.763) (not ANSI)'], &ISUP_PT_CCSS => [\&Message::ISUP::dissect_PT_CCSS, 'CCSS', 'CCSS (Q.763) (not ANSI)'], &ISUP_PT_FGVSN => [\&Message::ISUP::dissect_PT_FGVSN, 'FGVSN', 'Forward GVNS (Q.763) (not ANSI)'], &ISUP_PT_BGVNS => [\&Message::ISUP::dissect_PT_BGVNS, 'BGVNS', 'Backward GVNS (Q.763) (not ANSI)'], &ISUP_PT_RDCAP => [\&Message::ISUP::dissect_PT_RDCAP, 'RDCAP', 'Redirect capability (Nat use) (ANSI/GR-246-CORE)'], &ISUP_PT_NMC => [\&Message::ISUP::dissect_PT_NMC, 'NMC', 'Network management controls (ANSI/GR-246-CORE)'], &ISUP_PT_CID => [\&Message::ISUP::dissect_PT_CID, 'CID', 'Correlation id (Q.763) (not ANSI)'], &ISUP_PT_SCFID => [\&Message::ISUP::dissect_PT_SCFID, 'SCFID', 'SCF id (Q.763) (not ANSI)'], &ISUP_PT_CDTI => [\&Message::ISUP::dissect_PT_CDTI, 'CDTI', 'Call diversion treatment indicators (Q.763) (not ANSI)'], &ISUP_PT_CINN => [\&Message::ISUP::dissect_PT_CINN, 'CINN', 'Called IN number (Q.763) (not ANSI)'], &ISUP_PT_CTRI => [\&Message::ISUP::dissect_PT_CTRI, 'CTRI', 'Call offering treatment indicators (Q.763) (not ANSI)'], &ISUP_PT_CHPI => [\&Message::ISUP::dissect_PT_CHPI, 'CHPI', 'Charged party identification (Q.763) (not ANSI)'], &ISUP_PT_CTI => [\&Message::ISUP::dissect_PT_CTI, 'CTI', 'Conference treatment indicators (Q.763) (not ANSI)'], &ISUP_PT_DISP => [\&Message::ISUP::dissect_PT_DISP, 'DISP', 'Display information (Q.763) (not ANSI)'], &ISUP_PT_UAI => [\&Message::ISUP::dissect_PT_UAI, 'UAI', 'UID action indicators (Q.763) (not ANSI)'], &ISUP_PT_UCI => [\&Message::ISUP::dissect_PT_UCI, 'UCI', 'UID capability indicators (Q.763) (not ANSI)'], &ISUP_PT_RC => [\&Message::ISUP::dissect_PT_RC, 'RC', 'Redirect counter (Nat use) (ANSI/GR-246-CORE)/Reserved (B-ISUP)'], &ISUP_PT_AT => [\&Message::ISUP::dissect_PT_AT, 'AT', 'Application transport (Q.763)/Reserved (B-ISUP) (not ANSI)'], &ISUP_PT_CCR => [\&Message::ISUP::dissect_PT_CCR, 'CCR', 'Collect call request (Q.763)/Reserved (B-ISUP) (not ANSI)'], &ISUP_PT_CPI => [\&Message::ISUP::dissect_PT_CPI, 'CPI', 'CCNR possible indicator (Q.763)/Reserved (B-ISUP) (not ANSI)'], &ISUP_PT_PVTCA => [\&Message::ISUP::dissect_PT_PVTCA, 'PVTCA', 'Pivot capability (ANSI/Q.763)/Reserved (B-ISUP)'], &ISUP_PT_PVTRI => [\&Message::ISUP::dissect_PT_PVTRI, 'PVTRI', 'Pivot routing indicators (ANSI/Q.763)/Reserved (B-ISUP)'], &ISUP_PT_CDDN => [\&Message::ISUP::dissect_PT_CDDN, 'CDDN', 'Called directory number (Q.763)/Reserved (B-ISUP) (not ANSI)'], &ISUP_PT_OCDIN => [\&Message::ISUP::dissect_PT_OCDIN, 'OCDIN', 'Original called IN number (Q.763) (not ANSI)'], &ISUP_PT_GL => [\&Message::ISUP::dissect_PT_GL, 'GL', 'Calling geodetic location (ANSI/GR-246-CORE)'], &ISUP_PT_HTRI => [\&Message::ISUP::dissect_PT_HTRI, 'HTRI', 'HTR information (Q.763) (not ANSI)'], &ISUP_PT_NRN => [\&Message::ISUP::dissect_PT_NRN, 'NRN', 'Network routing number (Nat use) (Q.763) (not ANSI)'], &ISUP_PT_QORC => [\&Message::ISUP::dissect_PT_QORC, 'QORC', 'Query on release capability (Network option) (Q.763) (not ANSI)'], &ISUP_PT_PVTS => [\&Message::ISUP::dissect_PT_PVTS, 'PVTS', 'Pivot status (Nat use) (ANSI/Q.763) (not ANSI)'], &ISUP_PT_PVTC => [\&Message::ISUP::dissect_PT_PVTC, 'PVTC', 'Pivot counter (ANSI/Q.763) (not ANSI)'], &ISUP_PT_PVTFI => [\&Message::ISUP::dissect_PT_PVTFI, 'PVTFI', 'Pivot routing forward information (ANSI/Q.763) (not ANSI)'], &ISUP_PT_PVTBI => [\&Message::ISUP::dissect_PT_PVTBI, 'PVTBI', 'Pivot routing backward information (ANSI/Q.763) (not ANSI)'], &ISUP_PT_RDS => [\&Message::ISUP::dissect_PT_RDS, 'RDS', 'Redirect status (Nat use)'], &ISUP_PT_RDFI => [\&Message::ISUP::dissect_PT_RDFI, 'RDFI', 'Redirect forward information (Nat use)'], &ISUP_PT_RDBI => [\&Message::ISUP::dissect_PT_RDBI, 'RDBI', 'Redirect backward information (Nat use)'], &ISUP_PT_NPFI => [\&Message::ISUP::dissect_PT_NPFI, 'NPFI', 'Number portability forward information (Network option) (not ANSI)'], &ISUP_PT_GNUM => [\&Message::ISUP::dissect_PT_GNUM, 'GNUM', 'Generic number (Q.763)/Generic address (ANSI/GR-246-CORE)'], &ISUP_PT_GDIG => [\&Message::ISUP::dissect_PT_GDIG, 'GDIG', 'Generic digits (Nat use)'], &ISUP_PT_OSI => [\&Message::ISUP::dissect_PT_OSI, 'OSI', 'Operator services information (ANSI/GR-246-CORE)'], &ISUP_PT_EGRESS => [\&Message::ISUP::dissect_PT_EGRESS, 'EGRESS','Egress (ANSI/GR-246-CORE)'], &ISUP_PT_JUR => [\&Message::ISUP::dissect_PT_JUR, 'JUR', 'Jurisdiction (ANSI/GR-246-CORE)'], &ISUP_PT_CIDC => [\&Message::ISUP::dissect_PT_CIDC, 'CIDC', 'Carrier identification (ANSI/GR-246-CORE)'], &ISUP_PT_BGROUP => [\&Message::ISUP::dissect_PT_BGROUP, 'BGROUP','Business group (ANSI/GR-246-CORE)'], &ISUP_PT_GNAM => [\&Message::ISUP::dissect_PT_GNAM, 'GNAM', 'Generic name (ANSI/GR-246-CORE)'], &ISUP_PT_NOTI => [\&Message::ISUP::dissect_PT_NOTI, 'NOTI', 'Notification indicator (ANSI/GR-246-CORE)'], &ISUP_PT_CSPI => [\&Message::ISUP::dissect_PT_CSPI, 'CSPI', 'Carrier service provider identification (ANSI)'], &ISUP_PT_TRNSRQ => [\&Message::ISUP::dissect_PT_TRNSRQ, 'TRNSRQ','Transaction request (ANSI/GR-246-CORE)'], &ISUP_PT_LSPI => [\&Message::ISUP::dissect_PT_LSPI, 'LSPI', 'Local service provider identification (ANSI)'], &ISUP_PT_CGCI => [\&Message::ISUP::dissect_PT_CGCI, 'CGCI', 'Circuit group characteristic indicator (ANSI/GR-246-CORE)'], &ISUP_PT_CVRI => [\&Message::ISUP::dissect_PT_CVRI, 'CVRI', 'Circuit validation response indicator (ANSI/GR-246-CORE)'], &ISUP_PT_OTGN => [\&Message::ISUP::dissect_PT_OTGN, 'OTGN', 'Outgoing trunk group number (ANSI/GR-246-CORE)'], &ISUP_PT_CIN => [\&Message::ISUP::dissect_PT_CIN, 'CIN', 'Circuit identification name (ANSI/GR-246-CORE)'], &ISUP_PT_CLLI => [\&Message::ISUP::dissect_PT_CLLI, 'CLLI', 'Common language location identification (ANSI/GR-246-CORE)'], &ISUP_PT_OLI => [\&Message::ISUP::dissect_PT_OLI, 'OLI', 'Originating line information (ANSI/GR-246-CORE)'], &ISUP_PT_CHGN => [\&Message::ISUP::dissect_PT_CHGN, 'CHGN', 'Charge number (ANSI/GR-246-CORE)'], &ISUP_PT_SVCD => [\&Message::ISUP::dissect_PT_SVCD, 'SVCD', 'Service code indicator (ANSI/GR-246-CORE)'], &ISUP_PT_SPR => [\&Message::ISUP::dissect_PT_SPR, 'SPR', 'Special processing request (ANSI/GR-246-CORE)'], &ISUP_PT_CSEL => [\&Message::ISUP::dissect_PT_CSEL, 'CSEL', 'Carrier selection information (ANSI/GR-246-CORE)'], &ISUP_PT_NT => [\&Message::ISUP::dissect_PT_NT, 'NT', 'Network transport (ANSI/GR-246-CORE)'], &ISUP_PT_ORI => [\&Message::ISUP::dissect_PT_ORI, 'ORI', 'Outgoing route identification (Spain)'], &ISUP_PT_IRI => [\&Message::ISUP::dissect_PT_IRI, 'IRI', 'Incoming route identification (Spain)'], &ISUP_PT_RATE => [\&Message::ISUP::dissect_PT_RATE, 'RATE', 'Rate (Spain)'], &ISUP_PT_IIC => [\&Message::ISUP::dissect_PT_IIC, 'IIC', 'Identifier of incoming circuit (Spain)'], &ISUP_PT_TOI => [\&Message::ISUP::dissect_PT_TOI, 'TOI', 'Trunk offering information (Singapore)'], &ISUP_PT_TON => [\&Message::ISUP::dissect_PT_TON, 'TON', 'Type of notification (Spain)'], &ISUP_PT_CRI => [\&Message::ISUP::dissect_PT_CRI, 'CRI', 'Charge rate information (Singapore)'], &ISUP_PT_ICCI => [\&Message::ISUP::dissect_PT_ICCI, 'ICCI', 'Call charge information (Signapore)'], }, }; sub dissect_oparms { my ($self,$off,$end) = @_; my @oparms = (); for (;$off < $end;$off++) { my @fields = (); my $ptr = unpack('C',substr(${$self->{buf}},$off,1)); push @fields, [$off,Frame::bytes($ptr,0xff,1),'Pointer',$ptr]; my $poff = $off + $ptr; return unless $poff <= $end; my $ptag = unpack('C',substr(${$self->{buf}},$poff,1)); my $parm; if (exists ISUP_PARMS_DISSECT->{$ptag}) { my @args = @{ISUP_PARMS_DISSECT->{$ptag}}; my $sub = shift @args; $parm = sprintf '%s(%d) - %s', $args[0], $ptag, $args[1]; push @fields, [$poff,Frame::bytes($ptag,0xff,1),'Tag',$parm], $poff++; my ($plen,$pend) = (undef,$poff); if ($ptag) { $plen = unpack('C',substr(${$self->{buf}},$poff,1)); push @fields, [$poff,Frame::bytes($plen,0xff,1),'Length',$plen]; $poff++; $pend = $poff + $plen; } return unless $pend <= $self->{end}; push @fields, @{$sub->($self,$poff,$pend,$plen,@args,@_)}; } else { $parm = "Unknown($ptag) - Unknown parameter tag"; push @fields, [$poff,Frame::bytes($ptag,0xff,1),'Tag',$parm]; $poff++; my $plen = unpack('C',substr(${$self->{buf}},$poff,1)); push @fields, [$poff,Frame::bytes($plen,0xff,1),'Length',$plen]; $poff++; my $pend = $poff + $plen; return unless $pend <= $self->{end}; push @fields, [$poff,' ******** ','Parameter',Frame::pdata(substr(${$self->{buf}},$poff,$plen))]; } push @oparms, "Parameter $parm", \@fields; } return [ 'Optional Parameters', \@oparms ]; } sub pandl { my $self = shift; my ($p,$l) = ($self->{off},0); if ($p < $self->{end}) { $p = unpack('C',substr($$self->{buf},$self->{off},1)) + $self->{off}; $self->{off}++; if ($p < $self->{end}) { $l = unpack('C',substr($$self->{buf},$p,1)); $p++; $l = 0 unless $p + $l <= $self->{end}; } } return $p,$l; } # ------------------------------------- package Message::ISUP::NONE; our @ISA = qw(Message::ISUP); # ------------------------------------- sub unpack { return shift; } # ------------------------------------- package Message::ISUP::OPARMS; our @ISA = qw(Message::ISUP); # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_OP($self,$off); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_OP($self,$off), ); } # ------------------------------------- package Message::ITUT::ISUP; our @ISA = qw(Message::ISUP); # ------------------------------------- use constant { # This is not really just ITUT but anything with a 14-bit point code. ISUP_ITUT_TYPES=>{ &ISUP_MT_IAM => 'IAM', # 0000 0001 Initial address &ISUP_MT_SAM => 'SAM', # 0000 0010 Subsequent address message &ISUP_MT_INR => 'INR', # 0000 0011 Information request (national use) &ISUP_MT_INF => 'INF', # 0000 0100 Information response (national use) &ISUP_MT_COT => 'COT', # 0000 0101 Continuity &ISUP_MT_ACM => 'ACM', # 0000 0110 Address complete &ISUP_MT_CON => 'CON', # 0000 0111 Connect &ISUP_MT_FOT => 'FOT', # 0000 1000 Forward transfer &ISUP_MT_ANM => 'ANM', # 0000 1001 Answer #0x0a => '???', # 0000 1010 Reserved (Red book) #0x0b => '???', # 0000 1011 Reserved (Red book) &ISUP_MT_REL => 'REL', # 0000 1100 Release &ISUP_MT_SUS => 'SUS', # 0000 1101 Suspend &ISUP_MT_RES => 'RES', # 0000 1110 Resume #0x0f => '???', # 0000 1111 Reserved (Red book) &ISUP_MT_RLC => 'RLC', # 0001 0000 Release complete &ISUP_MT_CCR => 'CCR', # 0001 0001 Continuity check request &ISUP_MT_RSC => 'RSC', # 0001 0010 Reset circuit &ISUP_MT_BLO => 'BLO', # 0001 0011 Blocking &ISUP_MT_UBL => 'UBL', # 0001 0100 Unblocking &ISUP_MT_BLA => 'BLA', # 0001 0101 Blocking acknowledgement &ISUP_MT_UBA => 'UBA', # 0001 0110 Unblocking acknowledgement &ISUP_MT_GRS => 'GRS', # 0001 0111 Circuit group reset &ISUP_MT_CGB => 'CGB', # 0001 1000 Circuit group blocking &ISUP_MT_CGU => 'CGU', # 0001 1001 Circuit group unblocking &ISUP_MT_CGBA => 'CGBA', # 0001 1010 Circuit group blocking acknowledgement &ISUP_MT_CGUA => 'CGUA', # 0001 1011 Circuit group ublocking acknowledgement #&ISUP_MT_CMR => 'CMR', # 0001 1100 Call modification request (Reserved (Blue book)) #&ISUP_MT_CMC => 'CMC', # 0001 1101 Call modification complete (Reserved (Blue book)) #&ISUP_MT_CMRJ => 'CMRJ', # 0001 1110 Call modification reject (Reserved (Blue book)) &ISUP_MT_FAR => 'FAR' # 0001 1111 Facility request, &ISUP_MT_FAA => 'FAA', # 0010 0000 Facility accepted &ISUP_MT_FRJ => 'FRJ', # 0010 0001 Facility reject #&ISUP_MT_FAD => 'FAD', # 0010 0010 Facility deactivate (Reserved (Red book)) #&ISUP_MT_FAI => 'FAI', # 0010 0011 Facility information (Reserved (Red book)) &ISUP_MT_LPA => 'LPA', # 0010 0100 Loop back acknowledgement (national) #&ISUP_MT_CSVQ => 'CSVQ', # 0010 0101 Reserved (Red book) #&ISUP_MT_CSVR => 'CSVR', # 0010 0110 Reserved (Red book) #&ISUP_MT_DRS => 'DRS', # 0010 0111 Delayed release (Reserved (Blue book)) &ISUP_MT_PAM => 'PAM', # 0010 1000 Pass along message (national) &ISUP_MT_GRA => 'GRA', # 0010 1001 Circuit group reset acknowledgement &ISUP_MT_CQM => 'CQM', # 0010 1010 Circuit group query (national) &ISUP_MT_CQR => 'CQR', # 0010 1011 Circuit group query response (national) &ISUP_MT_CPG => 'CPG', # 0010 1100 Call progress &ISUP_MT_USR => 'USR', # 0010 1101 User to user information &ISUP_MT_UCIC => 'UCIC', # 0010 1110 Unequipped CIC (national) &ISUP_MT_CFN => 'CFN', # 0010 1111 Confusion &ISUP_MT_OLM => 'OLM', # 0011 0000 Overload (national) &ISUP_MT_CRG => 'CRG', # 0011 0001 Charge information (national) &ISUP_MT_NRM => 'NRM', # 0011 0010 Network resource managment &ISUP_MT_FAC => 'FAC', # 0011 0011 Facility &ISUP_MT_UPT => 'UPT', # 0011 0100 User part test &ISUP_MT_UPA => 'UPA', # 0011 0101 User part available &ISUP_MT_IDR => 'IDR', # 0011 0110 Identification request &ISUP_MT_IRS => 'IRS', # 0011 0111 Identification response &ISUP_MT_SGM => 'SGM', # 0011 1000 Segmentation #0x39 => '???', # 0011 1001 Reserved (B-ISUP) #0x3a => '???', # 0011 1010 Reserved (B-ISUP) #0x3b => '???', # 0011 1011 Reserved (B-ISUP) #0x3c => '???', # 0011 1100 Reserved (B-ISUP) #0x3d => '???', # 0011 1101 Reserved (B-ISUP) #0x3e => '???', # 0011 1110 #0x3f => '???', # 0011 1111 &ISUP_MT_LPR => 'LPR', # 0100 0000 Loop preservation &ISUP_MT_ATP => 'ATP', # 0100 0001 Application transport &ISUP_MT_PRI => 'PRI', # 0100 0010 Pre-releation information &ISUP_MT_SDN => 'SDN', # 0100 0011 Subsequent directory number (national) # #&ISUP_MT_CRA => 'CRA', # 1110 1001 Circuit reservation acknowledgment #&ISUP_MT_CRM => 'CRM', # 1110 1010 Circuit reservation #&ISUP_MT_CVR => 'CVR', # 1110 1011 Circuit validation response #&ISUP_MT_CVT => 'CVT', # 1110 1100 Circuit validation test #&ISUP_MT_EXM => 'EXM', # 1110 1101 Exit message # &ISUP_MT_NON => 'NON', # 1111 1000 National notification (Spain) # # 1111 1001 # # 1111 1010 # # 1111 1011 &ISUP_MT_LLM => 'LLM', # 1111 1100 National malicioius call (Spain), &ISUP_MT_CAK => 'CAK', # 1111 1101 Charge acknowledgement (Singapore) &ISUP_MT_TCM => 'TCM', # 1111 1110 Tariff charge (Signapore) &ISUP_MT_MCP => 'MCP', # 1111 1111 Malicious call print (Singapore) }, }; # ------------------------------------- package Message::ANSI::ISUP; our @ISA = qw(Message::ISUP); # ------------------------------------- use constant { # This is not really just ANSI but anything with a 24-bit point code. ISUP_ANSI_TYPES=>{ &ISUP_MT_IAM => 'IAM', # 0000 0001 Initial address #&ISUP_MT_SAM => 'SAM', # 0000 0010 Subsequent address message &ISUP_MT_INR => 'INR', # 0000 0011 Information request (national use) &ISUP_MT_INF => 'INF', # 0000 0100 Information response (national use) &ISUP_MT_COT => 'COT', # 0000 0101 Continuity &ISUP_MT_ACM => 'ACM', # 0000 0110 Address complete #&ISUP_MT_CON => 'CON', # 0000 0111 Connect &ISUP_MT_FOT => 'FOT', # 0000 1000 Forward transfer &ISUP_MT_ANM => 'ANM', # 0000 1001 Answer #0x0a => '???', # 0000 1010 Reserved (Red book) #0x0b => '???', # 0000 1011 Reserved (Red book) &ISUP_MT_REL => 'REL', # 0000 1100 Release &ISUP_MT_SUS => 'SUS', # 0000 1101 Suspend &ISUP_MT_RES => 'RES', # 0000 1110 Resume #0x0f => '???', # 0000 1111 Reserved (Red book) &ISUP_MT_RLC => 'RLC', # 0001 0000 Release complete &ISUP_MT_CCR => 'CCR', # 0001 0001 Continuity check request &ISUP_MT_RSC => 'RSC', # 0001 0010 Reset circuit &ISUP_MT_BLO => 'BLO', # 0001 0011 Blocking &ISUP_MT_UBL => 'UBL', # 0001 0100 Unblocking &ISUP_MT_BLA => 'BLA', # 0001 0101 Blocking acknowledgement &ISUP_MT_UBA => 'UBA', # 0001 0110 Unblocking acknowledgement &ISUP_MT_GRS => 'GRS', # 0001 0111 Circuit group reset &ISUP_MT_CGB => 'CGB', # 0001 1000 Circuit group blocking &ISUP_MT_CGU => 'CGU', # 0001 1001 Circuit group unblocking &ISUP_MT_CGBA => 'CGBA', # 0001 1010 Circuit group blocking acknowledgement &ISUP_MT_CGUA => 'CGUA', # 0001 1011 Circuit group ublocking acknowledgement #&ISUP_MT_CMR => 'CMR', # 0001 1100 Call modification request (Reserved (Blue book)) #&ISUP_MT_CMC => 'CMC', # 0001 1101 Call modification complete (Reserved (Blue book)) #&ISUP_MT_CMRJ => 'CMRJ', # 0001 1110 Call modification reject (Reserved (Blue book)) #&ISUP_MT_FAR => 'FAR' # 0001 1111 Facility request, #&ISUP_MT_FAA => 'FAA', # 0010 0000 Facility accepted #&ISUP_MT_FRJ => 'FRJ', # 0010 0001 Facility reject #&ISUP_MT_FAD => 'FAD', # 0010 0010 Facility deactivate (Reserved (Red book)) #&ISUP_MT_FAI => 'FAI', # 0010 0011 Facility information (Reserved (Red book)) &ISUP_MT_LPA => 'LPA', # 0010 0100 Loop back acknowledgement (national) #&ISUP_MT_CSVQ => 'CSVQ', # 0010 0101 Reserved (Red book) #&ISUP_MT_CSVR => 'CSVR', # 0010 0110 Reserved (Red book) #&ISUP_MT_DRS => 'DRS', # 0010 0111 Delayed release (Reserved (Blue book)) &ISUP_MT_PAM => 'PAM', # 0010 1000 Pass along message (national) &ISUP_MT_GRA => 'GRA', # 0010 1001 Circuit group reset acknowledgement &ISUP_MT_CQM => 'CQM', # 0010 1010 Circuit group query (national) &ISUP_MT_CQR => 'CQR', # 0010 1011 Circuit group query response (national) &ISUP_MT_CPG => 'CPG', # 0010 1100 Call progress #&ISUP_MT_USR => 'USR', # 0010 1101 User to user information &ISUP_MT_UCIC => 'UCIC', # 0010 1110 Unequipped CIC (national) &ISUP_MT_CFN => 'CFN', # 0010 1111 Confusion #&ISUP_MT_OLM => 'OLM', # 0011 0000 Overload (national) #&ISUP_MT_CRG => 'CRG', # 0011 0001 Charge information (national) #&ISUP_MT_NRM => 'NRM', # 0011 0010 Network resource managment &ISUP_MT_FAC => 'FAC', # 0011 0011 Facility #&ISUP_MT_UPT => 'UPT', # 0011 0100 User part test #&ISUP_MT_UPA => 'UPA', # 0011 0101 User part available #&ISUP_MT_IDR => 'IDR', # 0011 0110 Identification request #&ISUP_MT_IRS => 'IRS', # 0011 0111 Identification response &ISUP_MT_SGM => 'SGM', # 0011 1000 Segmentation #0x39 => '???', # 0011 1001 Reserved (B-ISUP) #0x3a => '???', # 0011 1010 Reserved (B-ISUP) #0x3b => '???', # 0011 1011 Reserved (B-ISUP) #0x3c => '???', # 0011 1100 Reserved (B-ISUP) #0x3d => '???', # 0011 1101 Reserved (B-ISUP) #0x3e => '???', # 0011 1110 #0x3f => '???', # 0011 1111 #&ISUP_MT_LPR => 'LPR', # 0100 0000 Loop preservation #&ISUP_MT_ATP => 'ATP', # 0100 0001 Application transport #&ISUP_MT_PRI => 'PRI', # 0100 0010 Pre-releation information #&ISUP_MT_SDN => 'SDN', # 0100 0011 Subsequent directory number (national) # &ISUP_MT_CRA => 'CRA', # 1110 1001 Circuit reservation acknowledgment &ISUP_MT_CRM => 'CRM', # 1110 1010 Circuit reservation &ISUP_MT_CVR => 'CVR', # 1110 1011 Circuit validation response &ISUP_MT_CVT => 'CVT', # 1110 1100 Circuit validation test &ISUP_MT_EXM => 'EXM', # 1110 1101 Exit message # #&ISUP_MT_NON => 'NON', # 1111 1000 National notification (Spain) # # 1111 1001 # # 1111 1010 # # 1111 1011 #&ISUP_MT_LLM => 'LLM', # 1111 1100 National malicioius call (Spain), #&ISUP_MT_CAK => 'CAK', # 1111 1101 Charge acknowledgement (Singapore) #&ISUP_MT_TCM => 'TCM', # 1111 1110 Tariff charge (Signapore) #&ISUP_MT_MCP => 'MCP', # 1111 1111 Malicious call print (Singapore) }, }; # ------------------------------------- package Message::ITUT::ISUP::NONE; our @ISA = qw(Message::ISUP::NONE); package Message::ITUT::ISUP::OPARMS; our @ISA = qw(Message::ISUP::OPARMS); # ------------------------------------- package Message::ANSI::ISUP::NONE; our @ISA = qw(Message::ISUP::NONE); package Message::ANSI::ISUP::OPARMS; our @ISA = qw(Message::ISUP::OPARMS); # ------------------------------------- # ------------------------------------- package Message::ITUT::ISUP::IAM; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: F(NCI FCI CPC TMR) V(CDPN) O(VEDI IEPS) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'NCI', $off,1); $off++; return unless Message::unpack_MF($self,'FCI', $off,2); $off+=2; return unless Message::unpack_MF($self,'CPC', $off,1); $off++; return unless Message::unpack_MF($self,'TMR', $off,1); $off++; return unless Message::unpack_MV($self,'CDPN', $off ); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'NCI', $off+0,1), Message::dissect_MF($self,'FCI', $off+1,2), Message::dissect_MF($self,'CPC', $off+3,1), Message::dissect_MF($self,'TMR', $off+4,1), Message::dissect_MV($self,'CDPN', $off+5 ), Message::dissect_OP($self, $off+6 ), ); } # ------------------------------------- package Message::ANSI::ISUP::IAM; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- # ANSI: F(NCI FCI CPC) V(USI CDPN) O() # ------------------------------------- sub unpack { my $self = shift; return unless $self->unpack_MF('NCI', $self->{off},1); $self->{off} += 1; return unless $self->unpack_MF('FCI', $self->{off},2); $self->{off} += 2; return unless $self->unpack_MF('CPC', $self->{off},1); $self->{off} += 1; return unless $self->unpack_MV('USI', $self->{off} ); $self->{off} += 1; return unless $self->unpack_MV('CDPN',$self->{off} ); $self->{off} += 1; return unless $self->unpack_OP( $self->{off} ); return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( $self->dissect_MF('NCI', $off+0,1), $self->dissect_MF('FCI', $off+1,2), $self->dissect_MF('CPC', $off+3,1), $self->dissect_MV('USI', $off+4), $self->dissect_MV('CDPN',$off+5), $self->dissect_OP( $off+6), ); } # ------------------------------------- package Message::ITUT::ISUP::SAM; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: V(SUBN) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'SUBN',$off); $off++; return unless Message::unpack_OP($self, $off); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'SUBN',$off+0), Message::dissect_OP($self, $off+1), ); } # ------------------------------------- package Message::ISUP::INM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(INRI) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'INRI',$off,2); $off+=2; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'INRI',$off+0,2), Message::dissect_OP($self, $off+1 ), ); } package Message::ITUT::ISUP::INR; our @ISA = qw(Message::ISUP::INM Message::ITUT::ISUP); package Message::ANSI::ISUP::INR; our @ISA = qw(Message::ISUP::INM Message::ANSI::ISUP); package Message::ITUT::ISUP::INF; our @ISA = qw(Message::ISUP::INM Message::ITUT::ISUP); package Message::ANSI::ISUP::INF; our @ISA = qw(Message::ISUP::INM Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::COT; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(COTI) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'COTI',$off,1); $off++; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::unpack_MF($self,'COTI',$off,1), ); } package Message::ITUT::ISUP::COT; our @ISA = qw(Message::ISUP::COT Message::ITUT::ISUP); package Message::ANSI::ISUP::COT; our @ISA = qw(Message::ISUP::COT Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::ACM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(BCI) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'BCI',$off,2); $off+=2; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'BCI',$off+0,2), Message::dissect_OP($self, $off+1 ), ); } package Message::ITUT::ISUP::ACM; our @ISA = qw(Message::ISUP::ACM Message::ITUT::ISUP); package Message::ANSI::ISUP::ACM; our @ISA = qw(Message::ISUP::ACM Message::ANSI::ISUP); # ------------------------------------- package Message::ITUT::ISUP::CON; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: F(BCI) O(VEDI) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'BCI',$off,2); $off+=2; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'BCI',$off+0,2), Message::dissect_OP($self, $off+2 ), ); } # ------------------------------------- package Message::ITUT::ISUP::FOT; our @ISA = qw(Message::ITUT::ISUP::OPARMS); package Message::ANSI::ISUP::FOT; our @ISA = qw(Message::ANSI::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::ANM; our @ISA = qw(Message::ITUT::ISUP::OPARMS); package Message::ANSI::ISUP::ANM; our @ISA = qw(Message::ANSI::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::REL; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ANSI::ISUP::REL; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- # ANSI: V(CAUS) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'CAUS',$off); $off++; return unless Message::unpack_OP($self, $off); $Off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'CAUS',$off+0), Message::dissect_OP($self, $off+1), ); } # ------------------------------------- package Message::ISUP::SRM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(SRIS) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'SRIS',$off,1); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'SRIS',$off+0,1), Message::dissect_OP($self, $off+1 ), ); } package Message::ITUT::ISUP::SUS; our @ISA = qw(Message::ISUP::SRM Message::ITUT::ISUP); package Message::ANSI::ISUP::SUS; our @ISA = qw(Message::ISUP::SRM Message::ANSI::ISUP); package Message::ITUT::ISUP::RES; our @ISA = qw(Message::ISUP::SRM Message::ITUT::ISUP); package Message::ANSI::ISUP::RES; our @ISA = qw(Message::ISUP::SRM Message::ANSI::ISUP); # ------------------------------------- package Message::ITUT::ISUP::RLC; our @ISA = qw(Message::ITUT::ISUP::OPARMS); package Message::ANSI::ISUP::RLC; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::CCR; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::CCR; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::RSC; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::RSC; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::BLO; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::BLO; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::UBL; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::UBL; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::BLA; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::BLA; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::UBA; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::UBA; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ISUP::GCM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: V(RS) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'RS',$off); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'RS',$off), ); } package Message::ITUT::ISUP::GRS; our @ISA = qw(Message::ISUP::GCM Message::ITUT::ISUP); package Message::ANSI::ISUP::GRS; our @ISA = qw(Message::ISUP::GCM Message::ANSI::ISUP); package Message::ITUT::ISUP::CQM; our @ISA = qw(Message::ISUP::GCM Message::ITUT::ISUP); package Message::ANSI::ISUP::CQM; our @ISA = qw(Message::ISUP::GCM Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::CGM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(CGI) V(RS) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'CGI',$off,1); $off++; return unless Message::unpack_MV($self,'RS' $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'CGI',$off+0,1), Message::dissect_MV($self,'RS' $off+1 ), ); } package Message::ITUT::ISUP::CGB; our @ISA = qw(Message::ISUP::CGM Message::ITUT::ISUP); package Message::ANSI::ISUP::CGB; our @ISA = qw(Message::ISUP::CGM Message::ANSI::ISUP); package Message::ITUT::ISUP::CGU; our @ISA = qw(Message::ISUP::CGM Message::ITUT::ISUP); package Message::ANSI::ISUP::CGU; our @ISA = qw(Message::ISUP::CGM Message::ANSI::ISUP); package Message::ITUT::ISUP::CGBA; our @ISA = qw(Message::ISUP::CGM Message::ITUT::ISUP); package Message::ANSI::ISUP::CGBA; our @ISA = qw(Message::ISUP::CGM Message::ANSI::ISUP); package Message::ITUT::ISUP::CGUA; our @ISA = qw(Message::ISUP::CGM Message::ITUT::ISUP); package Message::ANSI::ISUP::CGUA; our @ISA = qw(Message::ISUP::CGM Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::FAM; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(FACI) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'FACI',$off,1); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::unpack_MF($self,'FACI',$off+0,1), Message::unpack_OP($self, $off+1 ), }; } package Message::ITUT::ISUP::FAR; our @ISA = qw(Message::ISUP::FAM Message::ITUT::ISUP); package Message::ANSI::ISUP::FAR; our @ISA = qw(Message::ISUP::FAM Message::ANSI::ISUP); package Message::ITUT::ISUP::FAA; our @ISA = qw(Message::ISUP::FAM Message::ITUT::ISUP); package Message::ANSI::ISUP::FAA; our @ISA = qw(Message::ISUP::FAM Message::ANSI::ISUP); # ------------------------------------- package Message::ITUT::ISUP::FRJ; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: F(FACI) V(CAUS) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'FACI',$off,1); $off++; return unless Message::unpack_MV($self,'CAUS',$off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'FACI',$off+0,1), Message::dissect_MV($self,'CAUS',$off+1 ), ); } # ------------------------------------- package Message::ITUT::ISUP::LPA; our @ISA = qw(Message::ITUT::ISUP::NONE); # ------------------------------------- package Message::ANSI::ISUP::LPA; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::PAM; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: (encapsultated ISUP message) # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off} + 3; return [ @{$self->SUPER::dissect(@_)}, ]; } # ------------------------------------- package Message::ANSI::ISUP::PAM; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- # ANSI: (encapsultated ISUP message) # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off} + 3; return [ @{$self->SUPER::dissect(@_)}, ]; } # ------------------------------------- package Message::ISUP::GRA; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: V(RS) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'RS',$off); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'RS',$off), ); } package Message::ITUT::ISUP::GRA; our @ISA = qw(Message::ISUP::GRA Message::ITUT::ISUP); package Message::ANSI::ISUP::GRA; our @ISA = qw(Message::ISUP::GRA Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::CQR; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: V(RS) V(CSI) # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'RS', $off ); $off++; return unless Message::unpack_MV($self,'CSI',$off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'RS', $off+0), Message::dissect_MV($self,'CSI',$off+1), ); } # ------------------------------------- package Message::ITUT::ISUP::CQR; our @ISA = qw(Message::ISUP::CQR Message::ITUT::ISUP); package Message::ANSI::ISUP::CQR; our @ISA = qw(Message::ISUP::CQR Message::ANSI::ISUP); # ------------------------------------- package Message::ISUP::CPG; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: F(EVNT) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'EVNT',$off,1); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'EVNT',$off+0,1), Message::dissect_OP($self, $off+1 ), ); } package Message::ITUT::ISUP::CPG; our @ISA = qw(Message::ISUP::CPG Message::ITUT::ISUP); package Message::ANSI::ISUP::CPG; our @ISA = qw(Message::ISUP::CPG Message::ANSI::ISUP); # ------------------------------------- package Message::ITUT::ISUP::USR; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: V(UUI) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'UUI',$off); $off++; return unless Message::unpack_OP($self, $off); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'UUI',$off+0), Message::dissect_OP($self, $off+1), ); } # ------------------------------------- package Message::ITUT::ISUP::UCIC; our @ISA = qw(Message::ITUT::ISUP::NONE); package Message::ANSI::ISUP::UCIC; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ISUP::CFN; our @ISA = qw(Message::ISUP); # ------------------------------------- # BOTH: V(CAUS) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MV($self,'CAUS',$off); $off++; return unless Message::unpack_OP($self, $off); $off++; return $self; } sub dissect{ my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MV($self,'CAUSE',$off+0), Message::dissect_OP($self, $off+1), ); } package Message::ITUT::ISUP::CFN; our @ISA = qw(Message::ITUT::ISUP); package Message::ANSI::ISUP::CFN; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- package Message::ITUT::ISUP::OLM; our @ISA = qw(Message::ITUT::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::CRG; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: (none) # SING: ICCI O() # SPAIN: O() # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off} + 3; return [ @{$self->SUPER::dissect(@_)}, ]; } # ------------------------------------- package Message::ITUT::ISUP::NRM; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::FAC; our @ISA = qw(Message::ITUT::ISUP::OPARMS); package Message::ANSI::ISUP::FAC; our @ISA = qw(Message::ANSI::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::UPT; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::UPA; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::IDR; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::IRS; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::SGM; our @ISA = qw(Message::ITUT::ISUP::OPARMS); package Message::ANSI::ISUP::SGM; our @ISA = qw(Message::ANSI::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::LPR; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::ATP; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::PRI; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::SDN; our @ISA = qw(Message::ITUT::ISUP::OPARMS); # ------------------------------------- package Message::ANSI::ISUP::CRA; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ANSI::ISUP::CRM; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- # ANSI: NCI # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'NCI',$off,1); $off++; return unless $off == $self->{end}; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'NCI',$off,1), ); } # ------------------------------------- package Message::ANSI::ISUP::CVR; our @ISA = qw(Message::ANSI::ISUP); # ------------------------------------- # ANSI: F(CVRI CGCI) O() # ------------------------------------- sub unpack { my $self = shift; my $off = $self->{off}; return unless Message::unpack_MF($self,'CVRI',$off,1); $off++; return unless Message::unpack_MF($self,'CGCI',$off,1); $off++; return unless Message::unpack_OP($self, $off ); $off++; return $self; } sub dissect { my $self = shift; my $off = $self->{off}; return $self->SUPER::dissect( Message::dissect_MF($self,'CVRI',$off+0,1), Message::dissect_MF($self,'CGCI',$off+1,1), Message::dissect_OP($self, $off+2 ), ); } # ------------------------------------- package Message::ANSI::ISUP::CVT; our @ISA = qw(Message::ANSI::ISUP::NONE); # ------------------------------------- package Message::ANSI::ISUP::EXM; our @ISA = qw(Message::ANSI::ISUP::OPARMS); # ------------------------------------- package Message::ITUT::ISUP::NON; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: (no such message) # SPAN: TON # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off} + 3; return [ @{$self->SUPER::dissect(@_)}, ]; } # ------------------------------------- package Message::ITUT::ISUP::LLM; our @ISA = qw(Message::ITUT::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::CAK; our @ISA = qw(Message::ITUT::ISUP::NONE); # ------------------------------------- package Message::ITUT::ISUP::TCM; our @ISA = qw(Message::ITUT::ISUP); # ------------------------------------- # ITUT: (no such message) # SING: CRI # ------------------------------------- sub unpack { my $self = shift; return $self; } sub dissect { my $self = shift; my $off = $self->{isup}->{off} + 3; return [ @{$self->SUPER::dissect(@_)}, ]; } # ------------------------------------- package Message::ITUT::ISUP::MCP; our @ISA = qw(Message::ITUT::ISUP::NONE); # ------------------------------------- # ------------------------------------- package Message::TCAP; our @ISA = qw(Message); # ------------------------------------- use constant { TCAP_TAG_UNIV_INT => 2, # UNIV Integer TCAP_TAG_UNIV_OSTR => 4, # UNIV Octet String TCAP_TAG_UNIV_OID => 6, # UNIV Object Id TCAP_TAG_UNIV_PSEQ => 16, # UNIV Parameter Sequence TCAP_TAG_UNIV_UTC => 17, # UNIV Universal Time TCAP_TAG_UNIV_TS => 23, # UNIV Timestamp TCAP_TAG_UNIV_SEQ => 48, # UNIV Sequence # TCAP (application-context/national) parameter type tag values TCAP_TAG_TCAP_ACG => 1, # TCAP ACG Indicators TCAP_TAG_TCAP_STA => 2, # TCAP Standard Announcement TCAP_TAG_TCAP_CUA => 3, # TCAP Customized Announcment TCAP_TAG_TCAP_TDIG => 4, # TCAP Digits TCAP_TAG_TCAP_SUEC => 5, # TCAP Standard User Error Code TCAP_TAG_TCAP_PDTA => 6, # TCAP Problem Data TCAP_TAG_TCAP_TCGPA => 7, # TCAP SCCP Calling Party Address TCAP_TAG_TCAP_TRSID => 8, # TCAP Transaction ID TCAP_TAG_TCAP_PCTY => 9, # TCAP Package Type TCAP_TAG_TCAP_SKEY => 10, # TCAP Service Key (Constructor) TCAP_TAG_TCAP_BISTAT => 11, # TCAP Busy/Idle Status TCAP_TAG_TCAP_CFSTAT => 12, # TCAP Call Forwarding Status TCAP_TAG_TCAP_ORIGR => 13, # TCAP Origination Restrictions TCAP_TAG_TCAP_TERMR => 14, # TCAP Terminating Restrictions TCAP_TAG_TCAP_DNMAP => 15, # TCAP DN to Line Service TYpe Mapping TCAP_TAG_TCAP_DURTN => 16, # TCAP Duration TCAP_TAG_TCAP_RETD => 17, # TCAP Return Data (Constructor) TCAP_TAG_TCAP_BCRQ => 18, # TCAP Bearer Capability Requested TCAP_TAG_TCAP_BCSUP => 19, # TCAP Bearer Capability Supported TCAP_TAG_TCAP_REFID => 20, # TCAP Reference Id TCAP_TAG_TCAP_BGROUP => 21, # TCAP Business Group TCAP_TAG_TCAP_SNI => 22, # TCAP Signalling Networks Identifier TCAP_TAG_TCAP_GNAME => 23, # TCAP Generic Name TCAP_TAG_TCAP_MWIT => 24, # TCAP Message Waiting Indicator Type TCAP_TAG_TCAP_LAFB => 25, # TCAP Locall Ahead for Busy TCAP_TAG_TCAP_CIC => 26, # TCAP Circuit Identification Code TCAP_TAG_TCAP_PRECI => 27, # TCAP Precedence Identifier TCAP_TAG_TCAP_CRI => 28, # TCAP Call Reference Identifier TCAP_TAG_TCAP_AUTH => 29, # TCAP Authorization TCAP_TAG_TCAP_INTEG => 30, # TCAP Integrity TCAP_TAG_TCAP_SEQN => 31, # TCAP Sequence Number TCAP_TAG_TCAP_NMSGS => 32, # TCAP Number of Messages TCAP_TAG_TCAP_DTEXT => 33, # TCAP Display Text TCAP_TAG_TCAP_KEYX => 34, # TCAP Key Exchange TCAP_TAG_TCAP_TCDPA => 35, # TCAP SCCP Called Party Address #TCAP (private/private) parameter type tags TCAP_TAG_PRIV_BLGI => 1, # TCAP Billing indicators TCAP_TAG_PRIV_CTIME => 2, # TCAP Connect time TCAP_TAG_PRIV_ECHOD => 3, # TCAP Echo data TCAP_TAG_PRIV_ONC => 4, # TCAP Originating node capabilities TCAP_TAG_PRIV_OST => 5, # TCAP Originating station type TCAP_TAG_PRIV_TERMIND => 6, # TCAP Terminating indicators TCAP_TAG_PRIV_AGCP => 7, # TCAP AGC indicators (private) TCAP_TAG_PRIV_ALPHAS => 8, # TCAP Alphanumeric string TCAP_TAG_PRIV_PDIG => 9, # TCAP Digits (private) TCAP_TAG_PRIV_ASYNCTP => 10, # TCAP Asynchronous terminal profile TCAP_TAG_PRIV_ACBI => 11, # TCAP Automated callback indicator TCAP_TAG_PRIV_CSDI => 12, # TCAP CC account number service denial indicator TCAP_TAG_PRIV_CCSAN => 13, # TCAP Calling card subaccount number TCAP_TAG_PRIV_CHGII => 14, # TCAP Charging information indicator TCAP_TAG_PRIV_CUGFC => 15, # TCAP CUG facility code TCAP_TAG_PRIV_CUGI => 16, # TCAP CUG index TCAP_TAG_PRIV_CUGP => 17, # TCAP CUG parameters TCAP_TAG_PRIV_COLL => 18, # TCAP Collect acceptance indicator TCAP_TAG_PRIV_COMPID => 19, # TCAP Company ID TCAP_TAG_PRIV_DTPCL => 20, # TCAP Default throughput class TCAP_TAG_PRIV_FCNFI => 21, # TCAP Flow control negotiation facility indicator TCAP_TAG_PRIV_ICDR => 22, # TCAP IXC denial check response TCAP_TAG_PRIV_CARI => 23, # TCAP IXC (carrier) indicators TCAP_TAG_PRIV_ICPRE => 24, # TCAP IXC (carrier) preselect TCAP_TAG_PRIV_ICPREI => 25, # TCAP IXC (carrier) preselect indicator TCAP_TAG_PRIV_ICPT => 26, # TCAP Intercept indicator TCAP_TAG_PRIV_NSDPS => 27, # TCAP Non-standard default packet size TCAP_TAG_PRIV_NSDWS => 28, # TCAP Non-standard default window size TCAP_TAG_PRIV_MATCH => 29, # TCAP Match TCAP_TAG_PRIV_OBILL => 30, # TCAP Originating billing indicators TCAP_TAG_PRIV_CCVI2 => 31, # TCAP Calling card verification information 2 TCAP_TAG_PRIV_PIN => 32, # TCAP Personal identification number TCAP_TAG_PRIV_PINR => 33, # TCAP PIN restriction indicator TCAP_TAG_PRIV_PSDI => 34, # TCAP PIN service denial indicator TCAP_TAG_PRIV_PPSN => 35, # TCAP PPSN data services indicator # # TCAP_TAG_PRIV_PSNP => 38, # TcAP Private subscribe network preselect TCAP_TAG_PRIV_RSI => 39, # TCAP Record status indicator TCAP_TAG_PRIV_SST => 40, # TCAP service or equipment indicator (service station type) TCAP_TAG_PRIV_TERMLI => 41, # TCAP Terminating line indicators TCAP_TAG_PRIV_TN => 42, # TCAP Third number acceptance indicator TCAP_TAG_PRIV_TCNFI => 43, # TCAP Throughput class negotiation TCAP_TAG_PRIV_TREAT => 44, # TCAP Treatment indicator TCAP_TAG_PRIV_RPOASB => 45, # TCAP RPOA selection barred facility indicator TCAP_TAG_PRIV_INTINF => 46, # TCAP Intercept information TCAP_TAG_PRIV_OLNSI => 47, # TCAP Originating line number screening information TCAP_TAG_PRIV_CCVI1 => 48, # TCAP Calling card verification information 1 (Automated calling card service) TCAP_TAG_PRIV_BNS => 49, # TCAP Billed number screening information TCAP_TAG_PRIV_TLNSI => 50, # TCAP Terminating line number screening information TCAP_TAG_PRIV_NUI => 51, # TCAP NUI profile screening information TCAP_TAG_PRIV_SPAR1 => 52, # TCAP Spare indicator 1 TCAP_TAG_PRIV_SPAR2 => 53, # TCAP Spare indicator 2 TCAP_TAG_PRIV_TSPAR1 => 54, # TCAP Telco spare indicator 1 TCAP_TAG_PRIV_TSPAR2 => 55, # TCAP Telco spare indicator 2 TCAP_TAG_PRIV_TSPAR3 => 56, # TCAP Telco spare indicator 3 TCAP_TAG_PRIV_TSPAR4 => 57, # TCAP Telco spare indicator 4 TCAP_TAG_PRIV_OLSI1 => 58, # TCAP Originating listing services indicator 1 TCAP_TAG_PRIV_OLSI2 => 59, # TCAP Originating listing services indicator 2 TCAP_TAG_PRIV_LOCAL => 60, # TCAP Locality TCAP_TAG_PRIV_SPECA => 61, # TCAP Special announcement TCAP_TAG_PRIV_OST_VALUES=>{ 0x00=>'identified line, no special treatment', 0x01=>'ONI (multiparty)', 0x02=>'ANI failure', 0x06=>'hotel with room ID', 0x07=>'coinless, hospital, etc', 0x08=>'interLATA restricted', 0x0a=>'test call (1)', 0x14=>'AIOD (automatic inward/outward dialing) listed DN sent', 0x17=>'coin or non-coin identified line', 0x18=>'800 call', 0x44=>'interLATA restricted-hotel', 0x4e=>'interLATA restricted-coinless, etc', 0x5f=>'test call (2)', }, TCAP_TAG_PRIV_SPECA_VALUES=>{ 0x00=>'not used', 0x01=>'change 800 number (T1)', 0x02=>'change 800 number (T2)', 0x03=>'security failure, invalid SO', }, #TCAP (private/national) parameter type tags TCAP_TAG_PRIV_UNI => 1, # ANSI Unidirectional TCAP_TAG_PRIV_QWP => 2, # ANSI Query w/ permission TCAP_TAG_PRIV_QWOP => 3, # ANSI Query w/o permission TCAP_TAG_PRIV_RESP => 4, # ANSI Response TCAP_TAG_PRIV_CWP => 5, # ANSI Conversaion w/ permission TCAP_TAG_PRIV_CWOP => 6, # ANSI Conversaion w/o permission TCAP_TAG_PRIV_TRSID => 7, # ANSI Transaction Id TCAP_TAG_PRIV_CSEQ => 8, # ANSI Component Sequence TCAP_TAG_PRIV_INKL => 9, # ANSI Invoke (Last) TCAP_TAG_PRIV_RRL => 10, # ANSI Return Result (Last) TCAP_TAG_PRIV_RER => 11, # ANSI Return Error TCAP_TAG_PRIV_REJ => 12, # ANSI Reject TCAP_TAG_PRIV_INK => 13, # ANSI Invoke (Not Last) TCAP_TAG_PRIV_RR => 14, # ANSI Result (Not Last) TCAP_TAG_PRIV_CORID => 15, # ANSI Correlation Id(s) TCAP_TAG_PRIV_NOPCO => 16, # ANSI National Operation Code TCAP_TAG_PRIV_POPCO => 17, # ANSI Private Operation Code TCAP_TAG_PRIV_PSET => 18, # ANSI Parameter Set TCAP_TAG_PRIV_NECODE => 19, # ANSI National Error Code TCAP_TAG_PRIV_PECODE => 20, # ANSI Private Error Code TCAP_TAG_PRIV_PBCODE => 21, # ANSI Reject Problem Code TCAP_TAG_PRIV_PSEQ => 21, # ANSI Parameter Sequence TCAP_TAG_PRIV_ABORT => 22, # ANSI Abort TCAP_TAG_PRIV_PCAUSE => 23, # ANSI P-Abort Cause TCAP_TAG_PRIV_U_ABORT => 24, # ANSI User Abort Information TCAP_TAG_PRIV_DLGP => 25, # ANSI Dialog Portion TCAP_TAG_PRIV_VERSION => 26, # ANSI Protocol Version TCAP_TAG_PRIV_CONTEXT => 27, # ANSI Integer Application Context TCAP_TAG_PRIV_CTX_OID => 28, # ANSI OID Application Context TCAP_TAG_PRIV_UINFO => 29, # ANSI User Information TCAP_TAG_APPL_UNI => 1, # ITUT Unidirectional TCAP_TAG_APPL_BEGIN => 2, # ITUT Begin Transaction TCAP_TAG_APPL_END => 4, # ITUT End Transaction TCAP_TAG_APPL_CONT => 5, # ITUT Continue Transaction TCAP_TAG_APPL_ABORT => 7, # ITUT Abort Transaction TCAP_TAG_APPL_ORIGID => 8, # ITUT Origination Transaction Id TCAP_TAG_APPL_DESTID => 9, # ITUT Destination Transaction Id TCAP_TAG_APPL_PCAUSE => 10, # ITUT P-Abort Cause TCAP_TAG_APPL_DLGP => 11, # ITUT Dialog Portion TCAP_TAG_APPL_CSEQ => 12, # ITUT Component Portion TCAP_TAG_APPL_AUDT_PDU => 0, # ITUT AUDT APDU TCAP_TAG_APPL_AARQ_PDU => 0, # ITUT AARQ APDU TCAP_TAG_APPL_AARE_PDU => 1, # ITUT AARE APDU TCAP_TAG_APPL_RLRQ_PDU => 2, # ITUT RLRQ APDU TCAP_TAG_APPL_RLRE_PDU => 3, # ITUT RLRE APDU TCAP_TAG_APPL_ABRT_PDU => 4, # ITUT ABRT APDU TCAP_TAG_CNTX_LID => 0, # Linked Id TCAP_TAG_CNTX_INK => 1, # Invoke TCAP_TAG_CNTX_RRL => 2, # Return Result (Last) TCAP_TAG_CNTX_RER => 3, # Return Error TCAP_TAG_CNTX_REJ => 4, # Reject TCAP_TAG_CNTX_RR => 7, # Return Result (Not Last) TCAP_NAT_OP_FAMILY=>{ 0x00=>'All Families', 0x01=>'Parameter', 0x02=>'Charging', 0x03=>'Provide Instructions', 0x04=>'Connection Control', 0x05=>'Caller Interaction', 0x06=>'Send Notification', 0x07=>'Network Management', 0x08=>'Procedural', 0x09=>'Operation Control', 0x0a=>'Report Event', 0x7e=>'Miscellaneous', }, # Note: the high bit indicates whether a reply is required (1) or not (0) TCAP_NAT_OPERATIONS=>{ 0x00ff=>'Reserved', 0x0000=>'Spare', 0x0101=>'Provide Value', 0x0102=>'Set Value', 0x0201=>'Bill Call', 0x0301=>'Start', 0x0302=>'Assist', 0x0401=>'Connect', 0x0402=>'Temporary Connect', 0x0403=>'Disconnect', 0x0404=>'Forward Disconnect', 0x0501=>'Play Announcement', 0x0502=>'Play Announcement and Collect Digits', 0x0503=>'Indicate Information Waiting', 0x0504=>'Indicate Information Provided', 0x0601=>'When Party Free', 0x0701=>'Automatic Code Gap', 0x0801=>'Temporary Handover', 0x0802=>'Report Assist Termination', 0x0803=>'Security', 0x0901=>'Cancel', 0x0a01=>'Voice Message Available', 0x0a02=>'Voice Message Retrieved', 0x7e01=>'Queue Call', 0x7e02=>'Dequeue Call', }, TCAP_NAT_ERRORS=>{ 0x00=>'not used', 0x01=>'unexpected component sequence', 0x02=>'unexpected data value', 0x03=>'unavailable resource', 0x04=>'missing customer record', 0x05=>'spare', 0x06=>'data unavailable', 0x07=>'task refused', 0x08=>'queue full', 0x09=>'no queue', 0x0a=>'timer expired', 0x0b=>'data already exists', 0x0c=>'unauthorized request', 0x0d=>'not queued', 0x0e=>'unassigned directory number', 0x0f=>'spare', 0x10=>'notification unavailable for destination directory number', 0x11=>'VMSR system identification did not match user profile', 0x12=>'security error', 0x13=>'missing parameter', 0x14=>'unexpected parameter sequence', 0x15=>'unexpected message', 0x16=>'unexpected package type', }, TCAP_ACG_CTRL_CAUSE=>{ 0x01=>'vacant code', 0x02=>'out-of-band', 0x03=>'database overload', 0x04=>'destination mass calling', 0x05=>'operation support system initiated', }, TCAP_ACG_DURATION=>{ 0x00=>'not used', 0x01=>'1 second', 0x02=>'2 seconds', 0x03=>'4 seconds', 0x04=>'8 seconds', 0x05=>'16 seconds', 0x06=>'32 seconds', 0x07=>'64 seconds', 0x08=>'128 seconds', 0x09=>'256 seconds', 0x0a=>'512 seconds', 0x0b=>'1024 seconds', 0x0c=>'2048 seconds', }, TCAP_ACG_GAP=>{ 0x00=>'remove gap control', 0x01=>'0.00 seconds', 0x02=>'0.10 seconds', 0x03=>'0.25 seconds', 0x04=>'0.50 seconds', 0x05=>'1.00 seconds', 0x06=>'2.00 seconds', 0x07=>'5.00 seconds', 0x08=>'10.00 seconds', 0x09=>'15.00 seconds', 0x0a=>'30.00 seconds', 0x0b=>'60.00 seconds', 0x0c=>'120.00 seconds', 0x0d=>'300.00 seconds', 0x0e=>'600.00 seconds', 0x0f=>'stop all calls', }, TCAP_STA_STAI=>{ 0x00=>'not used', 0x01=>'out-of-band', 0x02=>'vacant code', 0x03=>'disconnected number', 0x04=>'reorder (120 ipm)', 0x05=>'busy (60 ipm)', 0x06=>'no circuit available', 0x07=>'reorder', 0x08=>'audible ring', }, TCAP_DIG_TOD=>{ 0x00=>'not used', 0x01=>'called party number', 0x02=>'calling party number', 0x03=>'caller interaction', }, }; use constant { TCAP_TYPE=>{ 0xa0 => { 0x01 => 'APPL::UNI', 0x02 => 'APPL::BEGIN', 0x04 => 'APPL::END', 0x05 => 'APPL::CONT', 0x07 => 'APPL::ABORT', }, 0xe0 => { 0x01 => 'PRIV::UNI', 0x02 => 'PRIV::QWP', 0x03 => 'PRIV::QWOP', 0x04 => 'PRIV::RESP', 0x05 => 'PRIV::CWP', 0x06 => 'PRIV::CWOP', 0x16 => 'PRIV::ABORT', }, }, }; sub unpack { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls; return unless exists TCAP_TYPE->{$cls}; return unless exists TCAP_TYPE->{$cls}->{$tag}; my $type = TCAP_TYPE->{$cls}->{$tag}; $self->{off} = $ptr; $self->{end} = $end; $self->{cls} = $cls; $self->{tag} = $tag; bless $self,ref($self)."::$type"; return $self->unpack(@_); } sub unpack_taglen { my ($self,$ptr,$end,$cls,$tag,$len) = @_; return unless $ptr < $end; $cls = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; if (($cls & 0x1f) != 0x1f) { # tag is not extended $tag = $cls & 0x1f; } else { my $ptag; $tag = 0; return unless $ptr < $end; $ptag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; $tag |= $ptag & 0x7f; if ($ptag & 0x80) { return unless $ptr < $end; $ptag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; $tag <<= 7; $tag |= $ptag & 0x7f; if ($ptag & 0x80) { return unless $ptr < $end; $ptag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; $tag <<= 7; $tag |= $ptag & 0x7f; if ($ptag & 0x80) { return unless $ptr < $end; $ptag = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; $tag <<= 7; $tag |= $ptag & 0x7f; return if $ptag & 0x80; } } } } return unless $ptr < $end; $len = unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; if (($len & 0x80) != 0x00) { # extended length my $plen; $plen = $len & 0x7f; return if $plen > 4 or $plen == 0; $len = 0; while ($plen--) { return unless $ptr < $end; $len <<= 8; $len |= unpack('C',substr($$self->{buf},$ptr,1)); $ptr++; } return unless $ptr + $len <= $end; $end = $ptr + $len; } $cls &= 0x1f; return $cls,$tag,$ptr,$end; } # ------------------------------------- package Message::TCAP::APPL; our @ISA = qw(Message::TCAP); # ------------------------------------- sub unpack { my $self = shift; $self->{dialportion} = new Message::TCAP::APPL::DLGP($self); $self->{compportion} = new Message::TCAP::APPL::CSEQ($self); return $self; } # ------------------------------------- package Message::TCAP::APPL::DLGP; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls and $cls & 0xe0 == 0x60 and $tag == TCAP_TAG_APPL_DLGP; $self->{cls} = $cls; $self->{tag} = $tag; $self->{off} = $ptr; $self->{end} = $end; return $self; } # ------------------------------------- package Message::TCAP::APPL::CSEQ; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls and $cls & 0xe0 == 0x60 and $tag == TCAP_TAG_APPL_CSEQ; $self->{cls} = $cls; $self->{tag} = $tag; $self->{off} = $ptr; $self->{end} = $end; return $self; } # ------------------------------------- package Message::TCAP::APPL::UNI; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::APPL::BEGIN; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::APPL::END; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::APPL::CONT; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::APPL::ABORT; our @ISA = qw(Message::TCAP::APPL); # ------------------------------------- sub unpack { my $self = shift; $self->{dialportion} = new Message::TCAP::APPL::DLGP($self); # FIXME: needs to be cause info # $self->{compportion} = new Message::TCAP::APPL::CSEQ($self); return $self; } # ------------------------------------- package Message::TCAP::PRIV::DLGP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls and $cls & 0xe0 == 0xe0 and $tag == TCAP_TAG_PRIV_DLGP; $self->{cls} = $cls; $self->{tag} = $tag; $self->{off} = $ptr; $self->{end} = $end; return $self; } # ------------------------------------- package Message::TCAP::PRIV::CSEQ; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls and $cls & 0xe0 == 0xe0 and $tag == TCAP_TAG_PRIV_CSEQ; $self->{cls} = $cls; $self->{tag} = $tag; $self->{off} = $ptr; $self->{end} = $end; return $self; } # ------------------------------------- package Message::TCAP::PRIV; our @ISA = qw(Message::TCAP); # ------------------------------------- sub unpack_prim { my $self = shift; my ($cls,$tag,$ptr,$end) = $self->unpack_taglen($self->{off},$self->{end}); return unless defined $cls; my $val = substr($$self->{buf},$ptr,$end-$ptr); return $cls,$tag,$end,$val; } sub unpack_TRSID { my $self = shift; my ($cls,$tag,$end,$val) = $self->unpack_prim($self->{off},$self->{end}); return unless defined $cls and $cls & 0xe0 == 0xc0 and $tag == TCAP_TAG_PRIV_TRSID; $self->{off} = $end; return $val; } sub unpack { my $self = shift; $self->{dialportion} = new Message::TCAP::PRIV::DLGP($self); $self->{compportion} = new Message::TCAP::PRIV::CSEQ($self); return $self; } # ------------------------------------- package Message::TCAP::PRIV::UNI; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 0; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::QWP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 4; $self->{origid} = unpack('N',$trnsid); return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::QWOP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 4; $self->{origid} = unpack('N',$trnsid); return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::RESP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 4; $self->{origid} = unpack('N',$trnsid); return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::CWP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 8; ($self->{origid},$self->{termid}) = unpack('NN',$trnsid); return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::CWOP; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); ($self->{origid},$self->{termid}) = unpack('NN',$trnsid); return unless defined $trsid and length $trsid == 8; return $self->SUPER::unpack(@_); } # ------------------------------------- package Message::TCAP::PRIV::ABORT; our @ISA = qw(Message::TCAP::PRIV); # ------------------------------------- sub unpack { my $self = shift; my $trsid = $self->unpack_TRSID($self->{off},$self->{end}); return unless defined $trsid and length $trsid == 4; $self->{origid} = unpack('N',$trnsid); $self->{dialportion} = new Message::TCAP::PRIV::DLGP($self); # FIXME: needs to be cause info # $self->{compportion} = new Message::TCAP::PRIV::CSEQ($self); return $self; }
agpl-3.0
empirical-org/Empirical-Wordpress
wp-content/plugins/invite-anyone/by-email/cloudsponge-integration.php
2189
<?php class Cloudsponge_Integration { var $enabled; var $key; /** * PHP 5 Constructor * * @package Invite Anyone * @since 0.8 */ function __construct() { if ( empty( $options ) ) $options = get_option( 'invite_anyone' ); $this->enabled = !empty( $options['cloudsponge_enabled'] ) ? $options['cloudsponge_enabled'] : false; $this->key = !empty( $options['cloudsponge_key'] ) ? $options['cloudsponge_key'] : false; if ( $this->enabled && $this->key ) { define( 'INVITE_ANYONE_CS_ENABLED', true ); add_action( 'invite_anyone_after_addresses', array( $this, 'import_markup' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script' ) ); } } /** * Registers and loads CS JS. * * @package Invite Anyone * @since 0.8.8 */ function enqueue_script() { wp_register_script( 'ia_cloudsponge_address_books', 'https://api.cloudsponge.com/address_books.js', array(), false, true ); wp_register_script( 'ia_cloudsponge', WP_PLUGIN_URL . '/invite-anyone/by-email/cloudsponge-js.js', array( 'ia_cloudsponge_address_books' ), false, true ); // The domain key must be printed as a javascript object so it's accessible to the // script $strings = array( 'domain_key' => $this->key ); if ( $locale = apply_filters( 'ia_cloudsponge_locale', '' ) ) { $strings['locale'] = $locale; } if ( $stylesheet = apply_filters( 'ia_cloudsponge_stylesheet', '' ) ) { $strings['stylesheet'] = $stylesheet; } wp_localize_script( 'ia_cloudsponge', 'ia_cloudsponge', $strings ); } /** * Inserts the Cloudsponge markup into the Send Invites front end page. * * Also responsible for enqueuing the necessary assets. * * @package Invite Anyone * @since 0.8 * * @param array $options Invite Anyone settings. Check em so we can bail if necessary */ function import_markup( $options = false ) { wp_enqueue_script( 'ia_cloudsponge' ); ?> <input type="hidden" id="cloudsponge-emails" name="cloudsponge-emails" value="" /> <?php _e( 'You can also add email addresses <a class="cs_import">from your Address Book</a>.', 'invite-anyone' ) ?> <?php } } $cloudsponge_integration = new Cloudsponge_Integration;
agpl-3.0
inspectIT/inspectIT
inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/repository/service/cmr/proxy/InterceptorUtils.java
3959
package rocks.inspectit.ui.rcp.repository.service.cmr.proxy; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import com.google.common.base.Defaults; import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition; import rocks.inspectit.ui.rcp.repository.service.cmr.ICmrService; /** * Utilities that will be used in interceptors. * * @author Ivan Senic * */ public final class InterceptorUtils { /** * Private constructor. */ private InterceptorUtils() { } /** * Is service method. * * @param methodInvocation * Method invocation. * @return Return if it is service method. */ public static boolean isServiceMethod(MethodInvocation methodInvocation) { return !methodInvocation.getMethod().getDeclaringClass().equals(ICmrService.class); } /** * Checks if the method being executed is executed on the proxy containing {@link ICmrService} * and service defines the default value on error value. * * @param methodInvocation * Method invocation. * @return <code>true</code> if {@link ICmrService} objects defines return default on error */ public static boolean isReturnDefaultReturnValue(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); return (null != cmrService) && cmrService.isDefaultValueOnError(); } /** * Tries to get the {@link CmrRepositoryDefinition} from the proxied {@link ICmrService} object. * * @param methodInvocation * {@link MethodInvocation}. * @return CMR invoked or null. */ public static CmrRepositoryDefinition getRepositoryDefinition(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); if (null != cmrService) { CmrRepositoryDefinition cmrRepositoryDefinition = cmrService.getCmrRepositoryDefinition(); return cmrRepositoryDefinition; } return null; } /** * Returns {@link ICmrService} object if one is bounded to the proxy being invoked in the given * {@link MethodInvocation} or <code>null</code> if one can not be obtained. * * @param methodInvocation * {@link MethodInvocation}. * @return {@link ICmrService} bounded on proxy or <code>null</code> */ private static ICmrService getCmrService(MethodInvocation methodInvocation) { if (methodInvocation instanceof ReflectiveMethodInvocation) { ReflectiveMethodInvocation reflectiveMethodInvocation = (ReflectiveMethodInvocation) methodInvocation; Object service = reflectiveMethodInvocation.getThis(); if (service instanceof ICmrService) { return (ICmrService) service; } } return null; } /** * Checks if the return type of the {@link java.lang.reflect.Method} invoked by * {@link MethodInvocation} is one of tree major collection types (List, Map, Set) and if it is * returns the empty collection of correct type. Otherwise it returns null. * * @param paramMethodInvocation * {@link MethodInvocation} * @return If the method invoked by {@link MethodInvocation} is one of tree major collection * types (List, Map, Set) method returns the empty collection of correct type. Otherwise * it returns null. */ public static Object getDefaultReturnValue(MethodInvocation paramMethodInvocation) { Class<?> returnType = paramMethodInvocation.getMethod().getReturnType(); if (returnType.isAssignableFrom(List.class)) { return Collections.emptyList(); } else if (returnType.isAssignableFrom(Map.class)) { return Collections.emptyMap(); } else if (returnType.isAssignableFrom(Set.class)) { return Collections.emptySet(); } else if (returnType.isPrimitive()) { try { return Defaults.defaultValue(returnType); } catch (Exception e) { return null; } } else { return null; } } }
agpl-3.0
asaadmahmoodspin/platform
model/client.go
84229
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package model import ( "bytes" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "strconv" "strings" "time" l4g "github.com/alecthomas/log4go" ) const ( HEADER_REQUEST_ID = "X-Request-ID" HEADER_VERSION_ID = "X-Version-ID" HEADER_CLUSTER_ID = "X-Cluster-ID" HEADER_ETAG_SERVER = "ETag" HEADER_ETAG_CLIENT = "If-None-Match" HEADER_FORWARDED = "X-Forwarded-For" HEADER_REAL_IP = "X-Real-IP" HEADER_FORWARDED_PROTO = "X-Forwarded-Proto" HEADER_TOKEN = "token" HEADER_BEARER = "BEARER" HEADER_AUTH = "Authorization" HEADER_REQUESTED_WITH = "X-Requested-With" HEADER_REQUESTED_WITH_XML = "XMLHttpRequest" STATUS = "status" STATUS_OK = "OK" STATUS_FAIL = "FAIL" STATUS_REMOVE = "REMOVE" CLIENT_DIR = "webapp/dist" API_URL_SUFFIX_V1 = "/api/v1" API_URL_SUFFIX_V3 = "/api/v3" API_URL_SUFFIX_V4 = "/api/v4" API_URL_SUFFIX = API_URL_SUFFIX_V4 ) type Result struct { RequestId string Etag string Data interface{} } type ResponseMetadata struct { StatusCode int Error *AppError RequestId string Etag string } type Client struct { Url string // The location of the server like "http://localhost:8065" ApiUrl string // The api location of the server like "http://localhost:8065/api/v3" HttpClient *http.Client // The http client AuthToken string AuthType string TeamId string RequestId string Etag string ServerVersion string } // NewClient constructs a new client with convienence methods for talking to // the server. func NewClient(url string) *Client { return &Client{url, url + API_URL_SUFFIX_V3, &http.Client{}, "", "", "", "", "", ""} } func closeBody(r *http.Response) { if r.Body != nil { ioutil.ReadAll(r.Body) r.Body.Close() } } func (c *Client) SetOAuthToken(token string) { c.AuthToken = token c.AuthType = HEADER_TOKEN } func (c *Client) ClearOAuthToken() { c.AuthToken = "" c.AuthType = HEADER_BEARER } func (c *Client) SetTeamId(teamId string) { c.TeamId = teamId } func (c *Client) GetTeamId() string { if len(c.TeamId) == 0 { println(`You are trying to use a route that requires a team_id, but you have not called SetTeamId() in client.go`) } return c.TeamId } func (c *Client) ClearTeamId() { c.TeamId = "" } func (c *Client) GetTeamRoute() string { return fmt.Sprintf("/teams/%v", c.GetTeamId()) } func (c *Client) GetChannelRoute(channelId string) string { return fmt.Sprintf("/teams/%v/channels/%v", c.GetTeamId(), channelId) } func (c *Client) GetUserRequiredRoute(userId string) string { return fmt.Sprintf("/users/%v", userId) } func (c *Client) GetChannelNameRoute(channelName string) string { return fmt.Sprintf("/teams/%v/channels/name/%v", c.GetTeamId(), channelName) } func (c *Client) GetEmojiRoute() string { return "/emoji" } func (c *Client) GetGeneralRoute() string { return "/general" } func (c *Client) GetFileRoute(fileId string) string { return fmt.Sprintf("/files/%v", fileId) } func (c *Client) DoPost(url, data, contentType string) (*http.Response, *AppError) { rq, _ := http.NewRequest("POST", c.Url+url, strings.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer closeBody(rp) return nil, AppErrorFromJson(rp.Body) } else { return rp, nil } } func (c *Client) DoApiPost(url string, data string) (*http.Response, *AppError) { rq, _ := http.NewRequest("POST", c.ApiUrl+url, strings.NewReader(data)) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer closeBody(rp) return nil, AppErrorFromJson(rp.Body) } else { return rp, nil } } func (c *Client) DoApiGet(url string, data string, etag string) (*http.Response, *AppError) { rq, _ := http.NewRequest("GET", c.ApiUrl+url, strings.NewReader(data)) rq.Close = true if len(etag) > 0 { rq.Header.Set(HEADER_ETAG_CLIENT, etag) } if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode == 304 { return rp, nil } else if rp.StatusCode >= 300 { defer closeBody(rp) return rp, AppErrorFromJson(rp.Body) } else { return rp, nil } } func getCookie(name string, resp *http.Response) *http.Cookie { for _, cookie := range resp.Cookies() { if cookie.Name == name { return cookie } } return nil } // Must is a convenience function used for testing. func (c *Client) Must(result *Result, err *AppError) *Result { if err != nil { l4g.Close() time.Sleep(time.Second) panic(err) } return result } // MustGeneric is a convenience function used for testing. func (c *Client) MustGeneric(result interface{}, err *AppError) interface{} { if err != nil { l4g.Close() time.Sleep(time.Second) panic(err) } return result } // CheckStatusOK is a convenience function for checking the return of Web Service // call that return the a map of status=OK. func (c *Client) CheckStatusOK(r *http.Response) bool { m := MapFromJson(r.Body) defer closeBody(r) if m != nil && m[STATUS] == STATUS_OK { return true } return false } func (c *Client) fillInExtraProperties(r *http.Response) { c.RequestId = r.Header.Get(HEADER_REQUEST_ID) c.Etag = r.Header.Get(HEADER_ETAG_SERVER) c.ServerVersion = r.Header.Get(HEADER_VERSION_ID) } func (c *Client) clearExtraProperties() { c.RequestId = "" c.Etag = "" c.ServerVersion = "" } // General Routes Section // GetClientProperties returns properties needed by the client to show/hide // certian features. It returns a map of strings. func (c *Client) GetClientProperties() (map[string]string, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetGeneralRoute()+"/client_props", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return MapFromJson(r.Body), nil } } // LogClient is a convenience Web Service call so clients can log messages into // the server-side logs. For example we typically log javascript error messages // into the server-side. It returns true if the logging was successful. func (c *Client) LogClient(message string) (bool, *AppError) { c.clearExtraProperties() m := make(map[string]string) m["level"] = "ERROR" m["message"] = message if r, err := c.DoApiPost(c.GetGeneralRoute()+"/log_client", MapToJson(m)); err != nil { return false, err } else { defer closeBody(r) c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } // GetPing returns a map of strings with server time, server version, and node Id. // Systems that want to check on health status of the server should check the // url /api/v3/ping for a 200 status response. func (c *Client) GetPing() (map[string]string, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetGeneralRoute()+"/ping", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return MapFromJson(r.Body), nil } } // Team Routes Section // CreateTeam creates a team based on the provided Team struct. On success it returns // the Team struct with the Id, CreateAt and other server-decided fields populated. func (c *Client) CreateTeam(team *Team) (*Result, *AppError) { if r, err := c.DoApiPost("/teams/create", team.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // GetAllTeams returns a map of all teams using team ids as the key. func (c *Client) GetAllTeams() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/all", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil } } // GetAllTeamListings returns a map of all teams that are available to join // using team ids as the key. Must be authenticated. func (c *Client) GetAllTeamListings() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/all_team_listings", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil } } // FindTeamByName returns the strings "true" or "false" depending on if a team // with the provided name was found. func (c *Client) FindTeamByName(name string) (*Result, *AppError) { m := make(map[string]string) m["name"] = name if r, err := c.DoApiPost("/teams/find_team_by_name", MapToJson(m)); err != nil { return nil, err } else { val := false if body, _ := ioutil.ReadAll(r.Body); string(body) == "true" { val = true } defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), val}, nil } } // Adds a user directly to the team without sending an invite. // The teamId and userId are required. You must be a valid member of the team and/or // have the correct role to add new users to the team. Returns a map of user_id=userId // if successful, otherwise returns an AppError. func (c *Client) AddUserToTeam(teamId string, userId string) (*Result, *AppError) { if len(teamId) == 0 { teamId = c.GetTeamId() } data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/add_user_to_team", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // AddUserToTeamFromInvite adds a user to a team based off data provided in an invite link. // Either hash and dataToHash are required or inviteId is required. func (c *Client) AddUserToTeamFromInvite(hash, dataToHash, inviteId string) (*Result, *AppError) { data := make(map[string]string) data["hash"] = hash data["data"] = dataToHash data["invite_id"] = inviteId if r, err := c.DoApiPost("/teams/add_user_to_team_from_invite", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // Removes a user directly from the team. // The teamId and userId are required. You must be a valid member of the team and/or // have the correct role to remove a user from the team. Returns a map of user_id=userId // if successful, otherwise returns an AppError. func (c *Client) RemoveUserFromTeam(teamId string, userId string) (*Result, *AppError) { if len(teamId) == 0 { teamId = c.GetTeamId() } data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/remove_user_from_team", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) InviteMembers(invites *Invites) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/invite_members", invites.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), InvitesFromJson(r.Body)}, nil } } // UpdateTeam updates a team based on the changes in the provided team struct. On success // it returns a sanitized version of the updated team. Must be authenticated as a team admin // for that team or a system admin. func (c *Client) UpdateTeam(team *Team) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/update", team.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // User Routes Section // CreateUser creates a user in the system based on the provided user struct. func (c *Client) CreateUser(user *User, hash string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/create", user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // CreateUserWithInvite creates a user based on the provided user struct. Either the hash and // data strings or the inviteId is required from the invite. func (c *Client) CreateUserWithInvite(user *User, hash string, data string, inviteId string) (*Result, *AppError) { url := "/users/create?d=" + url.QueryEscape(data) + "&h=" + url.QueryEscape(hash) + "&iid=" + url.QueryEscape(inviteId) if r, err := c.DoApiPost(url, user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) CreateUserFromSignup(user *User, data string, hash string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/create?d="+url.QueryEscape(data)+"&h="+hash, user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // GetUser returns a user based on a provided user id string. Must be authenticated. func (c *Client) GetUser(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/get", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // getByUsername returns a user based on a provided username string. Must be authenticated. func (c *Client) GetByUsername(username string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/users/name/%v", username), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // getByEmail returns a user based on a provided username string. Must be authenticated. func (c *Client) GetByEmail(email string, etag string) (*User, *ResponseMetadata) { if r, err := c.DoApiGet(fmt.Sprintf("/users/email/%v", email), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return UserFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } // GetMe returns the current user. func (c *Client) GetMe(etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/me", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // GetProfiles returns a map of users using user id as the key. Must be authenticated. func (c *Client) GetProfiles(offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/users/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesInTeam returns a map of users for a team using user id as the key. Must // be authenticated. func (c *Client) GetProfilesInTeam(teamId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/users/%v/%v", teamId, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesInChannel returns a map of users for a channel using user id as the key. Must // be authenticated. func (c *Client) GetProfilesInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesNotInChannel returns a map of users not in a channel but on the team using user id as the key. Must // be authenticated. func (c *Client) GetProfilesNotInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/not_in_channel/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesByIds returns a map of users based on the user ids provided. Must // be authenticated. func (c *Client) GetProfilesByIds(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // SearchUsers returns a list of users that have a username matching or similar to the search term. Must // be authenticated. func (c *Client) SearchUsers(params UserSearch) (*Result, *AppError) { if r, err := c.DoApiPost("/users/search", params.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil } } // AutocompleteUsersInChannel returns two lists for autocompletion of users in a channel. The first list "in_channel", // specifies users in the channel. The second list "out_of_channel" specifies users outside of the // channel. Term, the string to search against, is required, channel id is also required. Must be authenticated. func (c *Client) AutocompleteUsersInChannel(term string, channelId string) (*Result, *AppError) { url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetChannelRoute(channelId), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInChannelFromJson(r.Body)}, nil } } // AutocompleteUsersInTeam returns a list for autocompletion of users in a team. The list "in_team" specifies // the users in the team that match the provided term, matching against username, full name and // nickname. Must be authenticated. func (c *Client) AutocompleteUsersInTeam(term string) (*Result, *AppError) { url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInTeamFromJson(r.Body)}, nil } } // AutocompleteUsers returns a list for autocompletion of users on the system that match the provided term, // matching against username, full name and nickname. Must be authenticated. func (c *Client) AutocompleteUsers(term string) (*Result, *AppError) { url := fmt.Sprintf("/users/autocomplete?term=%s", url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil } } // LoginById authenticates a user by user id and password. func (c *Client) LoginById(id string, password string) (*Result, *AppError) { m := make(map[string]string) m["id"] = id m["password"] = password return c.login(m) } // Login authenticates a user by login id, which can be username, email or some sort // of SSO identifier based on configuration, and a password. func (c *Client) Login(loginId string, password string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password return c.login(m) } // LoginByLdap authenticates a user by LDAP id and password. func (c *Client) LoginByLdap(loginId string, password string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password m["ldap_only"] = "true" return c.login(m) } // LoginWithDevice authenticates a user by login id (username, email or some sort // of SSO identifier based on configuration), password and attaches a device id to // the session. func (c *Client) LoginWithDevice(loginId string, password string, deviceId string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password m["device_id"] = deviceId return c.login(m) } func (c *Client) login(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/login", MapToJson(m)); err != nil { return nil, err } else { c.AuthToken = r.Header.Get(HEADER_TOKEN) c.AuthType = HEADER_BEARER sessionToken := getCookie(SESSION_COOKIE_TOKEN, r) if c.AuthToken != sessionToken.Value { NewLocAppError("/users/login", "model.client.login.app_error", nil, "") } defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // Logout terminates the current user's session. func (c *Client) Logout() (*Result, *AppError) { if r, err := c.DoApiPost("/users/logout", ""); err != nil { return nil, err } else { c.AuthToken = "" c.AuthType = HEADER_BEARER c.TeamId = "" defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // CheckMfa returns a map with key "mfa_required" with the string value "true" or "false", // indicating whether MFA is required to log the user in, based on a provided login id // (username, email or some sort of SSO identifier based on configuration). func (c *Client) CheckMfa(loginId string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId if r, err := c.DoApiPost("/users/mfa", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GenerateMfaSecret returns a QR code image containing the secret, to be scanned // by a multi-factor authentication mobile application. It also returns the secret // for manual entry. Must be authenticated. func (c *Client) GenerateMfaSecret() (*Result, *AppError) { if r, err := c.DoApiGet("/users/generate_mfa_secret", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // UpdateMfa activates multi-factor authenticates for the current user if activate // is true and a valid token is provided. If activate is false, then token is not // required and multi-factor authentication is disabled for the current user. func (c *Client) UpdateMfa(activate bool, token string) (*Result, *AppError) { m := make(map[string]interface{}) m["activate"] = activate m["token"] = token if r, err := c.DoApiPost("/users/update_mfa", StringInterfaceToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AdminResetMfa(userId string) (*Result, *AppError) { m := make(map[string]string) m["user_id"] = userId if r, err := c.DoApiPost("/admin/reset_mfa", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) RevokeSession(sessionAltId string) (*Result, *AppError) { m := make(map[string]string) m["id"] = sessionAltId if r, err := c.DoApiPost("/users/revoke_session", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetSessions(id string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/sessions", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), SessionsFromJson(r.Body)}, nil } } func (c *Client) EmailToOAuth(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/email_to_oauth", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) OAuthToEmail(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/oauth_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) LDAPToEmail(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) EmailToLDAP(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) Command(channelId string, command string) (*Result, *AppError) { args := &CommandArgs{ChannelId: channelId, Command: command} if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/execute", args.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandResponseFromJson(r.Body)}, nil } } func (c *Client) ListCommands() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil } } func (c *Client) ListTeamCommands() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list_team_commands", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil } } func (c *Client) CreateCommand(cmd *Command) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/create", cmd.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) UpdateCommand(cmd *Command) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/update", cmd.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) RegenCommandToken(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/regen_token", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) DeleteCommand(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetAudits(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/audits", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil } } func (c *Client) GetLogs() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/logs", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ArrayFromJson(r.Body)}, nil } } func (c *Client) GetClusterStatus() ([]*ClusterInfo, *AppError) { if r, err := c.DoApiGet("/admin/cluster_status", "", ""); err != nil { return nil, err } else { defer closeBody(r) return ClusterInfosFromJson(r.Body), nil } } // GetRecentlyActiveUsers returns a map of users including lastActivityAt using user id as the key func (c *Client) GetRecentlyActiveUsers(teamId string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/recently_active_users/"+teamId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } func (c *Client) GetAllAudits() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/audits", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil } } func (c *Client) GetConfig() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/config", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ConfigFromJson(r.Body)}, nil } } // ReloadConfig will reload the config.json file from disk. Properties // requiring a server restart will still need a server restart. You must // have the system admin role to call this method. It will return status=OK // if it's successfully reloaded the config file, otherwise check the returned error. func (c *Client) ReloadConfig() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/reload_config", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) InvalidateAllCaches() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/invalidate_all_caches", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) SaveConfig(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/save_config", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // RecycleDatabaseConnection will attempt to recycle the database connections. // You must have the system admin role to call this method. It will return status=OK // if it's successfully recycled the connections, otherwise check the returned error. func (c *Client) RecycleDatabaseConnection() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/recycle_db_conn", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) TestEmail(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/test_email", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // TestLdap will run a connection test on the current LDAP settings. // It will return the standard OK response if settings work. Otherwise // it will return an appropriate error. func (c *Client) TestLdap(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/ldap_test", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetComplianceReports() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/compliance_reports", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CompliancesFromJson(r.Body)}, nil } } func (c *Client) SaveComplianceReport(job *Compliance) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/save_compliance_report", job.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ComplianceFromJson(r.Body)}, nil } } func (c *Client) DownloadComplianceReport(id string) (*Result, *AppError) { var rq *http.Request rq, _ = http.NewRequest("GET", c.ApiUrl+"/admin/download_compliance_report/"+id, nil) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError("/admin/download_compliance_report", "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer rp.Body.Close() return nil, AppErrorFromJson(rp.Body) } else { defer closeBody(rp) return &Result{rp.Header.Get(HEADER_REQUEST_ID), rp.Header.Get(HEADER_ETAG_SERVER), rp.Body}, nil } } func (c *Client) GetTeamAnalytics(teamId, name string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/analytics/"+teamId+"/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil } } func (c *Client) GetSystemAnalytics(name string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/analytics/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil } } // Initiate immediate synchronization of LDAP users. // The synchronization will be performed asynchronously and this function will // always return OK unless you don't have permissions. // You must be the system administrator to use this function. func (c *Client) LdapSyncNow() (*Result, *AppError) { if r, err := c.DoApiPost("/admin/ldap_sync_now", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) CreateChannel(channel *Channel) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create", channel.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) CreateDirectChannel(userId string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_direct", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) CreateGroupChannel(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_group", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannel(channel *Channel) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update", channel.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannelHeader(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_header", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannelPurpose(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_purpose", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateNotifyProps(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_notify_props", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetMyChannelMembers() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/members", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil } } func (c *Client) GetChannel(id, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelDataFromJson(r.Body)}, nil } } // SCHEDULED FOR DEPRECATION IN 3.7 - use GetMoreChannelsPage instead func (c *Client) GetMoreChannels(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/more", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // GetMoreChannelsPage will return a page of open channels the user is not in based on // the provided offset and limit. Must be authenticated. func (c *Client) GetMoreChannelsPage(offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetTeamRoute()+"/channels/more/%v/%v", offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // SearchMoreChannels will return a list of open channels the user is not in, that matches // the search criteria provided. Must be authenticated. func (c *Client) SearchMoreChannels(channelSearch ChannelSearch) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/more/search", channelSearch.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // AutocompleteChannels will return a list of open channels that match the provided // string. Must be authenticated. func (c *Client) AutocompleteChannels(term string) (*Result, *AppError) { url := fmt.Sprintf("%s/channels/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } func (c *Client) GetChannelCounts(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/counts", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelCountsFromJson(r.Body)}, nil } } func (c *Client) GetChannels(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } func (c *Client) GetChannelByName(channelName string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelNameRoute(channelName), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) JoinChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/join", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) JoinChannelByName(name string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelNameRoute(name)+"/join", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) LeaveChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/leave", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) DeleteChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/delete", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) AddChannelMember(id, user_id string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = user_id if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/add", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) RemoveChannelMember(id, user_id string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = user_id if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/remove", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } // UpdateLastViewedAt will mark a channel as read. // The channelId indicates the channel to mark as read. If active is true, push notifications // will be cleared if there are unread messages. The default for active is true. // SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead func (c *Client) UpdateLastViewedAt(channelId string, active bool) (*Result, *AppError) { data := make(map[string]interface{}) data["active"] = active if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_last_viewed_at", StringInterfaceToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } // ViewChannel performs all the actions related to viewing a channel. This includes marking // the channel and the previous one as read, and marking the channel as being actively viewed. // ChannelId is required but may be blank to indicate no channel is being viewed. // PrevChannelId is optional, populate to indicate a channel switch occurred. func (c *Client) ViewChannel(params ChannelView) (bool, *ResponseMetadata) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/view", params.ToJson()); err != nil { return false, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { return c.CheckStatusOK(r), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) GetChannelStats(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/stats", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelStatsFromJson(r.Body)}, nil } } func (c *Client) GetChannelMember(channelId string, userId string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/members/"+userId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMemberFromJson(r.Body)}, nil } } // GetChannelMembersByIds will return channel member objects as an array based on the // channel id and a list of user ids provided. Must be authenticated. func (c *Client) GetChannelMembersByIds(channelId string, userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/members/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil } } func (c *Client) CreatePost(post *Post) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/create", post.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) UpdatePost(post *Post) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/update", post.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) GetPosts(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/page/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsSince(channelId string, time int64) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/since/%v", time), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsBefore(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/before/%v/%v", postid, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsAfter(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/posts/%v/after/%v/%v", postid, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPost(channelId string, postId string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get", postId), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } // GetPostById returns a post and any posts in the same thread by post id func (c *Client) GetPostById(postId string, etag string) (*PostList, *ResponseMetadata) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/%v", postId), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return PostListFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } // GetPermalink returns a post list, based on the provided channel and post ID. func (c *Client) GetPermalink(channelId string, postId string, etag string) (*PostList, *ResponseMetadata) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/pltmp/%v", postId), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return PostListFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) DeletePost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/delete", postId), ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) SearchPosts(terms string, isOrSearch bool) (*Result, *AppError) { data := map[string]interface{}{} data["terms"] = terms data["is_or_search"] = isOrSearch if r, err := c.DoApiPost(c.GetTeamRoute()+"/posts/search", StringInterfaceToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } // GetFlaggedPosts will return a post list of posts that have been flagged by the user. // The page is set by the integer parameters offset and limit. func (c *Client) GetFlaggedPosts(offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/flagged/%v/%v", offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPinnedPosts(channelId string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/pinned", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) UploadProfileFile(data []byte, contentType string) (*Result, *AppError) { return c.uploadFile(c.ApiUrl+"/users/newimage", data, contentType) } func (c *Client) UploadPostAttachment(data []byte, channelId string, filename string) (*FileUploadResponse, *AppError) { c.clearExtraProperties() body := &bytes.Buffer{} writer := multipart.NewWriter(body) if part, err := writer.CreateFormFile("files", filename); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error()) } else if _, err = io.Copy(part, bytes.NewBuffer(data)); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error()) } if part, err := writer.CreateFormField("channel_id"); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error()) } else if _, err = io.Copy(part, strings.NewReader(channelId)); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error()) } if err := writer.Close(); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.writer.app_error", nil, err.Error()) } if result, err := c.uploadFile(c.ApiUrl+c.GetTeamRoute()+"/files/upload", body.Bytes(), writer.FormDataContentType()); err != nil { return nil, err } else { return result.Data.(*FileUploadResponse), nil } } func (c *Client) uploadFile(url string, data []byte, contentType string) (*Result, *AppError) { rq, _ := http.NewRequest("POST", url, bytes.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { return nil, AppErrorFromJson(rp.Body) } else { defer closeBody(rp) return &Result{rp.Header.Get(HEADER_REQUEST_ID), rp.Header.Get(HEADER_ETAG_SERVER), FileUploadResponseFromJson(rp.Body)}, nil } } func (c *Client) GetFile(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get", "", ""); err != nil { return nil, err } else { c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFileThumbnail(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_thumbnail", "", ""); err != nil { return nil, err } else { c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFilePreview(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_preview", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFileInfo(fileId string) (*FileInfo, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_info", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return FileInfoFromJson(r.Body), nil } } func (c *Client) GetPublicLink(fileId string) (string, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_public_link", "", ""); err != nil { return "", err } else { defer closeBody(r) c.fillInExtraProperties(r) return StringFromJson(r.Body), nil } } func (c *Client) UpdateUser(user *User) (*Result, *AppError) { if r, err := c.DoApiPost("/users/update", user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserRoles(userId string, roles string) (*Result, *AppError) { data := make(map[string]string) data["new_roles"] = roles if r, err := c.DoApiPost(c.GetUserRequiredRoute(userId)+"/update_roles", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) UpdateTeamRoles(userId string, roles string) (*Result, *AppError) { data := make(map[string]string) data["new_roles"] = roles data["user_id"] = userId if r, err := c.DoApiPost(c.GetTeamRoute()+"/update_member_roles", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AttachDeviceId(deviceId string) (*Result, *AppError) { data := make(map[string]string) data["device_id"] = deviceId if r, err := c.DoApiPost("/users/attach_device", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateActive(userId string, active bool) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = userId data["active"] = strconv.FormatBool(active) if r, err := c.DoApiPost("/users/update_active", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserNotify(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/update_notify", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserPassword(userId, currentPassword, newPassword string) (*Result, *AppError) { data := make(map[string]string) data["current_password"] = currentPassword data["new_password"] = newPassword data["user_id"] = userId if r, err := c.DoApiPost("/users/newpassword", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) SendPasswordReset(email string) (*Result, *AppError) { data := map[string]string{} data["email"] = email if r, err := c.DoApiPost("/users/send_password_reset", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ResetPassword(code, newPassword string) (*Result, *AppError) { data := map[string]string{} data["code"] = code data["new_password"] = newPassword if r, err := c.DoApiPost("/users/reset_password", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AdminResetPassword(userId, newPassword string) (*Result, *AppError) { data := map[string]string{} data["user_id"] = userId data["new_password"] = newPassword if r, err := c.DoApiPost("/admin/reset_password", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetStatuses returns a map of string statuses using user id as the key func (c *Client) GetStatuses() (*Result, *AppError) { if r, err := c.DoApiGet("/users/status", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetStatusesByIds returns a map of string statuses using user id as the key, // based on the provided user ids func (c *Client) GetStatusesByIds(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/status/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // SetActiveChannel sets the the channel id the user is currently viewing. // The channelId key is required but the value can be blank. Returns standard // response. // SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead func (c *Client) SetActiveChannel(channelId string) (*Result, *AppError) { data := map[string]string{} data["channel_id"] = channelId if r, err := c.DoApiPost("/users/status/set_active_channel", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetMyTeam(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/me", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // GetTeamMembers will return a page of team member objects as an array paged based on the // team id, offset and limit provided. Must be authenticated. func (c *Client) GetTeamMembers(teamId string, offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v/%v", teamId, offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // GetMyTeamMembers will return an array with team member objects that the current user // is a member of. Must be authenticated. func (c *Client) GetMyTeamMembers() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/members", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // GetMyTeamsUnread will return an array with TeamUnread objects that contain the amount of // unread messages and mentions the current user has for the teams it belongs to. // An optional team ID can be set to exclude that team from the results. Must be authenticated. func (c *Client) GetMyTeamsUnread(teamId string) (*Result, *AppError) { endpoint := "/teams/unread" if teamId != "" { endpoint += fmt.Sprintf("?id=%s", url.QueryEscape(teamId)) } if r, err := c.DoApiGet(endpoint, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamsUnreadFromJson(r.Body)}, nil } } // GetTeamMember will return a team member object based on the team id and user id provided. // Must be authenticated. func (c *Client) GetTeamMember(teamId string, userId string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v", teamId, userId), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMemberFromJson(r.Body)}, nil } } // GetTeamStats will return a team stats object containing the number of users on the team // based on the team id provided. Must be authenticated. func (c *Client) GetTeamStats(teamId string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/stats", teamId), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil } } // GetTeamStats will return a team stats object containing the number of users on the team // based on the team id provided. Must be authenticated. func (c *Client) GetTeamByName(teamName string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/name/%v", teamName), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil } } // GetTeamMembersByIds will return team member objects as an array based on the // team id and a list of user ids provided. Must be authenticated. func (c *Client) GetTeamMembersByIds(teamId string, userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v/members/ids", teamId), ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // RegisterApp creates a new OAuth2 app to be used with the OAuth2 Provider. On success // it returns the created app. Must be authenticated as a user. func (c *Client) RegisterApp(app *OAuthApp) (*Result, *AppError) { if r, err := c.DoApiPost("/oauth/register", app.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } // AllowOAuth allows a new session by an OAuth2 App. On success // it returns the url to be redirected back to the app which initiated the oauth2 flow. // Must be authenticated as a user. func (c *Client) AllowOAuth(rspType, clientId, redirect, scope, state string) (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/allow?response_type="+rspType+"&client_id="+clientId+"&redirect_uri="+url.QueryEscape(redirect)+"&scope="+scope+"&state="+url.QueryEscape(state), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetOAuthAppsByUser returns the OAuth2 Apps registered by the user. On success // it returns a list of OAuth2 Apps from the same user or all the registered apps if the user // is a System Administrator. Must be authenticated as a user. func (c *Client) GetOAuthAppsByUser() (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil } } // GetOAuthAppInfo lookup an OAuth2 App using the client_id. On success // it returns a Sanitized OAuth2 App. Must be authenticated as a user. func (c *Client) GetOAuthAppInfo(clientId string) (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/app/"+clientId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } // DeleteOAuthApp deletes an OAuth2 app, the app must be deleted by the same user who created it or // a System Administrator. On success returs Status OK. Must be authenticated as a user. func (c *Client) DeleteOAuthApp(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost("/oauth/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetOAuthAuthorizedApps returns the OAuth2 Apps authorized by the user. On success // it returns a list of sanitized OAuth2 Authorized Apps by the user. func (c *Client) GetOAuthAuthorizedApps() (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/authorized", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil } } // OAuthDeauthorizeApp deauthorize a user an OAuth 2.0 app. On success // it returns status OK or an AppError on fail. func (c *Client) OAuthDeauthorizeApp(clientId string) *AppError { if r, err := c.DoApiPost("/oauth/"+clientId+"/deauthorize", ""); err != nil { return err } else { defer closeBody(r) return nil } } // RegenerateOAuthAppSecret generates a new OAuth App Client Secret. On success // it returns an OAuth2 App. Must be authenticated as a user and the same user who // registered the app or a System Admin. func (c *Client) RegenerateOAuthAppSecret(clientId string) (*Result, *AppError) { if r, err := c.DoApiPost("/oauth/"+clientId+"/regen_secret", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } func (c *Client) GetAccessToken(data url.Values) (*Result, *AppError) { if r, err := c.DoPost("/oauth/access_token", data.Encode(), "application/x-www-form-urlencoded"); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AccessResponseFromJson(r.Body)}, nil } } func (c *Client) CreateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/create", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil } } func (c *Client) UpdateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/update", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil } } func (c *Client) PostToWebhook(id, payload string) (*Result, *AppError) { if r, err := c.DoPost("/hooks/"+id, payload, "application/x-www-form-urlencoded"); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) DeleteIncomingWebhook(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ListIncomingWebhooks() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/incoming/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookListFromJson(r.Body)}, nil } } func (c *Client) GetAllPreferences() (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/", "", ""); err != nil { return nil, err } else { defer closeBody(r) preferences, _ := PreferencesFromJson(r.Body) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } func (c *Client) SetPreferences(preferences *Preferences) (*Result, *AppError) { if r, err := c.DoApiPost("/preferences/save", preferences.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } func (c *Client) GetPreference(category string, name string) (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/"+category+"/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PreferenceFromJson(r.Body)}, nil } } func (c *Client) GetPreferenceCategory(category string) (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/"+category, "", ""); err != nil { return nil, err } else { defer closeBody(r) preferences, _ := PreferencesFromJson(r.Body) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } // DeletePreferences deletes a list of preferences owned by the current user. If successful, // it will return status=ok. Otherwise, an error will be returned. func (c *Client) DeletePreferences(preferences *Preferences) (bool, *AppError) { if r, err := c.DoApiPost("/preferences/delete", preferences.ToJson()); err != nil { return false, err } else { return c.CheckStatusOK(r), nil } } func (c *Client) CreateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/create", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) UpdateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/update", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) DeleteOutgoingWebhook(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ListOutgoingWebhooks() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/outgoing/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookListFromJson(r.Body)}, nil } } func (c *Client) RegenOutgoingWebhookToken(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/regen_token", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) MockSession(sessionToken string) { c.AuthToken = sessionToken c.AuthType = HEADER_BEARER } func (c *Client) GetClientLicenceConfig(etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/license/client_config", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetInitialLoad() (*Result, *AppError) { if r, err := c.DoApiGet("/users/initial_load", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), InitialLoadFromJson(r.Body)}, nil } } // ListEmoji returns a list of all user-created emoji for the server. func (c *Client) ListEmoji() ([]*Emoji, *AppError) { if r, err := c.DoApiGet(c.GetEmojiRoute()+"/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return EmojiListFromJson(r.Body), nil } } // CreateEmoji will save an emoji to the server if the current user has permission // to do so. If successful, the provided emoji will be returned with its Id field // filled in. Otherwise, an error will be returned. func (c *Client) CreateEmoji(emoji *Emoji, image []byte, filename string) (*Emoji, *AppError) { c.clearExtraProperties() body := &bytes.Buffer{} writer := multipart.NewWriter(body) if part, err := writer.CreateFormFile("image", filename); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error()) } else if _, err = io.Copy(part, bytes.NewBuffer(image)); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error()) } if err := writer.WriteField("emoji", emoji.ToJson()); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.emoji.app_error", nil, err.Error()) } if err := writer.Close(); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.writer.app_error", nil, err.Error()) } rq, _ := http.NewRequest("POST", c.ApiUrl+c.GetEmojiRoute()+"/create", body) rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if r, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.connecting.app_error", nil, err.Error()) } else if r.StatusCode >= 300 { return nil, AppErrorFromJson(r.Body) } else { defer closeBody(r) c.fillInExtraProperties(r) return EmojiFromJson(r.Body), nil } } // DeleteEmoji will delete an emoji from the server if the current user has permission // to do so. If successful, it will return status=ok. Otherwise, an error will be returned. func (c *Client) DeleteEmoji(id string) (bool, *AppError) { data := map[string]string{"id": id} if r, err := c.DoApiPost(c.GetEmojiRoute()+"/delete", MapToJson(data)); err != nil { return false, err } else { defer closeBody(r) c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } // GetCustomEmojiImageUrl returns the API route that can be used to get the image used by // the given emoji. func (c *Client) GetCustomEmojiImageUrl(id string) string { return c.GetEmojiRoute() + "/" + id } // Uploads a x509 base64 Certificate or Private Key file to be used with SAML. // data byte array is required and needs to be a Multi-Part with 'certificate' as the field name // contentType is also required. Returns nil if succesful, otherwise returns an AppError func (c *Client) UploadCertificateFile(data []byte, contentType string) *AppError { url := c.ApiUrl + "/admin/add_certificate" rq, _ := http.NewRequest("POST", url, bytes.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { return AppErrorFromJson(rp.Body) } else { defer closeBody(rp) c.fillInExtraProperties(rp) return nil } } // Removes a x509 base64 Certificate or Private Key file used with SAML. // filename is required. Returns nil if successful, otherwise returns an AppError func (c *Client) RemoveCertificateFile(filename string) *AppError { if r, err := c.DoApiPost("/admin/remove_certificate", MapToJson(map[string]string{"filename": filename})); err != nil { return err } else { defer closeBody(r) c.fillInExtraProperties(r) return nil } } // Checks if the x509 base64 Certificates and Private Key files used with SAML exists on the file system. // Returns a map[string]interface{} if successful, otherwise returns an AppError. Must be System Admin authenticated. func (c *Client) SamlCertificateStatus(filename string) (map[string]interface{}, *AppError) { if r, err := c.DoApiGet("/admin/remove_certificate", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return StringInterfaceFromJson(r.Body), nil } } // GetWebrtcToken if Successful returns a map with a valid token, stun server and turn server with credentials to use with // the Mattermost WebRTC service, otherwise returns an AppError. Must be authenticated user. func (c *Client) GetWebrtcToken() (map[string]string, *AppError) { if r, err := c.DoApiPost("/webrtc/token", ""); err != nil { return nil, err } else { defer closeBody(r) return MapFromJson(r.Body), nil } } // GetFileInfosForPost returns a list of FileInfo objects for a given post id, if successful. // Otherwise, it returns an error. func (c *Client) GetFileInfosForPost(channelId string, postId string, etag string) ([]*FileInfo, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get_file_infos", postId), "", etag); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return FileInfosFromJson(r.Body), nil } } // Saves an emoji reaction for a post in the given channel. Returns the saved reaction if successful, otherwise returns an AppError. func (c *Client) SaveReaction(channelId string, reaction *Reaction) (*Reaction, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/save", reaction.PostId), reaction.ToJson()); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return ReactionFromJson(r.Body), nil } } // Removes an emoji reaction for a post in the given channel. Returns nil if successful, otherwise returns an AppError. func (c *Client) DeleteReaction(channelId string, reaction *Reaction) *AppError { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/delete", reaction.PostId), reaction.ToJson()); err != nil { return err } else { defer closeBody(r) c.fillInExtraProperties(r) return nil } } // Lists all emoji reactions made for the given post in the given channel. Returns a list of Reactions if successful, otherwise returns an AppError. func (c *Client) ListReactions(channelId string, postId string) ([]*Reaction, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions", postId), "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return ReactionsFromJson(r.Body), nil } } // Updates the user's roles in the channel by replacing them with the roles provided. func (c *Client) UpdateChannelRoles(channelId string, userId string, roles string) (map[string]string, *ResponseMetadata) { data := make(map[string]string) data["new_roles"] = roles data["user_id"] = userId if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_member_roles", MapToJson(data)); err != nil { metadata := ResponseMetadata{Error: err} if r != nil { metadata.StatusCode = r.StatusCode } return nil, &metadata } else { defer closeBody(r) return MapFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) PinPost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/pin", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) UnpinPost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/unpin", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } }
agpl-3.0
MayOneUS/victorykit
spec/models/queries/signatures_export_spec.rb
963
require 'spec_helper' describe Queries::SignaturesExport do subject { Queries::SignaturesExport.new(petition_id: petition_id) } let(:petition_id) { '1' } it "should have generate some SQL" do subject.sql.should start_with("SELECT") end context "with objects" do let(:petition) { FactoryGirl.create(:petition) } let(:petition_id) { petition.id } let!(:signature) { FactoryGirl.create(:signature, petition: petition) } before(:each) do @result = "" subject.as_csv_stream.each do |chunk| @result << chunk end end context "when parsed" do before(:each) do @parsed = CSV.parse(@result) end describe "header" do let(:header) { @parsed[0] } specify{ header.should include("email")} end describe "first row" do let(:first_row) { @parsed[1] } specify{ first_row.should include(signature.email)} end end end end
agpl-3.0
raesjo/SKIRTcorona
SkirtMakeUp/SubItemPropertyWizardPane.cpp
3696
/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include "SubItemPropertyWizardPane.hpp" #include "ItemListPropertyHandler.hpp" #include "SimulationItemDiscovery.hpp" #include "SimulationItemTools.hpp" #include "SimulationItem.hpp" #include <QVBoxLayout> #include <QLabel> #include <QRadioButton> #include <QButtonGroup> #include <QVariant> using namespace SimulationItemDiscovery; //////////////////////////////////////////////////////////////////// SubItemPropertyWizardPane::SubItemPropertyWizardPane(PropertyHandlerPtr handler, QObject* target) : PropertyWizardPane(handler, target) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // create the layout so that we can add stuff one by one auto layout = new QVBoxLayout; // add the question layout->addWidget(new QLabel("Select one of the following options for item #" + QString::number(selectedIndex()+1) + " in " + hdlr->title() + " list:")); // determine the current and default item types QByteArray currentType = itemType(hdlr->value()[selectedIndex()]); QByteArray defaultType = hdlr->hasDefaultValue() ? hdlr->defaultItemType() : ""; // make a button group to contain the radio buttons reflecting the possible choices auto buttonGroup = new QButtonGroup; // add the choices for (auto choiceType : SimulationItemTools::allowedDescendants(hdlr->baseType(),hdlr->target())) { auto choiceTitle = title(choiceType); if (!choiceTitle.isEmpty()) choiceTitle.replace(0, 1, choiceTitle[0].toUpper()); if (SimulationItemDiscovery::inherits(choiceType,defaultType)) choiceTitle += " [default]"; auto choiceButton = new QRadioButton(choiceTitle); choiceButton->setFocusPolicy(Qt::NoFocus); buttonGroup->addButton(choiceButton); layout->addWidget(choiceButton); // associate the item type corresponding to this button with the button object choiceButton->setProperty("choiceType", choiceType); choiceButton->setToolTip(choiceType); // if this button corresponds to the current type, select it if (choiceType==currentType) { choiceButton->setChecked(true); emit propertyValidChanged(true); } } // connect the button group to ourselves connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(selectTypeFor(QAbstractButton*))); // finalize the layout and assign it to ourselves layout->addStretch(); setLayout(layout); } //////////////////////////////////////////////////////////////////// int SubItemPropertyWizardPane::selectedIndex() { auto hdlr = handlerCast<ItemListPropertyHandler>(); return SimulationItemTools::retrieveSelectedRow(hdlr->target(), hdlr->name()); } //////////////////////////////////////////////////////////////////// void SubItemPropertyWizardPane::selectTypeFor(QAbstractButton* button) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // update the value if needed auto newType = button->property("choiceType").toByteArray(); int index = selectedIndex(); if (itemType(hdlr->value()[index]) != newType) { hdlr->removeValueAt(index); hdlr->insertNewItemOfType(index, newType); emit propertyValueChanged(); } // signal the change emit propertyValidChanged(true); } ////////////////////////////////////////////////////////////////////
agpl-3.0
daowzq/ExtNet
ext.net.community/Ext.Net/Factory/ConfigOptions/TreeGridBooleanColumnConfigOptions.cs
2361
/******** * This file is part of Ext.NET. * * Ext.NET is free software: you can redistribute it and/or modify * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Ext.NET 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 Ext.NET. If not, see <http://www.gnu.org/licenses/>. * * * @version : 1.2.0 - Ext.NET Pro License * @author : Ext.NET, Inc. http://www.ext.net/ * @date : 2011-09-12 * @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved. * @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0. * See license.txt and http://www.ext.net/license/. * See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt ********/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using Newtonsoft.Json; namespace Ext.Net { public partial class TreeGridBooleanColumn { /// <summary> /// /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [XmlIgnore] [JsonIgnore] public override ConfigOptionsCollection ConfigOptions { get { ConfigOptionsCollection list = base.ConfigOptions; list.Add("xType", new ConfigOption("xType", new SerializationOptions("xtype"), null, this.XType )); list.Add("falseText", new ConfigOption("falseText", null, "false", this.FalseText )); list.Add("trueText", new ConfigOption("trueText", null, "true", this.TrueText )); list.Add("undefinedText", new ConfigOption("undefinedText", null, "&#160;", this.UndefinedText )); return list; } } } }
agpl-3.0
telefonicaid/fiware-tidoop
tidoop-hadoop-ext/src/main/java/com/telefonica/iot/tidoop/apiext/utils/CKANMapReduceExample.java
6139
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-tidoop (FI-WARE project). * * fiware-tidoop is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * fiware-tidoop 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 fiware-tidoop. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with * francisco.romerobueno at telefonica dot com */ package com.telefonica.iot.tidoop.apiext.utils; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANInputFormat; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANOutputFormat; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * * @author frb */ public final class CKANMapReduceExample extends Configured implements Tool { /** * Constructor. It is private since utility classes should not have a public or default constructor. */ private CKANMapReduceExample() { } // CKANMapReduceTest /** * Mapper class. It receives a CKAN record pair (Object key, Text ckanRecord) and returns a (Text globalKey, * IntWritable recordLength) pair about a common global key and the length of the record. */ public static class RecordSizeGetter extends Mapper<Object, Text, Text, IntWritable> { private final Text globalKey = new Text("size"); private final IntWritable recordLength = new IntWritable(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { recordLength.set(value.getLength()); context.write(globalKey, recordLength); } // map } // RecordSizeGetter /** * Reducer class. It receives a list of (Text globalKey, IntWritable length) pairs and computes the sum of all the * lengths, producing a final (Text globalKey, IntWritable totalLength). */ public static class RecordSizeAdder extends Reducer<Text, IntWritable, Text, IntWritable> { private final IntWritable totalLength = new IntWritable(); @Override public void reduce(Text globalKey, Iterable<IntWritable> recordLengths, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : recordLengths) { sum += val.get(); } // for totalLength.set(sum); context.write(globalKey, totalLength); } // reduce } // RecordSizeAdder /** * Main class. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new CKANMapReduceExample(), args); System.exit(res); } // main @Override public int run(String[] args) throws Exception { // check the number of arguments, show the usage if it is wrong if (args.length != 7) { showUsage(); return -1; } // if // get the arguments String ckanHost = args[0]; String ckanPort = args[1]; boolean sslEnabled = args[2].equals("true"); String ckanAPIKey = args[3]; String ckanInputs = args[4]; String ckanOutput = args[5]; String splitsLength = args[6]; // create and configure a MapReduce job Configuration conf = this.getConf(); Job job = Job.getInstance(conf, "CKAN MapReduce test"); job.setJarByClass(CKANMapReduceExample.class); job.setMapperClass(RecordSizeGetter.class); job.setCombinerClass(RecordSizeAdder.class); job.setReducerClass(RecordSizeAdder.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(CKANInputFormat.class); CKANInputFormat.setInput(job, ckanInputs); CKANInputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANInputFormat.setSplitsLength(job, splitsLength); job.setOutputFormatClass(CKANOutputFormat.class); CKANOutputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANOutputFormat.setOutputPkg(job, ckanOutput); // run the MapReduce job return job.waitForCompletion(true) ? 0 : 1; } // main private void showUsage() { System.out.println("Usage:"); System.out.println(); System.out.println("hadoop jar \\"); System.out.println(" target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" es.tid.fiware.fiwareconnectors.ckanprotocol.utils.CKANMapReduceTest \\"); System.out.println(" -libjars target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" <ckan host> \\"); System.out.println(" <ckan port> \\"); System.out.println(" <ssl enabled=true|false> \\"); System.out.println(" <ckan API key> \\"); System.out.println(" <comma-separated list of ckan inputs> \\"); System.out.println(" <ckan output package> \\"); System.out.println(" <splits length>"); } // showUsage } // CKANMapReduceTest
agpl-3.0
jbaudoux/account-invoicing
__unported__/stock_invoice_picking_incoterm/__openerp__.py
1830
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Agile Business Group sagl # (<http://www.agilebg.com>) # @author Alex Comba <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Stock Invoice Picking Incoterm", 'version': '0.1', 'category': 'Warehouse Management', 'description': """ This module adds the field incoterm to invoice and picking. In this way the user can specify the incoterm directly on these documents, with no need to refer to the incoterm of the order (which could even be missing). The module extends 'stock_invoice_picking' so that the invoices created from pickings will have the same incoterm set in the picking. """, 'author': 'Agile Business Group', 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', 'depends': [ 'stock_invoice_picking', ], 'data': [ 'account_invoice_view.xml', 'stock_view.xml', ], 'test': [ 'test/invoice_picking_incoterm.yml', ], 'installable': False }
agpl-3.0
fqqb/yamcs
yamcs-core/src/main/java/org/yamcs/parameter/FloatValue.java
767
package org.yamcs.parameter; import org.yamcs.protobuf.Yamcs.Value.Type; public class FloatValue extends Value { final float v; public FloatValue(float v) { this.v = v; } @Override public Type getType() { return Type.FLOAT; } @Override public float getFloatValue() { return v; } @Override public double toDouble() { return v; } @Override public int hashCode() { return Float.hashCode(v); } public boolean equals(Object obj) { return (obj instanceof FloatValue) && (Float.floatToIntBits(((FloatValue) obj).v) == Float.floatToIntBits(v)); } @Override public String toString() { return Float.toString(v); } }
agpl-3.0
befair/gasistafelice
gasistafelice/rest/views/blocks/transactions.py
6479
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy from django.core import urlresolvers from django.http import HttpResponse, HttpResponseServerError from flexi_auth.models import ObjectWithContext from rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction, CREATE_CSV from consts import VIEW_CONFIDENTIAL, CONFIDENTIAL_VERBOSE_HTML, CASH from gf.base.templatetags.accounting_tags import human_readable_account_csv,human_readable_kind, signed_ledger_entry_amount from django.template.loader import render_to_string import datetime, csv import cStringIO as StringIO #from simple_accounting.models import economic_subject, AccountingDescriptor #from simple_accounting.models import account_type #from simple_accounting.exceptions import MalformedTransaction #from simple_accounting.models import AccountingProxy #from simple_accounting.utils import register_transaction, register_simple_transaction #from gf.base.accounting import PersonAccountingProxy from lib.shortcuts import render_to_xml_response, render_to_context_response #------------------------------------------------------------------------------# # # #------------------------------------------------------------------------------# #OLD: ENCODING = "iso-8859-1" class Block(BlockSSDataTables): BLOCK_NAME = "transactions" BLOCK_DESCRIPTION = _("Economic transactions") BLOCK_VALID_RESOURCE_TYPES = ["gas", "supplier", "pact"] COLUMN_INDEX_NAME_MAP = { 0: 'id', 1: 'transaction__date', 2: '', 3: '', 4: 'amount', 5: 'transaction__description', } #WAS 2: 'transaction__issuer', #WAS 3: 'transaction__source', #WAS 3: 'transaction__kind', --> FIXME: In case of translation the search does not operate correctly def __init__(self, *args, **kw): super(Block, self).__init__(*args, **kw) # Default start closed. Mainly for GAS -> Accounting tab ("Conto") self.start_open = False def _check_permission(self, request): if request.resource.gas: return request.user.has_perm( CASH, obj=ObjectWithContext(request.resource.gas) ) else: return True def _get_resource_list(self, request): #Accounting.LedgerEntry or Transactions return request.resource.economic_movements def get_response(self, request, resource_type, resource_id, args): """Check for confidential access permission and call superclass if needed""" if not self._check_permission(request): return render_to_xml_response( "blocks/table_html_message.xml", { 'msg' : CONFIDENTIAL_VERBOSE_HTML } ) if args == CREATE_CSV: return self._create_csv(request) return super(Block, self).get_response(request, resource_type, resource_id, args) #TODO: Filter grid by # Date From --> To # Kind iof transctions: can be checkbox list multiselect # Subject: Radio or multiple checkbox onto values [GAS borselino, GASMemmbers, Suppliers] # def options_response(self, request, resource_type, resource_id): # """Get options for transaction block. # WARNING: call to this method doesn't pass through get_response # so you have to reset self.request and self.resource attribute if you want # """ # self.request = request # self.resource = request.resource # fields = [] # #DATE FROM # fields.append({ # 'field_type' : 'datetime', # 'field_label' : 'from date', # 'field_name' : 'from', # 'field_values' : [{ 'value' : '22/09/2012', 'selected' : ''}] # }) # #DATE TO # fields.append({ # 'field_type' : 'datetime', # 'field_label' : 'to date', # 'field_name' : 'to', # 'field_values' : [{ 'value' : '28/09/2012', 'label' : 'labelvalue', 'selected' : 'sel'}] # }) # ctx = { # 'block_name' : self.description, # 'fields': fields, # } # #Can use html template loader # return render_to_xml_response('eco-options.xml', ctx) def _get_user_actions(self, request): user_actions = [] resource_type = request.resource.resource_type if self._check_permission(request): user_actions += [ ResourceBlockAction( block_name = self.BLOCK_NAME, resource = request.resource, name=CREATE_CSV, verbose_name=_("Create CSV"), popup_form=False, method="OPENURL", ), ] return user_actions def _create_csv(self, request): """ Create CSV of this block transactions #MATTEO TOREMOVE: lascio la prima implementazione (da levare ovviamente dall'integrazione) come monito a me stesso --> kiss, kiss e ancora kiss !! #NOTA: eliminare nell'integrazione tutte le righe commentate con #OLD: """ headers = [_(u'Id'), _(u'Data'), _(u'Account'), _(u'Kind'), _(u'Cash amount'), _(u'Description')] records = self._get_resource_list(request) csvfile = StringIO.StringIO() writer = csv.writer(csvfile, delimiter=';',quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(headers) for res in self._get_resource_list(request): writer.writerow([res.pk, '{0:%a %d %b %Y %H:%M}'.format(res.date), human_readable_account_csv(res.account), human_readable_kind(res.transaction.kind), signed_ledger_entry_amount(res), res.transaction.description.encode("utf-8", "ignore") ]) csv_data = csvfile.getvalue() if not csv_data: rv = HttpResponseServerError(_('Report not generated')) else: response = HttpResponse(csv_data, content_type='text/csv') filename = "%(res)s_%(date)s.csv" % { 'res': request.resource, 'date' : '{0:%Y%m%d_%H%M}'.format(datetime.datetime.now()) } response['Content-Disposition'] = "attachment; filename=" + filename rv = response return rv
agpl-3.0
BCJonesey/CDB3
test/unit/helpers/currencies_helper_test.rb
77
require 'test_helper' class CurrenciesHelperTest < ActionView::TestCase end
agpl-3.0
kaltura/server
alpha/apps/kaltura/lib/events/interfaces/IKalturaMultiDeferredEvent.php
330
<?php /** * Interface denoting an event is a deferred event that should be raised only at the end of the multirequest * * @package Core * @subpackage events */ interface IKalturaMultiDeferredEvent { /** * @param array $partnerCriteriaParams */ public function setPartnerCriteriaParams(array $partnerCriteriaParams); }
agpl-3.0
Kagiu/Coherence
src/main/java/org/tasgoon/coherence/client/CohereUndoer.java
3832
package org.tasgoon.coherence.client; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FileUtils; import org.tasgoon.coherence.common.Library; import org.tasgoon.coherence.ziputils.ZipUtility; import joptsimple.OptionParser; import joptsimple.OptionSet; public class CohereUndoer { //public final Logger logger = LogManager.getLogger("Coherence"); public String pid, ip, minecraftCmd; public boolean crashed = false; public static void main(String[] args) throws IOException, InterruptedException { OptionParser parser = new OptionParser("i:p:c::"); /*OptionSpec<String> ip = parser.accepts("ip", "The previous IP Minecraft was connected to").withRequiredArg(); OptionSpec<String> pid = parser.accepts("pid", "PID of the minecraft process").withRequiredArg(); OptionSpec<String> cmd = parser.accepts("cmd", "The minecraft command, for crash recovery").withOptionalArg();*/ new CohereUndoer(parser.parse(args)); } public CohereUndoer(OptionSet options) throws IOException, InterruptedException { System.out.println("Starting coherence undoer"); pid = (String) options.valueOf("p"); ip = (String) options.valueOf("i"); if (options.has("c")) { crashed = true; minecraftCmd = (String) options.valueOf("c"); } System.out.println("Using command: " + getCommand()); System.out.println("Starting process kill detector"); waitForProcessEnd(); undo(); } public String getCommand() { String command; String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) command = System.getenv("windir") + "\\system32\\" + "tasklist.exe /FI \"PID eq %s\""; else command = "ps -p %s"; return String.format(command, pid); } public void waitForProcessEnd() throws IOException, InterruptedException { boolean detected = true; String line; while (detected) { detected = false; Process process = Runtime.getRuntime().exec(getCommand()); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = input.readLine()) != null) { if (line.contains(pid)) detected = true; } } } public void undo() { System.out.println("Moving files back."); File modsDir = new File("mods"); File originalModsDir = Library.getFile("coherence", "localhost", "mods"); /*//Because the reversal script is running from a file in the mods directory, I can't just remove the file. //So, I have to iterate through the folder and remove all the files save for Coherence. for (File file : cohereModsDir.listFiles()) FileUtils.deleteQuietly(file);*/ FileUtils.deleteQuietly(modsDir); for (File file : originalModsDir.listFiles()) { try { FileUtils.moveToDirectory(file, modsDir, false); } catch (IOException e) { System.err.println("Could not move file " + file.getAbsolutePath() + " back."); e.printStackTrace(); } } File config = new File("config"); File customConfig = Library.getFile("coherence", ip, "customConfig.zip"); System.out.println("Saving current configs to " + customConfig.getAbsolutePath()); ZipUtility.compressFolder(config, customConfig); System.out.println("Deleting configs from config folder"); try { FileUtils.forceDelete(config); } catch (IOException e) { System.err.println("Could not delete synchronized config files."); e.printStackTrace(); } System.out.println("Moving old configs back to main config folder"); new File("oldConfig").renameTo(config); FileUtils.deleteQuietly(new File("coherence", "localhost")); //Contains mods that were just moved back if (crashed) startMC(); } public void startMC() { try { Runtime.getRuntime().exec(minecraftCmd); } catch (IOException e) {} } }
agpl-3.0
RichardMarks/piskel
src/js/service/SelectedColorsService.js
1011
(function () { var ns = $.namespace('pskl.service'); ns.SelectedColorsService = function () { this.reset(); }; ns.SelectedColorsService.prototype.init = function () { $.subscribe(Events.PRIMARY_COLOR_SELECTED, this.onPrimaryColorUpdate_.bind(this)); $.subscribe(Events.SECONDARY_COLOR_SELECTED, this.onSecondaryColorUpdate_.bind(this)); }; ns.SelectedColorsService.prototype.getPrimaryColor = function () { return this.primaryColor_; }; ns.SelectedColorsService.prototype.getSecondaryColor = function () { return this.secondaryColor_; }; ns.SelectedColorsService.prototype.reset = function () { this.primaryColor_ = Constants.DEFAULT_PEN_COLOR; this.secondaryColor_ = Constants.TRANSPARENT_COLOR; }; ns.SelectedColorsService.prototype.onPrimaryColorUpdate_ = function (evt, color) { this.primaryColor_ = color; }; ns.SelectedColorsService.prototype.onSecondaryColorUpdate_ = function (evt, color) { this.secondaryColor_ = color; }; })();
agpl-3.0
Murima/asset-mgmt
resources/lang/fi/general.php
8191
<?php return [ 'accessories' => 'Accessories', 'activated' => 'Aktivoitu', 'accessory' => 'Accessory', 'accessory_report' => 'Accessory Report', 'action' => 'Toiminto', 'activity_report' => 'Activity Report', 'address' => 'Osoite', 'admin' => 'Ylläpitäjä', 'add_seats' => 'Added seats', 'all_assets' => 'Kaikki Laitteet', 'all' => 'Kaikki', 'archived' => 'Arkistoitu', 'asset_models' => 'Laitemallit', 'asset' => 'Laite', 'asset_report' => 'Laiteraportti', 'asset_tag' => 'Laitetunnus', 'assets_available' => 'laitetta vapaana', 'assets' => 'Laitteet', 'avatar_delete' => 'Poista käyttäjäkuva', 'avatar_upload' => 'Lähetä Käyttäjäkuva', 'back' => 'Edellinen', 'bad_data' => 'Nothing found. Maybe bad data?', 'bulk_checkout' => 'Bulk Checkout', 'cancel' => 'Peruuta', 'categories' => 'Kategoriat', 'category' => 'Kategoria', 'changeemail' => 'Muuta Email-osoite', 'changepassword' => 'Muuta Salasana', 'checkin' => 'Palauta', 'checkin_from' => 'Checkin from', 'checkout' => 'Luovuta', 'city' => 'Kaupunki', 'companies' => 'Yritykset', 'company' => 'Yritys', 'component' => 'Komponentti', 'components' => 'Komponentit', 'consumable' => 'Consumable', 'consumables' => 'Consumables', 'country' => 'Maa', 'create' => 'Luo Uusi', 'created' => 'Item Created', 'created_asset' => 'laite luotu', 'created_at' => 'Luontiaika', 'currency' => '€', // this is deprecated 'current' => 'Käytössä Olevat', 'custom_report' => 'Muokattu Laiteraportti', 'dashboard' => 'Hallintasivu', 'date' => 'Päivä', 'debug_warning' => 'Warning!', 'debug_warning_text' => 'This application is running in production mode with debugging enabled. This can expose sensitive data if your application is accessible to the outside world. Disable debug mode by setting the <code>APP_DEBUG</code> value in your <code>.env</code> file to <code>false</code>.', 'delete' => 'Poista', 'deleted' => 'Poistettu', 'delete_seats' => 'Deleted Seats', 'deployed' => 'Käyttöönotettu', 'depreciation_report' => 'Poistoraportti', 'download' => 'Lataa', 'depreciation' => 'Poistoluokka', 'editprofile' => 'Muokkaa Profiilia', 'eol' => 'Elinikä', 'email_domain' => 'Email Domain', 'email_format' => 'Email Format', 'email_domain_help' => 'This is used to generate email addresses when importing', 'filastname_format' => 'First Initial Last Name ([email protected])', 'firstname_lastname_format' => 'First Name Last Name ([email protected])', 'first' => 'Ensimmäinen', 'first_name' => 'Etunimi', 'first_name_format' => 'First Name ([email protected])', 'file_name' => 'Tiedosto', 'file_uploads' => 'Tiedostolataus', 'generate' => 'Luo', 'groups' => 'Ryhmät', 'gravatar_email' => 'Gravatarin Email-osoite', 'history' => 'History', 'history_for' => 'Laitehistoria käyttäjälle', 'id' => 'Tunnus', 'image_delete' => 'Poista Kuva', 'image_upload' => 'Lähetä Kuva', 'import' => 'Tuo tiedot', 'import-history' => 'Import History', 'asset_maintenance' => 'Asset Maintenance', 'asset_maintenance_report' => 'Asset Maintenance Report', 'asset_maintenances' => 'Asset Maintenances', 'item' => 'Item', 'insufficient_permissions' => 'Insufficient permissions!', 'language' => 'Kieli', 'last' => 'Last', 'last_name' => 'Sukunimi', 'license' => 'Lisenssi', 'license_report' => 'Lisenssiraportti', 'licenses_available' => 'Vapaana olevat lisenssit', 'licenses' => 'Lisenssit', 'list_all' => 'Listaa Kaikki', 'loading' => 'Ladataan', 'lock_passwords' => 'This field cannot be edited in this installation.', 'feature_disabled' => 'This feature has been disabled for the demo installation.', 'location' => 'Sijainti', 'locations' => 'Sijainnit', 'logout' => 'Kirjaudu Ulos', 'lookup_by_tag' => 'Lookup by Asset Tag', 'manufacturer' => 'Valmistaja', 'manufacturers' => 'Valmistajat', 'markdown' => 'This field allows <a href="https://help.github.com/articles/github-flavored-markdown/">Github flavored markdown</a>.', 'min_amt' => 'Min. QTY', 'min_amt_help' => 'Minimum number of items that should be available before an alert gets triggered.', 'model_no' => 'Mallinumero', 'months' => 'Kuukautta', 'moreinfo' => 'Lisätiedot', 'name' => 'Nimi', 'next' => 'Seuraava', 'new' => 'new!', 'no_depreciation' => 'Ei poistoluokkaa', 'no_results' => 'Ei tuloksia.', 'no' => 'Ei', 'notes' => 'Muistiinpanot', 'order_number' => 'Order Number', 'page_menu' => 'Showing _MENU_ items', 'pagination_info' => 'Showing _START_ to _END_ of _TOTAL_ items', 'pending' => 'Odottaa', 'people' => 'Ihmiset', 'per_page' => 'Tuloksia Per Sivu', 'previous' => 'Edellinen', 'processing' => 'Käsitellään', 'profile' => 'Profiilisi', 'purchase_cost' => 'Purchase Cost', 'purchase_date' => 'Purchase Date', 'qty' => 'KPL', 'quantity' => 'Määrä', 'ready_to_deploy' => 'Käyttöönotettavissa', 'recent_activity' => 'Viimeisin toiminta', 'remove_company' => 'Remove Company Association', 'reports' => 'Raportit', 'requested' => 'Requested', 'request_canceled' => 'Request Canceled', 'save' => 'Tallenna', 'select' => 'Valitse', 'search' => 'Etsi', 'select_category' => 'Select a Category', 'select_depreciation' => 'Select a Depreciation Type', 'select_location' => 'Valitse sijainti', 'select_manufacturer' => 'Valitse valmistaja', 'select_model' => 'Select a Model', 'select_supplier' => 'Valitse toimittaja', 'select_user' => 'Valitse käyttäjä', 'select_date' => 'Select Date', 'select_statuslabel' => 'Select Status', 'select_company' => 'Select Company', 'select_asset' => 'Select Asset', 'settings' => 'Asetukset', 'sign_in' => 'Kirjaudu sisään', 'signature' => 'Signature', 'some_features_disabled' => 'DEMO MODE: Some features are disabled for this installation.', 'site_name' => 'Sivuston Nimi', 'state' => 'Lääni', 'status_labels' => 'Tilamerkinnät', 'status' => 'Tila', 'supplier' => 'Supplier', 'suppliers' => 'Toimittajat', 'submit' => 'Submit', 'total_assets' => 'laitteita yhteensä', 'total_licenses' => 'lisenssejä yhteensä', 'total_accessories' => 'total accessories', 'total_consumables' => 'total consumables', 'type' => 'Tyyppi', 'undeployable' => 'Ei-käyttöönotettavissa', 'unknown_admin' => 'Tuntematon Ylläpitäjä', 'username_format' => 'Username Format', 'update' => 'Päivitä', 'uploaded' => 'Ladattu', 'user' => 'Käyttäjä', 'accepted' => 'hyväksytty', 'declined' => 'hylkää', 'unaccepted_asset_report' => 'Unaccepted Assets', 'users' => 'Käyttäjät', 'viewassets' => 'Näytä Käyttöönotetut Laitteet', 'website' => 'Verkkosivu', 'welcome' => 'Tervetuloa, :name', 'years' => 'vuotta', 'yes' => 'Kyllä', 'zip' => 'Postinumero', 'noimage' => 'No image uploaded or image not found.', 'token_expired' => 'Istuntosi on vanhentunut. Ole hyvä ja kirjaudu uudelleen.', ];
agpl-3.0
synapse-garden/sg-proto
vendor/github.com/go-mangos/mangos/examples/survey/survey.go
3364
// Copyright 2016 The Mangos Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use 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. // survey implements a survey example. server is a surveyor listening // socket, and clients are dialing respondent sockets. // // To use: // // $ go build . // $ url=tcp://127.0.0.1:40899 // $ ./survey server $url server & server=$! // $ ./survey client $url client0 & client0=$! // $ ./survey client $url client1 & client1=$! // $ ./survey client $url client2 & client2=$! // $ sleep 5 // $ kill $server $client0 $client1 $client2 // package main import ( "fmt" "github.com/go-mangos/mangos" "github.com/go-mangos/mangos/protocol/respondent" "github.com/go-mangos/mangos/protocol/surveyor" "github.com/go-mangos/mangos/transport/ipc" "github.com/go-mangos/mangos/transport/tcp" "os" "time" ) func die(format string, v ...interface{}) { fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...)) os.Exit(1) } func date() string { return time.Now().Format(time.ANSIC) } func server(url string) { var sock mangos.Socket var err error var msg []byte if sock, err = surveyor.NewSocket(); err != nil { die("can't get new surveyor socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on surveyor socket: %s", err.Error()) } err = sock.SetOption(mangos.OptionSurveyTime, time.Second/2) if err != nil { die("SetOption(): %s", err.Error()) } for { time.Sleep(time.Second) fmt.Println("SERVER: SENDING DATE SURVEY REQUEST") if err = sock.Send([]byte("DATE")); err != nil { die("Failed sending survey: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { break } fmt.Printf("SERVER: RECEIVED \"%s\" SURVEY RESPONSE\n", string(msg)) } fmt.Println("SERVER: SURVEY OVER") } } func client(url string, name string) { var sock mangos.Socket var err error var msg []byte if sock, err = respondent.NewSocket(); err != nil { die("can't get new respondent socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on respondent socket: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { die("Cannot recv: %s", err.Error()) } fmt.Printf("CLIENT(%s): RECEIVED \"%s\" SURVEY REQUEST\n", name, string(msg)) d := date() fmt.Printf("CLIENT(%s): SENDING DATE SURVEY RESPONSE\n", name) if err = sock.Send([]byte(d)); err != nil { die("Cannot send: %s", err.Error()) } } } func main() { if len(os.Args) > 2 && os.Args[1] == "server" { server(os.Args[2]) os.Exit(0) } if len(os.Args) > 3 && os.Args[1] == "client" { client(os.Args[2], os.Args[3]) os.Exit(0) } fmt.Fprintf(os.Stderr, "Usage: survey server|client <URL> <ARG>\n") os.Exit(1) }
agpl-3.0
mrcslws/nupic.research
projects/meta_cl/experiments/oml_regression_test.py
3610
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from copy import deepcopy from .oml_replicate import metacl_oml_replicate meta_test_test_kwargs = dict( # Setup the meta-testing phase and allow it to run. run_meta_test=True, # This resets the fast params (in this case the output layer of the OMLNetwork) reset_fast_params=True, # Results reported over 15 sampled. meta_test_sample_size=15, # Run meta-testing over 10 and 50 classes. num_meta_test_classes=[10, 50], # The best lr was chosen among the following; done separately for each number of # classes trained on. lr_sweep_range=[0.03, 0.01, 0.003, 0.001, 0.0003, 0.0001, 0.00003, 0.00001], # Run through meta-test testing 5 images at a time. No training occurs here. test_test_batch_size=60, ) # Run OML for 2000 steps to ensure meta=testing accuracy hasn't regressed. # |--------------------------------------------------------------| # | Num Classes | Meta-test test | Meta-test train | LR | # |--------------:|:-----------------|:------------------|------:| # | 10 | 0.84 ± 0.06 | 0.94 ± 0.05 | 0.003 | # | 50 | 0.75 ± 0.03 | 0.95 ± 0.01 | 0.001 | # |--------------------------------------------------------------| # oml_regression_test = deepcopy(metacl_oml_replicate) oml_regression_test.update( # The number of outer (i.e. slow) steps. epochs=2000, # Log results to wandb. wandb_args=dict( name="oml_regression_test", project="metacl", ), # Meta-testing specific arguments. **deepcopy(meta_test_test_kwargs), ) # This is meant as a quick run to ensure all functionality is fully working. # |---------------------------------------------------------------| # | Num Classes | Meta-test test | Meta-test train | LR | # |--------------:|:-----------------|:------------------|-------:| # | 10 | 0.51 ± 0.03 | 0.81 ± 0.01 | 0.001 | # |---------------------------------------------------------------| # oml_regression_test_50_epochs = deepcopy(oml_regression_test) oml_regression_test_50_epochs.update( # The number of outer (i.e. slow) steps. epochs=50, # Average over 10 meta-test runs. num_meta_testing_runs=3, num_meta_test_classes=[10], num_lr_search_runs=1, lr_sweep_range=[0.001], # Log results to wandb. wandb_args=dict( name="oml_regression_test_50_epochs", project="metacl", ), ) # ------------ # All configs. # ------------ CONFIGS = dict( oml_regression_test=oml_regression_test, oml_regression_test_50_epochs=oml_regression_test_50_epochs, )
agpl-3.0
freyes/juju
worker/stateconfigwatcher/manifold_test.go
6489
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package stateconfigwatcher_test import ( "sync" "time" "github.com/juju/names/v4" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "github.com/juju/utils/v2/voyeur" "github.com/juju/worker/v2" "github.com/juju/worker/v2/dependency" dt "github.com/juju/worker/v2/dependency/testing" gc "gopkg.in/check.v1" coreagent "github.com/juju/juju/agent" "github.com/juju/juju/controller" coretesting "github.com/juju/juju/testing" "github.com/juju/juju/worker/stateconfigwatcher" ) type ManifoldSuite struct { testing.IsolationSuite agent *mockAgent goodContext dependency.Context agentConfigChanged *voyeur.Value manifold dependency.Manifold worker worker.Worker } var _ = gc.Suite(&ManifoldSuite{}) func (s *ManifoldSuite) SetUpTest(c *gc.C) { s.IsolationSuite.SetUpTest(c) s.agent = new(mockAgent) s.agent.conf.setStateServingInfo(true) s.agent.conf.tag = names.NewMachineTag("99") s.goodContext = dt.StubContext(nil, map[string]interface{}{ "agent": s.agent, }) s.agentConfigChanged = voyeur.NewValue(0) s.manifold = stateconfigwatcher.Manifold(stateconfigwatcher.ManifoldConfig{ AgentName: "agent", AgentConfigChanged: s.agentConfigChanged, }) } func (s *ManifoldSuite) TestInputs(c *gc.C) { c.Assert(s.manifold.Inputs, jc.SameContents, []string{"agent"}) } func (s *ManifoldSuite) TestNoAgent(c *gc.C) { context := dt.StubContext(nil, map[string]interface{}{ "agent": dependency.ErrMissing, }) _, err := s.manifold.Start(context) c.Assert(err, gc.Equals, dependency.ErrMissing) } func (s *ManifoldSuite) TestNilAgentConfigChanged(c *gc.C) { manifold := stateconfigwatcher.Manifold(stateconfigwatcher.ManifoldConfig{ AgentName: "agent", }) _, err := manifold.Start(s.goodContext) c.Assert(err, gc.ErrorMatches, "nil AgentConfigChanged .+") } func (s *ManifoldSuite) TestNotMachineAgent(c *gc.C) { s.agent.conf.tag = names.NewUnitTag("foo/0") _, err := s.manifold.Start(s.goodContext) c.Assert(err, gc.ErrorMatches, "manifold can only be used with a machine or controller agent") } func (s *ManifoldSuite) TestStart(c *gc.C) { w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) checkStop(c, w) } func (s *ManifoldSuite) TestOutputBadWorker(c *gc.C) { var out bool err := s.manifold.Output(dummyWorker{}, &out) c.Check(err, gc.ErrorMatches, `in should be a \*stateconfigwatcher.stateConfigWatcher; .+`) } func (s *ManifoldSuite) TestOutputWrongType(c *gc.C) { w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) defer checkStop(c, w) var out int err = s.manifold.Output(w, &out) c.Check(err, gc.ErrorMatches, `out should be \*bool; got .+`) } func (s *ManifoldSuite) TestOutputSuccessNotStateServer(c *gc.C) { s.agent.conf.setStateServingInfo(false) w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) defer checkStop(c, w) var out bool err = s.manifold.Output(w, &out) c.Check(err, jc.ErrorIsNil) c.Check(out, jc.IsFalse) } func (s *ManifoldSuite) TestOutputSuccessStateServer(c *gc.C) { s.agent.conf.setStateServingInfo(true) w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) defer checkStop(c, w) var out bool err = s.manifold.Output(w, &out) c.Check(err, jc.ErrorIsNil) c.Check(out, jc.IsTrue) } func (s *ManifoldSuite) TestBounceOnChange(c *gc.C) { s.agent.conf.setStateServingInfo(false) w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) checkNotExiting(c, w) checkOutput := func(expected bool) { var out bool err = s.manifold.Output(w, &out) c.Assert(err, jc.ErrorIsNil) c.Check(out, gc.Equals, expected) } // Not a state server yet, initial output should be False. checkOutput(false) // Changing the config without changing the state server status - // worker should keep running and output should remain false. s.agentConfigChanged.Set(0) checkNotExiting(c, w) checkOutput(false) // Now change the config to include state serving info, worker // should bounce. s.agent.conf.setStateServingInfo(true) s.agentConfigChanged.Set(0) checkExitsWithError(c, w, dependency.ErrBounce) // Restart the worker, the output should now be true. w, err = s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) checkNotExiting(c, w) checkOutput(true) // Changing the config again without changing the state serving // info shouldn't cause the agent to exit. s.agentConfigChanged.Set(0) checkNotExiting(c, w) checkOutput(true) // Now remove the state serving info, the agent should bounce. s.agent.conf.setStateServingInfo(false) s.agentConfigChanged.Set(0) checkExitsWithError(c, w, dependency.ErrBounce) } func (s *ManifoldSuite) TestClosedVoyeur(c *gc.C) { w, err := s.manifold.Start(s.goodContext) c.Assert(err, jc.ErrorIsNil) checkNotExiting(c, w) s.agentConfigChanged.Close() c.Check(waitForExit(c, w), gc.ErrorMatches, "config changed value closed") } func checkStop(c *gc.C, w worker.Worker) { err := worker.Stop(w) c.Check(err, jc.ErrorIsNil) } func checkNotExiting(c *gc.C, w worker.Worker) { exited := make(chan bool) go func() { w.Wait() close(exited) }() select { case <-exited: c.Fatal("worker exited unexpectedly") case <-time.After(coretesting.ShortWait): // Worker didn't exit (good) } } func checkExitsWithError(c *gc.C, w worker.Worker, expectedErr error) { c.Check(waitForExit(c, w), gc.Equals, expectedErr) } func waitForExit(c *gc.C, w worker.Worker) error { errCh := make(chan error) go func() { errCh <- w.Wait() }() select { case err := <-errCh: return err case <-time.After(coretesting.LongWait): c.Fatal("timed out waiting for worker to exit") } panic("can't get here") } type mockAgent struct { coreagent.Agent conf mockConfig } func (ma *mockAgent) CurrentConfig() coreagent.Config { return &ma.conf } type mockConfig struct { coreagent.ConfigSetter tag names.Tag mu sync.Mutex ssInfoIsSet bool } func (mc *mockConfig) Tag() names.Tag { return mc.tag } func (mc *mockConfig) setStateServingInfo(isSet bool) { mc.mu.Lock() defer mc.mu.Unlock() mc.ssInfoIsSet = isSet } func (mc *mockConfig) StateServingInfo() (controller.StateServingInfo, bool) { mc.mu.Lock() defer mc.mu.Unlock() return controller.StateServingInfo{}, mc.ssInfoIsSet } type dummyWorker struct { worker.Worker }
agpl-3.0
ChrisAntaki/victorykit
app/controllers/admin/petitions_controller.rb
304
class Admin::PetitionsController < ApplicationController before_filter :require_admin def index params[:time_span] ||= 'month' respond_to do |format| format.html {} format.json { render json: PetitionsDatatable.new(view_context, PetitionReportRepository.new) } end end end
agpl-3.0
jessp01/server
plugins/audit/lib/model/AuditTrailConfig.php
560
<?php /** * Skeleton subclass for representing a row from the 'audit_trail_config' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package plugins.audit * @subpackage model */ class AuditTrailConfig extends BaseAuditTrailConfig { public function actionEnabled($action) { $actions = explode(',', $this->getActions()); return in_array($action, $actions); } } // AuditTrailConfig
agpl-3.0
s7design/otrs
Kernel/cpan-lib/Selenium/PhantomJS.pm
5870
package Selenium::PhantomJS; $Selenium::PhantomJS::VERSION = '1.11'; # ABSTRACT: Use GhostDriver without a Selenium server use Moo; use Selenium::CanStartBinary::FindBinary qw/coerce_simple_binary/; extends 'Selenium::Remote::Driver'; has '+browser_name' => ( is => 'ro', default => sub { 'phantomjs' } ); has 'binary' => ( is => 'lazy', coerce => \&coerce_simple_binary, default => sub { 'phantomjs' }, predicate => 1 ); has 'binary_port' => ( is => 'lazy', default => sub { 8910 } ); has '_binary_args' => ( is => 'lazy', builder => sub { my ($self) = @_; return ' --webdriver=127.0.0.1:' . $self->port; } ); with 'Selenium::CanStartBinary'; 1; __END__ =pod =encoding UTF-8 =head1 NAME Selenium::PhantomJS - Use GhostDriver without a Selenium server =head1 VERSION version 1.11 =head1 SYNOPSIS my $driver = Selenium::PhantomJS->new; # when you're done $driver->shutdown_binary; =head1 DESCRIPTION This class allows you to use PhantomJS via Ghostdriver without needing the JRE or a selenium server running. When you refrain from passing the C<remote_server_addr> and C<port> arguments, we will search for the phantomjs executable binary in your $PATH. We'll try to start the binary connect to it, shutting it down at the end of the test. If the binary is not found, we'll fall back to the default L<Selenium::Remote::Driver> behavior of assuming defaults of 127.0.0.1:4444 after waiting a few seconds. If you specify a remote server address, or a port, we'll assume you know what you're doing and take no additional behavior. If you're curious whether your Selenium::PhantomJS instance is using a separate PhantomJS binary, or through the selenium server, you can check the C<binary_mode> attr after instantiation. my $driver = Selenium::PhantomJS->new; print $driver->binary_mode; N.B. - if you're using Windows and you installed C<phantomjs> via C<npm install -g phantomjs>, there is a very high probability that we will _not_ close down your phantomjs binary correctly after your test. You will be able to tell if we leave around empty command windows that you didn't start yourself. The easiest way to fix this is to download PhantomJS manually from their L<website|http://phantomjs.org/download.html> and put it in your C<%PATH%>. If this is a blocking issue for you, let us know in L<Github|https://github.com/gempesaw/Selenium-Remote-Driver>; thanks! =head1 ATTRIBUTES =head2 binary Optional: specify the path to your binary. If you don't specify anything, we'll try to find it on our own via L<File::Which/which>. =head2 binary_port Optional: specify the port that we should bind to. If you don't specify anything, we'll default to the driver's default port. Since there's no a priori guarantee that this will be an open port, this is _not_ necessarily the port that we end up using - if the port here is already bound, we'll search above it until we find an open one. See L<Selenium::CanStartBinary/port> for more details, and L<Selenium::Remote::Driver/port> after instantiation to see what the actual port turned out to be. =head2 custom_args Optional: specify any additional command line arguments you'd like invoked during the binary startup. See L<Selenium::CanStartBinary/custom_args> for more information. =head2 startup_timeout Optional: specify how long to wait for the binary to start itself and listen on its port. The default duration is arbitrarily 10 seconds. It accepts an integer number of seconds to wait: the following will wait up to 20 seconds: Selenium::PhantomJS->new( startup_timeout => 20 ); See L<Selenium::CanStartBinary/startup_timeout> for more information. =head1 METHODS =head2 shutdown_binary Call this method instead of L<Selenium::Remote::Driver/quit> to ensure that the binary executable is also closed, instead of simply closing the browser itself. If the browser is still around, it will call C<quit> for you. After that, it will try to shutdown the browser binary by making a GET to /shutdown and on Windows, it will attempt to do a C<taskkill> on the binary CMD window. $self->shutdown_binary; It doesn't take any arguments, and it doesn't return anything. We do our best to call this when the C<$driver> option goes out of scope, but if that happens during global destruction, there's nothing we can do. =head1 SEE ALSO Please see those modules/websites for more information related to this module. =over 4 =item * L<Selenium::Remote::Driver|Selenium::Remote::Driver> =back =head1 BUGS Please report any bugs or feature requests on the bugtracker website https://github.com/gempesaw/Selenium-Remote-Driver/issues When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 AUTHORS Current Maintainers: =over 4 =item * Daniel Gempesaw <[email protected]> =item * Emmanuel Peroumalnaïk <[email protected]> =back Previous maintainers: =over 4 =item * Luke Closs <[email protected]> =item * Mark Stosberg <[email protected]> =back Original authors: =over 4 =item * Aditya Ivaturi <[email protected]> =back =head1 COPYRIGHT AND LICENSE Copyright (c) 2010-2011 Aditya Ivaturi, Gordon Child Copyright (c) 2014-2016 Daniel Gempesaw 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. =cut
agpl-3.0
openss7/openss7
src/java/javax/telephony/media/connection/async/Async_MediaConnectionListener.java
2435
/* * Async_MediaConnectionListener.java Version-1.4, 2002/11/22 09:26:10 -0800 (Fri) * ECTF S.410-R2 Source code distribution. * * Copyright (c) 2002, Enterprise Computer Telephony Forum (ECTF), * All Rights Reserved. * * Use and redistribution of this file is subject to a License. * For terms and conditions see: javax/telephony/media/LICENSE.HTML * * In short, you can use this source code if you keep and display * the ECTF Copyright and the License conditions. The code is supplied * "AS IS" and ECTF disclaims all warranties and liability. */ package javax.telephony.media.connection.async; import javax.telephony.media.connection.*; import javax.telephony.media.async.*; import javax.telephony.media.*; /** Transaction completion Listener for connect() and related methods. * * @author Jeff Peck * @since JTAPI-1.4 */ public interface Async_MediaConnectionListener extends MediaListener { /** * Connect complete. * <tt>event.getEventID()</tt> is one of the connection type Symbols: * <br>{<tt>ev_Bridge</tt>, <tt>ev_Join</tt>, <tt>ev_Loopback</tt>}. * <p> * <tt>event.getToken()</tt> identifies the connection: * <ul><li> * the other Group, * </li><li> * connection type, * </li><li> * dataFlow, * </li><li> * maxDataFlow. * </li></ul> * * @param event the MediaConnectionEvent that is done. */ void onConnectDone( MediaConnectionEvent event ); /** * Disconnect complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onDisconnectDone( MediaConnectionEvent event ); /** * SetDataFlow complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onSetDataFlowDone( MediaConnectionEvent event ); }
agpl-3.0
adrianbrink/tendereum
vendor/github.com/ethereumproject/go-ethereum/miner/miner.go
5441
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum 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 3 of the License, or // (at your option) any later version. // // The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // Package miner implements Ethereum block creation and mining. package miner import ( "errors" "math/big" "sync/atomic" "github.com/ethereumproject/go-ethereum/common" "github.com/ethereumproject/go-ethereum/core" "github.com/ethereumproject/go-ethereum/core/state" "github.com/ethereumproject/go-ethereum/core/types" "github.com/ethereumproject/go-ethereum/eth/downloader" "github.com/ethereumproject/go-ethereum/event" "github.com/ethereumproject/go-ethereum/logger" "github.com/ethereumproject/go-ethereum/logger/glog" "github.com/ethereumproject/go-ethereum/pow" ) // HeaderExtra is a freeform description. var HeaderExtra []byte type Miner struct { mux *event.TypeMux worker *worker MinAcceptedGasPrice *big.Int threads int coinbase common.Address mining int32 eth core.Backend pow pow.PoW canStart int32 // can start indicates whether we can start the mining operation shouldStart int32 // should start indicates whether we should start after sync } func New(eth core.Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner { miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(config, common.Address{}, eth), canStart: 1} go miner.update() return miner } // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks // and halt your mining operation for as long as the DOS continues. func (self *Miner) update() { events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{}) out: for ev := range events.Chan() { switch ev.Data.(type) { case downloader.StartEvent: atomic.StoreInt32(&self.canStart, 0) if self.Mining() { self.Stop() atomic.StoreInt32(&self.shouldStart, 1) glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation") } case downloader.DoneEvent, downloader.FailedEvent: shouldStart := atomic.LoadInt32(&self.shouldStart) == 1 atomic.StoreInt32(&self.canStart, 1) atomic.StoreInt32(&self.shouldStart, 0) if shouldStart { self.Start(self.coinbase, self.threads) } // unsubscribe. we're only interested in this event once events.Unsubscribe() // stop immediately and ignore all further pending events break out } } } func (m *Miner) SetGasPrice(price *big.Int) error { if price == nil { return nil } if m.MinAcceptedGasPrice != nil && price.Cmp(m.MinAcceptedGasPrice) == -1 { priceTooLowError := errors.New("Gas price lower than minimum allowed.") return priceTooLowError } m.worker.setGasPrice(price) return nil } func (self *Miner) Start(coinbase common.Address, threads int) { atomic.StoreInt32(&self.shouldStart, 1) self.threads = threads self.worker.coinbase = coinbase self.coinbase = coinbase if atomic.LoadInt32(&self.canStart) == 0 { glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)") return } atomic.StoreInt32(&self.mining, 1) for i := 0; i < threads; i++ { self.worker.register(NewCpuAgent(i, self.pow)) } mlogMinerStart.AssignDetails( coinbase.Hex(), threads, ).Send(mlogMiner) glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents)) self.worker.start() self.worker.commitNewWork() } func (self *Miner) Stop() { self.worker.stop() atomic.StoreInt32(&self.mining, 0) atomic.StoreInt32(&self.shouldStart, 0) if logger.MlogEnabled() { mlogMinerStop.AssignDetails( self.coinbase.Hex(), self.threads, ).Send(mlogMiner) } } func (self *Miner) Register(agent Agent) { if self.Mining() { agent.Start() } self.worker.register(agent) } func (self *Miner) Unregister(agent Agent) { self.worker.unregister(agent) } func (self *Miner) Mining() bool { return atomic.LoadInt32(&self.mining) > 0 } func (self *Miner) HashRate() (tot int64) { tot += self.pow.GetHashrate() // do we care this might race? is it worth we're rewriting some // aspects of the worker/locking up agents so we can get an accurate // hashrate? for agent := range self.worker.agents { tot += agent.GetHashRate() } return } // Pending returns the currently pending block and associated state. func (self *Miner) Pending() (*types.Block, *state.StateDB) { return self.worker.pending() } func (self *Miner) SetEtherbase(addr common.Address) { self.coinbase = addr self.worker.setEtherbase(addr) }
agpl-3.0
baloo/shinken
contrib/ui/mockups/htdocs/css/forms.css
5862
form { clear: both; margin-right: 20px; padding: 0; width: 95%; } fieldset { border: 1px solid #ccc; margin-bottom: 1em; padding: 16px 20px; } fieldset legend { background:#fff; color: #e32; font-size: 160%; font-weight: bold; } fieldset fieldset { margin-top: 0px; margin-bottom: 20px; padding: 16px 10px; } fieldset fieldset legend { font-size: 120%; font-weight: normal; } fieldset fieldset div { clear: left; margin: 0 20px; } form div { clear: both; margin-bottom: 1em; padding: .5em; vertical-align: text-top; } form .input { color: #444; } form .required { font-weight: bold; } form .required label:after { color: #e32; content: '*'; display:inline; } form div.submit { border: 0; clear: both; margin-top: 10px; } label { display: block; font-size: 110%; margin-bottom:3px; } input, textarea { clear: both; font-size: 140%; font-family: "frutiger linotype", "lucida grande", "verdana", sans-serif; padding: 1%; width:98%; } select { clear: both; font-size: 120%; vertical-align: text-bottom; } select[multiple=multiple] { width: 100%; } option { font-size: 120%; padding: 0 3px; } input[type=checkbox] { clear: left; float: left; margin: 0px 6px 7px 2px; width: auto; } div.checkbox label { display: inline; } input[type=radio] { float:left; width:auto; margin: 0 3px 7px 0; } div.radio label { margin: 0 0 6px 20px; } input[type=submit] { display: inline; font-size: 110%; width: auto; } form .submit input[type=submit] { background:#62af56; background: -webkit-gradient(linear, left top, left bottom, from(#a8ea9c), to(#62af56)); background-image: -moz-linear-gradient(top, #a8ea9c, #62af56); border-color: #2d6324; color: #000; text-shadow: #8cee7c 0px 1px 0px; } form .submit input[type=submit]:hover { background:#4ca83d; background: -webkit-gradient(linear, left top, left bottom, from(#85e573), to(#4ca83d)); background-image: -moz-linear-gradient(top, #85e573, #4ca83d); } input, textarea { -moz-border-radius: 3px 3px 3px 3px; border: 1px solid #AAAAAA; } #### .buttons { float: left; padding-bottom: 20px; clear: both; } a.button { color: #6e6e6e; font: bold 12px Helvetica, Arial, sans-serif; text-decoration: none; padding: 7px 12px; position: relative; display: inline-block; text-shadow: 0 1px 0 #fff; -webkit-transition: border-color .218s; -moz-transition: border .218s; -o-transition: border-color .218s; transition: border-color .218s; background: #f3f3f3; background: -webkit-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1)); background: -moz-linear-gradient(linear,0% 40%,0% 70%,from(#F5F5F5),to(#F1F1F1)); border: solid 1px #dcdcdc; border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px; margin-right: 10px; } a.button:hover { color: #333; border-color: #999; -moz-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2) -webkit-box-shadow:0 2px 5px rgba(0, 0, 0, 0.2); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); } a.button:active { color: #000; border-color: #444; } a.left { -webkit-border-top-right-radius: 0; -moz-border-radius-topright: 0; border-top-right-radius: 0; -webkit-border-bottom-right-radius: 0; -moz-border-radius-bottomright: 0; border-bottom-right-radius: 0; margin: 0; } a.middle { border-radius: 0; -webkit-border-radius: 0; -moz-border-radius: 0; border-left: solid 1px #f3f3f3; margin: 0; border-left: solid 1px rgba(255, 255, 255, 0); } a.middle:hover, a.right:hover { border-left: solid 1px #999 } a.right { -webkit-border-top-left-radius: 0; -moz-border-radius-topleft: 0; border-top-left-radius: 0; -webkit-border-bottom-left-radius: 0; -moz-border-radius-bottomleft: 0; border-bottom-left-radius: 0; border-left: solid 1px #f3f3f3; border-left: solid 1px rgba(255, 255, 255, 0); } a.big { font-size: 16px; padding: 10px 15px; } a.supersize { font-size: 20px; padding: 15px 20px; } a.save { background: url(sprite.png) 10px 7px no-repeat #f3f3f3; padding-left: 30px; } a.add { background: url(sprite.png) 10px -27px no-repeat #f3f3f3; padding-left: 30px; } a.delete { background: url(sprite.png) 10px -61px no-repeat #f3f3f3; padding-left: 30px; } a.flag { background: url(sprite.png) 10px -96px no-repeat #f3f3f3; padding-left: 30px; } a.up { background: url(sprite.png) 13px -133px no-repeat #f3f3f3; width: 18px; } a.down { background: url(sprite.png) 13px -168px no-repeat #f3f3f3; width: 18px; } a.save-big { background: url(sprite.png) 15px 11px no-repeat #f3f3f3; font-size: 16px; padding: 10px 15px 10px 35px; } a.add-big { background: url(sprite.png) 15px -23px no-repeat #f3f3f3; font-size: 16px; padding: 10px 15px 10px 35px; } a.delete-big { background: url(sprite.png) 15px -57px no-repeat #f3f3f3; font-size: 16px; padding: 10px 15px 10px 35px; } a.flag-big { background: url(sprite.png) 15px -92px no-repeat #f3f3f3; font-size: 16px; padding: 10px 15px 10px 35px; } a.up-big { background: url(sprite.png) 15px -128px no-repeat #f3f3f3; width: 18px; font-size: 16px; padding: 10px 15px; } a.down-big { background: url(sprite.png) 15px -163px no-repeat #f3f3f3; width: 18px; font-size: 16px; padding: 10px 15px; }
agpl-3.0
cloudowski/abixen-platform
abixen-platform-business-intelligence-service/src/main/java/com/abixen/platform/service/businessintelligence/multivisualisation/service/DomainBuilderService.java
1441
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.abixen.platform.service.businessintelligence.multivisualisation.service; import com.abixen.platform.service.businessintelligence.multivisualisation.model.enumtype.DataValueType; import com.abixen.platform.service.businessintelligence.multivisualisation.util.*; public interface DomainBuilderService { DatabaseDataSourceBuilder newDatabaseDataSourceBuilderInstance(); FileDataSourceBuilder newFileDataSourceBuilderInstance(); DataFileBuilder newDataFileBuilderInstance(); DataSetBuilder newDataSetBuilderInstance(); DataSetSeriesBuilder newDataSetSeriesBuilderInstance(); DataSetSeriesColumnBuilder newDataSetSeriesColumnBuilderInstance(); DataSourceColumnBuilder newDataSourceColumnBuilderInstance(); DataSourceValueBuilder newDataSourceValueBuilderInstance(DataValueType dataValueType); }
lgpl-2.1
BalticPinguin/libmesh
include/error_estimation/error_estimator.h
6259
// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 #ifndef LIBMESH_ERROR_ESTIMATOR_H #define LIBMESH_ERROR_ESTIMATOR_H // Local Includes #include "libmesh/libmesh_common.h" #include "libmesh/system_norm.h" #ifdef LIBMESH_FORWARD_DECLARE_ENUMS namespace libMesh { enum ErrorEstimatorType : int; } #else #include "libmesh/enum_error_estimator_type.h" #endif // C++ includes #include <cstddef> #include <map> #include <string> #include <vector> namespace libMesh { // Forward Declarations class ErrorVector; class EquationSystems; class System; template <typename T> class NumericVector; namespace Parallel { class Communicator; } /** * This class holds functions that will estimate the error * in a finite element solution on a given mesh. These error * estimates can be useful in their own right, or may be used * to guide adaptive mesh refinement. * * \note The computed errors are stored as floats rather * than doubles since the required precision is low. * * \author Benjamin S. Kirk * \date 2003 */ class ErrorEstimator { public: /** * Constructor. Empty. Derived classes should reset error_norm as * appropriate. */ ErrorEstimator() = default; /** * Copy/move ctor, copy/move assignment operator, and destructor are * all explicitly defaulted for this simple class. */ ErrorEstimator (const ErrorEstimator &) = default; ErrorEstimator (ErrorEstimator &&) = default; ErrorEstimator & operator= (const ErrorEstimator &) = default; ErrorEstimator & operator= (ErrorEstimator &&) = default; virtual ~ErrorEstimator() = default; /** * This pure virtual function must be redefined * in derived classes to compute the error for each * active element and place it in the "error_per_cell" vector. * * If solution_vector is not nullptr, the estimator will * (if able) attempt to estimate an error in that field * instead of in system.solution. * * If estimate_parent_error is not false, the estimator will (if * able) attempt to give a consistent estimate of errors in parent * elements that would be generated by coarsening. */ virtual void estimate_error (const System & system, ErrorVector & error_per_cell, const NumericVector<Number> * solution_vector = nullptr, bool estimate_parent_error = false) = 0; /** * This virtual function can be redefined * in derived classes, but by default computes the sum of * the error_per_cell for each system in the equation_systems. * * Currently this function ignores the error_norm member variable, * and uses the function argument error_norms instead. * * This function is named estimate_errors instead of estimate_error * because otherwise C++ can get confused. */ virtual void estimate_errors (const EquationSystems & equation_systems, ErrorVector & error_per_cell, const std::map<const System *, SystemNorm> & error_norms, const std::map<const System *, const NumericVector<Number> *> * solution_vectors = nullptr, bool estimate_parent_error = false); /** * When calculating many error vectors at once, we need a data structure to * hold them all */ typedef std::map<std::pair<const System *, unsigned int>, ErrorVector *> ErrorMap; /** * This virtual function can be redefined * in derived classes, but by default it calls estimate_error * repeatedly to calculate the requested error vectors. * * Currently this function ignores the error_norm.weight() values * because it calculates each variable's error individually, unscaled. * * The user selects which errors get computed by filling a map with error * vectors: If errors_per_cell[&system][v] exists, it will be filled with the * error values in variable \p v of \p system */ virtual void estimate_errors (const EquationSystems & equation_systems, ErrorMap & errors_per_cell, const std::map<const System *, const NumericVector<Number> *> * solution_vectors = nullptr, bool estimate_parent_error = false); /** * \returns The type for the ErrorEstimator subclass. */ virtual ErrorEstimatorType type() const = 0; /** * When estimating the error in a single system, the \p error_norm * is used to control the scaling and norm choice for each variable. * Not all estimators will support all norm choices. The default * scaling is for all variables to be weighted equally. The default * norm choice depends on the error estimator. * * Part of this functionality was supported via component_scale and * sobolev_order in older libMesh versions, and a small part was * supported via component_mask in even older versions. Hopefully * the encapsulation here will allow us to avoid changing this API * again. */ SystemNorm error_norm; protected: /** * This method takes the local error contributions in * \p error_per_cell from each processor and combines * them to get the global error vector. */ void reduce_error (std::vector<ErrorVectorReal> & error_per_cell, const Parallel::Communicator & comm) const; }; } // namespace libMesh #endif // LIBMESH_ERROR_ESTIMATOR_H
lgpl-2.1
ascorbic/doctrine-tracker
tests/Ticket/DC187TestCase.php
3118
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.phpdoctrine.org>. */ /** * Doctrine_Ticket_DC187_TestCase * * @package Doctrine * @author Konsta Vesterinen <[email protected]> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @category Object Relational Mapping * @link www.phpdoctrine.org * @since 1.0 * @version $Revision$ */ class Doctrine_Ticket_DC187_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_DC187_User'; parent::prepareTables(); } public function testTest() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = '[email protected]'; $user->password = 'changeme'; $user->save(); $user->delete(); try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = '[email protected]'; $user->password = 'changeme'; $user->save(); $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = '[email protected]'; $user->password = 'changeme'; $user->save(); $this->fail(); } catch (Exception $e) { $this->pass(); } Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } } class Ticket_DC187_User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('username', 'string', 255); $this->hasColumn('email', 'string', 255); $this->hasColumn('password', 'string', 255); $this->unique( array('username', 'email'), array('where' => "deleted_at IS NULL"), false ); } public function setUp() { $this->actAs('SoftDelete'); } }
lgpl-2.1
iulian787/spack
lib/spack/spack/build_systems/xorg.py
1541
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import spack.util.url import spack.package class XorgPackage(spack.package.PackageBase): """Mixin that takes care of setting url and mirrors for x.org packages.""" #: Path of the package in a x.org mirror xorg_mirror_path = None #: List of x.org mirrors used by Spack # Note: x.org mirrors are a bit tricky, since many are out-of-sync or off. # A good package to test with is `util-macros`, which had a "recent" # release. base_mirrors = [ 'https://www.x.org/archive/individual/', 'https://mirrors.ircam.fr/pub/x.org/individual/', 'https://mirror.transip.net/xorg/individual/', 'ftp://ftp.freedesktop.org/pub/xorg/individual/', 'http://xorg.mirrors.pair.com/individual/' ] @property def urls(self): self._ensure_xorg_mirror_path_is_set_or_raise() return [ spack.util.url.join(m, self.xorg_mirror_path, resolve_href=True) for m in self.base_mirrors ] def _ensure_xorg_mirror_path_is_set_or_raise(self): if self.xorg_mirror_path is None: cls_name = type(self).__name__ msg = ('{0} must define a `xorg_mirror_path` attribute' ' [none defined]') raise AttributeError(msg.format(cls_name))
lgpl-2.1
CompEvol/beast2
src/beast/math/Binomial.java
2920
/* * Binomial.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package beast.math; /** * Binomial coefficients * * @author Andrew Rambaut * @author Alexei Drummond * @author Korbinian Strimmer * @version $Id: Binomial.java,v 1.11 2005/05/24 20:26:00 rambaut Exp $ */ public class Binomial { // // Public stuff // public static double logChoose(final int n, final int k) { return GammaFunction.lnGamma(n + 1.0) - GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0); } /** * @param n total elements * @param k chosen elements * @return Binomial coefficient n choose k */ public static double choose(double n, double k) { n = Math.floor(n + 0.5); k = Math.floor(k + 0.5); final double lchoose = GammaFunction.lnGamma(n + 1.0) - GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0); return Math.floor(Math.exp(lchoose) + 0.5); } /** * @param n # elements * @return n choose 2 (number of distinct ways to choose a pair from n elements) */ public static double choose2(final int n) { // not sure how much overhead there is with try-catch blocks // i.e. would an if statement be better? try { return choose2LUT[n]; } catch (ArrayIndexOutOfBoundsException e) { if (n < 0) { return 0; } while (maxN < n) { maxN += 1000; } initialize(); return choose2LUT[n]; } } private static void initialize() { choose2LUT = new double[maxN + 1]; choose2LUT[0] = 0; choose2LUT[1] = 0; choose2LUT[2] = 1; for (int i = 3; i <= maxN; i++) { choose2LUT[i] = (i * (i - 1)) * 0.5; } } private static int maxN = 5000; private static double[] choose2LUT; static { // initialize(); } }
lgpl-2.1
BalticPinguin/libmesh
include/systems/elem_assembly.h
2082
// The libMesh Finite Element Library. // Copyright (C) 2002-2022 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 #ifndef LIBMESH_ELEM_ASSEMBLY_H #define LIBMESH_ELEM_ASSEMBLY_H #include "libmesh/reference_counted_object.h" #include "libmesh/dense_matrix.h" namespace libMesh { class FEMContext; class System; class Node; /** * ElemAssembly provides a per-element (interior and boundary) assembly * functionality. * * \author David J. Knezevic * \date 2011 */ class ElemAssembly : public ReferenceCountedObject<ElemAssembly> { public: /** * Constructor. */ ElemAssembly () = default; /** * Destructor. */ virtual ~ElemAssembly () = default; /** * Perform the element interior assembly. */ virtual void interior_assembly(FEMContext &) { } /** * Perform the element boundary assembly. */ virtual void boundary_assembly(FEMContext &) { } /** * Get values to add to the matrix or rhs vector based on \p node. * This allows one to impose point loads or springs, for example. */ virtual void get_nodal_values(std::vector<dof_id_type>& , DenseMatrix<Number>& , DenseVector<Number>& , const System & , const Node &) { // Do nothing by default } protected: }; } #endif // LIBMESH_ELEM_ASSEMBLY_H
lgpl-2.1
SoftCreatR/WCF
wcfsetup/install/files/lib/data/devtools/missing/language/item/DevtoolsMissingLanguageItem.class.php
2209
<?php namespace wcf\data\devtools\missing\language\item; use wcf\data\DatabaseObject; use wcf\data\language\Language; use wcf\system\language\LanguageFactory; use wcf\system\WCF; use wcf\util\JSON; /** * Represents a missing language item log entry. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Devtools\Missing\Language\Item * @since 5.3 * * @property-read int $itemID unique id of the missing language item log entry * @property-read int $languageID id of the language the missing language item was requested for * @property-read string $languageItem name of the missing language item * @property-read int $lastTime timestamp of the last time the missing language item was requested * @property-read string $stackTrace stack trace of how the missing language item was requested for the last time */ class DevtoolsMissingLanguageItem extends DatabaseObject { /** * Returns the language the missing language item was requested for or `null` if the language * does not exist anymore. * * @return null|Language */ public function getLanguage() { if ($this->languageID === null) { return null; } return LanguageFactory::getInstance()->getLanguage($this->languageID); } /** * Returns the formatted stack trace of how the missing language item was requested for the * last time. * * @return string */ public function getStackTrace() { $stackTrace = JSON::decode($this->stackTrace); foreach ($stackTrace as &$stackEntry) { foreach ($stackEntry['args'] as &$stackEntryArg) { if (\gettype($stackEntryArg) === 'string') { $stackEntryArg = \str_replace(["\n", "\t"], ['\n', '\t'], $stackEntryArg); } } unset($stackEntryArg); } unset($stackEntry); return WCF::getTPL()->fetch('__devtoolsMissingLanguageItemStackTrace', 'wcf', [ 'stackTrace' => $stackTrace, ]); } }
lgpl-2.1
Arabidopsis-Information-Portal/intermine
bio/sources/araport/araport-chado-db/resources/sql/strain.sql
1744
SELECT distinct o.genus || ' ' || o.species scientific_name, o.organism_id, o.abbreviation organism_abbreviation, o.infraspecific_name , c.name organism_type, o.common_name accession_abbreviation, V.organism_name accession_original_name, VA.accession_number, H.habitat, nd.location, db.name || ':' || xr.accession accession_xref FROM organism o LEFT JOIN organism_dbxref dbx ON dbx.organism_id = o.organism_id LEFT JOIN dbxref xr ON xr.dbxref_id = dbx.dbxref_id LEFT JOIN db ON db.db_id = xr.db_id LEFT JOIN cvterm c ON c.cvterm_id = o.type_id LEFT JOIN ( SELECT op.organism_id, op.value organism_name FROM organismprop op JOIN organism o ON op.organism_id = o.organism_id JOIN cvterm opc ON opc.cvterm_id = op.type_id AND opc.name = 'original_name' ) V ON V.organism_id = o.organism_id left join ( SELECT op.organism_id, op.value accession_number, opc.name FROM organismprop op JOIN organism o ON op.organism_id = o.organism_id JOIN cvterm opc ON opc.cvterm_id = op.type_id AND opc.name = 'accession_number' ) VA on VA.organism_id = o.organism_id LEFT JOIN ( SELECT op.organism_id, op.value habitat FROM organismprop op JOIN organism o ON op.organism_id = o.organism_id JOIN cvterm opc ON opc.cvterm_id = op.type_id AND opc.name = 'habitat' ) H ON H.organism_id = o.organism_id LEFT JOIN ( SELECT ond.organism_id, ndg.description as location FROM organism o JOIN organism_nd_geolocation ond ON ond.organism_id = o.organism_id JOIN nd_geolocation ndg ON ndg.nd_geolocation_id = ond.nd_geolocation_id ) nd ON nd.organism_id = o.organism_id WHERE o.infraspecific_name IS NOT null AND o.abbreviation = 'A.thaliana'
lgpl-2.1
matthias-christen/patus
src/ch/unibas/cs/hpwc/patus/grammar/stencil2/StencilSpecificationAnalyzer.java
4059
package ch.unibas.cs.hpwc.patus.grammar.stencil2; import cetus.hir.BinaryExpression; import cetus.hir.BinaryOperator; import cetus.hir.DepthFirstIterator; import cetus.hir.Expression; import cetus.hir.IDExpression; import cetus.hir.IntegerLiteral; import cetus.hir.NameID; import ch.unibas.cs.hpwc.patus.representation.Stencil; import ch.unibas.cs.hpwc.patus.representation.StencilBundle; import ch.unibas.cs.hpwc.patus.representation.StencilNode; import ch.unibas.cs.hpwc.patus.symbolic.Symbolic; import ch.unibas.cs.hpwc.patus.util.CodeGeneratorUtil; import ch.unibas.cs.hpwc.patus.util.StringUtil; public class StencilSpecificationAnalyzer { /** * * @param bundle */ public static void normalizeStencilNodesForBoundariesAndIntial (StencilBundle bundle) { for (Stencil stencil : bundle) { for (StencilNode node : stencil.getAllNodes ()) { Expression[] rgIdx = node.getIndex ().getSpaceIndexEx (); Expression[] rgIdxNew = new Expression[rgIdx.length]; for (int i = 0; i < rgIdx.length; i++) { String strDimId = StencilSpecificationAnalyzer.getContainedDimensionIdentifier (rgIdx[i], i); if (strDimId != null) { // if an entry I contains the corresponding dimension identifier id, compute I-id // we expect this to be an integer value rgIdxNew[i] = Symbolic.simplify (new BinaryExpression (rgIdx[i].clone (), BinaryOperator.SUBTRACT, new NameID (strDimId))); if (!(rgIdxNew[i] instanceof IntegerLiteral)) { throw new RuntimeException (StringUtil.concat ("Illegal coordinate ", rgIdx[i].toString (), " in grid reference ", node.toString ()," in definition ", stencil.toString () )); } } else { // if the entry doesn't contain a dimension identifier, set the corresponding spatial index coordinate // to 0 (=> do something when the point becomes the center point), and add a constraint setting the // corresponding subdomain index (dimension identifier) to the expression of the index entry rgIdxNew[i] = new IntegerLiteral (0); node.addConstraint (new BinaryExpression (new NameID (CodeGeneratorUtil.getDimensionName (i)), BinaryOperator.COMPARE_EQ, rgIdx[i])); } } node.getIndex ().setSpaceIndex (rgIdxNew); } } } /** * Check that all the stencil nodes in the stencils of the bundle are legal, * i.e., that the spatial index has the form [x+dx, y+dy, ...]. Note that * the dimension identifiers (x, y, ...) have been subtracted already, so * the spatial index should be an array of integer numbers. * * @param bundle * The bundle to check */ public static void checkStencilNodesLegality (StencilBundle bundle) { for (Stencil stencil : bundle) for (StencilNode node : stencil) for (Expression exprIdx : node.getIndex ().getSpaceIndexEx ()) if (!(exprIdx instanceof IntegerLiteral)) throw new RuntimeException (StringUtil.concat ("Illegal grid reference", exprIdx.toString ())); // TODO: handle in parser } /** * Determines whether the expression <code>expr</code> contains a dimension * identifier corresponding to dimension <code>nDim</code>. * * @param expr * The expression to examine * @param nDim * The dimension whose identifier to detect * @return <code>true</code> iff <code>expr</code> contains a dimension * identifier corresponding to the dimension <code>nDim</code> */ public static String getContainedDimensionIdentifier (Expression expr, int nDim) { String strId = CodeGeneratorUtil.getDimensionName (nDim); String strIdAlt = CodeGeneratorUtil.getAltDimensionName (nDim); for (DepthFirstIterator it = new DepthFirstIterator (Symbolic.simplify (expr)); it.hasNext (); ) { Object o = it.next (); if (o instanceof IDExpression) { if (((IDExpression) o).getName ().equals (strId)) return strId; if (((IDExpression) o).getName ().equals (strIdAlt)) return strIdAlt; } } return null; } }
lgpl-2.1
FabienPean/sofa
modules/SofaBoundaryCondition/SurfacePressureForceField.cpp
2847
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #define SOFA_COMPONENT_FORCEFIELD_SURFACEPRESSUREFORCEFIELD_CPP #include <SofaBoundaryCondition/SurfacePressureForceField.inl> #include <sofa/core/ObjectFactory.h> #include <sofa/defaulttype/Vec3Types.h> namespace sofa { namespace component { namespace forcefield { using namespace sofa::defaulttype; SOFA_DECL_CLASS(SurfacePressureForceField) int SurfacePressureForceFieldClass = core::RegisterObject("SurfacePressure") #ifndef SOFA_FLOAT .add< SurfacePressureForceField<Vec3dTypes> >() .add< SurfacePressureForceField<Rigid3Types> >() #endif #ifndef SOFA_DOUBLE .add< SurfacePressureForceField<Vec3fTypes> >() .add< SurfacePressureForceField<Rigid3fTypes> >() #endif ; #ifndef SOFA_FLOAT template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Vec3dTypes>; template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Rigid3dTypes>; #endif #ifndef SOFA_DOUBLE template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Vec3fTypes>; template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Rigid3fTypes>; #endif } // namespace forcefield } // namespace component } // namespace sofa
lgpl-2.1
ACS-Community/ACS
LGPL/CommonSoftware/acsGUIs/AlarmSystemProfiler/src/alma/acs/alarmsystemprofiler/document/flood/FloodContainer.java
7180
/* * ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2010 * * 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 alma.acs.alarmsystemprofiler.document.flood; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Vector; import org.eclipse.jface.viewers.TableViewer; import cern.laser.client.data.Alarm; import alma.acs.alarmsystemprofiler.document.DocumentBase; import alma.acs.alarmsystemprofiler.engine.AlarmCategoryListener; import alma.acs.alarmsystemprofiler.save.TableData; /** * Count the number of floods and generate the statistics * * @author acaproni */ public class FloodContainer extends DocumentBase implements AlarmCategoryListener { public enum FloodItem { NUM_OF_FLOODS("Num. of floods",false,false), ACTUALLY_IN_FLOOD("Actually in flood", false,true), TOT_ALARMS("Tot. alarms in floods",false,false), HIGHEST_ALARMS("Highest num. of alarms in flood",false,false), AVG_ALARMS("Avg. alarms per flood",false,false), MEASURED_TIME("Monitoring time",true,false), FLOOD_TIME("Time of Alarm service in flood",true,false); /** * The name show in the first column */ public String description; /** * <code>true</code> if number represents a time value */ private final boolean isTime; /** * <code>true</code> if number represents a boolean value (0 means <code>false</code>, * all other values mean <code>true</code>) */ private final boolean isBoolean; /** * The value */ private Number value; /** * The formatter of the times */ private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.S"); /** * Constructor * * @param name The description of the value */ private FloodItem(String name, boolean isTm, boolean isBool) { this.description=name; this.isTime=isTm; this.isBoolean=isBool; value=Integer.valueOf(0); } public void setNumber(Number newValue) { value=newValue; } /** * Getter */ public Number getValue() { return value; } @Override public String toString() { if (isBoolean) { int val = value.intValue(); if (val==0) { return "No"; } else { return "Yes"; } } if (isTime) { Date date = new Date(value.longValue()); Calendar cal = Calendar.getInstance(); cal.setTime(date); int day = cal.get(Calendar.DAY_OF_MONTH)-1; synchronized (timeFormat) { if (day>0) { return ""+day+" days, "+timeFormat.format(date); } else { return timeFormat.format(date); } } } if ((value instanceof Float) || (value instanceof Double)) { double d = value.doubleValue(); return String.format("%.2f", d); } return value.toString(); } }; /** * The singleton */ private static FloodContainer singleton=null; public static FloodContainer getInstance() { if (singleton==null) { singleton = new FloodContainer(); } return singleton; } /** * Constructor */ private FloodContainer() { super("Alarm floods statistics", new String[] { "Entry", "Value" }); actualFlood=new AlarmFlood(this); } /** * The floods registered since the system started */ private final Vector<AlarmFlood> floods = new Vector<AlarmFlood>(); /** * The start time of this container in mesec */ private final long startTime=System.currentTimeMillis(); /** * The actual counter of alarm floods */ private AlarmFlood actualFlood; /** * * @return The number of alarms registered in all the floods */ public synchronized int getTotAlarmsInFloods() { int ret=0; for (AlarmFlood af: floods) { ret+=af.getAlarmsInFlood(); } ret+=actualFlood.getAlarmsInFlood(); return ret; } /** * * @return The total time the alarm system was in flood in msec */ public synchronized long getTotTimeInFloods() { long ret=0; for (AlarmFlood af: floods) { ret+=af.lengthOfFlood(); } if (actualFlood.getStartTimeOfFlood()>0) { ret+=actualFlood.lengthOfFlood(); } return ret; } /** * * @return The average number of alarms registered in all the floods */ public synchronized float getAvgAlarmsInFloods() { if (floods.size()==0) { return 0; } float ret=0; for (AlarmFlood af: floods) { ret+=af.getAlarmsInFlood(); } return ret/(float)floods.size(); } /** * * @return The highest number of alarms registered between all the floods */ public synchronized int getHighestAlarmsCountInFloods() { int ret=0; for (AlarmFlood af: floods) { if (ret<af.getAlarmsInFlood()) { ret=af.getAlarmsInFlood(); } } return ret; } /** * @return The total number of floods */ public synchronized int getNumOfFloods() { return floods.size(); } /** * @return The values of the flood to be shown in the table */ @Override public synchronized Collection<FloodItem> getNumbers() { FloodItem.AVG_ALARMS.setNumber(Float.valueOf(getAvgAlarmsInFloods())); FloodItem.FLOOD_TIME.setNumber(Long.valueOf(getTotTimeInFloods())); FloodItem.HIGHEST_ALARMS.setNumber(Integer.valueOf(getHighestAlarmsCountInFloods())); FloodItem.MEASURED_TIME.setNumber(Long.valueOf(System.currentTimeMillis()-startTime)); FloodItem.NUM_OF_FLOODS.setNumber(Integer.valueOf(getNumOfFloods())); FloodItem.TOT_ALARMS.setNumber(Integer.valueOf(getTotAlarmsInFloods())); FloodItem.ACTUALLY_IN_FLOOD.setNumber(Integer.valueOf(actualFlood.isFloodStarted()?1:0)); Vector<FloodContainer.FloodItem> ret= new Vector<FloodContainer.FloodItem>(FloodItem.values().length); for (FloodItem fi: FloodItem.values()) { ret.add(fi); } return ret; } @Override public synchronized void shutdownContainer() { super.shutdownContainer(); actualFlood.stop(); } @Override public void setTableViewer(TableViewer table) { super.setTableViewer(table); } public synchronized void doneFlood() { floods.add(actualFlood); actualFlood=new AlarmFlood(this); System.out.println("Refreshing table"); System.out.println("doneFlood done"); } @Override public synchronized void onAlarm(Alarm alarm) { actualFlood.onAlarm(alarm); } @Override public void setTableContent(TableData tData) { Collection<FloodItem> vals=getNumbers(); for (FloodItem val: vals) { String[] row = new String[2]; row[0]=val.description; row[1]=val.toString(); tData.addRowData(row); } } }
lgpl-2.1
adfernandes/pcp
src/pmdas/linux_zfs/zfs_utils.c
999
/* * Copyright (c) 2021 Red Hat. * * 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. */ #include <sys/stat.h> #include "pmapi.h" #include "libpcp.h" #include "pmda.h" #include "zfs_utils.h" char zfs_path[MAXPATHLEN]; int zfs_stats_file_check(char *fname, size_t fnamelen, const char *sname) { struct stat buffer; pmsprintf(fname, fnamelen, "%s%c%s", zfs_path, pmPathSeparator(), sname); if (stat(fname, &buffer) != 0) { pmNotifyErr(LOG_WARNING, "File does not exist: %s", fname); return 1; } return 0; }
lgpl-2.1