Example #1
0
def get_user_client():
    """
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    """
    app = webapp2.get_app()
    request = webapp2.get_request()

    username = request.registry["session"].get("username")
    password = request.registry["session"].get("password")
    user_key = "user_client:{}".format(username)

    # check if we already have the client
    user_client = app.registry.get(user_key)
    if not user_client:
        user_client = Client(USR_URL, cache=None)
        user_client.add_prefix("srv", "http://service.user.core.mtrak.digi.com")
        user_client.add_prefix("vo", "http://vo.user.core.mtrak.digi.com/xsd")

        app.registry[user_key] = user_client

    user_client.set_options(soapheaders=(Element("username").setText(username), Element("password").setText(password)))

    return user_client
Example #2
0
def get_lgn_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    lgn_key = 'lgn_client:{}'.format(username)

    # Check if we already have the client
    lgn_client = app.registry.get(lgn_key)

    if not lgn_client:
        lgn_client = Client(LGN_URL, cache=None)
        lgn_client.add_prefix(
            'srv', "http://service.login.core.mtrak.digi.com")
        lgn_client.add_prefix(
            'vo', "http://vo.login.core.mtrak.digi.com/xsd")

        app.registry[lgn_key] = lgn_client

    lgn_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return lgn_client
Example #3
0
class SoapConnection(object):

    def __init__(self, url=None, sessionid=None, app_name=None):
        if url is None:
            port = config.getint('hydra_client', 'port', 80)
            domain = config.get('hydra_client', 'domain', '127.0.0.1')
            path = config.get('hydra_client', 'soap_path', 'soap')
            #The domain may or may not specify the protocol, so do a check.
            if domain.find('http') == -1:
                self.url = "http://%s:%s/%s?wsdl" % (domain, port, path)
            else:
                self.url = "%s:%s/%s?wsdl" % (domain, port, path)
        else:
            log.info("Using user-defined URL: %s", url)
            port = _get_port(url)
            hostname = _get_hostname(url)
            path = _get_path(url)
            protocol = _get_protocol(url)
            self.url = "%s://%s:%s%s/soap?wsdl" % (protocol, hostname, port, path)
        log.info("Setting URL %s", self.url)

        self.app_name = app_name
        self.sessionid = sessionid
        self.retxml = False
        self.client = Client(self.url,
                             timeout=3600,
                             plugins=[FixNamespace()],
                             retxml=self.retxml)
        self.client.add_prefix('hyd', 'soap_server.hydra_complexmodels')

        cache = self.client.options.cache
        cache.setduration(days=10)

    def login(self, username=None, password=None):
        """Establish a connection to the specified server. If the URL of the
        server is not specified as an argument of this function, the URL
        defined in the configuration file is used."""

        # Connect
        token = self.client.factory.create('RequestHeader')
        if self.sessionid is None:
            if username is None:
                user = config.get('hydra_client', 'user')
            if password is None:
                passwd = config.get('hydra_client', 'password')
            login_response = self.client.service.login(user, passwd)
            token.user_id = login_response.user_id
            sessionid = login_response.sessionid
            token.username = user

        token.sessionid = sessionid
        self.client.set_options(soapheaders=token)

        return session_id
Example #4
0
class SoapConnection(object):
    def __init__(self, url=None, sessionid=None, app_name=None):
        if url is None:
            port = config.getint('hydra_client', 'port', 80)
            domain = config.get('hydra_client', 'domain', '127.0.0.1')
            path = config.get('hydra_client', 'soap_path', 'soap')
            #The domain may or may not specify the protocol, so do a check.
            if domain.find('http') == -1:
                self.url = "http://%s:%s/%s?wsdl" % (domain, port, path)
            else:
                self.url = "%s:%s/%s?wsdl" % (domain, port, path)
        else:
            log.info("Using user-defined URL: %s", url)
            port = _get_port(url)
            hostname = _get_hostname(url)
            path = _get_path(url)
            protocol = _get_protocol(url)
            self.url = "%s://%s:%s%s/soap?wsdl" % (protocol, hostname, port,
                                                   path)
        log.info("Setting URL %s", self.url)

        self.app_name = app_name
        self.sessionid = sessionid
        self.retxml = False
        self.client = Client(self.url,
                             timeout=3600,
                             plugins=[FixNamespace()],
                             retxml=self.retxml)
        self.client.add_prefix('hyd', 'soap_server.hydra_complexmodels')

        cache = self.client.options.cache
        cache.setduration(days=10)

    def login(self, username=None, password=None):
        """Establish a connection to the specified server. If the URL of the
        server is not specified as an argument of this function, the URL
        defined in the configuration file is used."""

        # Connect
        token = self.client.factory.create('RequestHeader')
        if self.sessionid is None:
            if username is None:
                user = config.get('hydra_client', 'user')
            if password is None:
                passwd = config.get('hydra_client', 'password')
            login_response = self.client.service.login(user, passwd)
            token.user_id = login_response.user_id
            sessionid = login_response.sessionid
            token.username = user

        token.sessionid = sessionid
        self.client.set_options(soapheaders=token)

        return session_id
Example #5
0
def connect(url=None):
    if url is None:
        port = config.getint('hydra_server', 'port', '8080')
        domain = config.get('hydra_server', 'domain', 'localhost')
        path = config.get('hydra_server', 'soap_path', 'soap')
        if path:
            if path[0] == '/':
                path = path[1:]
            url = 'http://%s:%s/%s?wsdl' % (domain, port, path)
        else:
            url = 'http://%s:%s?wsdl' % (domain, port)

    client = Client(url, plugins=[FixNamespace()])

    cache = client.options.cache
    cache.setduration(days=10)

    client.add_prefix('hyd', 'soap_server.hydra_complexmodels')
    return client
