Beispiel #1
0
    def Invoke(cls, method, *req, **kwargs):
        try:

            def date_handler(obj):
                return (obj.isoformat() if isinstance(obj, datetime.datetime)
                        or isinstance(obj, datetime.date) else None)

            confSection = kwargs.get('confSection', 'Dubbo')
            confFile = kwargs.get('confFile', '/config/test.conf')
            host = ConfigUtil.get(confSection, 'Host', confFile)
            port = ConfigUtil.get(confSection, 'Port', confFile)
            service = ConfigUtil.get(confSection, 'Service', confFile)
            interface = ConfigUtil.get(confSection, 'Interface', confFile)
            url = host + ':' + port + '/' + service + '.' + interface

            print '\r\nInvoke Hessian Interface:\r\nURL:\t', url
            print 'Method:\t', method
            res = FormatObject(
                getattr(HessianProxy(url, timeout=60), method)(*req))
            print 'Req:\t', [FormatObject(i) for i in req]
            print 'Res:\t', json.dumps(res,
                                       default=date_handler,
                                       ensure_ascii=False)
            return res

        except Exception as e:
            print e
Beispiel #2
0
 def getresult(self):
     try:
         result = HessianProxy(self.url + self.interface)
         return_result = getattr(result, self.method)(self.interfaceparam)
         res = {'code': 0, 'result': return_result}
     except Exception as e:
         res = {'code': 1, 'result': e}
     return res
Beispiel #3
0
 def getresult(self):
     try:
         result = HessianProxy(self.url + self.interface)
         return_result = getattr(result, self.method)(self.interface_param)
         LOG.info('测试返回结果:%s' % return_result)
         res = {'code': 0, 'result': return_result}
     except Exception as e:
         LOG.info('测试失败,原因:%s' % e)
         res = {'code': 1, 'result': e}
     return res
Beispiel #4
0
    def run(self):
        service = HessianProxy(
            "http://10.103.16.147:8081/hessian/smsSendService")
        for fon in fons:
            welcomeMsg = {
                "msgTel": fon,
                "msgContent": 'welcome, ACCOUNT job monitor is running.',
                "msgType": "HOME"
            }
            welcomeJson = json.dumps(welcomeMsg)
            #inform that mission starts, inform only once
            service.sendMessage(welcomeJson)

        while True:
            #check job
            db = MySQLdb.connect('10.103.16.190',
                                 'sf_quartz',
                                 'X2qBcQ0oawr2',
                                 'sf_quartz_db',
                                 charset="utf8")
            cursor = db.cursor()
            sql = "SELECT job_name,trigger_state FROM `ACCOUNT_TRIGGERS` WHERE trigger_state = 'BLOCKED' AND next_fire_time + 60*6*1000 < UNIX_TIMESTAMP(NOW())*1000"
            cursor.execute(sql)
            rows = cursor.fetchall()
            if rows:
                print "abnormal job detected!"
                try:
                    print rows
                except:
                    pass

                for row in rows:
                    msg = "job [" + row[0] + "] state is " + row[
                        1] + ",please recover it"
                    self.sendSms(service, msg, row[0])
            else:
                print "no abnormal job currently, rest for 5mins..."

            #rest for 6 mins
            time.sleep(60 * 6)

            #clear lastsend flag
            #1.delete lastsend value=0's key
            for key in lastsend.keys():
                if lastsend.get(key) == 0:
                    lastsend.pop(key)
            #2.set all value = 0
            for key in lastsend.keys():
                lastsend[key] = 0

            #clear db
            if cursor:
                cursor.close()
            if db:
                db.close()
def hessian_client_ssl(servlet_process, support_dir):
    cert_dir = os.path.join(support_dir, 'certs')
    server_crt = os.path.join(cert_dir, 'caroot.crt')
    client_crt = os.path.join(cert_dir, 'client.crt')
    client_key = os.path.join(cert_dir, 'client.key')
    context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=server_crt)
    context.load_cert_chain(certfile=client_crt, keyfile=client_key)
    client = HessianProxy(servlet_process.https_url, version=1, context=context)
    yield client
    if getattr(client, '_client', None):
        client._client.close()
