repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.url
def url(self, url, owner=None, **kwargs): """ Create the URL TI object. Args: owner: url: **kwargs: Return: """ return URL(self.tcex, url, owner=owner, **kwargs)
python
def url(self, url, owner=None, **kwargs): """ Create the URL TI object. Args: owner: url: **kwargs: Return: """ return URL(self.tcex, url, owner=owner, **kwargs)
[ "def", "url", "(", "self", ",", "url", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "URL", "(", "self", ".", "tcex", ",", "url", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the URL TI object. Args: owner: url: **kwargs: Return:
[ "Create", "the", "URL", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L66-L78
train
27,600
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.email_address
def email_address(self, address, owner=None, **kwargs): """ Create the Email Address TI object. Args: owner: address: **kwargs: Return: """ return EmailAddress(self.tcex, address, owner=owner, **kwargs)
python
def email_address(self, address, owner=None, **kwargs): """ Create the Email Address TI object. Args: owner: address: **kwargs: Return: """ return EmailAddress(self.tcex, address, owner=owner, **kwargs)
[ "def", "email_address", "(", "self", ",", "address", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "EmailAddress", "(", "self", ".", "tcex", ",", "address", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Email Address TI object. Args: owner: address: **kwargs: Return:
[ "Create", "the", "Email", "Address", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L80-L92
train
27,601
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.file
def file(self, owner=None, **kwargs): """ Create the File TI object. Args: owner: **kwargs: Return: """ return File(self.tcex, owner=owner, **kwargs)
python
def file(self, owner=None, **kwargs): """ Create the File TI object. Args: owner: **kwargs: Return: """ return File(self.tcex, owner=owner, **kwargs)
[ "def", "file", "(", "self", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "File", "(", "self", ".", "tcex", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the File TI object. Args: owner: **kwargs: Return:
[ "Create", "the", "File", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L94-L105
train
27,602
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.host
def host(self, hostname, owner=None, **kwargs): """ Create the Host TI object. Args: owner: hostname: **kwargs: Return: """ return Host(self.tcex, hostname, owner=owner, **kwargs)
python
def host(self, hostname, owner=None, **kwargs): """ Create the Host TI object. Args: owner: hostname: **kwargs: Return: """ return Host(self.tcex, hostname, owner=owner, **kwargs)
[ "def", "host", "(", "self", ",", "hostname", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Host", "(", "self", ".", "tcex", ",", "hostname", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Host TI object. Args: owner: hostname: **kwargs: Return:
[ "Create", "the", "Host", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L107-L119
train
27,603
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.indicator
def indicator(self, indicator_type=None, owner=None, **kwargs): """ Create the Indicator TI object. Args: owner: indicator_type: **kwargs: Return: """ if not indicator_type: return Indicator(self.tcex, None, owner=owner, **kwargs) upper_indicator_type = indicator_type.upper() indicator = None if upper_indicator_type == 'ADDRESS': indicator = Address(self.tcex, kwargs.pop('ip', None), owner=owner, **kwargs) elif upper_indicator_type == 'EMAILADDRESS': indicator = EmailAddress(self.tcex, kwargs.pop('address', None), owner=owner, **kwargs) elif upper_indicator_type == 'FILE': indicator = File(self.tcex, **kwargs) elif upper_indicator_type == 'HOST': indicator = Host(self.tcex, kwargs.pop('hostname', None), owner=owner, **kwargs) elif upper_indicator_type == 'URL': indicator = URL(self.tcex, kwargs.pop('url', None), owner=owner, **kwargs) else: try: if upper_indicator_type in self._custom_indicator_classes.keys(): custom_indicator_details = self._custom_indicator_classes[indicator_type] value_fields = custom_indicator_details.get('value_fields') c = getattr(module, custom_indicator_details.get('branch')) if len(value_fields) == 1: indicator = c(value_fields[0], owner=owner, **kwargs) elif len(value_fields) == 2: indicator = c(value_fields[0], value_fields[1], owner=owner, **kwargs) elif len(value_fields) == 3: indicator = c(value_fields[0], value_fields[2], owner=owner, **kwargs) except Exception: return None return indicator
python
def indicator(self, indicator_type=None, owner=None, **kwargs): """ Create the Indicator TI object. Args: owner: indicator_type: **kwargs: Return: """ if not indicator_type: return Indicator(self.tcex, None, owner=owner, **kwargs) upper_indicator_type = indicator_type.upper() indicator = None if upper_indicator_type == 'ADDRESS': indicator = Address(self.tcex, kwargs.pop('ip', None), owner=owner, **kwargs) elif upper_indicator_type == 'EMAILADDRESS': indicator = EmailAddress(self.tcex, kwargs.pop('address', None), owner=owner, **kwargs) elif upper_indicator_type == 'FILE': indicator = File(self.tcex, **kwargs) elif upper_indicator_type == 'HOST': indicator = Host(self.tcex, kwargs.pop('hostname', None), owner=owner, **kwargs) elif upper_indicator_type == 'URL': indicator = URL(self.tcex, kwargs.pop('url', None), owner=owner, **kwargs) else: try: if upper_indicator_type in self._custom_indicator_classes.keys(): custom_indicator_details = self._custom_indicator_classes[indicator_type] value_fields = custom_indicator_details.get('value_fields') c = getattr(module, custom_indicator_details.get('branch')) if len(value_fields) == 1: indicator = c(value_fields[0], owner=owner, **kwargs) elif len(value_fields) == 2: indicator = c(value_fields[0], value_fields[1], owner=owner, **kwargs) elif len(value_fields) == 3: indicator = c(value_fields[0], value_fields[2], owner=owner, **kwargs) except Exception: return None return indicator
[ "def", "indicator", "(", "self", ",", "indicator_type", "=", "None", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "indicator_type", ":", "return", "Indicator", "(", "self", ".", "tcex", ",", "None", ",", "owner", "=", "o...
Create the Indicator TI object. Args: owner: indicator_type: **kwargs: Return:
[ "Create", "the", "Indicator", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L125-L167
train
27,604
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.group
def group(self, group_type=None, owner=None, **kwargs): """ Create the Group TI object. Args: owner: group_type: **kwargs: Return: """ group = None if not group_type: return Group(self.tcex, None, None, owner=owner, **kwargs) name = kwargs.pop('name', None) group_type = group_type.upper() if group_type == 'ADVERSARY': group = Adversary(self.tcex, name, owner=owner, **kwargs) if group_type == 'CAMPAIGN': group = Campaign(self.tcex, name, owner=owner, **kwargs) if group_type == 'DOCUMENT': group = Document(self.tcex, name, kwargs.pop('file_name', None), owner=owner, **kwargs) if group_type == 'EVENT': group = Event(self.tcex, name, owner=owner, **kwargs) if group_type == 'EMAIL': group = Email( self.tcex, name, kwargs.pop('to', None), kwargs.pop('from_addr', None), kwargs.pop('subject', None), kwargs.pop('body', None), kwargs.pop('header', None), owner=owner, **kwargs ) if group_type == 'INCIDENT': group = Incident(self.tcex, name, owner=owner, **kwargs) if group_type == 'INTRUSION SET': group = IntrusionSet(self.tcex, name, owner=owner, **kwargs) if group_type == 'REPORT': group = Report(self.tcex, name, owner=owner, **kwargs) if group_type == 'SIGNATURE': group = Signature( self.tcex, name, kwargs.pop('file_name', None), kwargs.pop('file_type', None), kwargs.pop('file_text', None), owner=owner, **kwargs ) if group_type == 'THREAT': group = Threat(self.tcex, name, owner=owner, **kwargs) if group_type == 'TASK': group = Task( self.tcex, name, kwargs.pop('status', 'Not Started'), kwargs.pop('due_date', None), kwargs.pop('reminder_date', None), kwargs.pop('escalation_date', None), owner=owner, **kwargs ) return group
python
def group(self, group_type=None, owner=None, **kwargs): """ Create the Group TI object. Args: owner: group_type: **kwargs: Return: """ group = None if not group_type: return Group(self.tcex, None, None, owner=owner, **kwargs) name = kwargs.pop('name', None) group_type = group_type.upper() if group_type == 'ADVERSARY': group = Adversary(self.tcex, name, owner=owner, **kwargs) if group_type == 'CAMPAIGN': group = Campaign(self.tcex, name, owner=owner, **kwargs) if group_type == 'DOCUMENT': group = Document(self.tcex, name, kwargs.pop('file_name', None), owner=owner, **kwargs) if group_type == 'EVENT': group = Event(self.tcex, name, owner=owner, **kwargs) if group_type == 'EMAIL': group = Email( self.tcex, name, kwargs.pop('to', None), kwargs.pop('from_addr', None), kwargs.pop('subject', None), kwargs.pop('body', None), kwargs.pop('header', None), owner=owner, **kwargs ) if group_type == 'INCIDENT': group = Incident(self.tcex, name, owner=owner, **kwargs) if group_type == 'INTRUSION SET': group = IntrusionSet(self.tcex, name, owner=owner, **kwargs) if group_type == 'REPORT': group = Report(self.tcex, name, owner=owner, **kwargs) if group_type == 'SIGNATURE': group = Signature( self.tcex, name, kwargs.pop('file_name', None), kwargs.pop('file_type', None), kwargs.pop('file_text', None), owner=owner, **kwargs ) if group_type == 'THREAT': group = Threat(self.tcex, name, owner=owner, **kwargs) if group_type == 'TASK': group = Task( self.tcex, name, kwargs.pop('status', 'Not Started'), kwargs.pop('due_date', None), kwargs.pop('reminder_date', None), kwargs.pop('escalation_date', None), owner=owner, **kwargs ) return group
[ "def", "group", "(", "self", ",", "group_type", "=", "None", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "group", "=", "None", "if", "not", "group_type", ":", "return", "Group", "(", "self", ".", "tcex", ",", "None", ",", "None", ...
Create the Group TI object. Args: owner: group_type: **kwargs: Return:
[ "Create", "the", "Group", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L169-L237
train
27,605
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.adversary
def adversary(self, name, owner=None, **kwargs): """ Create the Adversary TI object. Args: owner: name: **kwargs: Return: """ return Adversary(self.tcex, name, owner=owner, **kwargs)
python
def adversary(self, name, owner=None, **kwargs): """ Create the Adversary TI object. Args: owner: name: **kwargs: Return: """ return Adversary(self.tcex, name, owner=owner, **kwargs)
[ "def", "adversary", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Adversary", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Adversary TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Adversary", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L239-L251
train
27,606
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.campaign
def campaign(self, name, owner=None, **kwargs): """ Create the Campaign TI object. Args: owner: name: **kwargs: Return: """ return Campaign(self.tcex, name, owner=owner, **kwargs)
python
def campaign(self, name, owner=None, **kwargs): """ Create the Campaign TI object. Args: owner: name: **kwargs: Return: """ return Campaign(self.tcex, name, owner=owner, **kwargs)
[ "def", "campaign", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Campaign", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Campaign TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Campaign", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L253-L265
train
27,607
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.document
def document(self, name, file_name, owner=None, **kwargs): """ Create the Document TI object. Args: owner: name: file_name: **kwargs: Return: """ return Document(self.tcex, name, file_name, owner=owner, **kwargs)
python
def document(self, name, file_name, owner=None, **kwargs): """ Create the Document TI object. Args: owner: name: file_name: **kwargs: Return: """ return Document(self.tcex, name, file_name, owner=owner, **kwargs)
[ "def", "document", "(", "self", ",", "name", ",", "file_name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Document", "(", "self", ".", "tcex", ",", "name", ",", "file_name", ",", "owner", "=", "owner", ",", "*", "*", ...
Create the Document TI object. Args: owner: name: file_name: **kwargs: Return:
[ "Create", "the", "Document", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L267-L280
train
27,608
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.event
def event(self, name, owner=None, **kwargs): """ Create the Event TI object. Args: name: **kwargs: Return: """ return Event(self.tcex, name, owner=owner, **kwargs)
python
def event(self, name, owner=None, **kwargs): """ Create the Event TI object. Args: name: **kwargs: Return: """ return Event(self.tcex, name, owner=owner, **kwargs)
[ "def", "event", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Event", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Event TI object. Args: name: **kwargs: Return:
[ "Create", "the", "Event", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L282-L293
train
27,609
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.email
def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs): """ Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return: """ return Email(self.tcex, name, to, from_addr, subject, body, header, owner=owner, **kwargs)
python
def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs): """ Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return: """ return Email(self.tcex, name, to, from_addr, subject, body, header, owner=owner, **kwargs)
[ "def", "email", "(", "self", ",", "name", ",", "to", ",", "from_addr", ",", "subject", ",", "body", ",", "header", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Email", "(", "self", ".", "tcex", ",", "name", ",", "to", ...
Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return:
[ "Create", "the", "Email", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L295-L312
train
27,610
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.incident
def incident(self, name, owner=None, **kwargs): """ Create the Incident TI object. Args: owner: name: **kwargs: Return: """ return Incident(self.tcex, name, owner=owner, **kwargs)
python
def incident(self, name, owner=None, **kwargs): """ Create the Incident TI object. Args: owner: name: **kwargs: Return: """ return Incident(self.tcex, name, owner=owner, **kwargs)
[ "def", "incident", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Incident", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Incident TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Incident", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L314-L326
train
27,611
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.intrusion_sets
def intrusion_sets(self, name, owner=None, **kwargs): """ Create the Intrustion Set TI object. Args: owner: name: **kwargs: Return: """ return IntrusionSet(self.tcex, name, owner=owner, **kwargs)
python
def intrusion_sets(self, name, owner=None, **kwargs): """ Create the Intrustion Set TI object. Args: owner: name: **kwargs: Return: """ return IntrusionSet(self.tcex, name, owner=owner, **kwargs)
[ "def", "intrusion_sets", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "IntrusionSet", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Intrustion Set TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Intrustion", "Set", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L328-L340
train
27,612
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.report
def report(self, name, owner=None, **kwargs): """ Create the Report TI object. Args: owner: name: **kwargs: Return: """ return Report(self.tcex, name, owner=owner, **kwargs)
python
def report(self, name, owner=None, **kwargs): """ Create the Report TI object. Args: owner: name: **kwargs: Return: """ return Report(self.tcex, name, owner=owner, **kwargs)
[ "def", "report", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Report", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Report TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Report", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L342-L354
train
27,613
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.signature
def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs): """ Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return: """ return Signature(self.tcex, name, file_name, file_type, file_content, owner=owner, **kwargs)
python
def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs): """ Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return: """ return Signature(self.tcex, name, file_name, file_type, file_content, owner=owner, **kwargs)
[ "def", "signature", "(", "self", ",", "name", ",", "file_name", ",", "file_type", ",", "file_content", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Signature", "(", "self", ".", "tcex", ",", "name", ",", "file_name", ",", ...
Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return:
[ "Create", "the", "Signature", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L356-L371
train
27,614
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.threat
def threat(self, name, owner=None, **kwargs): """ Create the Threat TI object. Args: owner: name: **kwargs: Return: """ return Threat(self.tcex, name, owner=owner, **kwargs)
python
def threat(self, name, owner=None, **kwargs): """ Create the Threat TI object. Args: owner: name: **kwargs: Return: """ return Threat(self.tcex, name, owner=owner, **kwargs)
[ "def", "threat", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Threat", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Threat TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Threat", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L373-L385
train
27,615
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti.py
TcExTi.victim
def victim(self, name, owner=None, **kwargs): """ Create the Victim TI object. Args: owner: name: **kwargs: Return: """ return Victim(self.tcex, name, owner=owner, **kwargs)
python
def victim(self, name, owner=None, **kwargs): """ Create the Victim TI object. Args: owner: name: **kwargs: Return: """ return Victim(self.tcex, name, owner=owner, **kwargs)
[ "def", "victim", "(", "self", ",", "name", ",", "owner", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Victim", "(", "self", ".", "tcex", ",", "name", ",", "owner", "=", "owner", ",", "*", "*", "kwargs", ")" ]
Create the Victim TI object. Args: owner: name: **kwargs: Return:
[ "Create", "the", "Victim", "TI", "object", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L387-L399
train
27,616
ThreatConnect-Inc/tcex
tcex/tcex_logger.py
TcExLogFormatter.format
def format(self, record): """Format log record for ThreatConnect API. Example log event:: [{ "timestamp": 1478907537000, "message": "Test Message", "level": "DEBUG" }] """ return { 'timestamp': int(float(record.created or time.time()) * 1000), 'message': record.msg or '', 'level': record.levelname or 'DEBUG', }
python
def format(self, record): """Format log record for ThreatConnect API. Example log event:: [{ "timestamp": 1478907537000, "message": "Test Message", "level": "DEBUG" }] """ return { 'timestamp': int(float(record.created or time.time()) * 1000), 'message': record.msg or '', 'level': record.levelname or 'DEBUG', }
[ "def", "format", "(", "self", ",", "record", ")", ":", "return", "{", "'timestamp'", ":", "int", "(", "float", "(", "record", ".", "created", "or", "time", ".", "time", "(", ")", ")", "*", "1000", ")", ",", "'message'", ":", "record", ".", "msg", ...
Format log record for ThreatConnect API. Example log event:: [{ "timestamp": 1478907537000, "message": "Test Message", "level": "DEBUG" }]
[ "Format", "log", "record", "for", "ThreatConnect", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_logger.py#L15-L30
train
27,617
ThreatConnect-Inc/tcex
tcex/tcex_logger.py
TcExLogHandler.emit
def emit(self, record): """Emit the log record.""" self.entries.append(self.format(record)) if len(self.entries) > self.flush_limit and not self.session.auth.renewing: self.log_to_api() self.entries = []
python
def emit(self, record): """Emit the log record.""" self.entries.append(self.format(record)) if len(self.entries) > self.flush_limit and not self.session.auth.renewing: self.log_to_api() self.entries = []
[ "def", "emit", "(", "self", ",", "record", ")", ":", "self", ".", "entries", ".", "append", "(", "self", ".", "format", "(", "record", ")", ")", "if", "len", "(", "self", ".", "entries", ")", ">", "self", ".", "flush_limit", "and", "not", "self", ...
Emit the log record.
[ "Emit", "the", "log", "record", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_logger.py#L53-L58
train
27,618
ThreatConnect-Inc/tcex
tcex/tcex_logger.py
TcExLogHandler.log_to_api
def log_to_api(self): """Best effort API logger. Send logs to the ThreatConnect API and do nothing if the attempt fails. """ if self.entries: try: headers = {'Content-Type': 'application/json'} self.session.post('/v2/logs/app', headers=headers, json=self.entries) # self.entries = [] # clear entries except Exception: # best effort on api logging pass
python
def log_to_api(self): """Best effort API logger. Send logs to the ThreatConnect API and do nothing if the attempt fails. """ if self.entries: try: headers = {'Content-Type': 'application/json'} self.session.post('/v2/logs/app', headers=headers, json=self.entries) # self.entries = [] # clear entries except Exception: # best effort on api logging pass
[ "def", "log_to_api", "(", "self", ")", ":", "if", "self", ".", "entries", ":", "try", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "self", ".", "session", ".", "post", "(", "'/v2/logs/app'", ",", "headers", "=", "headers", ...
Best effort API logger. Send logs to the ThreatConnect API and do nothing if the attempt fails.
[ "Best", "effort", "API", "logger", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_logger.py#L60-L72
train
27,619
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
class_factory
def class_factory(name, base_class, class_dict): """Internal method for dynamically building Custom Indicator classes.""" def __init__(self, tcex): base_class.__init__(self, tcex) for k, v in class_dict.items(): setattr(self, k, v) newclass = type(str(name), (base_class,), {'__init__': __init__}) return newclass
python
def class_factory(name, base_class, class_dict): """Internal method for dynamically building Custom Indicator classes.""" def __init__(self, tcex): base_class.__init__(self, tcex) for k, v in class_dict.items(): setattr(self, k, v) newclass = type(str(name), (base_class,), {'__init__': __init__}) return newclass
[ "def", "class_factory", "(", "name", ",", "base_class", ",", "class_dict", ")", ":", "def", "__init__", "(", "self", ",", "tcex", ")", ":", "base_class", ".", "__init__", "(", "self", ",", "tcex", ")", "for", "k", ",", "v", "in", "class_dict", ".", "...
Internal method for dynamically building Custom Indicator classes.
[ "Internal", "method", "for", "dynamically", "building", "Custom", "Indicator", "classes", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2637-L2646
train
27,620
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._apply_filters
def _apply_filters(self): """Apply any filters added to the resource. """ # apply filters filters = [] for f in self._filters: filters.append('{}{}{}'.format(f['name'], f['operator'], f['value'])) self.tcex.log.debug(u'filters: {}'.format(filters)) if filters: self._request.add_payload('filters', ','.join(filters))
python
def _apply_filters(self): """Apply any filters added to the resource. """ # apply filters filters = [] for f in self._filters: filters.append('{}{}{}'.format(f['name'], f['operator'], f['value'])) self.tcex.log.debug(u'filters: {}'.format(filters)) if filters: self._request.add_payload('filters', ','.join(filters))
[ "def", "_apply_filters", "(", "self", ")", ":", "# apply filters", "filters", "=", "[", "]", "for", "f", "in", "self", ".", "_filters", ":", "filters", ".", "append", "(", "'{}{}{}'", ".", "format", "(", "f", "[", "'name'", "]", ",", "f", "[", "'oper...
Apply any filters added to the resource.
[ "Apply", "any", "filters", "added", "to", "the", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L54-L64
train
27,621
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._request_process_json
def _request_process_json(self, response): """Handle response data of type JSON Return: (string): The data from the download (string): The status of the download """ data = [] try: if self._api_branch == 'bulk': response_data = self._request_bulk(response) else: response_data = response.json() if self._request_entity is None: data = response_data status = 'Success' elif self._api_branch == 'bulk': data, status = self._request_process_json_bulk(response_data) elif response_data.get('data') is None: data, status = self._request_process_json_status(response_data) elif response_data.get('status') == 'Success': data, status = self._request_process_json_standard(response_data) # setup pagination if self._result_count is None: self._result_count = response_data.get('data', {}).get('resultCount') else: self.tcex.log.error('Failed Request: {}'.format(response.text)) status = 'Failure' except KeyError as e: # TODO: Remove try/except block status = 'Failure' msg = u'Error: Invalid key {}. [{}] '.format(e, self.request_entity) self.tcex.log.error(msg) except ValueError as e: # TODO: Remove try/except block status = 'Failure' msg = u'Error: ({})'.format(e) self.tcex.log.error(msg) return data, status
python
def _request_process_json(self, response): """Handle response data of type JSON Return: (string): The data from the download (string): The status of the download """ data = [] try: if self._api_branch == 'bulk': response_data = self._request_bulk(response) else: response_data = response.json() if self._request_entity is None: data = response_data status = 'Success' elif self._api_branch == 'bulk': data, status = self._request_process_json_bulk(response_data) elif response_data.get('data') is None: data, status = self._request_process_json_status(response_data) elif response_data.get('status') == 'Success': data, status = self._request_process_json_standard(response_data) # setup pagination if self._result_count is None: self._result_count = response_data.get('data', {}).get('resultCount') else: self.tcex.log.error('Failed Request: {}'.format(response.text)) status = 'Failure' except KeyError as e: # TODO: Remove try/except block status = 'Failure' msg = u'Error: Invalid key {}. [{}] '.format(e, self.request_entity) self.tcex.log.error(msg) except ValueError as e: # TODO: Remove try/except block status = 'Failure' msg = u'Error: ({})'.format(e) self.tcex.log.error(msg) return data, status
[ "def", "_request_process_json", "(", "self", ",", "response", ")", ":", "data", "=", "[", "]", "try", ":", "if", "self", ".", "_api_branch", "==", "'bulk'", ":", "response_data", "=", "self", ".", "_request_bulk", "(", "response", ")", "else", ":", "resp...
Handle response data of type JSON Return: (string): The data from the download (string): The status of the download
[ "Handle", "response", "data", "of", "type", "JSON" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L135-L176
train
27,622
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._request_process_json_bulk
def _request_process_json_bulk(self, response_data): """Handle bulk JSON response Return: (string): The response data (string): The response status """ status = 'Failure' data = response_data.get(self.request_entity, []) if data: status = 'Success' return data, status
python
def _request_process_json_bulk(self, response_data): """Handle bulk JSON response Return: (string): The response data (string): The response status """ status = 'Failure' data = response_data.get(self.request_entity, []) if data: status = 'Success' return data, status
[ "def", "_request_process_json_bulk", "(", "self", ",", "response_data", ")", ":", "status", "=", "'Failure'", "data", "=", "response_data", ".", "get", "(", "self", ".", "request_entity", ",", "[", "]", ")", "if", "data", ":", "status", "=", "'Success'", "...
Handle bulk JSON response Return: (string): The response data (string): The response status
[ "Handle", "bulk", "JSON", "response" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L178-L189
train
27,623
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._request_process_json_standard
def _request_process_json_standard(self, response_data): """Handle JSON response This should be the most common response from the ThreatConnect API. Return: (string): The response data (string): The response status """ data = response_data.get('data', {}).get(self.request_entity, []) status = response_data.get('status', 'Failure') return data, status
python
def _request_process_json_standard(self, response_data): """Handle JSON response This should be the most common response from the ThreatConnect API. Return: (string): The response data (string): The response status """ data = response_data.get('data', {}).get(self.request_entity, []) status = response_data.get('status', 'Failure') return data, status
[ "def", "_request_process_json_standard", "(", "self", ",", "response_data", ")", ":", "data", "=", "response_data", ".", "get", "(", "'data'", ",", "{", "}", ")", ".", "get", "(", "self", ".", "request_entity", ",", "[", "]", ")", "status", "=", "respons...
Handle JSON response This should be the most common response from the ThreatConnect API. Return: (string): The response data (string): The response status
[ "Handle", "JSON", "response" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L191-L202
train
27,624
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._request_process_octet
def _request_process_octet(response): """Handle Document download. Return: (string): The data from the download (string): The status of the download """ status = 'Failure' # Handle document download data = response.content if data: status = 'Success' return data, status
python
def _request_process_octet(response): """Handle Document download. Return: (string): The data from the download (string): The status of the download """ status = 'Failure' # Handle document download data = response.content if data: status = 'Success' return data, status
[ "def", "_request_process_octet", "(", "response", ")", ":", "status", "=", "'Failure'", "# Handle document download", "data", "=", "response", ".", "content", "if", "data", ":", "status", "=", "'Success'", "return", "data", ",", "status" ]
Handle Document download. Return: (string): The data from the download (string): The status of the download
[ "Handle", "Document", "download", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L219-L232
train
27,625
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource._request_process_text
def _request_process_text(response): """Handle Signature download. Return: (string): The data from the download (string): The status of the download """ status = 'Failure' # Handle document download data = response.content if data: status = 'Success' return data, status
python
def _request_process_text(response): """Handle Signature download. Return: (string): The data from the download (string): The status of the download """ status = 'Failure' # Handle document download data = response.content if data: status = 'Success' return data, status
[ "def", "_request_process_text", "(", "response", ")", ":", "status", "=", "'Failure'", "# Handle document download", "data", "=", "response", ".", "content", "if", "data", ":", "status", "=", "'Success'", "return", "data", ",", "status" ]
Handle Signature download. Return: (string): The data from the download (string): The status of the download
[ "Handle", "Signature", "download", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L235-L248
train
27,626
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.add_filter
def add_filter(self, name, operator, value): """Add ThreatConnect API Filter for this resource request. External Reference: https://docs.threatconnect.com Args: name (string): The filter field name. operator (string): The filter comparison operator. value (string): The filter value. """ self._filters.append({'name': name, 'operator': operator, 'value': value})
python
def add_filter(self, name, operator, value): """Add ThreatConnect API Filter for this resource request. External Reference: https://docs.threatconnect.com Args: name (string): The filter field name. operator (string): The filter comparison operator. value (string): The filter value. """ self._filters.append({'name': name, 'operator': operator, 'value': value})
[ "def", "add_filter", "(", "self", ",", "name", ",", "operator", ",", "value", ")", ":", "self", ".", "_filters", ".", "append", "(", "{", "'name'", ":", "name", ",", "'operator'", ":", "operator", ",", "'value'", ":", "value", "}", ")" ]
Add ThreatConnect API Filter for this resource request. External Reference: https://docs.threatconnect.com Args: name (string): The filter field name. operator (string): The filter comparison operator. value (string): The filter value.
[ "Add", "ThreatConnect", "API", "Filter", "for", "this", "resource", "request", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L250-L261
train
27,627
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.association_custom
def association_custom(self, association_name, association_resource=None): """Custom Indicator association for this resource with resource value. **Example Endpoints URI's** +--------+--------------------------------------------------------------------------+ | HTTP | API Endpoint URI's | +========+==========================================================================+ | {base} | /v2/indicators/{indicatorType}/{uniqueId}/associations/{associationName} | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators/{indicatorType} | +--------+--------------------------------------------------------------------------+ | DELETE | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ | POST | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ Args: association_name (string): The name of the custom association as defined in the UI. association_resource (object): An instance of Resource for an Indicator or sub type. """ resource = self.copy() association_api_branch = self.tcex.indicator_associations_types_data.get( association_name, {} ).get('apiBranch') if association_api_branch is None: self.tcex.handle_error(305, [association_name]) # handle URL difference between Custom Associations and File Actions custom_type = 'associations' file_action = self.tcex.utils.to_bool( self.tcex.indicator_associations_types_data.get(association_name, {}).get('fileAction') ) if file_action: custom_type = 'actions' resource._request_entity = 'indicator' if association_resource is not None: resource._request_uri = '{}/{}/{}/{}'.format( resource._request_uri, custom_type, association_api_branch, association_resource.request_uri, ) else: resource._request_uri = '{}/{}/{}/indicators'.format( resource._request_uri, custom_type, association_api_branch ) return resource
python
def association_custom(self, association_name, association_resource=None): """Custom Indicator association for this resource with resource value. **Example Endpoints URI's** +--------+--------------------------------------------------------------------------+ | HTTP | API Endpoint URI's | +========+==========================================================================+ | {base} | /v2/indicators/{indicatorType}/{uniqueId}/associations/{associationName} | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators/{indicatorType} | +--------+--------------------------------------------------------------------------+ | DELETE | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ | POST | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ Args: association_name (string): The name of the custom association as defined in the UI. association_resource (object): An instance of Resource for an Indicator or sub type. """ resource = self.copy() association_api_branch = self.tcex.indicator_associations_types_data.get( association_name, {} ).get('apiBranch') if association_api_branch is None: self.tcex.handle_error(305, [association_name]) # handle URL difference between Custom Associations and File Actions custom_type = 'associations' file_action = self.tcex.utils.to_bool( self.tcex.indicator_associations_types_data.get(association_name, {}).get('fileAction') ) if file_action: custom_type = 'actions' resource._request_entity = 'indicator' if association_resource is not None: resource._request_uri = '{}/{}/{}/{}'.format( resource._request_uri, custom_type, association_api_branch, association_resource.request_uri, ) else: resource._request_uri = '{}/{}/{}/indicators'.format( resource._request_uri, custom_type, association_api_branch ) return resource
[ "def", "association_custom", "(", "self", ",", "association_name", ",", "association_resource", "=", "None", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "association_api_branch", "=", "self", ".", "tcex", ".", "indicator_associations_types_data", "."...
Custom Indicator association for this resource with resource value. **Example Endpoints URI's** +--------+--------------------------------------------------------------------------+ | HTTP | API Endpoint URI's | +========+==========================================================================+ | {base} | /v2/indicators/{indicatorType}/{uniqueId}/associations/{associationName} | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators | +--------+--------------------------------------------------------------------------+ | GET | {base}/indicators/{indicatorType} | +--------+--------------------------------------------------------------------------+ | DELETE | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ | POST | {base}/indicators/{indicatorType}/{value} | +--------+--------------------------------------------------------------------------+ Args: association_name (string): The name of the custom association as defined in the UI. association_resource (object): An instance of Resource for an Indicator or sub type.
[ "Custom", "Indicator", "association", "for", "this", "resource", "with", "resource", "value", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L312-L362
train
27,628
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.association_pivot
def association_pivot(self, association_resource): """Pivot point on association for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | METHOD | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/indicator/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ Args: resource_api_branch (string): The resource pivot api branch including resource id. """ resource = self.copy() resource._request_uri = '{}/{}'.format( association_resource.request_uri, resource._request_uri ) return resource
python
def association_pivot(self, association_resource): """Pivot point on association for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | METHOD | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/indicator/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ Args: resource_api_branch (string): The resource pivot api branch including resource id. """ resource = self.copy() resource._request_uri = '{}/{}'.format( association_resource.request_uri, resource._request_uri ) return resource
[ "def", "association_pivot", "(", "self", ",", "association_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "association_resource", ".", "request_uri", ",", "resource", "....
Pivot point on association for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | METHOD | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/indicator/{pivot resourceType}/{pivot uniqueId}/{resourceType}/{uniqueId} | +---------+--------------------------------------------------------------------------------+ Args: resource_api_branch (string): The resource pivot api branch including resource id.
[ "Pivot", "point", "on", "association", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L364-L395
train
27,629
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.associations
def associations(self, association_resource): """Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. **Example Endpoints URI's** +--------+----------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+======================================================================+ | {base} | /v2/{resourceClass}/{resourceType}/{resourceId} | +--------+----------------------------------------------------------------------+ | GET | {base}/{assoc resourceClass}/{assoc resourceType} | +--------+----------------------------------------------------------------------+ | POST | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ | DELETE | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ + resourceClass - Groups/Indicators + resourceType - Adversary, Incident, etc / Address, EmailAddress, etc + resourceId - Group Id / Indicator Value Args: association_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for associations. """ resource = self.copy() resource._request_entity = association_resource.api_entity resource._request_uri = '{}/{}'.format( resource._request_uri, association_resource.request_uri ) return resource
python
def associations(self, association_resource): """Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. **Example Endpoints URI's** +--------+----------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+======================================================================+ | {base} | /v2/{resourceClass}/{resourceType}/{resourceId} | +--------+----------------------------------------------------------------------+ | GET | {base}/{assoc resourceClass}/{assoc resourceType} | +--------+----------------------------------------------------------------------+ | POST | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ | DELETE | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ + resourceClass - Groups/Indicators + resourceType - Adversary, Incident, etc / Address, EmailAddress, etc + resourceId - Group Id / Indicator Value Args: association_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for associations. """ resource = self.copy() resource._request_entity = association_resource.api_entity resource._request_uri = '{}/{}'.format( resource._request_uri, association_resource.request_uri ) return resource
[ "def", "associations", "(", "self", ",", "association_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_entity", "=", "association_resource", ".", "api_entity", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", ...
Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. **Example Endpoints URI's** +--------+----------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+======================================================================+ | {base} | /v2/{resourceClass}/{resourceType}/{resourceId} | +--------+----------------------------------------------------------------------+ | GET | {base}/{assoc resourceClass}/{assoc resourceType} | +--------+----------------------------------------------------------------------+ | POST | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ | DELETE | {base}/{assoc resourceClass}/{assoc resourceType}/{assoc resourceId} | +--------+----------------------------------------------------------------------+ + resourceClass - Groups/Indicators + resourceType - Adversary, Incident, etc / Address, EmailAddress, etc + resourceId - Group Id / Indicator Value Args: association_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for associations.
[ "Retrieve", "Association", "for", "this", "resource", "of", "the", "type", "in", "association_resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L397-L431
train
27,630
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.attributes
def attributes(self, resource_id=None): """Attribute endpoint for this resource with optional attribute id. This method will set the resource endpoint for working with Attributes. The HTTP GET method will return all attributes applied to this resource or if a resource id (attribute id) is provided it will return the provided attribute if exists on this resource. An attribute can be added to this resource using the HTTP POST method and passing a JSON body containing the attribute type and attribute value. Using the HTTP PUT method with a provided resource id an attribute can be updated. The HTTP DELETE method will remove the provided attribute from this resource. **Example Endpoints URI's** +--------------+--------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+==============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | PUT | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (attribute id). """ resource = self.copy() resource._request_entity = 'attribute' resource._request_uri = '{}/attributes'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, resource_id) return resource
python
def attributes(self, resource_id=None): """Attribute endpoint for this resource with optional attribute id. This method will set the resource endpoint for working with Attributes. The HTTP GET method will return all attributes applied to this resource or if a resource id (attribute id) is provided it will return the provided attribute if exists on this resource. An attribute can be added to this resource using the HTTP POST method and passing a JSON body containing the attribute type and attribute value. Using the HTTP PUT method with a provided resource id an attribute can be updated. The HTTP DELETE method will remove the provided attribute from this resource. **Example Endpoints URI's** +--------------+--------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+==============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | PUT | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (attribute id). """ resource = self.copy() resource._request_entity = 'attribute' resource._request_uri = '{}/attributes'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, resource_id) return resource
[ "def", "attributes", "(", "self", ",", "resource_id", "=", "None", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_entity", "=", "'attribute'", "resource", ".", "_request_uri", "=", "'{}/attributes'", ".", "format", "(", ...
Attribute endpoint for this resource with optional attribute id. This method will set the resource endpoint for working with Attributes. The HTTP GET method will return all attributes applied to this resource or if a resource id (attribute id) is provided it will return the provided attribute if exists on this resource. An attribute can be added to this resource using the HTTP POST method and passing a JSON body containing the attribute type and attribute value. Using the HTTP PUT method with a provided resource id an attribute can be updated. The HTTP DELETE method will remove the provided attribute from this resource. **Example Endpoints URI's** +--------------+--------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+==============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/attributes | +--------------+--------------------------------------------------------------+ | PUT | /v2/groups/{resourceType}/{uniqueId}/attributes/{resourceId} | +--------------+--------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (attribute id).
[ "Attribute", "endpoint", "for", "this", "resource", "with", "optional", "attribute", "id", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L433-L470
train
27,631
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.copy_reset
def copy_reset(self): """Reset values after instance has been copied""" # Reset settings self._filters = [] self._filter_or = False self._paginate = True self._paginate_count = 0 self._result_count = None self._result_limit = 500 self._result_start = 0
python
def copy_reset(self): """Reset values after instance has been copied""" # Reset settings self._filters = [] self._filter_or = False self._paginate = True self._paginate_count = 0 self._result_count = None self._result_limit = 500 self._result_start = 0
[ "def", "copy_reset", "(", "self", ")", ":", "# Reset settings", "self", ".", "_filters", "=", "[", "]", "self", ".", "_filter_or", "=", "False", "self", ".", "_paginate", "=", "True", "self", ".", "_paginate_count", "=", "0", "self", ".", "_result_count", ...
Reset values after instance has been copied
[ "Reset", "values", "after", "instance", "has", "been", "copied" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L513-L522
train
27,632
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.copy
def copy(self): """Return a "clean" copy of this instance. Return: (instance): A clean copy of this instance. """ resource = copy.copy(self) # workaround for bytes/str issue in Py3 with copy of instance # TypeError: a bytes-like object is required, not 'str' (ssl.py) resource._request = self.tcex.request(self.tcex.session) # reset properties of resource resource.copy_reset() # Preserve settings resource.http_method = self.http_method if self._request.payload.get('owner') is not None: resource.owner = self._request.payload.get('owner') # future bcs - these should not need to be reset. correct? # resource._request_entity = self._api_entity # resource._request_uri = self._api_uri return resource
python
def copy(self): """Return a "clean" copy of this instance. Return: (instance): A clean copy of this instance. """ resource = copy.copy(self) # workaround for bytes/str issue in Py3 with copy of instance # TypeError: a bytes-like object is required, not 'str' (ssl.py) resource._request = self.tcex.request(self.tcex.session) # reset properties of resource resource.copy_reset() # Preserve settings resource.http_method = self.http_method if self._request.payload.get('owner') is not None: resource.owner = self._request.payload.get('owner') # future bcs - these should not need to be reset. correct? # resource._request_entity = self._api_entity # resource._request_uri = self._api_uri return resource
[ "def", "copy", "(", "self", ")", ":", "resource", "=", "copy", ".", "copy", "(", "self", ")", "# workaround for bytes/str issue in Py3 with copy of instance", "# TypeError: a bytes-like object is required, not 'str' (ssl.py)", "resource", ".", "_request", "=", "self", ".", ...
Return a "clean" copy of this instance. Return: (instance): A clean copy of this instance.
[ "Return", "a", "clean", "copy", "of", "this", "instance", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L524-L547
train
27,633
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.group_pivot
def group_pivot(self, group_resource): """Pivot point on groups for this resource. This method will return all *resources* (indicators, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: group_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for group associations. """ resource = self.copy() resource._request_uri = '{}/{}'.format(group_resource.request_uri, resource._request_uri) return resource
python
def group_pivot(self, group_resource): """Pivot point on groups for this resource. This method will return all *resources* (indicators, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: group_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for group associations. """ resource = self.copy() resource._request_uri = '{}/{}'.format(group_resource.request_uri, resource._request_uri) return resource
[ "def", "group_pivot", "(", "self", ",", "group_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "group_resource", ".", "request_uri", ",", "resource", ".", "_request_uri...
Pivot point on groups for this resource. This method will return all *resources* (indicators, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: group_resource (Resource Instance): A resource object with optional resource_id. Return: (instance): A copy of this resource instance cleaned and updated for group associations.
[ "Pivot", "point", "on", "groups", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L558-L590
train
27,634
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.http_method
def http_method(self, data): """The HTTP Method for this resource request.""" data = data.upper() if data in ['DELETE', 'GET', 'POST', 'PUT']: self._request.http_method = data self._http_method = data
python
def http_method(self, data): """The HTTP Method for this resource request.""" data = data.upper() if data in ['DELETE', 'GET', 'POST', 'PUT']: self._request.http_method = data self._http_method = data
[ "def", "http_method", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "upper", "(", ")", "if", "data", "in", "[", "'DELETE'", ",", "'GET'", ",", "'POST'", ",", "'PUT'", "]", ":", "self", ".", "_request", ".", "http_method", "=", "data...
The HTTP Method for this resource request.
[ "The", "HTTP", "Method", "for", "this", "resource", "request", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L602-L607
train
27,635
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.indicator_pivot
def indicator_pivot(self, indicator_resource): """Pivot point on indicators for this resource. This method will return all *resources* (groups, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: resource_type (string): The resource pivot resource type (indicator type). resource_id (integer): The resource pivot id (indicator value). """ resource = self.copy() resource._request_uri = '{}/{}'.format( indicator_resource.request_uri, resource._request_uri ) return resource
python
def indicator_pivot(self, indicator_resource): """Pivot point on indicators for this resource. This method will return all *resources* (groups, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: resource_type (string): The resource pivot resource type (indicator type). resource_id (integer): The resource pivot id (indicator value). """ resource = self.copy() resource._request_uri = '{}/{}'.format( indicator_resource.request_uri, resource._request_uri ) return resource
[ "def", "indicator_pivot", "(", "self", ",", "indicator_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "indicator_resource", ".", "request_uri", ",", "resource", ".", "...
Pivot point on indicators for this resource. This method will return all *resources* (groups, tasks, victims, etc) for this resource that are associated with the provided resource id (indicator value). **Example Endpoints URI's** +--------+---------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +========+=================================================================================+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/groups/{resourceType}/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/tasks/{uniqueId} | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/ | +--------+---------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{resourceId}/victims/{uniqueId} | +--------+---------------------------------------------------------------------------------+ Args: resource_type (string): The resource pivot resource type (indicator type). resource_id (integer): The resource pivot id (indicator value).
[ "Pivot", "point", "on", "indicators", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L609-L642
train
27,636
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.owner
def owner(self, data): """The Owner payload value for this resource request.""" if data is not None: self._request.add_payload('owner', data) else: self.tcex.log.warn(u'Provided owner was invalid. ({})'.format(data))
python
def owner(self, data): """The Owner payload value for this resource request.""" if data is not None: self._request.add_payload('owner', data) else: self.tcex.log.warn(u'Provided owner was invalid. ({})'.format(data))
[ "def", "owner", "(", "self", ",", "data", ")", ":", "if", "data", "is", "not", "None", ":", "self", ".", "_request", ".", "add_payload", "(", "'owner'", ",", "data", ")", "else", ":", "self", ".", "tcex", ".", "log", ".", "warn", "(", "u'Provided o...
The Owner payload value for this resource request.
[ "The", "Owner", "payload", "value", "for", "this", "resource", "request", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L663-L668
train
27,637
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.paginate
def paginate(self): """Paginate results from ThreatConnect API .. Attention:: This method will be deprecated in a future release. Return: (dictionary): Resource Data """ self.tcex.log.warning(u'Using deprecated method (paginate).') resources = [] self._request.add_payload('resultStart', self._result_start) self._request.add_payload('resultLimit', self._result_limit) results = self.request() response = results.get('response') if results.get('status') == 'Success': data = response.json()['data'] resources = data[self.request_entity] # set results count returned by first API call if data.get('resultCount') is not None: self._result_count = data.get('resultCount') # self._result_start = self._result_limit self.tcex.log.debug(u'Result Count: {}'.format(self._result_count)) while True: if len(resources) >= self._result_count: break self._result_start += self._result_limit self._request.add_payload('resultStart', self._result_start) results = self.request() resources.extend(results['data']) self.tcex.log.debug(u'Resource Count: {}'.format(len(resources))) return resources
python
def paginate(self): """Paginate results from ThreatConnect API .. Attention:: This method will be deprecated in a future release. Return: (dictionary): Resource Data """ self.tcex.log.warning(u'Using deprecated method (paginate).') resources = [] self._request.add_payload('resultStart', self._result_start) self._request.add_payload('resultLimit', self._result_limit) results = self.request() response = results.get('response') if results.get('status') == 'Success': data = response.json()['data'] resources = data[self.request_entity] # set results count returned by first API call if data.get('resultCount') is not None: self._result_count = data.get('resultCount') # self._result_start = self._result_limit self.tcex.log.debug(u'Result Count: {}'.format(self._result_count)) while True: if len(resources) >= self._result_count: break self._result_start += self._result_limit self._request.add_payload('resultStart', self._result_start) results = self.request() resources.extend(results['data']) self.tcex.log.debug(u'Resource Count: {}'.format(len(resources))) return resources
[ "def", "paginate", "(", "self", ")", ":", "self", ".", "tcex", ".", "log", ".", "warning", "(", "u'Using deprecated method (paginate).'", ")", "resources", "=", "[", "]", "self", ".", "_request", ".", "add_payload", "(", "'resultStart'", ",", "self", ".", ...
Paginate results from ThreatConnect API .. Attention:: This method will be deprecated in a future release. Return: (dictionary): Resource Data
[ "Paginate", "results", "from", "ThreatConnect", "API" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L680-L715
train
27,638
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.request
def request(self): """Send the request to the API. This method will send the request to the API. It will try to handle all the types of responses and provide the relevant data when possible. Some basic error detection and handling is implemented, but not all failure cases will get caught. Return: (dictionary): Response/Results data. """ # self._request.authorization_method(self._authorization_method) self._request.url = '{}/v2/{}'.format(self.tcex.default_args.tc_api_path, self._request_uri) self._apply_filters() self.tcex.log.debug(u'Resource URL: ({})'.format(self._request.url)) response = self._request.send(stream=self._stream) data, status = self._request_process(response) # # bcs - to reset or not to reset? # self._request.body = None # # self._request.reset_headers() # # self._request.reset_payload() # self._request_uri = self._api_uri # self._request_entity = self._api_entity return {'data': data, 'response': response, 'status': status}
python
def request(self): """Send the request to the API. This method will send the request to the API. It will try to handle all the types of responses and provide the relevant data when possible. Some basic error detection and handling is implemented, but not all failure cases will get caught. Return: (dictionary): Response/Results data. """ # self._request.authorization_method(self._authorization_method) self._request.url = '{}/v2/{}'.format(self.tcex.default_args.tc_api_path, self._request_uri) self._apply_filters() self.tcex.log.debug(u'Resource URL: ({})'.format(self._request.url)) response = self._request.send(stream=self._stream) data, status = self._request_process(response) # # bcs - to reset or not to reset? # self._request.body = None # # self._request.reset_headers() # # self._request.reset_payload() # self._request_uri = self._api_uri # self._request_entity = self._api_entity return {'data': data, 'response': response, 'status': status}
[ "def", "request", "(", "self", ")", ":", "# self._request.authorization_method(self._authorization_method)", "self", ".", "_request", ".", "url", "=", "'{}/v2/{}'", ".", "format", "(", "self", ".", "tcex", ".", "default_args", ".", "tc_api_path", ",", "self", ".",...
Send the request to the API. This method will send the request to the API. It will try to handle all the types of responses and provide the relevant data when possible. Some basic error detection and handling is implemented, but not all failure cases will get caught. Return: (dictionary): Response/Results data.
[ "Send", "the", "request", "to", "the", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L726-L752
train
27,639
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.security_label_pivot
def security_label_pivot(self, security_label_resource): """Pivot point on security labels for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided security label applied. **Example Endpoints URI's** +--------------+----------------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+======================================================================+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (security label name). """ resource = self.copy() resource._request_uri = '{}/{}'.format( security_label_resource.request_uri, resource._request_uri ) return resource
python
def security_label_pivot(self, security_label_resource): """Pivot point on security labels for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided security label applied. **Example Endpoints URI's** +--------------+----------------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+======================================================================+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (security label name). """ resource = self.copy() resource._request_uri = '{}/{}'.format( security_label_resource.request_uri, resource._request_uri ) return resource
[ "def", "security_label_pivot", "(", "self", ",", "security_label_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "security_label_resource", ".", "request_uri", ",", "resour...
Pivot point on security labels for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided security label applied. **Example Endpoints URI's** +--------------+----------------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+======================================================================+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType} | +--------------+----------------------------------------------------------------------+ | GET | /v2/securityLabels/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+----------------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (security label name).
[ "Pivot", "point", "on", "security", "labels", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L807-L835
train
27,640
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.security_labels
def security_labels(self, resource_id=None): """Security Label endpoint for this resource with optional label name. This method will set the resource endpoint for working with Security Labels. The HTTP GET method will return all security labels applied to this resource or if a resource id (security label name) is provided it will return the provided security label if it has been applied, which could be useful to verify a security label is applied. The provided resource_id (security label name) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided security label from this resource. **Example Endpoints URI's** +--------------+-----------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+===========================================================+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels | +--------------+-----------------------------------------------------------+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | DELETE | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | POST | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (security label name). """ resource = self.copy() resource._request_entity = 'securityLabel' resource._request_uri = '{}/securityLabels'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, resource_id) return resource
python
def security_labels(self, resource_id=None): """Security Label endpoint for this resource with optional label name. This method will set the resource endpoint for working with Security Labels. The HTTP GET method will return all security labels applied to this resource or if a resource id (security label name) is provided it will return the provided security label if it has been applied, which could be useful to verify a security label is applied. The provided resource_id (security label name) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided security label from this resource. **Example Endpoints URI's** +--------------+-----------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+===========================================================+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels | +--------------+-----------------------------------------------------------+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | DELETE | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | POST | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (security label name). """ resource = self.copy() resource._request_entity = 'securityLabel' resource._request_uri = '{}/securityLabels'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, resource_id) return resource
[ "def", "security_labels", "(", "self", ",", "resource_id", "=", "None", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_entity", "=", "'securityLabel'", "resource", ".", "_request_uri", "=", "'{}/securityLabels'", ".", "for...
Security Label endpoint for this resource with optional label name. This method will set the resource endpoint for working with Security Labels. The HTTP GET method will return all security labels applied to this resource or if a resource id (security label name) is provided it will return the provided security label if it has been applied, which could be useful to verify a security label is applied. The provided resource_id (security label name) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided security label from this resource. **Example Endpoints URI's** +--------------+-----------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+===========================================================+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels | +--------------+-----------------------------------------------------------+ | GET | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | DELETE | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ | POST | /v2/{resourceType}/{uniqueId}/securityLabels/{resourceId} | +--------------+-----------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (security label name).
[ "Security", "Label", "endpoint", "for", "this", "resource", "with", "optional", "label", "name", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L837-L871
train
27,641
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.tag_pivot
def tag_pivot(self, tag_resource): """Pivot point on tags for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided tag applied. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/tags/{resourceId}/groups/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (tag name). """ resource = self.copy() resource._request_uri = '{}/{}'.format(tag_resource.request_uri, resource._request_uri) return resource
python
def tag_pivot(self, tag_resource): """Pivot point on tags for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided tag applied. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/tags/{resourceId}/groups/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (tag name). """ resource = self.copy() resource._request_uri = '{}/{}'.format(tag_resource.request_uri, resource._request_uri) return resource
[ "def", "tag_pivot", "(", "self", ",", "tag_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "tag_resource", ".", "request_uri", ",", "resource", ".", "_request_uri", "...
Pivot point on tags for this resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that have the provided tag applied. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/tags/{resourceId}/groups/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType} | +--------------+------------------------------------------------------------+ | GET | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ | POST | /v2/tags/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+------------------------------------------------------------+ Args: resource_id (string): The resource pivot id (tag name).
[ "Pivot", "point", "on", "tags", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L873-L902
train
27,642
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.tags
def tags(self, resource_id=None): """Tag endpoint for this resource with optional tag name. This method will set the resource endpoint for working with Tags. The HTTP GET method will return all tags applied to this resource or if a resource id (tag name) is provided it will return the provided tag if it has been applied, which could be useful to verify a tag is applied. The provided resource_id (tag) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (tag name). """ resource = self.copy() resource._request_entity = 'tag' resource._request_uri = '{}/tags'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format( resource._request_uri, self.tcex.safetag(resource_id) ) return resource
python
def tags(self, resource_id=None): """Tag endpoint for this resource with optional tag name. This method will set the resource endpoint for working with Tags. The HTTP GET method will return all tags applied to this resource or if a resource id (tag name) is provided it will return the provided tag if it has been applied, which could be useful to verify a tag is applied. The provided resource_id (tag) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (tag name). """ resource = self.copy() resource._request_entity = 'tag' resource._request_uri = '{}/tags'.format(resource._request_uri) if resource_id is not None: resource._request_uri = '{}/{}'.format( resource._request_uri, self.tcex.safetag(resource_id) ) return resource
[ "def", "tags", "(", "self", ",", "resource_id", "=", "None", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_entity", "=", "'tag'", "resource", ".", "_request_uri", "=", "'{}/tags'", ".", "format", "(", "resource", "....
Tag endpoint for this resource with optional tag name. This method will set the resource endpoint for working with Tags. The HTTP GET method will return all tags applied to this resource or if a resource id (tag name) is provided it will return the provided tag if it has been applied, which could be useful to verify a tag is applied. The provided resource_id (tag) can be applied to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +--------------+------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+============================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags | +--------------+------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | DELETE | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ | POST | /v2/indicators/{resourceType}/{uniqueId}/tags/{resourceId} | +--------------+------------------------------------------------------------+ Args: resource_id (Optional [string]): The resource id (tag name).
[ "Tag", "endpoint", "for", "this", "resource", "with", "optional", "tag", "name", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L904-L947
train
27,643
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.task_pivot
def task_pivot(self, task_resource): """Pivot point on Tasks for this resource. This method will return all *resources* (group, indicators, victims, etc) for this resource that are associated with the provided task id. **Example Endpoints URI's** +--------------+-------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+=============================================================+ | GET | /v2/tasks/{resourceId}/groups/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ Args: resource_id (integer): The resource pivot id (task id). """ resource = self.copy() resource._request_uri = '{}/{}'.format(task_resource.request_uri, resource._request_uri) return resource
python
def task_pivot(self, task_resource): """Pivot point on Tasks for this resource. This method will return all *resources* (group, indicators, victims, etc) for this resource that are associated with the provided task id. **Example Endpoints URI's** +--------------+-------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+=============================================================+ | GET | /v2/tasks/{resourceId}/groups/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ Args: resource_id (integer): The resource pivot id (task id). """ resource = self.copy() resource._request_uri = '{}/{}'.format(task_resource.request_uri, resource._request_uri) return resource
[ "def", "task_pivot", "(", "self", ",", "task_resource", ")", ":", "resource", "=", "self", ".", "copy", "(", ")", "resource", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "task_resource", ".", "request_uri", ",", "resource", ".", "_request_uri", ...
Pivot point on Tasks for this resource. This method will return all *resources* (group, indicators, victims, etc) for this resource that are associated with the provided task id. **Example Endpoints URI's** +--------------+-------------------------------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+=============================================================+ | GET | /v2/tasks/{resourceId}/groups/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/groups/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType} | +--------------+-------------------------------------------------------------+ | GET | /v2/tasks/{resourceId}/indicators/{resourceType}/{uniqueId} | +--------------+-------------------------------------------------------------+ Args: resource_id (integer): The resource pivot id (task id).
[ "Pivot", "point", "on", "Tasks", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L949-L974
train
27,644
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.victim_assets
def victim_assets(self, asset_type=None, asset_id=None): """Victim Asset endpoint for this resource with optional asset type. This method will set the resource endpoint for working with Victim Assets. The HTTP GET method will return all Victim Assets associated with this resource or if a asset type is provided it will return the provided asset type if it has been associated. The provided asset type can be associated to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ Args: asset_type (Optional [string]): The asset type. asset_id (Optional [string]): The asset id. """ type_entity_map = { 'emailAddresses': 'victimEmailAddress', 'networkAccounts': 'victimNetworkAccount', 'phoneNumbers': 'victimPhone', 'socialNetworks': 'victimSocialNetwork', 'webSites': 'victimWebSite', } resource = self.copy() resource._request_entity = 'victimAsset' resource._request_uri = '{}/victimAssets'.format(resource._request_uri) if asset_type is not None: resource._request_entity = type_entity_map.get(asset_type, 'victimAsset') resource._request_uri = '{}/{}'.format(resource._request_uri, asset_type) if asset_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, asset_id) return resource
python
def victim_assets(self, asset_type=None, asset_id=None): """Victim Asset endpoint for this resource with optional asset type. This method will set the resource endpoint for working with Victim Assets. The HTTP GET method will return all Victim Assets associated with this resource or if a asset type is provided it will return the provided asset type if it has been associated. The provided asset type can be associated to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ Args: asset_type (Optional [string]): The asset type. asset_id (Optional [string]): The asset id. """ type_entity_map = { 'emailAddresses': 'victimEmailAddress', 'networkAccounts': 'victimNetworkAccount', 'phoneNumbers': 'victimPhone', 'socialNetworks': 'victimSocialNetwork', 'webSites': 'victimWebSite', } resource = self.copy() resource._request_entity = 'victimAsset' resource._request_uri = '{}/victimAssets'.format(resource._request_uri) if asset_type is not None: resource._request_entity = type_entity_map.get(asset_type, 'victimAsset') resource._request_uri = '{}/{}'.format(resource._request_uri, asset_type) if asset_id is not None: resource._request_uri = '{}/{}'.format(resource._request_uri, asset_id) return resource
[ "def", "victim_assets", "(", "self", ",", "asset_type", "=", "None", ",", "asset_id", "=", "None", ")", ":", "type_entity_map", "=", "{", "'emailAddresses'", ":", "'victimEmailAddress'", ",", "'networkAccounts'", ":", "'victimNetworkAccount'", ",", "'phoneNumbers'",...
Victim Asset endpoint for this resource with optional asset type. This method will set the resource endpoint for working with Victim Assets. The HTTP GET method will return all Victim Assets associated with this resource or if a asset type is provided it will return the provided asset type if it has been associated. The provided asset type can be associated to this resource using the HTTP POST method. The HTTP DELETE method will remove the provided tag from this resource. **Example Endpoints URI's** +---------+--------------------------------------------------------------------------------+ | Method | API Endpoint URI's | +=========+================================================================================+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/indicators/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType} | +---------+--------------------------------------------------------------------------------+ | GET | /v2/victim/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | DELETE | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ | POST | /v2/groups/{resourceType}/{uniqueId}/victimAssets/{assetType}/{resourceId} | +---------+--------------------------------------------------------------------------------+ Args: asset_type (Optional [string]): The asset type. asset_id (Optional [string]): The asset id.
[ "Victim", "Asset", "endpoint", "for", "this", "resource", "with", "optional", "asset", "type", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1045-L1100
train
27,645
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Indicator.indicators
def indicators(self, indicator_data): """Generator for indicator values. Some indicator such as Files (hashes) and Custom Indicators can have multiple indicator values (e.g. md5, sha1, sha256). This method provides a generator to iterate over all indicator values. Both the **summary** field and the individual indicator fields (e.g. **md5**, **sha1**, **sha256**) are supported. For indicators that have only one value such as **ip** or **hostName** the generator will only return the one result. .. code-block:: python :linenos: :lineno-start: 1 # the individual indicator JSON from the API for i in resource.indicators(indicator_data): print(i.get('type')) # md5, sha1, sha256, etc print(i.get('value')) # hash or custom indicator value .. Warning:: This method could break for custom indicators that have " : " in the value of the indicator while using the summary field. .. Note:: For ``/v2/indicators`` and ``/v2/indicators/bulk/json`` API endpoints only one hash is returned for a file Indicator even if there are multiple in the platform. If all hashes are required the ``/v2/indicators/files`` or ``/v2/indicators/files/<hash>`` endpoints will provide all hashes. Args: indicator_data (dict): The indicator dictionary. Returns: (dictionary): A dict containing the indicator type and value. """ # indicator_list = [] for indicator_field in self.value_fields: if indicator_field == 'summary': indicators = self.tcex.expand_indicators(indicator_data.get('summary')) if indicator_data.get('type') == 'File': hash_patterns = { 'md5': re.compile(r'^([a-fA-F\d]{32})$'), 'sha1': re.compile(r'^([a-fA-F\d]{40})$'), 'sha256': re.compile(r'^([a-fA-F\d]{64})$'), } for i in indicators: if not i: continue i = i.strip() # clean up badly formatted summary string i_type = None if hash_patterns['md5'].match(i): i_type = 'md5' elif hash_patterns['sha1'].match(i): i_type = 'sha1' elif hash_patterns['sha256'].match(i): i_type = 'sha256' else: msg = u'Cannot determine hash type: "{}"'.format( indicator_data.get('summary') ) self.tcex.log.warning(msg) data = {'type': i_type, 'value': i} yield data else: resource = getattr( self.tcex.resources, self.tcex.safe_rt(indicator_data.get('type')) )(self.tcex) values = resource.value_fields index = 0 for i in indicators: if i is None: continue i = i.strip() # clean up badly formatted summary string # TODO: remove workaround for bug in indicatorTypes API endpoint if len(values) - 1 < index: break data = {'type': values[index], 'value': i} index += 1 yield data else: if indicator_data.get(indicator_field) is not None: yield {'type': indicator_field, 'value': indicator_data.get(indicator_field)}
python
def indicators(self, indicator_data): """Generator for indicator values. Some indicator such as Files (hashes) and Custom Indicators can have multiple indicator values (e.g. md5, sha1, sha256). This method provides a generator to iterate over all indicator values. Both the **summary** field and the individual indicator fields (e.g. **md5**, **sha1**, **sha256**) are supported. For indicators that have only one value such as **ip** or **hostName** the generator will only return the one result. .. code-block:: python :linenos: :lineno-start: 1 # the individual indicator JSON from the API for i in resource.indicators(indicator_data): print(i.get('type')) # md5, sha1, sha256, etc print(i.get('value')) # hash or custom indicator value .. Warning:: This method could break for custom indicators that have " : " in the value of the indicator while using the summary field. .. Note:: For ``/v2/indicators`` and ``/v2/indicators/bulk/json`` API endpoints only one hash is returned for a file Indicator even if there are multiple in the platform. If all hashes are required the ``/v2/indicators/files`` or ``/v2/indicators/files/<hash>`` endpoints will provide all hashes. Args: indicator_data (dict): The indicator dictionary. Returns: (dictionary): A dict containing the indicator type and value. """ # indicator_list = [] for indicator_field in self.value_fields: if indicator_field == 'summary': indicators = self.tcex.expand_indicators(indicator_data.get('summary')) if indicator_data.get('type') == 'File': hash_patterns = { 'md5': re.compile(r'^([a-fA-F\d]{32})$'), 'sha1': re.compile(r'^([a-fA-F\d]{40})$'), 'sha256': re.compile(r'^([a-fA-F\d]{64})$'), } for i in indicators: if not i: continue i = i.strip() # clean up badly formatted summary string i_type = None if hash_patterns['md5'].match(i): i_type = 'md5' elif hash_patterns['sha1'].match(i): i_type = 'sha1' elif hash_patterns['sha256'].match(i): i_type = 'sha256' else: msg = u'Cannot determine hash type: "{}"'.format( indicator_data.get('summary') ) self.tcex.log.warning(msg) data = {'type': i_type, 'value': i} yield data else: resource = getattr( self.tcex.resources, self.tcex.safe_rt(indicator_data.get('type')) )(self.tcex) values = resource.value_fields index = 0 for i in indicators: if i is None: continue i = i.strip() # clean up badly formatted summary string # TODO: remove workaround for bug in indicatorTypes API endpoint if len(values) - 1 < index: break data = {'type': values[index], 'value': i} index += 1 yield data else: if indicator_data.get(indicator_field) is not None: yield {'type': indicator_field, 'value': indicator_data.get(indicator_field)}
[ "def", "indicators", "(", "self", ",", "indicator_data", ")", ":", "# indicator_list = []", "for", "indicator_field", "in", "self", ".", "value_fields", ":", "if", "indicator_field", "==", "'summary'", ":", "indicators", "=", "self", ".", "tcex", ".", "expand_in...
Generator for indicator values. Some indicator such as Files (hashes) and Custom Indicators can have multiple indicator values (e.g. md5, sha1, sha256). This method provides a generator to iterate over all indicator values. Both the **summary** field and the individual indicator fields (e.g. **md5**, **sha1**, **sha256**) are supported. For indicators that have only one value such as **ip** or **hostName** the generator will only return the one result. .. code-block:: python :linenos: :lineno-start: 1 # the individual indicator JSON from the API for i in resource.indicators(indicator_data): print(i.get('type')) # md5, sha1, sha256, etc print(i.get('value')) # hash or custom indicator value .. Warning:: This method could break for custom indicators that have " : " in the value of the indicator while using the summary field. .. Note:: For ``/v2/indicators`` and ``/v2/indicators/bulk/json`` API endpoints only one hash is returned for a file Indicator even if there are multiple in the platform. If all hashes are required the ``/v2/indicators/files`` or ``/v2/indicators/files/<hash>`` endpoints will provide all hashes. Args: indicator_data (dict): The indicator dictionary. Returns: (dictionary): A dict containing the indicator type and value.
[ "Generator", "for", "indicator", "values", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1287-L1374
train
27,646
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Indicator.observed
def observed(self, date_observed=None): """Retrieve indicator observations count for top 10""" if self.name != 'Indicator': self.tcex.log.warning(u'Observed endpoint only available for "indicator" endpoint.') else: self._request_uri = '{}/observed'.format(self._request_uri) if date_observed is not None: self._request.add_payload('dateObserved', date_observed)
python
def observed(self, date_observed=None): """Retrieve indicator observations count for top 10""" if self.name != 'Indicator': self.tcex.log.warning(u'Observed endpoint only available for "indicator" endpoint.') else: self._request_uri = '{}/observed'.format(self._request_uri) if date_observed is not None: self._request.add_payload('dateObserved', date_observed)
[ "def", "observed", "(", "self", ",", "date_observed", "=", "None", ")", ":", "if", "self", ".", "name", "!=", "'Indicator'", ":", "self", ".", "tcex", ".", "log", ".", "warning", "(", "u'Observed endpoint only available for \"indicator\" endpoint.'", ")", "else"...
Retrieve indicator observations count for top 10
[ "Retrieve", "indicator", "observations", "count", "for", "top", "10" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1386-L1393
train
27,647
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Bulk.csv
def csv(self, ondemand=False): """Update request URI to return CSV data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation. """ self._request_uri = '{}/{}'.format(self._api_uri, 'csv') self._stream = True if ondemand: self._request.add_payload('runNow', True)
python
def csv(self, ondemand=False): """Update request URI to return CSV data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation. """ self._request_uri = '{}/{}'.format(self._api_uri, 'csv') self._stream = True if ondemand: self._request.add_payload('runNow', True)
[ "def", "csv", "(", "self", ",", "ondemand", "=", "False", ")", ":", "self", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "_api_uri", ",", "'csv'", ")", "self", ".", "_stream", "=", "True", "if", "ondemand", ":", "self", ".", ...
Update request URI to return CSV data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation.
[ "Update", "request", "URI", "to", "return", "CSV", "data", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1495-L1507
train
27,648
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Bulk.json
def json(self, ondemand=False): """Update request URI to return JSON data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation. """ self._request_entity = 'indicator' self._request_uri = '{}/{}'.format(self._api_uri, 'json') self._stream = True if ondemand: self._request.add_payload('runNow', True)
python
def json(self, ondemand=False): """Update request URI to return JSON data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation. """ self._request_entity = 'indicator' self._request_uri = '{}/{}'.format(self._api_uri, 'json') self._stream = True if ondemand: self._request.add_payload('runNow', True)
[ "def", "json", "(", "self", ",", "ondemand", "=", "False", ")", ":", "self", ".", "_request_entity", "=", "'indicator'", "self", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "_api_uri", ",", "'json'", ")", "self", ".", "_stream",...
Update request URI to return JSON data. For onDemand bulk generation to work it must first be enabled in the ThreatConnect platform under System settings. Args: ondemand (boolean): Enable on demand bulk generation.
[ "Update", "request", "URI", "to", "return", "JSON", "data", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1509-L1522
train
27,649
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
File.indicator_body
def indicator_body(indicators): """Generate the appropriate dictionary content for POST of an File indicator Args: indicators (list): A list of one or more hash value(s). """ hash_patterns = { 'md5': re.compile(r'^([a-fA-F\d]{32})$'), 'sha1': re.compile(r'^([a-fA-F\d]{40})$'), 'sha256': re.compile(r'^([a-fA-F\d]{64})$'), } body = {} for indicator in indicators: if indicator is None: continue if hash_patterns['md5'].match(indicator): body['md5'] = indicator elif hash_patterns['sha1'].match(indicator): body['sha1'] = indicator elif hash_patterns['sha256'].match(indicator): body['sha256'] = indicator return body
python
def indicator_body(indicators): """Generate the appropriate dictionary content for POST of an File indicator Args: indicators (list): A list of one or more hash value(s). """ hash_patterns = { 'md5': re.compile(r'^([a-fA-F\d]{32})$'), 'sha1': re.compile(r'^([a-fA-F\d]{40})$'), 'sha256': re.compile(r'^([a-fA-F\d]{64})$'), } body = {} for indicator in indicators: if indicator is None: continue if hash_patterns['md5'].match(indicator): body['md5'] = indicator elif hash_patterns['sha1'].match(indicator): body['sha1'] = indicator elif hash_patterns['sha256'].match(indicator): body['sha256'] = indicator return body
[ "def", "indicator_body", "(", "indicators", ")", ":", "hash_patterns", "=", "{", "'md5'", ":", "re", ".", "compile", "(", "r'^([a-fA-F\\d]{32})$'", ")", ",", "'sha1'", ":", "re", ".", "compile", "(", "r'^([a-fA-F\\d]{40})$'", ")", ",", "'sha256'", ":", "re",...
Generate the appropriate dictionary content for POST of an File indicator Args: indicators (list): A list of one or more hash value(s).
[ "Generate", "the", "appropriate", "dictionary", "content", "for", "POST", "of", "an", "File", "indicator" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1632-L1655
train
27,650
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
File.occurrence
def occurrence(self, indicator=None): """Update the URI to retrieve file occurrences for the provided indicator. Args: indicator (string): The indicator to retrieve file occurrences. """ self._request_entity = 'fileOccurrence' self._request_uri = '{}/fileOccurrences'.format(self._request_uri) if indicator is not None: self._request_uri = '{}/{}/fileOccurrences'.format(self._api_uri, indicator)
python
def occurrence(self, indicator=None): """Update the URI to retrieve file occurrences for the provided indicator. Args: indicator (string): The indicator to retrieve file occurrences. """ self._request_entity = 'fileOccurrence' self._request_uri = '{}/fileOccurrences'.format(self._request_uri) if indicator is not None: self._request_uri = '{}/{}/fileOccurrences'.format(self._api_uri, indicator)
[ "def", "occurrence", "(", "self", ",", "indicator", "=", "None", ")", ":", "self", ".", "_request_entity", "=", "'fileOccurrence'", "self", ".", "_request_uri", "=", "'{}/fileOccurrences'", ".", "format", "(", "self", ".", "_request_uri", ")", "if", "indicator...
Update the URI to retrieve file occurrences for the provided indicator. Args: indicator (string): The indicator to retrieve file occurrences.
[ "Update", "the", "URI", "to", "retrieve", "file", "occurrences", "for", "the", "provided", "indicator", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1657-L1666
train
27,651
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Host.resolution
def resolution(self, indicator=None): """Update the URI to retrieve host resolutions for the provided indicator. Args: indicator (string): The indicator to retrieve resolutions. """ self._request_entity = 'dnsResolution' self._request_uri = '{}/dnsResolutions'.format(self._request_uri) if indicator is not None: self._request_uri = '{}/{}/dnsResolutions'.format(self._api_uri, indicator)
python
def resolution(self, indicator=None): """Update the URI to retrieve host resolutions for the provided indicator. Args: indicator (string): The indicator to retrieve resolutions. """ self._request_entity = 'dnsResolution' self._request_uri = '{}/dnsResolutions'.format(self._request_uri) if indicator is not None: self._request_uri = '{}/{}/dnsResolutions'.format(self._api_uri, indicator)
[ "def", "resolution", "(", "self", ",", "indicator", "=", "None", ")", ":", "self", ".", "_request_entity", "=", "'dnsResolution'", "self", ".", "_request_uri", "=", "'{}/dnsResolutions'", ".", "format", "(", "self", ".", "_request_uri", ")", "if", "indicator",...
Update the URI to retrieve host resolutions for the provided indicator. Args: indicator (string): The indicator to retrieve resolutions.
[ "Update", "the", "URI", "to", "retrieve", "host", "resolutions", "for", "the", "provided", "indicator", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1697-L1706
train
27,652
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Group.group_id
def group_id(self, resource_id): """Update the request URI to include the Group ID for specific group retrieval. Args: resource_id (string): The group id. """ if self._name != 'group': self._request_uri = '{}/{}'.format(self._api_uri, resource_id)
python
def group_id(self, resource_id): """Update the request URI to include the Group ID for specific group retrieval. Args: resource_id (string): The group id. """ if self._name != 'group': self._request_uri = '{}/{}'.format(self._api_uri, resource_id)
[ "def", "group_id", "(", "self", ",", "resource_id", ")", ":", "if", "self", ".", "_name", "!=", "'group'", ":", "self", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "_api_uri", ",", "resource_id", ")" ]
Update the request URI to include the Group ID for specific group retrieval. Args: resource_id (string): The group id.
[ "Update", "the", "request", "URI", "to", "include", "the", "Group", "ID", "for", "specific", "group", "retrieval", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1756-L1763
train
27,653
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Adversary.pdf
def pdf(self, resource_id): """Update the request URI to get the pdf for this resource. Args: resource_id (integer): The group id. """ self.resource_id(str(resource_id)) self._request_uri = '{}/pdf'.format(self._request_uri)
python
def pdf(self, resource_id): """Update the request URI to get the pdf for this resource. Args: resource_id (integer): The group id. """ self.resource_id(str(resource_id)) self._request_uri = '{}/pdf'.format(self._request_uri)
[ "def", "pdf", "(", "self", ",", "resource_id", ")", ":", "self", ".", "resource_id", "(", "str", "(", "resource_id", ")", ")", "self", ".", "_request_uri", "=", "'{}/pdf'", ".", "format", "(", "self", ".", "_request_uri", ")" ]
Update the request URI to get the pdf for this resource. Args: resource_id (integer): The group id.
[ "Update", "the", "request", "URI", "to", "get", "the", "pdf", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1792-L1799
train
27,654
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Document.download
def download(self, resource_id): """Update the request URI to download the document for this resource. Args: resource_id (integer): The group id. """ self.resource_id(str(resource_id)) self._request_uri = '{}/download'.format(self._request_uri)
python
def download(self, resource_id): """Update the request URI to download the document for this resource. Args: resource_id (integer): The group id. """ self.resource_id(str(resource_id)) self._request_uri = '{}/download'.format(self._request_uri)
[ "def", "download", "(", "self", ",", "resource_id", ")", ":", "self", ".", "resource_id", "(", "str", "(", "resource_id", ")", ")", "self", ".", "_request_uri", "=", "'{}/download'", ".", "format", "(", "self", ".", "_request_uri", ")" ]
Update the request URI to download the document for this resource. Args: resource_id (integer): The group id.
[ "Update", "the", "request", "URI", "to", "download", "the", "document", "for", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1852-L1859
train
27,655
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Document.upload
def upload(self, resource_id, data): """Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload. """ self.body = data self.content_type = 'application/octet-stream' self.resource_id(str(resource_id)) self._request_uri = '{}/upload'.format(self._request_uri)
python
def upload(self, resource_id, data): """Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload. """ self.body = data self.content_type = 'application/octet-stream' self.resource_id(str(resource_id)) self._request_uri = '{}/upload'.format(self._request_uri)
[ "def", "upload", "(", "self", ",", "resource_id", ",", "data", ")", ":", "self", ".", "body", "=", "data", "self", ".", "content_type", "=", "'application/octet-stream'", "self", ".", "resource_id", "(", "str", "(", "resource_id", ")", ")", "self", ".", ...
Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload.
[ "Update", "the", "request", "URI", "to", "upload", "the", "a", "document", "to", "this", "resource", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L1861-L1871
train
27,656
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
CustomMetric.data
def data(self, resource_value, return_value=False): """Alias for metric_name method +--------------+------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+====================================+ | POST | /v2/customMetrics/{id}|{name}/data | +--------------+------------------------------------+ Example ------- The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, } **Keyed Example** The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, "name": "src1" } Args: resource_name (string): The metric name. """ if return_value: self._request_entity = None self._request.add_payload('returnValue', True) self._request_uri = '{}/{}/data'.format(self._request_uri, resource_value)
python
def data(self, resource_value, return_value=False): """Alias for metric_name method +--------------+------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+====================================+ | POST | /v2/customMetrics/{id}|{name}/data | +--------------+------------------------------------+ Example ------- The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, } **Keyed Example** The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, "name": "src1" } Args: resource_name (string): The metric name. """ if return_value: self._request_entity = None self._request.add_payload('returnValue', True) self._request_uri = '{}/{}/data'.format(self._request_uri, resource_value)
[ "def", "data", "(", "self", ",", "resource_value", ",", "return_value", "=", "False", ")", ":", "if", "return_value", ":", "self", ".", "_request_entity", "=", "None", "self", ".", "_request", ".", "add_payload", "(", "'returnValue'", ",", "True", ")", "se...
Alias for metric_name method +--------------+------------------------------------+ | HTTP Method | API Endpoint URI's | +==============+====================================+ | POST | /v2/customMetrics/{id}|{name}/data | +--------------+------------------------------------+ Example ------- The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, } **Keyed Example** The weight value is optional. .. code-block:: javascript { "value": 1, "weight": 1, "name": "src1" } Args: resource_name (string): The metric name.
[ "Alias", "for", "metric_name", "method" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2182-L2221
train
27,657
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Tag.tag
def tag(self, resource_id): """Update the request URI to include the Tag for specific retrieval. Args: resource_id (string): The tag name. """ self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id))
python
def tag(self, resource_id): """Update the request URI to include the Tag for specific retrieval. Args: resource_id (string): The tag name. """ self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id))
[ "def", "tag", "(", "self", ",", "resource_id", ")", ":", "self", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "_request_uri", ",", "self", ".", "tcex", ".", "safetag", "(", "resource_id", ")", ")" ]
Update the request URI to include the Tag for specific retrieval. Args: resource_id (string): The tag name.
[ "Update", "the", "request", "URI", "to", "include", "the", "Tag", "for", "specific", "retrieval", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2332-L2338
train
27,658
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Task.assignees
def assignees(self, assignee=None, resource_id=None): """Add an assignee to a Task GET: /v2/tasks/{uniqueId}/assignees GET: /v2/tasks/{uniqueId}/assignees/{assigneeId} POST: /v2/tasks/{uniqueId}/assignees/{assigneeId} DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId} Args: assignee (Optional [string]): The assignee name. resource_id (Optional [string]): The task ID. """ if resource_id is not None: self.resource_id(resource_id) self._request_uri = '{}/assignees'.format(self._request_uri) if assignee is not None: self._request_uri = '{}/{}'.format(self._request_uri, assignee)
python
def assignees(self, assignee=None, resource_id=None): """Add an assignee to a Task GET: /v2/tasks/{uniqueId}/assignees GET: /v2/tasks/{uniqueId}/assignees/{assigneeId} POST: /v2/tasks/{uniqueId}/assignees/{assigneeId} DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId} Args: assignee (Optional [string]): The assignee name. resource_id (Optional [string]): The task ID. """ if resource_id is not None: self.resource_id(resource_id) self._request_uri = '{}/assignees'.format(self._request_uri) if assignee is not None: self._request_uri = '{}/{}'.format(self._request_uri, assignee)
[ "def", "assignees", "(", "self", ",", "assignee", "=", "None", ",", "resource_id", "=", "None", ")", ":", "if", "resource_id", "is", "not", "None", ":", "self", ".", "resource_id", "(", "resource_id", ")", "self", ".", "_request_uri", "=", "'{}/assignees'"...
Add an assignee to a Task GET: /v2/tasks/{uniqueId}/assignees GET: /v2/tasks/{uniqueId}/assignees/{assigneeId} POST: /v2/tasks/{uniqueId}/assignees/{assigneeId} DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId} Args: assignee (Optional [string]): The assignee name. resource_id (Optional [string]): The task ID.
[ "Add", "an", "assignee", "to", "a", "Task" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2375-L2391
train
27,659
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Task.escalatees
def escalatees(self, escalatee=None, resource_id=None): """Add an escalatee to a Task GET: /v2/tasks/{uniqueId}/escalatees GET: /v2/tasks/{uniqueId}/escalatees/{escalateeId} POST: /v2/tasks/{uniqueId}/escalatees/{escalateeId} DELETE: /v2/tasks/{uniqueId}/escalatees/{escalateeId} Args: escalatee (Optional [string]): The escalatee name. resource_id (Optional [string]): The task ID. """ if resource_id is not None: self.resource_id(resource_id) self._request_uri = '{}/escalatees'.format(self._request_uri) if escalatee is not None: self._request_uri = '{}/{}'.format(self._request_uri, escalatee)
python
def escalatees(self, escalatee=None, resource_id=None): """Add an escalatee to a Task GET: /v2/tasks/{uniqueId}/escalatees GET: /v2/tasks/{uniqueId}/escalatees/{escalateeId} POST: /v2/tasks/{uniqueId}/escalatees/{escalateeId} DELETE: /v2/tasks/{uniqueId}/escalatees/{escalateeId} Args: escalatee (Optional [string]): The escalatee name. resource_id (Optional [string]): The task ID. """ if resource_id is not None: self.resource_id(resource_id) self._request_uri = '{}/escalatees'.format(self._request_uri) if escalatee is not None: self._request_uri = '{}/{}'.format(self._request_uri, escalatee)
[ "def", "escalatees", "(", "self", ",", "escalatee", "=", "None", ",", "resource_id", "=", "None", ")", ":", "if", "resource_id", "is", "not", "None", ":", "self", ".", "resource_id", "(", "resource_id", ")", "self", ".", "_request_uri", "=", "'{}/escalatee...
Add an escalatee to a Task GET: /v2/tasks/{uniqueId}/escalatees GET: /v2/tasks/{uniqueId}/escalatees/{escalateeId} POST: /v2/tasks/{uniqueId}/escalatees/{escalateeId} DELETE: /v2/tasks/{uniqueId}/escalatees/{escalateeId} Args: escalatee (Optional [string]): The escalatee name. resource_id (Optional [string]): The task ID.
[ "Add", "an", "escalatee", "to", "a", "Task" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2393-L2409
train
27,660
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
DataStore._request
def _request(self, domain, type_name, search_command, db_method, body=None): """Make the API request for a Data Store CRUD operation Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. db_method (string): The DB method 'DELETE', 'GET', 'POST', or 'PUT' body (dict): JSON body """ headers = {'Content-Type': 'application/json', 'DB-Method': db_method} search_command = self._clean_datastore_path(search_command) url = '/v2/exchange/db/{}/{}/{}'.format(domain, type_name, search_command) r = self.tcex.session.post(url, data=body, headers=headers, params=self._params) data = [] status = 'Failed' if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(350, [r.status_code, r.text]) data = r.json() status = 'Success' return {'data': data, 'response': r, 'status': status}
python
def _request(self, domain, type_name, search_command, db_method, body=None): """Make the API request for a Data Store CRUD operation Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. db_method (string): The DB method 'DELETE', 'GET', 'POST', or 'PUT' body (dict): JSON body """ headers = {'Content-Type': 'application/json', 'DB-Method': db_method} search_command = self._clean_datastore_path(search_command) url = '/v2/exchange/db/{}/{}/{}'.format(domain, type_name, search_command) r = self.tcex.session.post(url, data=body, headers=headers, params=self._params) data = [] status = 'Failed' if not r.ok or 'application/json' not in r.headers.get('content-type', ''): self.tcex.handle_error(350, [r.status_code, r.text]) data = r.json() status = 'Success' return {'data': data, 'response': r, 'status': status}
[ "def", "_request", "(", "self", ",", "domain", ",", "type_name", ",", "search_command", ",", "db_method", ",", "body", "=", "None", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'DB-Method'", ":", "db_method", "}", "search...
Make the API request for a Data Store CRUD operation Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. db_method (string): The DB method 'DELETE', 'GET', 'POST', or 'PUT' body (dict): JSON body
[ "Make", "the", "API", "request", "for", "a", "Data", "Store", "CRUD", "operation" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2503-L2526
train
27,661
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
DataStore.create
def create(self, domain, type_name, search_command, body): """Create entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON serialized data. """ return self._request(domain, type_name, search_command, 'POST', body)
python
def create(self, domain, type_name, search_command, body): """Create entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON serialized data. """ return self._request(domain, type_name, search_command, 'POST', body)
[ "def", "create", "(", "self", ",", "domain", ",", "type_name", ",", "search_command", ",", "body", ")", ":", "return", "self", ".", "_request", "(", "domain", ",", "type_name", ",", "search_command", ",", "'POST'", ",", "body", ")" ]
Create entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON serialized data.
[ "Create", "entry", "in", "ThreatConnect", "Data", "Store" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2543-L2553
train
27,662
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
DataStore.delete
def delete(self, domain, type_name, search_command): """Delete entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. """ return self._request(domain, type_name, search_command, 'DELETE', None)
python
def delete(self, domain, type_name, search_command): """Delete entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. """ return self._request(domain, type_name, search_command, 'DELETE', None)
[ "def", "delete", "(", "self", ",", "domain", ",", "type_name", ",", "search_command", ")", ":", "return", "self", ".", "_request", "(", "domain", ",", "type_name", ",", "search_command", ",", "'DELETE'", ",", "None", ")" ]
Delete entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES.
[ "Delete", "entry", "in", "ThreatConnect", "Data", "Store" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2555-L2564
train
27,663
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
DataStore.read
def read(self, domain, type_name, search_command, body=None): """Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body """ return self._request(domain, type_name, search_command, 'GET', body)
python
def read(self, domain, type_name, search_command, body=None): """Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body """ return self._request(domain, type_name, search_command, 'GET', body)
[ "def", "read", "(", "self", ",", "domain", ",", "type_name", ",", "search_command", ",", "body", "=", "None", ")", ":", "return", "self", ".", "_request", "(", "domain", ",", "type_name", ",", "search_command", ",", "'GET'", ",", "body", ")" ]
Read entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body
[ "Read", "entry", "in", "ThreatConnect", "Data", "Store" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2566-L2576
train
27,664
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
DataStore.update
def update(self, domain, type_name, search_command, body): """Update entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body """ return self._request(domain, type_name, search_command, 'PUT', body)
python
def update(self, domain, type_name, search_command, body): """Update entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body """ return self._request(domain, type_name, search_command, 'PUT', body)
[ "def", "update", "(", "self", ",", "domain", ",", "type_name", ",", "search_command", ",", "body", ")", ":", "return", "self", ".", "_request", "(", "domain", ",", "type_name", ",", "search_command", ",", "'PUT'", ",", "body", ")" ]
Update entry in ThreatConnect Data Store Args: domain (string): One of 'local', 'organization', or 'system'. type_name (string): This is a free form index type name. The ThreatConnect API will use this resource verbatim. search_command (string): Search command to pass to ES. body (str): JSON body
[ "Update", "entry", "in", "ThreatConnect", "Data", "Store" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L2578-L2588
train
27,665
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/group/group_types/document.py
Document.file_content
def file_content(self, file_content, update_if_exists=True): """ Updates the file content. Args: file_content: The file_content to upload. update_if_exists: Returns: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['fileContent'] = file_content return self.tc_requests.upload( self.api_type, self.api_sub_type, self.unique_id, file_content, update_if_exists=update_if_exists, )
python
def file_content(self, file_content, update_if_exists=True): """ Updates the file content. Args: file_content: The file_content to upload. update_if_exists: Returns: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['fileContent'] = file_content return self.tc_requests.upload( self.api_type, self.api_sub_type, self.unique_id, file_content, update_if_exists=update_if_exists, )
[ "def", "file_content", "(", "self", ",", "file_content", ",", "update_if_exists", "=", "True", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ...
Updates the file content. Args: file_content: The file_content to upload. update_if_exists: Returns:
[ "Updates", "the", "file", "content", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/document.py#L32-L53
train
27,666
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/group/group_types/document.py
Document.file_name
def file_name(self, file_name): """ Updates the file_name. Args: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['fileName'] = file_name request = {'fileName': file_name} return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request)
python
def file_name(self, file_name): """ Updates the file_name. Args: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['fileName'] = file_name request = {'fileName': file_name} return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request)
[ "def", "file_name", "(", "self", ",", "file_name", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "self", ".", "_data", "[", "'fileNam...
Updates the file_name. Args: file_name:
[ "Updates", "the", "file_name", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/document.py#L55-L67
train
27,667
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/group/group_types/document.py
Document.malware
def malware(self, malware, password, file_name): """ Uploads to malware vault. Args: malware: password: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['malware'] = malware self._data['password'] = password self._data['fileName'] = file_name request = {'malware': malware, 'password': password, 'fileName': file_name} return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request)
python
def malware(self, malware, password, file_name): """ Uploads to malware vault. Args: malware: password: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['malware'] = malware self._data['password'] = password self._data['fileName'] = file_name request = {'malware': malware, 'password': password, 'fileName': file_name} return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request)
[ "def", "malware", "(", "self", ",", "malware", ",", "password", ",", "file_name", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "self...
Uploads to malware vault. Args: malware: password: file_name:
[ "Uploads", "to", "malware", "vault", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/document.py#L104-L120
train
27,668
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_imports
def check_imports(self): """Check the projects top level directory for missing imports. This method will check only files ending in **.py** and does not handle imports validation for sub-directories. """ modules = [] for filename in sorted(os.listdir(self.app_path)): if not filename.endswith('.py'): continue fq_path = os.path.join(self.app_path, filename) with open(fq_path, 'rb') as f: # TODO: fix this code_lines = deque([(f.read(), 1)]) while code_lines: m_status = True code, lineno = code_lines.popleft() # pylint: disable=W0612 try: parsed_code = ast.parse(code) for node in ast.walk(parsed_code): if isinstance(node, ast.Import): for n in node.names: m = n.name.split('.')[0] if self.check_import_stdlib(m): # stdlib module, not need to proceed continue m_status = self.check_imported(m) modules.append( {'file': filename, 'module': m, 'status': m_status} ) elif isinstance(node, ast.ImportFrom): m = node.module.split('.')[0] if self.check_import_stdlib(m): # stdlib module, not need to proceed continue m_status = self.check_imported(m) modules.append({'file': filename, 'module': m, 'status': m_status}) else: continue except SyntaxError: pass for module_data in modules: status = True if not module_data.get('status'): status = False # update validation data errors self.validation_data['errors'].append( 'Module validation failed for {} (module "{}" could not be imported).'.format( module_data.get('file'), module_data.get('module') ) ) # update validation data for module self.validation_data['moduleImports'].append( { 'filename': module_data.get('file'), 'module': module_data.get('module'), 'status': status, } )
python
def check_imports(self): """Check the projects top level directory for missing imports. This method will check only files ending in **.py** and does not handle imports validation for sub-directories. """ modules = [] for filename in sorted(os.listdir(self.app_path)): if not filename.endswith('.py'): continue fq_path = os.path.join(self.app_path, filename) with open(fq_path, 'rb') as f: # TODO: fix this code_lines = deque([(f.read(), 1)]) while code_lines: m_status = True code, lineno = code_lines.popleft() # pylint: disable=W0612 try: parsed_code = ast.parse(code) for node in ast.walk(parsed_code): if isinstance(node, ast.Import): for n in node.names: m = n.name.split('.')[0] if self.check_import_stdlib(m): # stdlib module, not need to proceed continue m_status = self.check_imported(m) modules.append( {'file': filename, 'module': m, 'status': m_status} ) elif isinstance(node, ast.ImportFrom): m = node.module.split('.')[0] if self.check_import_stdlib(m): # stdlib module, not need to proceed continue m_status = self.check_imported(m) modules.append({'file': filename, 'module': m, 'status': m_status}) else: continue except SyntaxError: pass for module_data in modules: status = True if not module_data.get('status'): status = False # update validation data errors self.validation_data['errors'].append( 'Module validation failed for {} (module "{}" could not be imported).'.format( module_data.get('file'), module_data.get('module') ) ) # update validation data for module self.validation_data['moduleImports'].append( { 'filename': module_data.get('file'), 'module': module_data.get('module'), 'status': status, } )
[ "def", "check_imports", "(", "self", ")", ":", "modules", "=", "[", "]", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "self", ".", "app_path", ")", ")", ":", "if", "not", "filename", ".", "endswith", "(", "'.py'", ")", ":", "c...
Check the projects top level directory for missing imports. This method will check only files ending in **.py** and does not handle imports validation for sub-directories.
[ "Check", "the", "projects", "top", "level", "directory", "for", "missing", "imports", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L76-L137
train
27,669
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_import_stdlib
def check_import_stdlib(module): """Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template. """ if ( module in stdlib_list('2.7') # pylint: disable=R0916 or module in stdlib_list('3.4') or module in stdlib_list('3.5') or module in stdlib_list('3.6') or module in stdlib_list('3.7') or module in ['app', 'args', 'playbook_app'] ): return True return False
python
def check_import_stdlib(module): """Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template. """ if ( module in stdlib_list('2.7') # pylint: disable=R0916 or module in stdlib_list('3.4') or module in stdlib_list('3.5') or module in stdlib_list('3.6') or module in stdlib_list('3.7') or module in ['app', 'args', 'playbook_app'] ): return True return False
[ "def", "check_import_stdlib", "(", "module", ")", ":", "if", "(", "module", "in", "stdlib_list", "(", "'2.7'", ")", "# pylint: disable=R0916", "or", "module", "in", "stdlib_list", "(", "'3.4'", ")", "or", "module", "in", "stdlib_list", "(", "'3.5'", ")", "or...
Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template.
[ "Check", "if", "module", "is", "in", "Python", "stdlib", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L140-L158
train
27,670
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_install_json
def check_install_json(self): """Check all install.json files for valid schema.""" if self.install_json_schema is None: return contents = os.listdir(self.app_path) if self.args.install_json is not None: contents = [self.args.install_json] for install_json in sorted(contents): # skip files that are not install.json files if 'install.json' not in install_json: continue error = None status = True try: # loading explicitly here to keep all error catching in this file with open(install_json) as fh: data = json.loads(fh.read()) validate(data, self.install_json_schema) except SchemaError as e: status = False error = e except ValidationError as e: status = False error = e.message except ValueError: # any JSON decode error will be caught during syntax validation return if error: # update validation data errors self.validation_data['errors'].append( 'Schema validation failed for {} ({}).'.format(install_json, error) ) # update validation data for module self.validation_data['schema'].append({'filename': install_json, 'status': status})
python
def check_install_json(self): """Check all install.json files for valid schema.""" if self.install_json_schema is None: return contents = os.listdir(self.app_path) if self.args.install_json is not None: contents = [self.args.install_json] for install_json in sorted(contents): # skip files that are not install.json files if 'install.json' not in install_json: continue error = None status = True try: # loading explicitly here to keep all error catching in this file with open(install_json) as fh: data = json.loads(fh.read()) validate(data, self.install_json_schema) except SchemaError as e: status = False error = e except ValidationError as e: status = False error = e.message except ValueError: # any JSON decode error will be caught during syntax validation return if error: # update validation data errors self.validation_data['errors'].append( 'Schema validation failed for {} ({}).'.format(install_json, error) ) # update validation data for module self.validation_data['schema'].append({'filename': install_json, 'status': status})
[ "def", "check_install_json", "(", "self", ")", ":", "if", "self", ".", "install_json_schema", "is", "None", ":", "return", "contents", "=", "os", ".", "listdir", "(", "self", ".", "app_path", ")", "if", "self", ".", "args", ".", "install_json", "is", "no...
Check all install.json files for valid schema.
[ "Check", "all", "install", ".", "json", "files", "for", "valid", "schema", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L197-L236
train
27,671
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_layout_json
def check_layout_json(self): """Check all layout.json files for valid schema.""" # the install.json files can't be validates if the schema file is not present layout_json_file = 'layout.json' if self.layout_json_schema is None or not os.path.isfile(layout_json_file): return error = None status = True try: # loading explicitly here to keep all error catching in this file with open(layout_json_file) as fh: data = json.loads(fh.read()) validate(data, self.layout_json_schema) except SchemaError as e: status = False error = e except ValidationError as e: status = False error = e.message except ValueError: # any JSON decode error will be caught during syntax validation return # update validation data for module self.validation_data['schema'].append({'filename': layout_json_file, 'status': status}) if error: # update validation data errors self.validation_data['errors'].append( 'Schema validation failed for {} ({}).'.format(layout_json_file, error) ) else: self.check_layout_params()
python
def check_layout_json(self): """Check all layout.json files for valid schema.""" # the install.json files can't be validates if the schema file is not present layout_json_file = 'layout.json' if self.layout_json_schema is None or not os.path.isfile(layout_json_file): return error = None status = True try: # loading explicitly here to keep all error catching in this file with open(layout_json_file) as fh: data = json.loads(fh.read()) validate(data, self.layout_json_schema) except SchemaError as e: status = False error = e except ValidationError as e: status = False error = e.message except ValueError: # any JSON decode error will be caught during syntax validation return # update validation data for module self.validation_data['schema'].append({'filename': layout_json_file, 'status': status}) if error: # update validation data errors self.validation_data['errors'].append( 'Schema validation failed for {} ({}).'.format(layout_json_file, error) ) else: self.check_layout_params()
[ "def", "check_layout_json", "(", "self", ")", ":", "# the install.json files can't be validates if the schema file is not present", "layout_json_file", "=", "'layout.json'", "if", "self", ".", "layout_json_schema", "is", "None", "or", "not", "os", ".", "path", ".", "isfil...
Check all layout.json files for valid schema.
[ "Check", "all", "layout", ".", "json", "files", "for", "valid", "schema", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L238-L271
train
27,672
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_layout_params
def check_layout_params(self): """Check that the layout.json is consistent with install.json. The layout.json files references the params.name from the install.json file. The method will validate that no reference appear for inputs in install.json that don't exist. """ ij_input_names = [] ij_output_names = [] if os.path.isfile('install.json'): try: with open('install.json') as fh: ij = json.loads(fh.read()) for p in ij.get('params', []): ij_input_names.append(p.get('name')) for o in ij.get('playbook', {}).get('outputVariables', []): ij_output_names.append(o.get('name')) except Exception: # checking parameters isn't possible if install.json can't be parsed return if 'sqlite3' in sys.modules: # create temporary inputs tables self.db_create_table(self.input_table, ij_input_names) # inputs status = True for i in self.layout_json.get('inputs', []): for p in i.get('parameters'): if p.get('name') not in ij_input_names: # update validation data errors self.validation_data['errors'].append( 'Layouts input.parameters[].name validations failed ("{}" is defined in ' 'layout.json, but not found in install.json).'.format(p.get('name')) ) status = False if 'sqlite3' in sys.modules: if p.get('display'): display_query = 'SELECT * FROM {} WHERE {}'.format( self.input_table, p.get('display') ) try: self.db_conn.execute(display_query.replace('"', '')) except sqlite3.Error: self.validation_data['errors'].append( 'Layouts input.parameters[].display validations failed ("{}" query ' 'is an invalid statement).'.format(p.get('display')) ) status = False # update validation data for module self.validation_data['layouts'].append({'params': 'inputs', 'status': status}) # outputs status = True for o in self.layout_json.get('outputs', []): if o.get('name') not in ij_output_names: # update validation data errors self.validation_data['errors'].append( 'Layouts output validations failed ({} is defined in layout.json, but not ' 'found in install.json).'.format(o.get('name')) ) status = False if 'sqlite3' in sys.modules: if o.get('display'): display_query = 'SELECT * FROM {} WHERE {}'.format( self.input_table, o.get('display') ) try: self.db_conn.execute(display_query.replace('"', '')) except sqlite3.Error: self.validation_data['errors'].append( 'Layouts outputs.display validations failed ("{}" query is ' 'an invalid statement).'.format(o.get('display')) ) status = False # update validation data for module self.validation_data['layouts'].append({'params': 'outputs', 'status': status})
python
def check_layout_params(self): """Check that the layout.json is consistent with install.json. The layout.json files references the params.name from the install.json file. The method will validate that no reference appear for inputs in install.json that don't exist. """ ij_input_names = [] ij_output_names = [] if os.path.isfile('install.json'): try: with open('install.json') as fh: ij = json.loads(fh.read()) for p in ij.get('params', []): ij_input_names.append(p.get('name')) for o in ij.get('playbook', {}).get('outputVariables', []): ij_output_names.append(o.get('name')) except Exception: # checking parameters isn't possible if install.json can't be parsed return if 'sqlite3' in sys.modules: # create temporary inputs tables self.db_create_table(self.input_table, ij_input_names) # inputs status = True for i in self.layout_json.get('inputs', []): for p in i.get('parameters'): if p.get('name') not in ij_input_names: # update validation data errors self.validation_data['errors'].append( 'Layouts input.parameters[].name validations failed ("{}" is defined in ' 'layout.json, but not found in install.json).'.format(p.get('name')) ) status = False if 'sqlite3' in sys.modules: if p.get('display'): display_query = 'SELECT * FROM {} WHERE {}'.format( self.input_table, p.get('display') ) try: self.db_conn.execute(display_query.replace('"', '')) except sqlite3.Error: self.validation_data['errors'].append( 'Layouts input.parameters[].display validations failed ("{}" query ' 'is an invalid statement).'.format(p.get('display')) ) status = False # update validation data for module self.validation_data['layouts'].append({'params': 'inputs', 'status': status}) # outputs status = True for o in self.layout_json.get('outputs', []): if o.get('name') not in ij_output_names: # update validation data errors self.validation_data['errors'].append( 'Layouts output validations failed ({} is defined in layout.json, but not ' 'found in install.json).'.format(o.get('name')) ) status = False if 'sqlite3' in sys.modules: if o.get('display'): display_query = 'SELECT * FROM {} WHERE {}'.format( self.input_table, o.get('display') ) try: self.db_conn.execute(display_query.replace('"', '')) except sqlite3.Error: self.validation_data['errors'].append( 'Layouts outputs.display validations failed ("{}" query is ' 'an invalid statement).'.format(o.get('display')) ) status = False # update validation data for module self.validation_data['layouts'].append({'params': 'outputs', 'status': status})
[ "def", "check_layout_params", "(", "self", ")", ":", "ij_input_names", "=", "[", "]", "ij_output_names", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "'install.json'", ")", ":", "try", ":", "with", "open", "(", "'install.json'", ")", "as",...
Check that the layout.json is consistent with install.json. The layout.json files references the params.name from the install.json file. The method will validate that no reference appear for inputs in install.json that don't exist.
[ "Check", "that", "the", "layout", ".", "json", "is", "consistent", "with", "install", ".", "json", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L273-L353
train
27,673
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.check_syntax
def check_syntax(self, app_path=None): """Run syntax on each ".py" and ".json" file. Args: app_path (str, optional): Defaults to None. The path of Python files. """ app_path = app_path or '.' for filename in sorted(os.listdir(app_path)): error = None status = True if filename.endswith('.py'): try: with open(filename, 'rb') as f: ast.parse(f.read(), filename=filename) except SyntaxError: status = False # cleanup output e = [] for line in traceback.format_exc().split('\n')[-5:-2]: e.append(line.strip()) error = ' '.join(e) elif filename.endswith('.json'): try: with open(filename, 'r') as fh: json.load(fh) except ValueError as e: status = False error = e else: # skip unsupported file types continue if error: # update validation data errors self.validation_data['errors'].append( 'Syntax validation failed for {} ({}).'.format(filename, error) ) # store status for this file self.validation_data['fileSyntax'].append({'filename': filename, 'status': status})
python
def check_syntax(self, app_path=None): """Run syntax on each ".py" and ".json" file. Args: app_path (str, optional): Defaults to None. The path of Python files. """ app_path = app_path or '.' for filename in sorted(os.listdir(app_path)): error = None status = True if filename.endswith('.py'): try: with open(filename, 'rb') as f: ast.parse(f.read(), filename=filename) except SyntaxError: status = False # cleanup output e = [] for line in traceback.format_exc().split('\n')[-5:-2]: e.append(line.strip()) error = ' '.join(e) elif filename.endswith('.json'): try: with open(filename, 'r') as fh: json.load(fh) except ValueError as e: status = False error = e else: # skip unsupported file types continue if error: # update validation data errors self.validation_data['errors'].append( 'Syntax validation failed for {} ({}).'.format(filename, error) ) # store status for this file self.validation_data['fileSyntax'].append({'filename': filename, 'status': status})
[ "def", "check_syntax", "(", "self", ",", "app_path", "=", "None", ")", ":", "app_path", "=", "app_path", "or", "'.'", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "app_path", ")", ")", ":", "error", "=", "None", "status", "=", "...
Run syntax on each ".py" and ".json" file. Args: app_path (str, optional): Defaults to None. The path of Python files.
[ "Run", "syntax", "on", "each", ".", "py", "and", ".", "json", "file", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L355-L396
train
27,674
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.install_json_schema
def install_json_schema(self): """Load install.json schema file.""" if self._install_json_schema is None and self.install_json_schema_file is not None: # remove old schema file if os.path.isfile('tcex_json_schema.json'): # this file is now part of tcex. os.remove('tcex_json_schema.json') if os.path.isfile(self.install_json_schema_file): with open(self.install_json_schema_file) as fh: self._install_json_schema = json.load(fh) return self._install_json_schema
python
def install_json_schema(self): """Load install.json schema file.""" if self._install_json_schema is None and self.install_json_schema_file is not None: # remove old schema file if os.path.isfile('tcex_json_schema.json'): # this file is now part of tcex. os.remove('tcex_json_schema.json') if os.path.isfile(self.install_json_schema_file): with open(self.install_json_schema_file) as fh: self._install_json_schema = json.load(fh) return self._install_json_schema
[ "def", "install_json_schema", "(", "self", ")", ":", "if", "self", ".", "_install_json_schema", "is", "None", "and", "self", ".", "install_json_schema_file", "is", "not", "None", ":", "# remove old schema file", "if", "os", ".", "path", ".", "isfile", "(", "'t...
Load install.json schema file.
[ "Load", "install", ".", "json", "schema", "file", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L399-L410
train
27,675
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.interactive
def interactive(self): """Run in interactive mode.""" while True: line = sys.stdin.readline().strip() if line == 'quit': sys.exit() elif line == 'validate': self.check_syntax() self.check_imports() self.check_install_json() self.check_layout_json() self.print_json() # reset validation_data self.validation_data = self._validation_data
python
def interactive(self): """Run in interactive mode.""" while True: line = sys.stdin.readline().strip() if line == 'quit': sys.exit() elif line == 'validate': self.check_syntax() self.check_imports() self.check_install_json() self.check_layout_json() self.print_json() # reset validation_data self.validation_data = self._validation_data
[ "def", "interactive", "(", "self", ")", ":", "while", "True", ":", "line", "=", "sys", ".", "stdin", ".", "readline", "(", ")", ".", "strip", "(", ")", "if", "line", "==", "'quit'", ":", "sys", ".", "exit", "(", ")", "elif", "line", "==", "'valid...
Run in interactive mode.
[ "Run", "in", "interactive", "mode", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L412-L426
train
27,676
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.layout_json_schema
def layout_json_schema(self): """Load layout.json schema file.""" if self._layout_json_schema is None and self.layout_json_schema_file is not None: if os.path.isfile(self.layout_json_schema_file): with open(self.layout_json_schema_file) as fh: self._layout_json_schema = json.load(fh) return self._layout_json_schema
python
def layout_json_schema(self): """Load layout.json schema file.""" if self._layout_json_schema is None and self.layout_json_schema_file is not None: if os.path.isfile(self.layout_json_schema_file): with open(self.layout_json_schema_file) as fh: self._layout_json_schema = json.load(fh) return self._layout_json_schema
[ "def", "layout_json_schema", "(", "self", ")", ":", "if", "self", ".", "_layout_json_schema", "is", "None", "and", "self", ".", "layout_json_schema_file", "is", "not", "None", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "layout_json_schema...
Load layout.json schema file.
[ "Load", "layout", ".", "json", "schema", "file", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L429-L435
train
27,677
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.print_results
def print_results(self): """Print results.""" # Validating Syntax if self.validation_data.get('fileSyntax'): print('\n{}{}Validated File Syntax:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Status:')) for f in self.validation_data.get('fileSyntax'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('filename'), status_color, status_value)) # Validating Imports if self.validation_data.get('moduleImports'): print('\n{}{}Validated Imports:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print( '{}{!s:<30}{!s:<30}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Module:', 'Status:') ) for f in self.validation_data.get('moduleImports'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print( '{!s:<30}{}{!s:<30}{}{!s:<25}'.format( f.get('filename'), c.Fore.WHITE, f.get('module'), status_color, status_value ) ) # Validating Schema if self.validation_data.get('schema'): print('\n{}{}Validated Schema:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Status:')) for f in self.validation_data.get('schema'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('filename'), status_color, status_value)) # Validating Layouts if self.validation_data.get('layouts'): print('\n{}{}Validated Layouts:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'Params:', 'Status:')) for f in self.validation_data.get('layouts'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('params'), status_color, status_value)) if self.validation_data.get('errors'): print('\n') # separate errors from normal output for error in self.validation_data.get('errors'): # print all errors print('* {}{}'.format(c.Fore.RED, error)) # ignore exit code if not self.args.ignore_validation: self.exit_code = 1
python
def print_results(self): """Print results.""" # Validating Syntax if self.validation_data.get('fileSyntax'): print('\n{}{}Validated File Syntax:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Status:')) for f in self.validation_data.get('fileSyntax'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('filename'), status_color, status_value)) # Validating Imports if self.validation_data.get('moduleImports'): print('\n{}{}Validated Imports:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print( '{}{!s:<30}{!s:<30}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Module:', 'Status:') ) for f in self.validation_data.get('moduleImports'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print( '{!s:<30}{}{!s:<30}{}{!s:<25}'.format( f.get('filename'), c.Fore.WHITE, f.get('module'), status_color, status_value ) ) # Validating Schema if self.validation_data.get('schema'): print('\n{}{}Validated Schema:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'File:', 'Status:')) for f in self.validation_data.get('schema'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('filename'), status_color, status_value)) # Validating Layouts if self.validation_data.get('layouts'): print('\n{}{}Validated Layouts:'.format(c.Style.BRIGHT, c.Fore.BLUE)) print('{}{!s:<60}{!s:<25}'.format(c.Style.BRIGHT, 'Params:', 'Status:')) for f in self.validation_data.get('layouts'): status_color = self.status_color(f.get('status')) status_value = self.status_value(f.get('status')) print('{!s:<60}{}{!s:<25}'.format(f.get('params'), status_color, status_value)) if self.validation_data.get('errors'): print('\n') # separate errors from normal output for error in self.validation_data.get('errors'): # print all errors print('* {}{}'.format(c.Fore.RED, error)) # ignore exit code if not self.args.ignore_validation: self.exit_code = 1
[ "def", "print_results", "(", "self", ")", ":", "# Validating Syntax", "if", "self", ".", "validation_data", ".", "get", "(", "'fileSyntax'", ")", ":", "print", "(", "'\\n{}{}Validated File Syntax:'", ".", "format", "(", "c", ".", "Style", ".", "BRIGHT", ",", ...
Print results.
[ "Print", "results", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L441-L493
train
27,678
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
TcExValidate.status_color
def status_color(status): """Return the appropriate status color.""" status_color = c.Fore.GREEN if not status: status_color = c.Fore.RED return status_color
python
def status_color(status): """Return the appropriate status color.""" status_color = c.Fore.GREEN if not status: status_color = c.Fore.RED return status_color
[ "def", "status_color", "(", "status", ")", ":", "status_color", "=", "c", ".", "Fore", ".", "GREEN", "if", "not", "status", ":", "status_color", "=", "c", ".", "Fore", ".", "RED", "return", "status_color" ]
Return the appropriate status color.
[ "Return", "the", "appropriate", "status", "color", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L496-L501
train
27,679
ThreatConnect-Inc/tcex
tcex/tcex_cache.py
TcExCache._dt_to_epoch
def _dt_to_epoch(dt): """Convert datetime to epoch seconds.""" try: epoch = dt.timestamp() except AttributeError: # py2 epoch = (dt - datetime(1970, 1, 1)).total_seconds() return epoch
python
def _dt_to_epoch(dt): """Convert datetime to epoch seconds.""" try: epoch = dt.timestamp() except AttributeError: # py2 epoch = (dt - datetime(1970, 1, 1)).total_seconds() return epoch
[ "def", "_dt_to_epoch", "(", "dt", ")", ":", "try", ":", "epoch", "=", "dt", ".", "timestamp", "(", ")", "except", "AttributeError", ":", "# py2", "epoch", "=", "(", "dt", "-", "datetime", "(", "1970", ",", "1", ",", "1", ")", ")", ".", "total_secon...
Convert datetime to epoch seconds.
[ "Convert", "datetime", "to", "epoch", "seconds", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_cache.py#L28-L34
train
27,680
ThreatConnect-Inc/tcex
tcex/tcex_cache.py
TcExCache.get
def get(self, rid, data_callback=None, raise_on_error=True): """Get cached data from the data store. Args: rid (str): The record identifier. data_callback (callable): A method that will return the data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response. """ cached_data = None ds_data = self.ds.get(rid, raise_on_error=False) if ds_data is not None: expired = True if ds_data.get('found') is True: if self.ttl < int(ds_data.get('_source', {}).get('cache-date', 0)): cached_data = ds_data.get('_source', {}).get('cache-data') expired = False self.tcex.log.debug('Using cached data for ({}).'.format(rid)) else: self.tcex.log.debug('Cached data is expired for ({}).'.format(rid)) if expired or ds_data.get('found') is False: # when cache is expired or does not exist use callback to get data if possible if callable(data_callback): cached_data = data_callback(rid) self.tcex.log.debug('Using callback data for ({}).'.format(rid)) if cached_data: self.update(rid, cached_data, raise_on_error) # update the cache data return cached_data
python
def get(self, rid, data_callback=None, raise_on_error=True): """Get cached data from the data store. Args: rid (str): The record identifier. data_callback (callable): A method that will return the data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response. """ cached_data = None ds_data = self.ds.get(rid, raise_on_error=False) if ds_data is not None: expired = True if ds_data.get('found') is True: if self.ttl < int(ds_data.get('_source', {}).get('cache-date', 0)): cached_data = ds_data.get('_source', {}).get('cache-data') expired = False self.tcex.log.debug('Using cached data for ({}).'.format(rid)) else: self.tcex.log.debug('Cached data is expired for ({}).'.format(rid)) if expired or ds_data.get('found') is False: # when cache is expired or does not exist use callback to get data if possible if callable(data_callback): cached_data = data_callback(rid) self.tcex.log.debug('Using callback data for ({}).'.format(rid)) if cached_data: self.update(rid, cached_data, raise_on_error) # update the cache data return cached_data
[ "def", "get", "(", "self", ",", "rid", ",", "data_callback", "=", "None", ",", "raise_on_error", "=", "True", ")", ":", "cached_data", "=", "None", "ds_data", "=", "self", ".", "ds", ".", "get", "(", "rid", ",", "raise_on_error", "=", "False", ")", "...
Get cached data from the data store. Args: rid (str): The record identifier. data_callback (callable): A method that will return the data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response.
[ "Get", "cached", "data", "from", "the", "data", "store", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_cache.py#L62-L92
train
27,681
ThreatConnect-Inc/tcex
tcex/tcex_cache.py
TcExCache.update
def update(self, rid, data, raise_on_error=True): """Write updated cache data to the DataStore. Args: rid (str): The record identifier. data (dict): The record data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response. """ cache_data = {'cache-date': self._dt_to_epoch(datetime.now()), 'cache-data': data} return self.ds.put(rid, cache_data, raise_on_error)
python
def update(self, rid, data, raise_on_error=True): """Write updated cache data to the DataStore. Args: rid (str): The record identifier. data (dict): The record data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response. """ cache_data = {'cache-date': self._dt_to_epoch(datetime.now()), 'cache-data': data} return self.ds.put(rid, cache_data, raise_on_error)
[ "def", "update", "(", "self", ",", "rid", ",", "data", ",", "raise_on_error", "=", "True", ")", ":", "cache_data", "=", "{", "'cache-date'", ":", "self", ".", "_dt_to_epoch", "(", "datetime", ".", "now", "(", ")", ")", ",", "'cache-data'", ":", "data",...
Write updated cache data to the DataStore. Args: rid (str): The record identifier. data (dict): The record data. raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError. Returns: object : Python request response.
[ "Write", "updated", "cache", "data", "to", "the", "DataStore", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_cache.py#L94-L106
train
27,682
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._association_types
def _association_types(self): """Retrieve Custom Indicator Associations types from the ThreatConnect API.""" # Dynamically create custom indicator class r = self.session.get('/v2/types/associationTypes') # check for bad status code and response that is not JSON if not r.ok or 'application/json' not in r.headers.get('content-type', ''): warn = u'Custom Indicators Associations are not supported.' self.log.warning(warn) return # validate successful API results data = r.json() if data.get('status') != 'Success': warn = u'Bad Status: Custom Indicators Associations are not supported.' self.log.warning(warn) return try: # Association Type Name is not a unique value at this time, but should be. for association in data.get('data', {}).get('associationType', []): self._indicator_associations_types_data[association.get('name')] = association except Exception as e: self.handle_error(200, [e])
python
def _association_types(self): """Retrieve Custom Indicator Associations types from the ThreatConnect API.""" # Dynamically create custom indicator class r = self.session.get('/v2/types/associationTypes') # check for bad status code and response that is not JSON if not r.ok or 'application/json' not in r.headers.get('content-type', ''): warn = u'Custom Indicators Associations are not supported.' self.log.warning(warn) return # validate successful API results data = r.json() if data.get('status') != 'Success': warn = u'Bad Status: Custom Indicators Associations are not supported.' self.log.warning(warn) return try: # Association Type Name is not a unique value at this time, but should be. for association in data.get('data', {}).get('associationType', []): self._indicator_associations_types_data[association.get('name')] = association except Exception as e: self.handle_error(200, [e])
[ "def", "_association_types", "(", "self", ")", ":", "# Dynamically create custom indicator class", "r", "=", "self", ".", "session", ".", "get", "(", "'/v2/types/associationTypes'", ")", "# check for bad status code and response that is not JSON", "if", "not", "r", ".", "...
Retrieve Custom Indicator Associations types from the ThreatConnect API.
[ "Retrieve", "Custom", "Indicator", "Associations", "types", "from", "the", "ThreatConnect", "API", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L63-L86
train
27,683
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._log
def _log(self): """Send System and App data to logs.""" self._log_platform() self._log_app_data() self._log_python_version() self._log_tcex_version() self._log_tc_proxy()
python
def _log(self): """Send System and App data to logs.""" self._log_platform() self._log_app_data() self._log_python_version() self._log_tcex_version() self._log_tc_proxy()
[ "def", "_log", "(", "self", ")", ":", "self", ".", "_log_platform", "(", ")", "self", ".", "_log_app_data", "(", ")", "self", ".", "_log_python_version", "(", ")", "self", ".", "_log_tcex_version", "(", ")", "self", ".", "_log_tc_proxy", "(", ")" ]
Send System and App data to logs.
[ "Send", "System", "and", "App", "data", "to", "logs", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L88-L94
train
27,684
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._log_app_data
def _log_app_data(self): """Log the App data information.""" # Best Effort if self.install_json: app_commit_hash = self.install_json.get('commitHash') app_features = ','.join(self.install_json.get('features', [])) app_min_ver = self.install_json.get('minServerVersion', 'N/A') app_name = self.install_json.get('displayName') app_runtime_level = self.install_json.get('runtimeLevel') app_version = self.install_json.get('programVersion') self.log.info(u'App Name: {}'.format(app_name)) if app_features: self.log.info(u'App Features: {}'.format(app_features)) self.log.info(u'App Minimum ThreatConnect Version: {}'.format(app_min_ver)) self.log.info(u'App Runtime Level: {}'.format(app_runtime_level)) self.log.info(u'App Version: {}'.format(app_version)) if app_commit_hash is not None: self.log.info(u'App Commit Hash: {}'.format(app_commit_hash))
python
def _log_app_data(self): """Log the App data information.""" # Best Effort if self.install_json: app_commit_hash = self.install_json.get('commitHash') app_features = ','.join(self.install_json.get('features', [])) app_min_ver = self.install_json.get('minServerVersion', 'N/A') app_name = self.install_json.get('displayName') app_runtime_level = self.install_json.get('runtimeLevel') app_version = self.install_json.get('programVersion') self.log.info(u'App Name: {}'.format(app_name)) if app_features: self.log.info(u'App Features: {}'.format(app_features)) self.log.info(u'App Minimum ThreatConnect Version: {}'.format(app_min_ver)) self.log.info(u'App Runtime Level: {}'.format(app_runtime_level)) self.log.info(u'App Version: {}'.format(app_version)) if app_commit_hash is not None: self.log.info(u'App Commit Hash: {}'.format(app_commit_hash))
[ "def", "_log_app_data", "(", "self", ")", ":", "# Best Effort", "if", "self", ".", "install_json", ":", "app_commit_hash", "=", "self", ".", "install_json", ".", "get", "(", "'commitHash'", ")", "app_features", "=", "','", ".", "join", "(", "self", ".", "i...
Log the App data information.
[ "Log", "the", "App", "data", "information", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L96-L114
train
27,685
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._log_python_version
def _log_python_version(self): """Log the current Python version.""" self.log.info( u'Python Version: {}.{}.{}'.format( sys.version_info.major, sys.version_info.minor, sys.version_info.micro ) )
python
def _log_python_version(self): """Log the current Python version.""" self.log.info( u'Python Version: {}.{}.{}'.format( sys.version_info.major, sys.version_info.minor, sys.version_info.micro ) )
[ "def", "_log_python_version", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "u'Python Version: {}.{}.{}'", ".", "format", "(", "sys", ".", "version_info", ".", "major", ",", "sys", ".", "version_info", ".", "minor", ",", "sys", ".", "version...
Log the current Python version.
[ "Log", "the", "current", "Python", "version", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L120-L126
train
27,686
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._log_tc_proxy
def _log_tc_proxy(self): """Log the proxy settings.""" if self.default_args.tc_proxy_tc: self.log.info( u'Proxy Server (TC): {}:{}.'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) )
python
def _log_tc_proxy(self): """Log the proxy settings.""" if self.default_args.tc_proxy_tc: self.log.info( u'Proxy Server (TC): {}:{}.'.format( self.default_args.tc_proxy_host, self.default_args.tc_proxy_port ) )
[ "def", "_log_tc_proxy", "(", "self", ")", ":", "if", "self", ".", "default_args", ".", "tc_proxy_tc", ":", "self", ".", "log", ".", "info", "(", "u'Proxy Server (TC): {}:{}.'", ".", "format", "(", "self", ".", "default_args", ".", "tc_proxy_host", ",", "self...
Log the proxy settings.
[ "Log", "the", "proxy", "settings", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L128-L135
train
27,687
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._log_tcex_version
def _log_tcex_version(self): """Log the current TcEx version number.""" self.log.info(u'TcEx Version: {}'.format(__import__(__name__).__version__))
python
def _log_tcex_version(self): """Log the current TcEx version number.""" self.log.info(u'TcEx Version: {}'.format(__import__(__name__).__version__))
[ "def", "_log_tcex_version", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "u'TcEx Version: {}'", ".", "format", "(", "__import__", "(", "__name__", ")", ".", "__version__", ")", ")" ]
Log the current TcEx version number.
[ "Log", "the", "current", "TcEx", "version", "number", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L137-L139
train
27,688
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._logger
def _logger(self): """Create TcEx app logger instance. The logger is accessible via the ``tc.log.<level>`` call. **Logging examples** .. code-block:: python :linenos: :lineno-start: 1 tcex.log.debug('logging debug') tcex.log.info('logging info') tcex.log.warning('logging warning') tcex.log.error('logging error') Args: stream_only (bool, default:False): If True only the Stream handler will be enabled. Returns: logger: An instance of logging """ level = logging.INFO self.log.setLevel(level) # clear all handlers self.log.handlers = [] # update logging level if self.default_args.logging is not None: level = self._logger_levels[self.default_args.logging] elif self.default_args.tc_log_level is not None: level = self._logger_levels[self.default_args.tc_log_level] self.log.setLevel(level) # add file handler if not already added if self.default_args.tc_log_path: self._logger_fh() # add api handler if not already added if self.default_args.tc_token is not None and self.default_args.tc_log_to_api: self._logger_api() self.log.info('Logging Level: {}'.format(logging.getLevelName(level)))
python
def _logger(self): """Create TcEx app logger instance. The logger is accessible via the ``tc.log.<level>`` call. **Logging examples** .. code-block:: python :linenos: :lineno-start: 1 tcex.log.debug('logging debug') tcex.log.info('logging info') tcex.log.warning('logging warning') tcex.log.error('logging error') Args: stream_only (bool, default:False): If True only the Stream handler will be enabled. Returns: logger: An instance of logging """ level = logging.INFO self.log.setLevel(level) # clear all handlers self.log.handlers = [] # update logging level if self.default_args.logging is not None: level = self._logger_levels[self.default_args.logging] elif self.default_args.tc_log_level is not None: level = self._logger_levels[self.default_args.tc_log_level] self.log.setLevel(level) # add file handler if not already added if self.default_args.tc_log_path: self._logger_fh() # add api handler if not already added if self.default_args.tc_token is not None and self.default_args.tc_log_to_api: self._logger_api() self.log.info('Logging Level: {}'.format(logging.getLevelName(level)))
[ "def", "_logger", "(", "self", ")", ":", "level", "=", "logging", ".", "INFO", "self", ".", "log", ".", "setLevel", "(", "level", ")", "# clear all handlers", "self", ".", "log", ".", "handlers", "=", "[", "]", "# update logging level", "if", "self", "."...
Create TcEx app logger instance. The logger is accessible via the ``tc.log.<level>`` call. **Logging examples** .. code-block:: python :linenos: :lineno-start: 1 tcex.log.debug('logging debug') tcex.log.info('logging info') tcex.log.warning('logging warning') tcex.log.error('logging error') Args: stream_only (bool, default:False): If True only the Stream handler will be enabled. Returns: logger: An instance of logging
[ "Create", "TcEx", "app", "logger", "instance", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L141-L184
train
27,689
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._logger_api
def _logger_api(self): """Add API logging handler.""" from .tcex_logger import TcExLogHandler, TcExLogFormatter api = TcExLogHandler(self.session) api.set_name('api') api.setLevel(logging.DEBUG) api.setFormatter(TcExLogFormatter()) self.log.addHandler(api)
python
def _logger_api(self): """Add API logging handler.""" from .tcex_logger import TcExLogHandler, TcExLogFormatter api = TcExLogHandler(self.session) api.set_name('api') api.setLevel(logging.DEBUG) api.setFormatter(TcExLogFormatter()) self.log.addHandler(api)
[ "def", "_logger_api", "(", "self", ")", ":", "from", ".", "tcex_logger", "import", "TcExLogHandler", ",", "TcExLogFormatter", "api", "=", "TcExLogHandler", "(", "self", ".", "session", ")", "api", ".", "set_name", "(", "'api'", ")", "api", ".", "setLevel", ...
Add API logging handler.
[ "Add", "API", "logging", "handler", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L186-L194
train
27,690
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._logger_fh
def _logger_fh(self): """Add File logging handler.""" logfile = os.path.join(self.default_args.tc_log_path, self.default_args.tc_log_file) fh = logging.FileHandler(logfile) fh.set_name('fh') fh.setLevel(logging.DEBUG) fh.setFormatter(self._logger_formatter) self.log.addHandler(fh)
python
def _logger_fh(self): """Add File logging handler.""" logfile = os.path.join(self.default_args.tc_log_path, self.default_args.tc_log_file) fh = logging.FileHandler(logfile) fh.set_name('fh') fh.setLevel(logging.DEBUG) fh.setFormatter(self._logger_formatter) self.log.addHandler(fh)
[ "def", "_logger_fh", "(", "self", ")", ":", "logfile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "default_args", ".", "tc_log_path", ",", "self", ".", "default_args", ".", "tc_log_file", ")", "fh", "=", "logging", ".", "FileHandler", "(", ...
Add File logging handler.
[ "Add", "File", "logging", "handler", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L196-L203
train
27,691
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._logger_levels
def _logger_levels(self): """Return log levels.""" return { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, }
python
def _logger_levels(self): """Return log levels.""" return { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, }
[ "def", "_logger_levels", "(", "self", ")", ":", "return", "{", "'debug'", ":", "logging", ".", "DEBUG", ",", "'info'", ":", "logging", ".", "INFO", ",", "'warning'", ":", "logging", ".", "WARNING", ",", "'error'", ":", "logging", ".", "ERROR", ",", "'c...
Return log levels.
[ "Return", "log", "levels", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L213-L221
train
27,692
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._logger_stream
def _logger_stream(self): """Add stream logging handler.""" sh = logging.StreamHandler() sh.set_name('sh') sh.setLevel(logging.INFO) sh.setFormatter(self._logger_formatter) self.log.addHandler(sh)
python
def _logger_stream(self): """Add stream logging handler.""" sh = logging.StreamHandler() sh.set_name('sh') sh.setLevel(logging.INFO) sh.setFormatter(self._logger_formatter) self.log.addHandler(sh)
[ "def", "_logger_stream", "(", "self", ")", ":", "sh", "=", "logging", ".", "StreamHandler", "(", ")", "sh", ".", "set_name", "(", "'sh'", ")", "sh", ".", "setLevel", "(", "logging", ".", "INFO", ")", "sh", ".", "setFormatter", "(", "self", ".", "_log...
Add stream logging handler.
[ "Add", "stream", "logging", "handler", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L223-L229
train
27,693
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx._resources
def _resources(self, custom_indicators=False): """Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource Classes can be accessed using ``tcex.resources.<Class>`` or using tcex.resource('<resource name>'). """ from importlib import import_module # create resource object self.resources = import_module('tcex.tcex_resources') if custom_indicators: self.log.info('Loading custom indicator types.') # Retrieve all indicator types from the API r = self.session.get('/v2/types/indicatorTypes') # check for bad status code and response that is not JSON if not r.ok or 'application/json' not in r.headers.get('content-type', ''): warn = u'Custom Indicators are not supported ({}).'.format(r.text) self.log.warning(warn) return response = r.json() if response.get('status') != 'Success': warn = u'Bad Status: Custom Indicators are not supported ({}).'.format(r.text) self.log.warning(warn) return try: # Dynamically create custom indicator class data = response.get('data', {}).get('indicatorType', []) for entry in data: name = self.safe_rt(entry.get('name')) # temp fix for API issue where boolean are returned as strings entry['custom'] = self.utils.to_bool(entry.get('custom')) entry['parsable'] = self.utils.to_bool(entry.get('parsable')) self._indicator_types.append(u'{}'.format(entry.get('name'))) self._indicator_types_data[entry.get('name')] = entry if not entry['custom']: continue # Custom Indicator have 3 values. Only add the value if it is set. value_fields = [] if entry.get('value1Label'): value_fields.append(entry.get('value1Label')) if entry.get('value2Label'): value_fields.append(entry.get('value2Label')) if entry.get('value3Label'): value_fields.append(entry.get('value3Label')) # get instance of Indicator Class i = self.resources.Indicator(self) custom = { '_api_branch': entry['apiBranch'], '_api_entity': entry['apiEntity'], '_api_uri': '{}/{}'.format(i.api_branch, entry['apiBranch']), '_case_preference': entry['casePreference'], '_custom': entry['custom'], '_name': name, '_parsable': entry['parsable'], '_request_entity': entry['apiEntity'], '_request_uri': '{}/{}'.format(i.api_branch, entry['apiBranch']), '_status_codes': { 'DELETE': [200], 'GET': [200], 'POST': [200, 201], 'PUT': [200], }, '_value_fields': value_fields, } # Call custom indicator class factory setattr( self.resources, name, self.resources.class_factory(name, self.resources.Indicator, custom), ) except Exception as e: self.handle_error(220, [e])
python
def _resources(self, custom_indicators=False): """Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource Classes can be accessed using ``tcex.resources.<Class>`` or using tcex.resource('<resource name>'). """ from importlib import import_module # create resource object self.resources = import_module('tcex.tcex_resources') if custom_indicators: self.log.info('Loading custom indicator types.') # Retrieve all indicator types from the API r = self.session.get('/v2/types/indicatorTypes') # check for bad status code and response that is not JSON if not r.ok or 'application/json' not in r.headers.get('content-type', ''): warn = u'Custom Indicators are not supported ({}).'.format(r.text) self.log.warning(warn) return response = r.json() if response.get('status') != 'Success': warn = u'Bad Status: Custom Indicators are not supported ({}).'.format(r.text) self.log.warning(warn) return try: # Dynamically create custom indicator class data = response.get('data', {}).get('indicatorType', []) for entry in data: name = self.safe_rt(entry.get('name')) # temp fix for API issue where boolean are returned as strings entry['custom'] = self.utils.to_bool(entry.get('custom')) entry['parsable'] = self.utils.to_bool(entry.get('parsable')) self._indicator_types.append(u'{}'.format(entry.get('name'))) self._indicator_types_data[entry.get('name')] = entry if not entry['custom']: continue # Custom Indicator have 3 values. Only add the value if it is set. value_fields = [] if entry.get('value1Label'): value_fields.append(entry.get('value1Label')) if entry.get('value2Label'): value_fields.append(entry.get('value2Label')) if entry.get('value3Label'): value_fields.append(entry.get('value3Label')) # get instance of Indicator Class i = self.resources.Indicator(self) custom = { '_api_branch': entry['apiBranch'], '_api_entity': entry['apiEntity'], '_api_uri': '{}/{}'.format(i.api_branch, entry['apiBranch']), '_case_preference': entry['casePreference'], '_custom': entry['custom'], '_name': name, '_parsable': entry['parsable'], '_request_entity': entry['apiEntity'], '_request_uri': '{}/{}'.format(i.api_branch, entry['apiBranch']), '_status_codes': { 'DELETE': [200], 'GET': [200], 'POST': [200, 201], 'PUT': [200], }, '_value_fields': value_fields, } # Call custom indicator class factory setattr( self.resources, name, self.resources.class_factory(name, self.resources.Indicator, custom), ) except Exception as e: self.handle_error(220, [e])
[ "def", "_resources", "(", "self", ",", "custom_indicators", "=", "False", ")", ":", "from", "importlib", "import", "import_module", "# create resource object", "self", ".", "resources", "=", "import_module", "(", "'tcex.tcex_resources'", ")", "if", "custom_indicators"...
Initialize the resource module. This method will make a request to the ThreatConnect API to dynamically build classes to support custom Indicators. All other resources are available via this class. .. Note:: Resource Classes can be accessed using ``tcex.resources.<Class>`` or using tcex.resource('<resource name>').
[ "Initialize", "the", "resource", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L231-L311
train
27,694
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.utils
def utils(self): """Include the Utils module. .. Note:: Utils methods can be accessed using ``tcex.utils.<method>``. """ if self._utils is None: from .tcex_utils import TcExUtils self._utils = TcExUtils(self) return self._utils
python
def utils(self): """Include the Utils module. .. Note:: Utils methods can be accessed using ``tcex.utils.<method>``. """ if self._utils is None: from .tcex_utils import TcExUtils self._utils = TcExUtils(self) return self._utils
[ "def", "utils", "(", "self", ")", ":", "if", "self", ".", "_utils", "is", "None", ":", "from", ".", "tcex_utils", "import", "TcExUtils", "self", ".", "_utils", "=", "TcExUtils", "(", "self", ")", "return", "self", ".", "_utils" ]
Include the Utils module. .. Note:: Utils methods can be accessed using ``tcex.utils.<method>``.
[ "Include", "the", "Utils", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L327-L336
train
27,695
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.batch
def batch( self, owner, action=None, attribute_write_type=None, halt_on_error=False, playbook_triggers_enabled=None, ): """Return instance of Batch""" from .tcex_ti_batch import TcExBatch return TcExBatch( self, owner, action, attribute_write_type, halt_on_error, playbook_triggers_enabled )
python
def batch( self, owner, action=None, attribute_write_type=None, halt_on_error=False, playbook_triggers_enabled=None, ): """Return instance of Batch""" from .tcex_ti_batch import TcExBatch return TcExBatch( self, owner, action, attribute_write_type, halt_on_error, playbook_triggers_enabled )
[ "def", "batch", "(", "self", ",", "owner", ",", "action", "=", "None", ",", "attribute_write_type", "=", "None", ",", "halt_on_error", "=", "False", ",", "playbook_triggers_enabled", "=", "None", ",", ")", ":", "from", ".", "tcex_ti_batch", "import", "TcExBa...
Return instance of Batch
[ "Return", "instance", "of", "Batch" ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L348-L361
train
27,696
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.cache
def cache(self, domain, data_type, ttl_minutes=None, mapping=None): """Get instance of the Cache module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). ttl_minutes (int): The number of minutes the cache is valid. Returns: object: An instance of the Cache Class. """ from .tcex_cache import TcExCache return TcExCache(self, domain, data_type, ttl_minutes, mapping)
python
def cache(self, domain, data_type, ttl_minutes=None, mapping=None): """Get instance of the Cache module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). ttl_minutes (int): The number of minutes the cache is valid. Returns: object: An instance of the Cache Class. """ from .tcex_cache import TcExCache return TcExCache(self, domain, data_type, ttl_minutes, mapping)
[ "def", "cache", "(", "self", ",", "domain", ",", "data_type", ",", "ttl_minutes", "=", "None", ",", "mapping", "=", "None", ")", ":", "from", ".", "tcex_cache", "import", "TcExCache", "return", "TcExCache", "(", "self", ",", "domain", ",", "data_type", "...
Get instance of the Cache module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). ttl_minutes (int): The number of minutes the cache is valid. Returns: object: An instance of the Cache Class.
[ "Get", "instance", "of", "the", "Cache", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L363-L379
train
27,697
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.data_filter
def data_filter(self, data): """Return an instance of the Data Filter Class. A simple helper module to filter results from ThreatConnect API or other data source. For example if results need to be filtered by an unsupported field the module allows you to pass the data array/list in and specify one or more filters to get just the results required. Args: data (list): The list of dictionary structure to filter. Returns: (object): An instance of DataFilter Class """ try: from .tcex_data_filter import DataFilter return DataFilter(self, data) except ImportError as e: warn = u'Required Module is not installed ({}).'.format(e) self.log.warning(warn)
python
def data_filter(self, data): """Return an instance of the Data Filter Class. A simple helper module to filter results from ThreatConnect API or other data source. For example if results need to be filtered by an unsupported field the module allows you to pass the data array/list in and specify one or more filters to get just the results required. Args: data (list): The list of dictionary structure to filter. Returns: (object): An instance of DataFilter Class """ try: from .tcex_data_filter import DataFilter return DataFilter(self, data) except ImportError as e: warn = u'Required Module is not installed ({}).'.format(e) self.log.warning(warn)
[ "def", "data_filter", "(", "self", ",", "data", ")", ":", "try", ":", "from", ".", "tcex_data_filter", "import", "DataFilter", "return", "DataFilter", "(", "self", ",", "data", ")", "except", "ImportError", "as", "e", ":", "warn", "=", "u'Required Module is ...
Return an instance of the Data Filter Class. A simple helper module to filter results from ThreatConnect API or other data source. For example if results need to be filtered by an unsupported field the module allows you to pass the data array/list in and specify one or more filters to get just the results required. Args: data (list): The list of dictionary structure to filter. Returns: (object): An instance of DataFilter Class
[ "Return", "an", "instance", "of", "the", "Data", "Filter", "Class", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L382-L402
train
27,698
ThreatConnect-Inc/tcex
tcex/tcex.py
TcEx.datastore
def datastore(self, domain, data_type, mapping=None): """Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). Returns: object: An instance of the DataStore Class. """ from .tcex_datastore import TcExDataStore return TcExDataStore(self, domain, data_type, mapping)
python
def datastore(self, domain, data_type, mapping=None): """Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). Returns: object: An instance of the DataStore Class. """ from .tcex_datastore import TcExDataStore return TcExDataStore(self, domain, data_type, mapping)
[ "def", "datastore", "(", "self", ",", "domain", ",", "data_type", ",", "mapping", "=", "None", ")", ":", "from", ".", "tcex_datastore", "import", "TcExDataStore", "return", "TcExDataStore", "(", "self", ",", "domain", ",", "data_type", ",", "mapping", ")" ]
Get instance of the DataStore module. Args: domain (str): The domain can be either "system", "organization", or "local". When using "organization" the data store can be accessed by any Application in the entire org, while "local" access is restricted to the App writing the data. The "system" option should not be used in almost all cases. data_type (str): The data type descriptor (e.g., tc:whois:cache). Returns: object: An instance of the DataStore Class.
[ "Get", "instance", "of", "the", "DataStore", "module", "." ]
dd4d7a1ef723af1561687120191886b9a2fd4b47
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L404-L419
train
27,699