Example #6
0
def connect(url=None):
    if url is None:
        port = config.getint('hydra_server', 'port', '8080')
        domain = config.get('hydra_server', 'domain', 'localhost')
        path = config.get('hydra_server', 'soap_path', 'soap')
        if path:
            if path[0] == '/':
                path = path[1:]
            url = 'http://%s:%s/%s?wsdl' % (domain, port, path)
        else:
            url = 'http://%s:%s?wsdl' % (domain, port)

    client = Client(url, plugins=[FixNamespace()])

    cache = client.options.cache
    cache.setduration(days=10)

    client.add_prefix('hyd', 'soap_server.hydra_complexmodels')
    return client
Example #7
0
def get_device_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    # check if we already have the client
    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    device_key = 'device_client:{}'.format(username)

    # check if we aleady have the client
    device_client = app.registry.get(device_key)
    if not device_client:
        device_client = Client(DEV_URL, cache=None)
        device_client.add_prefix(
            'rsp', "http://response.devicemanagement.core.mtrak.digi.com/xsd")
        device_client.add_prefix(
            'srv', "http://service.devicemanagement.core.mtrak.digi.com")
        device_client.add_prefix(
            'vo', "http://vo.devicemanagement.core.mtrak.digi.com/xsd")

        app.registry[device_key] = device_client

    device_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return device_client
Example #8
0
class SOAPConnection(BaseConnection):

    def __init__(self, url=None, session_id=None, app_name=None):
        super(SOAPConnection, self).__init__(app_name=app_name)

        self.url = self.get_url(url, 'soap?wsdl')

        log.info("Setting URL %s", self.url)

        self.app_name = app_name
        self.session_id = session_id
        self.retxml = False
        self.client = Client(self.url,
                             timeout=3600,
                             plugins=[FixNamespace()],
                             retxml=self.retxml)
        self.client.add_prefix('hyd', 'server.complexmodels')

        cache = self.client.options.cache
        cache.setduration(days=10)

    def login(self, username=None, password=None):
        """Establish a connection to the specified server. If the URL of the
        server is not specified as an argument of this function, the URL
        defined in the configuration file is used."""

        # Connect
        token = self.client.factory.create('RequestHeader')
        if self.session_id is None:
            parsed_username, parsed_password = self.get_username_and_password(username, password)

            login_response = self.client.service.login(parsed_username, parsed_password)
            token.user_id = login_response.user_id
            self.user_id = login_response.user_id

        #This needs to be 'sessionid' instead if 'session_id' because of apache
        #not handling '_' well in request headers
        self.client.set_options(soapheaders=token)

        return token.user_id
Example #9
0
class DirectEmailTypeService:
    def __init__(self, auth_info):
        self.__url = 'https://td41.tripolis.com/api2/soap/DirectEmailTypeService?wsdl'
        self.__client = Client(self.__url, plugins=[MultipartFilter()])

        ns0 = "http://common.services.tripolis.com/"
        ns1 = "http://request.services.tripolis.com/"
        ns2 = "http://response.services.tripolis.com/"
        ns3 = "http://services.tripolis.com/"
        ns4 = "http://type.directemail.services.tripolis.com/"

        self.__client.add_prefix('ns0', ns0)
        self.__client.add_prefix('ns1', ns1)
        self.__client.add_prefix('ns2', ns2)
        self.__client.add_prefix('ns3', ns3)
        self.__client.add_prefix('ns4', ns4)

        self.__client.set_options(soapheaders=auth_info.get())

    """
    Returns a list of DirectEmailType objects or None if not workspace found, i.e.
    [(DirectEmailType){
       id = "OmJE+2eqsaLTSwPcIsPl2w"
       label = "Fase1 mails"
       name = "mails"
       fromName = "KPN"
       fromAddress = "*****@*****.**"
       toEmailFieldId = "j2j6ec3aAQn+zNNj5j8OpA"
       replyToAddress = None
       externalHtmlUrl = None
       externalTextUrl = None
       enableWysiwygEditor = False
       encoding = "UTF8"
       enableAttachments = False
    },
    ...]
    """

    def getByWorkspaceId(self, workspace_id):
        request = self.__client.factory.create('ns1:WorkspaceIDRequest')
        request.workspaceId = workspace_id

        try:
            response = self.__client.service.getByWorkspaceId(request)
            return response.directEmailTypes.directEmailType
        except WebFault as e:
            if e.fault.detail.errorResponse.errors.error.message == 'workspaceId not found':
                return None
            raise Tripoli2ApiException(
                e.fault.detail.errorResponse.errors.error.message)
Example #10
0
class WorkspaceService:
    def __init__(self, auth_info):
        self.__url = 'https://td41.tripolis.com/api2/soap/WorkspaceService?wsdl'
        self.__client = Client(self.__url, plugins=[MultipartFilter()])

        ns0 = "http://common.services.tripolis.com/"
        ns1 = "http://request.services.tripolis.com/"
        ns2 = "http://response.services.tripolis.com/"
        ns3 = "http://services.tripolis.com/"
        ns4 = "http://workspace.services.tripolis.com/"

        self.__client.add_prefix('ns0', ns0)
        self.__client.add_prefix('ns1', ns1)
        self.__client.add_prefix('ns2', ns2)
        self.__client.add_prefix('ns3', ns3)
        self.__client.add_prefix('ns4', ns4)

        self.__client.set_options(soapheaders=auth_info.get())

    def getAll(self):
        service_request = self.__client.factory.create('ns1:ServiceRequest')
        return self.__client.service.getAll(service_request)

    """
    Returns a Workspace object or None if not found. An example of a Workspace object:
    (Workspace){
      id = "qvo8NMAolbA_3AFrodmdgQ"
      label = "kpncompleetdev"
      name = "kpncompleetdev"
      contactDatabaseId = "3nnH+KDcs9N8TlT6WqeEeg"
      publicDomainName = None
      bounceDomainName = None
      listUnsubscribeHeader = False
    }
    Field is one of the attributes of a Workspace object, i.e. 'name'
    """

    def getByField(self, field, value):
        for workspace in self.getAll().workspaces.workspace:
            if workspace[field] == value:
                return workspace