Beispiel #6
0
def InvokeHessian(service, interface, method, req, retcode='000000'):
    url = 'dubbo://10.0.23.66:20882/' + service + '.' + interface

    print('URL:\t%s' % url)

    print('Method:\t%s' % method)


    res = getattr(HessianProxy(url), method)(req)

    print('Res:\t%s' % json.dumps(res, ensure_ascii=False))
Beispiel #7
0
def InvokeHessian(service,interface,method,req,retcode='200'):
    try:
        url='http://192.168.100.35:20880/'+service+'.'+interface
        
        print 'URL:\t%s'%url
        print 'Method:\t%s'%method
        print 'Req:\t%s'%req
        res=getattr(HessianProxy(url),method)(req)
        print 'Res:\t%s'%json.dumps(res,ensure_ascii=False)
        
    except Exception,e:
        print e
 def handle(self, *args, **options):
     error = False
     message = []
     try:
         dept_list = ['780>781>6>', '780>782>2567>']
         url = CRON_ALL_USERS_API
         hr_users = []
         for dept in dept_list:
             res = HessianProxy(url,
                                timeout=300).findEmpInfoListByDepRel(dept)
             if len(res):
                 for item in res:
                     hr_users.append(item.ad)
                     try:
                         cmis_sync_user, created = DdUsers.objects.filter(
                             enable=0).get_or_create(
                                 username=item.ad,
                                 defaults={
                                     'display_name':
                                     item.displayName
                                     if item.displayName else '',
                                     'email':
                                     item.email,
                                     'enable':
                                     0,
                                     'telephone':
                                     item.phone,
                                     'username_ch':
                                     str(item.displayName[(
                                         item.displayName.rfind('_') +
                                         1):-1])
                                     if item.displayName else '',
                                 })
                         if not created:
                             cmis_sync_user.display_name = item.displayName if item.displayName else ''
                             cmis_sync_user.email = item.email
                             cmis_sync_user.enable = 0
                             cmis_sync_user.telephone = item.phone
                             cmis_sync_user.username_ch = str(
                                 item.displayName[(
                                     item.displayName.rfind('_') +
                                     1):-1]) if item.displayName else ''
                             cmis_sync_user.save()
                     except Exception, e:
                         error = True
                         message.append('error: id=%d, detail: %s' %
                                        (item['id'], str(e)))
                         break
                 message.append(stamp2str(time.time()) + ':finish')
         # 反向查询更新已离职人员状态
         DdUsers.objects.filter(enable=0).exclude(
             username__in=hr_users).update(enable=1)
Beispiel #9
0
    def proxy(self):
        url = "http://10.102.36.151:8080/hessian/orderService"
        try:
            proxy = HessianProxy(url)