Example #11
0
    def getInventory(self,
                     network,
                     station='*',
                     location='*',
                     channel='*',
                     starttime=UTCDateTime(),
                     endtime=UTCDateTime(),
                     instruments=True,
                     min_latitude=-90,
                     max_latitude=90,
                     min_longitude=-180,
                     max_longitude=180,
                     modified_after=None,
                     format='SUDS'):
        """
        Returns information about the available networks and stations in that
        particular space/time region.

        :type network: str
        :param network: Network code, e.g. ``'BW'``.
        :type station: str
        :param station: Station code, e.g. ``'MANZ'``. Station code may contain
            wild cards.
        :type location: str
        :param location: Location code, e.g. ``'01'``. Location code may
            contain wild cards.
        :type channel: str
        :param channel: Channel code, e.g. ``'EHE'``. Channel code may contain
            wild cards.
        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param starttime: Start date and time.
        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param endtime: End date and time.
        :type instruments: boolean, optional
        :param instruments: Include instrument data. Default is ``True``.
        :type min_latitude: float, optional
        :param min_latitude: Minimum latitude, defaults to ``-90.0``
        :type max_latitude: float, optional
        :param max_latitude: Maximum latitude, defaults to ``90.0``
        :type min_longitude: float, optional
        :param min_longitude: Minimum longitude, defaults to ``-180.0``
        :type max_longitude: float, optional
        :param max_longitude: Maximum longitude, defaults to ``180.0``.
        :type modified_after: :class:`~obspy.core.utcdatetime.UTCDateTime`,
            optional
        :param modified_after: Returns only data modified after given date.
            Default is ``None``, returning all available data.
        :type format: ``'XML'`` or ``'SUDS'``, optional
        :param format: Output format. Either returns a XML document or a
            parsed SUDS object. Defaults to ``SUDS``.
        :return: XML document or a parsed SUDS object containing inventory
            information.

        .. rubric:: Example

        >>> from obspy.neries import Client
        >>> from obspy import UTCDateTime
        >>> client = Client(user='******')
        >>> dt = UTCDateTime("2011-01-01T00:00:00")
        >>> result = client.getInventory('GE', 'SNAA', '', 'BHZ', dt, dt+10,
        ...                              instruments=True)
        >>> paz = result.ArclinkInventory.inventory.responsePAZ
        >>> print(paz.poles)  # doctest: +ELLIPSIS
        (-0.037004,0.037016) (-0.037004,-0.037016) (-251.33,0.0) ...
        """
        # enable logging if debug option is set
        if self.debug:
            import logging
            logging.basicConfig(level=logging.INFO)
            logging.getLogger('suds.client').setLevel(logging.DEBUG)
        # initialize client
        client = SudsClient(SEISMOLINK_WSDL, retxml=(format == 'XML'))
        # set prefixes for easier debugging
        client.add_prefix('gml', 'http://www.opengis.net/gml')
        client.add_prefix('ogc', 'http://www.opengis.net/ogc')
        client.add_prefix('xlin', 'http://www.w3.org/1999/xlink')
        client.add_prefix('urn', 'urn:xml:seisml:orfeus:neries:org')
        # set cache of 5 days
        cache = client.options.cache
        cache.setduration(days=5)
        # create user token
        usertoken = client.factory.create('UserTokenType')
        usertoken.email = self.user
        usertoken.password = self.password
        usertoken.label = self.user_agent.replace(' ', '_')
        usertoken.locale = ""
        # create station filter
        stationid = client.factory.create('StationIdentifierType')
        stationid.NetworkCode = network
        stationid.StationCode = station
        stationid.ChannelCode = channel
        stationid.LocId = location
        stationid.TimeSpan.TimePeriod.beginPosition = \
            UTCDateTime(starttime).strftime("%Y-%m-%dT%H:%M:%S")
        stationid.TimeSpan.TimePeriod.endPosition = \
            UTCDateTime(endtime).strftime("%Y-%m-%dT%H:%M:%S")
        # create spatial filters
        spatialbounds = client.factory.create('SpatialBoundsType')
        spatialbounds.BoundingBox.PropertyName = "e gero"
        spatialbounds.BoundingBox.Envelope.lowerCorner = "%f %f" %\
            (min(min_latitude, max_latitude),
             min(min_longitude, max_longitude))
        spatialbounds.BoundingBox.Envelope.upperCorner = "%f %f" %\
            (max(min_latitude, max_latitude),
             max(min_longitude, max_longitude))
        # instruments attribute
        if instruments:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'true'}))
        else:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'false'}))
        # modified_after attribute
        if modified_after:
            dt = UTCDateTime(modified_after).strftime("%Y-%m-%dT%H:%M:%S")
            client.options.plugins.append(
                _AttributePlugin({'ModifiedAfter': dt}))
        # add version attribute needed for instruments
        client.options.plugins.append(_AttributePlugin({'Version': '1.0'}))
        # request data
        response = client.service.getInventory(usertoken, stationid,
                                               spatialbounds)
        if format == 'XML':
            # response is a full SOAP response
            from xml.etree.ElementTree import fromstring, tostring
            temp = fromstring(response)
            xpath = '*/*/{urn:xml:seisml:orfeus:neries:org}ArclinkInventory'
            inventory = temp.find(xpath)
            # export XML prepending a XML declaration
            XML_DECLARATION = "<?xml version='1.0' encoding='UTF-8'?>\n\n"
            return XML_DECLARATION + tostring(inventory, encoding='utf-8')
        else:
            # response is a SUDS object
            return response
Example #12
0
    def getInventory(self, network, station='*', location='*', channel='*',
                     starttime=UTCDateTime(), endtime=UTCDateTime(),
                     instruments=True, min_latitude=-90, max_latitude=90,
                     min_longitude=-180, max_longitude=180,
                     modified_after=None, format='SUDS'):
        """
        Returns information about the available networks and stations in that
        particular space/time region.

        :type network: str
        :param network: Network code, e.g. ``'BW'``.
        :type station: str
        :param station: Station code, e.g. ``'MANZ'``. Station code may contain
            wild cards.
        :type location: str
        :param location: Location code, e.g. ``'01'``. Location code may
            contain wild cards.
        :type channel: str
        :param channel: Channel code, e.g. ``'EHE'``. Channel code may contain
            wild cards.
        :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param starttime: Start date and time.
        :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime`
        :param endtime: End date and time.
        :type instruments: boolean, optional
        :param instruments: Include instrument data. Default is ``True``.
        :type min_latitude: float, optional
        :param min_latitude: Minimum latitude, defaults to ``-90.0``
        :type max_latitude: float, optional
        :param max_latitude: Maximum latitude, defaults to ``90.0``
        :type min_longitude: float, optional
        :param min_longitude: Minimum longitude, defaults to ``-180.0``
        :type max_longitude: float, optional
        :param max_longitude: Maximum longitude, defaults to ``180.0``.
        :type modified_after: :class:`~obspy.core.utcdatetime.UTCDateTime`,
            optional
        :param modified_after: Returns only data modified after given date.
            Default is ``None``, returning all available data.
        :type format: ``'XML'`` or ``'SUDS'``, optional
        :param format: Output format. Either returns a XML document or a
            parsed SUDS object. Defaults to ``SUDS``.
        :return: XML document or a parsed SUDS object containing inventory
            information.

        .. rubric:: Example

        >>> from obspy.neries import Client
        >>> from obspy import UTCDateTime
        >>> client = Client(user='******')
        >>> dt = UTCDateTime("2011-01-01T00:00:00")
        >>> result = client.getInventory('GE', 'SNAA', '', 'BHZ', dt, dt+10,
        ...                              instruments=True)
        >>> paz = result.ArclinkInventory.inventory.responsePAZ
        >>> print(paz.poles)  # doctest: +ELLIPSIS
        (-0.037004,0.037016) (-0.037004,-0.037016) (-251.33,0.0) ...
        """
        # enable logging if debug option is set
        if self.debug:
            import logging
            logging.basicConfig(level=logging.INFO)
            logging.getLogger('suds.client').setLevel(logging.DEBUG)
        # initialize client
        client = SudsClient(SEISMOLINK_WSDL,
                            retxml=(format == 'XML'))
        # set prefixes for easier debugging
        client.add_prefix('gml', 'http://www.opengis.net/gml')
        client.add_prefix('ogc', 'http://www.opengis.net/ogc')
        client.add_prefix('xlin', 'http://www.w3.org/1999/xlink')
        client.add_prefix('urn', 'urn:xml:seisml:orfeus:neries:org')
        # set cache of 5 days
        cache = client.options.cache
        cache.setduration(days=5)
        # create user token
        usertoken = client.factory.create('UserTokenType')
        usertoken.email = self.user
        usertoken.password = self.password
        usertoken.label = self.user_agent.replace(' ', '_')
        usertoken.locale = ""
        # create station filter
        stationid = client.factory.create('StationIdentifierType')
        stationid.NetworkCode = network
        stationid.StationCode = station
        stationid.ChannelCode = channel
        stationid.LocId = location
        stationid.TimeSpan.TimePeriod.beginPosition = \
            UTCDateTime(starttime).strftime("%Y-%m-%dT%H:%M:%S")
        stationid.TimeSpan.TimePeriod.endPosition = \
            UTCDateTime(endtime).strftime("%Y-%m-%dT%H:%M:%S")
        # create spatial filters
        spatialbounds = client.factory.create('SpatialBoundsType')
        spatialbounds.BoundingBox.PropertyName = "e gero"
        spatialbounds.BoundingBox.Envelope.lowerCorner = "%f %f" %\
            (min(min_latitude, max_latitude),
             min(min_longitude, max_longitude))
        spatialbounds.BoundingBox.Envelope.upperCorner = "%f %f" %\
            (max(min_latitude, max_latitude),
             max(min_longitude, max_longitude))
        # instruments attribute
        if instruments:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'true'}))
        else:
            client.options.plugins.append(
                _AttributePlugin({'Instruments': 'false'}))
        # modified_after attribute
        if modified_after:
            dt = UTCDateTime(modified_after).strftime("%Y-%m-%dT%H:%M:%S")
            client.options.plugins.append(
                _AttributePlugin({'ModifiedAfter': dt}))
        # add version attribute needed for instruments
        client.options.plugins.append(
                _AttributePlugin({'Version': '1.0'}))
        # request data
        response = client.service.getInventory(usertoken, stationid,
                                               spatialbounds)
        if format == 'XML':
            # response is a full SOAP response
            from xml.etree.ElementTree import fromstring, tostring
            temp = fromstring(response)
            xpath = '*/*/{urn:xml:seisml:orfeus:neries:org}ArclinkInventory'
            inventory = temp.find(xpath)
            # export XML prepending a XML declaration
            XML_DECLARATION = "<?xml version='1.0' encoding='UTF-8'?>\n\n"
            return XML_DECLARATION + tostring(inventory, encoding='utf-8')
        else:
            # response is a SUDS object
            return response