#            addr='{"orderId":null,"orderSn":null,"parentOrderId":null,"parentOrderSn":null,"userId":88892059,"opencityId":0,"orderStatus":null,"consignee":null,"country":null,"province":null,"city":null,"district":null,"area":null,"areaNumber":null,"address":null,"zipCode":null,"telNumber":null,"mobile":null,"email":null,"ip":null,"bestDate":0,"isTogether":0,"bestTime":0,"shippingId":null,"sfairline":null,"invoiceId":null,"userRank":null,"favourableId":null,"payId":1,"shippingFee":0,"productAmount":null,"orderAmount":null,"discount":null,"balance":0,"couponId":null,"couponType":null,"couponMoney":0,"useIntegral":null,"integralMoney":null,"integral":null,"giftCard":null,"giftCardMoney":0,"addTime":null,"orderType":null,"projetDeliveryTime":null,"orderSource":null,"orderProducts":[{"productId":2386,"productName":null,"productSn":null,"productNum":1,"returnMoney":null,"productPrice":null,"subtotal":null,"sellPrice":null,"integral":null,"weight":null,"totalWeight":null,"giftWeight":null,"activityEntities":[],"isShow":null,"isMaster":null,"sfshipping":null,"sfairline":null,"productPic":null,"giftType":0,"stockType":null,"integralF":null,"difference":null,"productType":"0","couponId":null,"fatherId":null,"fatherNum":null,"isPresale":null,"parentId":null,"orderProductId":null,"dmDiscount":null,"giftBagBase":null,"businessModel":null,"isSell":null,"inPrice":null,"dmCode":"0","sfvMinSellNum":null,"sfvShippingTime":null,"isBook":null,"isHave":null,"merchantNumber":null,"dmDiscountActivity":null,"id":null,"orderId":null,"sellNum":null,"activeId":null,"addTime":null,"productStatus":null,"linkId":null,"couponAmout":null,"reduceAmout":null,"activityCombinations":null,"giftBag":null,"subProducts":[],"actId":null,"addId":null,"mpiecePrice":null,"couponMoney":null,"wareHouseId":null,"brandId":0,"categoryOne":0,"categoryTwo":0,"categoryThree":0,"wareHouseCode":null,"shippingTimeId":0,"shippingFee":0,"serviceFee":0,"cod":null}],"invoice":null,"dmMoney":0,"productNum":null,"totalProductNum":null,"device":12,"activityEntities":[],"totalWeight":null,"couponSn":"","isBalance":0,"isGiftCard":0,"chanDiZhiCaiPrice":0,"consigneeAddr":{"addrId":null,"userId":null,"country":null,"province":2,"city":52,"district":500,"area":3409,"address":"xcfbcxvnvbgncvxbncvbn","zipCode":null,"telNumber":"","mobile":"18512345678","email":"","receiverName":"qqq","storeCode":null},"greetCard":null,"consignorAddr":null,"senderFlag":0,"payTime":null,"senderAddrId":null,"greetCardId":null,"smsType":null,"payAmount":null,"dmCode":"","couponTypeId":null,"stopAct":[],"isList":1,"giverName":null,"giverProvince":null,"giverCity":null,"giverDistrict":null,"giverArea":null,"giverAddress":null,"giverMobile":null,"sendTime":0,"isShowTogether":null,"sfarea":null,"areaFlag":null,"moneyPaid":null,"channelName":null,"promtionChannels":2,"orderRemark":null,"vendorRemark":null,"outerId":null,"userName":null,"orderBelong":0,"temperatureType":0,"saleType":0,"orderCps":null,"storeCode":null,"orderBelongMark":null,"userMdId":null,"orderBelongMdId":null,"orderBelongHbId":null,"serviceFee":0,"orderSort":null,"pickupMode":null,"lastToHomeTime":null,"activityId":null,"groupId":null,"preSale":false,"freshOrder":false},"iscart":0}'
#            data=json.dumps(addr)
#            #print proxy.status_code
#            print proxy.createOrderByJson(data)
        except NotImplementedError:
            print 'url error'
        return proxy
Beispiel #10
0
def InvokeHessian(service,
                  interface,
                  method,
                  orderId,
                  packNum,
                  retcode='000000'):
    try:
        url = 'http://172.16.195.19:9001/' + service + '.' + interface

        print('URL:\t%s' % url)
        print('Method:\t%s' % method)
        print('Req:\t%s' % orderId)
        res = getattr(HessianProxy(url), method)(orderId, packNum)
        print('Res:\t%s' % json.dumps(res, ensure_ascii=False))

    except Exception as e:
        print(e)
Beispiel #11
0
def dubbo_api(url, interface, method, param_obj, **kwargs):
    '''
    :param url: url地址
    :param interface: 接口名称,因为这里可能还有别的服务要测,接口名不一样,这里定义成变量
    :param method: 调用哪个方法
    :param param_obj: 入参的对象
    :param kwargs: 这个用关键字参数,因为每个接口的参数都不一样,不固定,所以这里用关键字参数
    :return:
        '''
    req_param = protocol.object_factory(param_obj, **kwargs)
    #这个是用来构造二进制的入参的,也就是把入参序列化
    try:  #用try捕捉一下异常
        req_obj = HessianProxy(url + interface)
        #这个req是生成一个请求对象
        res = getattr(req_obj, method)(req_param)
        #getattr是python的内置方法,获取对象的方法,咱们从构造的请求对象里面获取到方法,然后调用,把前面生成的
        #序列化好的参数传进去,然后获取到返回的数据
    except Exception as e:
        print('有异常了,异常信息是:%s' % e)
        res = {"msg": "异常:%s" % e, "code": 300}
        #这个是自己定义的异常,如果调用出错了,就返回这个
    return res
Beispiel #12
0
def modify_contact(name, mobile, mail):
    contact_params = {'username': name, 'mobile': mobile, 'mail': mail}
    json_contact_params = json.dumps(contact_params)
    proxy = HessianProxy(url)
    res = proxy.updateContact(json_contact_params)  # 修改个人信息
    return res