Example #13
0
class Fiskalizacija():
    
    def __init__(self, msgtype, wsdl, key, cert, cr, uid, oe_obj=None):
        self.set_start_time() 
        self.wsdl=wsdl  
        self.key=key 
        self.cert=cert
        self.msgtype=msgtype
        self.oe_obj=oe_obj
        self.oe_id=oe_obj and oe_obj.id or 0 #openerp id racuna ili pprostora ili 0 za echo i ostalo
        self.cr=cr            #openerp cursor radi log-a 
        self.uid=uid          #openerp cursor radi log-a 
        SetFiskalFilePaths(key, cert)
        self.client2 = Client(wsdl, cache=None, prettyxml=True, timeout=15, faults=False, plugins=[DodajPotpis()] ) 
        self.client2.add_prefix('tns', 'http://www.apis-it.hr/fin/2012/types/f73')
        self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
        if msgtype in ('echo'):
            pass
        elif msgtype in ('prostor_prijava', 'prostor_odjava', 'PoslovniProstor'):
            #self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
            self.prostor = self.client2.factory.create('tns:PoslovniProstor')
        elif msgtype in ('racun', 'racun_ponovo', 'Racun'):
            #self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
            self.racun = self.client2.factory.create('tns:Racun') 
        self.greska =''

    def time_formated(self): 
        tstamp = zagreb_now() 
        #tstamp=datetime.now()
        v_date='%02d.%02d.%02d' % (tstamp.day, tstamp.month, tstamp.year)
        v_datum_vrijeme='%02d.%02d.%02dT%02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        v_datum_racun='%02d.%02d.%02d %02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        vrijeme={'datum':v_date,                    #vrijeme SAD
                 'datum_vrijeme':v_datum_vrijeme,   # format za zaglavlje XML poruke
                 'datum_racun':v_datum_racun,       # format za ispis na računu
                 'time_stamp':tstamp}               # timestamp, za zapis i izračun vremena obrade
        return vrijeme

    def set_start_time(self):
        self.start_time = self.time_formated()

    def set_stop_time(self):
        self.stop_time = self.time_formated()
        
    def log_fiskal(self):
        fiskal_prostor_id = invoice_id = None
        if self.msgtype in ('echo'):
            fiskal_prostor_id = self.oe_id
        elif self.msgtype in ('prostor_prijava', 'prostor_odjava', 'PoslovniProstor'):
            fiskal_prostor_id = self.oe_id
        elif self.msgtype in ('racun', 'racun_ponovo', 'Racun'):
            invoice_id = self.oe_id
        company_id = self.oe_obj and self.oe_obj.company_id and self.oe_obj.company_id.id or 1
                     
        self.set_stop_time()
        t_obrada = self.stop_time['time_stamp'] - self.start_time['time_stamp']
        time_obr='%s.%s s'%(t_obrada.seconds, t_obrada.microseconds)
        
        self.cr.execute("""
            INSERT INTO fiskal_log(
                         user_id, create_uid, create_date
                        ,name, type, time_stamp 
                        ,sadrzaj, odgovor, greska
                        ,fiskal_prostor_id, invoice_id, time_obr
                        ,company_id )
                VALUES ( %s, %s, %s,  %s, %s, %s,  %s, %s, %s,  %s, %s, %s, %s );
            """, ( self.uid, self.uid, datetime.now(),
                   self.zaglavlje.IdPoruke, self.msgtype, datetime.now(),
                   str(self.poruka_zahtjev), str(self.poruka_odgovor), self.greska,
                   fiskal_prostor_id, invoice_id, time_obr,
                   company_id
                  ) 
        )

    def echo(self):
        try:
            odgovor = self.client2.service.echo('TEST PORUKA')
            poruka_zahtjev =  self.client2.last_sent().str()
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
        except:
            #return 'No ECHO reply','TEST PORUKA'
            poruka_zahtjev='TEST PORUKA' #TODO pitat suds di je zapelo...
            self.greska ='Ostale greske - Nema Odgovor! '
        finally:
            self.log_fiskal()
        return self.poruka_odgovor

    def posalji_prostor(self):
        res=False
        try:
            odgovor=self.client2.service.poslovniProstor(self.zaglavlje, self.prostor)
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
            if odgovor[0] == 200:
                res = True
            elif odgovor[0] == 500:
                self.greska = '=>'.join(( odgovor[1]['Greske'][0][0]['SifraGreske'],
                                          odgovor[1]['Greske'][0][0]['PorukaGreske'].replace('http://www.apis-it.hr/fin/2012/types/','')
                                       ))
        except:
            self.greska ='Nepoznata vrsta odgovora!'  #odgovor[0] not in (200,500)
        finally:
            self.log_fiskal()
        return self.poruka_odgovor
            
    def izracunaj_zastitni_kod(self):    
        self.racun.ZastKod = self.get_zastitni_kod(self.racun.Oib,
                                                  self.racun.DatVrijeme,
                                                  str(self.racun.BrRac.BrOznRac),
                                                  self.racun.BrRac.OznPosPr,
                                                  self.racun.BrRac.OznNapUr,
                                                  str(self.racun.IznosUkupno)
                                                  )

    def get_zastitni_kod(self, Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno):    
        medjurezultat = ''.join((Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno)) 
        pkey = RSA.load_key(keyFile)
        signature = pkey.sign(hashlib.sha1(medjurezultat).digest())
        return hashlib.md5(signature).hexdigest()

    def posalji_racun(self):
        self.greska =''
        res = False
        try:
            odgovor=self.client2.service.racuni(self.zaglavlje, self.racun)
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
            if odgovor[0] == 200:
                res = True
            elif odgovor[0] == 500:
                self.greska = '=>'.join(( odgovor[1]['Greske'][0][0]['SifraGreske'],
                                          odgovor[1]['Greske'][0][0]['PorukaGreske'].replace('http://www.apis-it.hr/fin/2012/types/','')
                                       ))
            else:
                self.greska ='Nepoznata vrsta odgovora!'  #odgovor[0] not in (200,500)
        except:
            #return 'Error - no reply!', self.poruka
            self.greska ='Ostale greske - Nema Odgovor! '
        finally:
            self.log_fiskal()
        return res
        

    def generiraj_poruku(self):
        self.client2.options.nosend = True
        poruka = str(self.client2.service.racuni(self.zaglavlje, self.racun).envelope)
        self.client2.options.nosend = False
        return poruka
Example #14
0
class DirectEmailService:
    def __init__(self, auth_info):
        self.__url = 'https://td41.tripolis.com/api2/soap/DirectEmailService?wsdl'
        self.__client = Client(self.__url, plugins=[MultipartFilter()])

        ns0 = "http://common.services.tripolis.com/"
        ns1 = "http://directemail.services.tripolis.com/"
        ns2 = "http://request.services.tripolis.com/"
        ns3 = "http://response.services.tripolis.com/"
        ns4 = "http://services.tripolis.com/"

        self.__client.add_prefix('ns0', ns0)
        self.__client.add_prefix('ns1', ns1)
        self.__client.add_prefix('ns2', ns2)
        self.__client.add_prefix('ns3', ns3)
        self.__client.add_prefix('ns4', ns4)

        self.__client.set_options(soapheaders=auth_info.get())

    """
    Returns a list of DirectEmailForListing objects or None if not workspace found, i.e.
    [(DirectEmailForListing){
     id = "Yy2tB_Q2nS9bPIwy7RzKEg"
     directEmailTypeId = "fcw6GMjj1fk__uaAFGsVFQ"
     label = "09_reset_password"
     name = "09_reset_password"
     subject = "Wachtwoord reset FLITS helpdesk applicatie"
     fromName = "KPN"
     fromAddress = "*****@*****.**"
     replyToAddress = None
     description = None
     author = "*****@*****.**"
     modifiedAt = 2016-02-01 13:29:59+01:00
     isArchived = False
    },
    ...]
    """

    def getByDirectEmailTypeId(self, direct_email_type_id):
        request = self.__client.factory.create('ns2:DirectEmailTypeIDRequest')
        request.directEmailTypeId = direct_email_type_id
        request.paging.pageNr = 1
        request.paging.pageSize = 1000
        request.sorting.sortBy = 'name'
        request.sorting.sortOrder = 'ASC'

        try:
            response = self.__client.service.getByDirectEmailTypeId(request)
            # response.directEmails is an empty string, of no emails are in the direct email type
            if isinstance(response.directEmails, Text):
                return []
            return response.directEmails.directEmail
        except WebFault as e:
            if e.fault.detail.errorResponse.errors.error.message == 'directEmailTypeId not found':
                return None
            raise Tripoli2ApiException(
                e.fault.detail.errorResponse.errors.error.message)

    def update(self, direct_email_for_listing, tripolis_direct_email):

        request = self.__client.factory.create('UpdateDirectEmailRequest')
        request.id = direct_email_for_listing.id
        request.label = tripolis_direct_email.getLabel()
        request.name = tripolis_direct_email.getName()
        request.subject = unicode(tripolis_direct_email.getSubject(),
                                  encoding='utf-8')
        request.description = tripolis_direct_email.getDescription()
        request.htmlSource = unicode(tripolis_direct_email.getHtml(),
                                     encoding='utf-8')
        request.textSource = unicode(tripolis_direct_email.getText(),
                                     encoding='utf-8')
        request.fromName = unicode(tripolis_direct_email.getFromName(),
                                   encoding='utf-8')
        request.fromAddress = tripolis_direct_email.getFromAddress()
        request.replyToAddress = tripolis_direct_email.getReplyTo()

        try:
            return self.__client.service.update(request).id
        except WebFault as e:
            raise Tripoli2ApiException(
                e.fault.detail.errorResponse.errors.error.message)

    def create(self, direct_email_type_id, tripolis_direct_email):

        request = self.__client.factory.create('CreateDirectEmailRequest')
        request.directEmailTypeId = direct_email_type_id
        request.label = tripolis_direct_email.getLabel()
        request.name = tripolis_direct_email.getName()
        request.subject = unicode(tripolis_direct_email.getSubject(),
                                  encoding='utf-8')
        request.description = tripolis_direct_email.getDescription()
        request.htmlSource = unicode(tripolis_direct_email.getHtml(),
                                     encoding='utf-8')
        request.textSource = unicode(tripolis_direct_email.getText(),
                                     encoding='utf-8')
        request.fromName = unicode(tripolis_direct_email.getFromName(),
                                   encoding='utf-8')
        request.fromAddress = tripolis_direct_email.getFromAddress()
        request.replyToAddress = tripolis_direct_email.getReplyTo()

        try:
            return self.__client.service.create(request).id
        except WebFault as e:
            raise Tripoli2ApiException(
                e.fault.detail.errorResponse.errors.error.message)