Beispiel #13
0
import sys
from pyhessian.client import HessianProxy

url = "http://localhost:8080/"
# url = "http://localhost:8080/HessianServer.php"

if len(sys.argv) > 1:
    url = sys.argv[1]

proxy = HessianProxy(url)


def showMenu():
    print("Select option:")
    print("---BOOKS---------------------------------")
    print("0. all books")
    print("1. search book by [column, value]")
    print("2. insert book [title, author_id]")
    print("3. delete book [id]")
    print("4. patch book [id, column, value]")
    print("---AUTHORS-------------------------------")
    print("5. all authors")
    print("6. search author by [column, value]")
    print("7. insert author [name]")
    print("8. delete author [id]")
    print("9. patch author [id, column, value]")


def main():
    while (True):
        showMenu()
Beispiel #14
0
from pyhessian.client import HessianProxy
service = HessianProxy("http://hessian.caucho.com/test/test")
print service.replyDate_1()
Beispiel #15
0
def modify_pwd(name, pwd):
    params = {'username': name, 'password': pwd}
    json_params = json.dumps(params)
    proxy = HessianProxy(url)
    res = proxy.updatePassword(json_params)  # 修改密码
    return res
Beispiel #16
0
from pyhessian.client import HessianProxy

__author__ = 'bida'

service = HessianProxy('http://localhost:8080/HessianService')

print service.sayHello()
# List
print service.myLoveFruit()
# Dict
print type(service.myBabays())
print service.myBabays()
print service.myBabays()['daughter']
# Object,Java class
print service.getMyCar().carName
print service.getMyCar().carModel
Beispiel #17
0
 def proxy(self, paras):
     proxy = HessianProxy(self.host)
     s = "result = proxy.%s(%s)" % (self.funcname, str(paras))
     exec(s)
     exec('return result')
def hessian_auth_client(servlet_process):
    client = HessianProxy(servlet_process.http_auth_url, version=1)
    yield client
    if getattr(client, '_client', None):
        client._client.close()
from pyhessian.client import HessianProxy

ips = [
    "10.102.26.145", "10.102.26.144", "10.102.26.146", "10.102.26.143",
    "10.102.26.142", "10.102.26.141", "10.102.27.137", "10.102.27.136",
    "10.102.27.135", "10.102.27.134", "10.102.8.193", "10.102.8.192",
    "10.102.8.191", "10.102.8.190", "10.102.8.19", "10.102.8.189",
    "10.102.8.188", "10.102.8.187", "10.102.8.186", "10.102.8.185"
]
path = "http://127.0.0.1:8081/search/remoteSearcher.hessian"
params = '{"channelCodes":["HPC001"],"isreach":true,"isstock":true,"keyword":"beef","pageNo":0,"pageSize":1}'

running = 0
exception = 0
for ip in ips:
    url = path.replace("127.0.0.1", ip)
    print url
    service = HessianProxy(url)

    try:
        result = service.search(params)
        print ip + " 正常运行中..."
        running += 1
    except Exception, e:
        print ip + " 服务异常!!!"
        exception += 1

print "总机器数:" + str(len(ips))
print "运行机器数:" + str(running)
print "异常机器数:" + str(exception)
Beispiel #20
0
from dataclasses import dataclass

from pyhessian.client import HessianProxy
from pyhessian.protocol import cls_factory

NiceObject = cls_factory(name='com.gyxr.adam.dataservice.model.BrandItem',
                         fields=['id', 'name'])

nice_object = NiceObject(id="1", name='中文')

service = HessianProxy("http://localhost:8080/rmi/sync/brand")
service.save(nice_object)
Beispiel #21
0
# -*- coding: UTF-8 -*-
# encoding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import urllib
import json
from pyhessian.client import HessianProxy

service = HessianProxy(
    "http://search.sfbest.com/search/remoteSearcher.hessian")
result = service.search(
    "{\"channelCodes\":[\"HAP001\"],\"ltrType\":1,\"threeRegion\":500,\"isreach\":true,\"isstock\":true,\"keyword\":\"牛肉\",\"pageNo\":0,\"pageSize\":36}"
)
result = urllib.unquote(result)
rstJson = json.loads(result)
print rstJson['result']['productList']
Beispiel #22
0
 def setUp(self):
     self.client = HessianProxy(self.api_url, version=self.version)