Example #15
0
class Fiskalizacija():
    def init(self, msgtype, wsdl, key, cert, oe_id=None):
        #file paths for wsdl, key, cert
        self.wsdl = wsdl  
        self.key = key 
        self.cert = cert
        self.msgtype =msgtype
        self.oe_id = oe_id or 0 #openerp id racuna ili pprostora ili 0 za echo i ostalo

        SetFiskalFilePaths(key, cert)

        self.client2 = Client(wsdl, cache=None, prettyxml=True, timeout=15, faults=False, plugins=[DodajPotpis()] ) 
        self.client2.add_prefix('tns', 'http://www.apis-it.hr/fin/2012/types/f73')
        self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')

        if msgtype in ('echo'):
            pass
        elif msgtype in ('prostor_prijava', 'prostor_odjava', 'PoslovniProstor'):
            self.prostor = self.client2.factory.create('tns:PoslovniProstor')
        elif msgtype in ('racun', 'racun_ponovo', 'Racun'):
            self.racun = self.client2.factory.create('tns:Racun') 

    def time_formated(self): 
        tstamp = zagreb_now() #datetime.datetime.now() this was server def. tz time
        v_date='%02d.%02d.%02d' % (tstamp.day, tstamp.month, tstamp.year)
        v_datum_vrijeme='%02d.%02d.%02dT%02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        v_datum_racun='%02d.%02d.%02d %02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        vrijeme={'datum':v_date,                    #vrijeme SAD
                 'datum_vrijeme':v_datum_vrijeme,   # format za zaglavlje XML poruke
                 'datum_racun':v_datum_racun,       # format za ispis na računu
                 'time_stamp':tstamp}               # timestamp, za zapis i izračun vremena obrade
        return vrijeme
        
        
    def set_start_time(self):
        self.start_time = self.time_formated()

    def set_stop_time(self):
        self.stop_time = self.time_formated()

    def echo(self):
        try:
            pingtest=self.client2.service.echo('TEST PORUKA')
            poruka_zahtjev =  self.client2.last_sent().str()
            return pingtest, poruka_zahtjev
        except:
            return 'No ECHO reply','TEST PORUKA'

    def posalji_prostor(self):
        try:
            odgovor=self.client2.service.poslovniProstor(self.zaglavlje, self.pp)
            poruka_zahtjev =  self.client2.last_sent().str()
            poruka_odgovor = str(odgovor)
            return poruka_odgovor, poruka_zahtjev
        except:
            return 'Error - no reply!', poruka

    def izracunaj_zastitni_kod(self):    
        self.racun.ZastKod = self.get_zastitni_kod(self.racun.Oib,
                                                  self.racun.DatVrijeme,
                                                  str(self.racun.BrRac.BrOznRac),
                                                  self.racun.BrRac.OznPosPr,
                                                  self.racun.BrRac.OznNapUr,
                                                  str(self.racun.IznosUkupno)
                                                  )

    def get_zastitni_kod(self, Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno):    
        medjurezultat = ''.join((Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno)) 
        pkey = RSA.load_key(keyFile)
        signature = pkey.sign(hashlib.sha1(medjurezultat).digest())
        return hashlib.md5(signature).hexdigest()

    def posalji_racun(self):
        try:
            return self.client2.service.racuni(self.zaglavlje, self.racun)
        except:
            pass#a=self.client2.service.racuni(self.zaglavlje, self.racun)
            return 'greška u slanju podataka' 

    def generiraj_poruku(self):
        self.client2.options.nosend = True
        poruka = str(self.client2.service.racuni(self.zaglavlje, self.racun).envelope)
        self.client2.options.nosend = False
        return poruka
                        sub = get_suds_element(item, str(left))
                        el.append(sub)
                else:
                    sub = get_suds_element(right, str(left))
                    el.append(sub)
        return el

    print "OMWS 1.0 test (v1)"
    print "=================="

    # General settings
    wsdl = 'http://openmodeller.cria.org.br/ws/1.0/openModeller.wsdl'

    # Instantiate SOAP client
    soap_client = Client(wsdl, location=endpoint, prettyxml=True)
    soap_client.add_prefix('om', 'http://openmodeller.cria.org.br/xml/1.0')
    soap_client.add_prefix('soap', 'http://schemas.xmlsoap.org/soap/envelope/')

    # Ignore logs
    h = NullLogHandler()
    logging.getLogger('suds.client').addHandler(h)
    logging.getLogger('suds.umx.typed').addHandler(h)
    logging.getLogger('suds.plugin').addHandler(h)

    #####  PING
    ###################################
    try:
        status = soap_client.service.ping()
    except Exception, e:
        print 'ping call failure:', str(e)
        exit(2)
Example #17
0
class Fiskalizacija():
    
    def __init__(self, msgtype, wsdl, key, cert, cr, uid, oe_obj=None):
        self.set_start_time() 
        self.wsdl=wsdl  
        self.key=key 
        self.cert=cert
        self.msgtype=msgtype
        self.oe_obj=oe_obj
        self.oe_id=oe_obj and oe_obj.id or 0 #openerp id racuna ili pprostora ili 0 za echo i ostalo
        self.cr=cr            #openerp cursor radi log-a 
        self.uid=uid          #openerp cursor radi log-a 
        SetFiskalFilePaths(key, cert)
        self.client2 = Client(wsdl, cache=None, prettyxml=True, timeout=15, faults=False, plugins=[DodajPotpis()] ) 
        self.client2.add_prefix('tns', 'http://www.apis-it.hr/fin/2012/types/f73')
        self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
        if msgtype in ('echo'):
            pass
        elif msgtype in ('prostor_prijava', 'prostor_odjava', 'PoslovniProstor'):
            #self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
            self.prostor = self.client2.factory.create('tns:PoslovniProstor')
        elif msgtype in ('racun', 'racun_ponovo', 'Racun'):
            #self.zaglavlje = self.client2.factory.create('tns:Zaglavlje')
            self.racun = self.client2.factory.create('tns:Racun') 
        self.greska =''

    def time_formated(self): 
        tstamp = zagreb_now() 
        v_date='%02d.%02d.%02d' % (tstamp.day, tstamp.month, tstamp.year)
        v_datum_vrijeme='%02d.%02d.%02dT%02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        v_datum_racun='%02d.%02d.%02d %02d:%02d:%02d' % (tstamp.day, tstamp.month, tstamp.year, tstamp.hour, tstamp.minute, tstamp.second)
        vrijeme={'datum':v_date,                    #vrijeme SAD
                 'datum_vrijeme':v_datum_vrijeme,   # format za zaglavlje XML poruke
                 'datum_racun':v_datum_racun,       # format za ispis na računu
                 'time_stamp':tstamp}               # timestamp, za zapis i izračun vremena obrade
        return vrijeme

    def set_start_time(self):
        self.start_time = self.time_formated()

    def set_stop_time(self):
        self.stop_time = self.time_formated()
        
    def log_fiskal(self):
        fiskal_prostor_id = invoice_id = None
        if self.msgtype in ('echo'):
            fiskal_prostor_id = self.oe_id
        elif self.msgtype in ('prostor_prijava', 'prostor_odjava', 'PoslovniProstor'):
            fiskal_prostor_id = self.oe_id
        elif self.msgtype in ('racun', 'racun_ponovo', 'Racun'):
            invoice_id = self.oe_id
        company_id = self.oe_obj and self.oe_obj.company_id and self.oe_obj.company_id.id or 1
                     
        self.set_stop_time()
        t_obrada = self.stop_time['time_stamp'] - self.start_time['time_stamp']
        time_obr='%s.%s s'%(t_obrada.seconds, t_obrada.microseconds)
        
        self.cr.execute("""
            INSERT INTO fiskal_log(
                         user_id, create_uid, create_date
                        ,name, type, time_stamp 
                        ,sadrzaj, odgovor, greska
                        ,fiskal_prostor_id, invoice_id, time_obr
                        ,company_id )
                VALUES ( %s, %s, %s,  %s, %s, %s,  %s, %s, %s,  %s, %s, %s, %s );
            """, ( self.uid, self.uid, datetime.now(),
                   self.zaglavlje.IdPoruke, self.msgtype, datetime.now(),
                   str(self.poruka_zahtjev), str(self.poruka_odgovor), self.greska,
                   fiskal_prostor_id, invoice_id, time_obr,
                   company_id
                  ) 
        )

    def echo(self):
        try:
            odgovor = self.client2.service.echo('TEST PORUKA')
            poruka_zahtjev =  self.client2.last_sent().str()
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
        except:
            #return 'No ECHO reply','TEST PORUKA'
            poruka_zahtjev='TEST PORUKA' #TODO pitat suds di je zapelo...
            self.greska ='Ostale greske - Nema Odgovor! '
        finally:
            self.log_fiskal()
        return self.poruka_odgovor

    def posalji_prostor(self):
        res=False
        try:
            odgovor=self.client2.service.poslovniProstor(self.zaglavlje, self.prostor)
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
            if odgovor[0] == 200:
                res = True
            elif odgovor[0] == 500:
                self.greska = '=>'.join(( odgovor[1]['Greske'][0][0]['SifraGreske'],
                                          odgovor[1]['Greske'][0][0]['PorukaGreske'].replace('http://www.apis-it.hr/fin/2012/types/','')
                                       ))
        except:
            self.greska ='Nepoznata vrsta odgovora!'  #odgovor[0] not in (200,500)
        finally:
            self.log_fiskal()
        return self.poruka_odgovor
            
    def izracunaj_zastitni_kod(self):    
        self.racun.ZastKod = self.get_zastitni_kod(self.racun.Oib,
                                                  self.racun.DatVrijeme,
                                                  str(self.racun.BrRac.BrOznRac),
                                                  self.racun.BrRac.OznPosPr,
                                                  self.racun.BrRac.OznNapUr,
                                                  str(self.racun.IznosUkupno)
                                                  )

    def get_zastitni_kod(self, Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno):    
        medjurezultat = ''.join((Oib, DatVrijeme, BrOznRac, OznPosPr, OznNapUr, IznosUkupno)) 
        pkey = RSA.load_key(keyFile)
        signature = pkey.sign(hashlib.sha1(medjurezultat).digest())
        return hashlib.md5(signature).hexdigest()

    def posalji_racun(self):
        self.greska =''
        res = False
        try:
            odgovor=self.client2.service.racuni(self.zaglavlje, self.racun)
            self.poruka_zahtjev =  self.client2.last_sent()
            self.poruka_odgovor = odgovor
            if odgovor[0] == 200:
                res = True
            elif odgovor[0] == 500:
                self.greska = '=>'.join(( odgovor[1]['Greske'][0][0]['SifraGreske'],
                                          odgovor[1]['Greske'][0][0]['PorukaGreske'].replace('http://www.apis-it.hr/fin/2012/types/','')
                                       ))
            else:
                self.greska ='Nepoznata vrsta odgovora!'  #odgovor[0] not in (200,500)
        except:
            #return 'Error - no reply!', self.poruka
            self.greska ='Ostale greske - Nema Odgovor! '
        finally:
            self.log_fiskal()
        return res
        

    def generiraj_poruku(self):
        self.client2.options.nosend = True
        poruka = str(self.client2.service.racuni(self.zaglavlje, self.racun).envelope)
        self.client2.options.nosend = False
        return poruka
Example #18
0
    # Instantiate SOAP client
    if verbosity == 3:
        print 'Checking endpoint:', endpoint

    try:
        soap_client = Client(wsdl,
                             location=endpoint,
                             prettyxml=True,
                             plugins=[DumperPlugin()])
    except URLError, u:
        close(
            'XML Schema referenced by WSDL not found (release suds cache when changing schema location)',
            1)

    soap_client.add_prefix('om', xml_ns)
    soap_client.add_prefix('soap', 'http://schemas.xmlsoap.org/soap/envelope/')

    # Ignore logs
    h = NullLogHandler()
    logging.getLogger('suds.client').addHandler(h)
    logging.getLogger('suds.umx.typed').addHandler(h)
    logging.getLogger('suds.plugin').addHandler(h)

    # Test configuration
    check_layers = True
    run_model = True
    run_model_test = True
    run_projection = True
    run_model_evaluation = True
    run_sample_points = True