Ejemplo n.º 1
0
def update(id, _org_label, _prj_label, _payload):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        view = nxs.views.fetch(org_label=_org_label, project_label=_prj_label, view_id=id)
        view_md5_before = utils.generate_nexus_payload_checksum(view, debug=True)
        current_revision = view["_rev"]

        if _payload is not None:
            view = json.loads(_payload)
        else:
            # If no payload given, load up the entry in a text file and open default editor
            new_file, filename = tempfile.mkstemp()
            print("Opening an editor: %s" % filename)
            f = open(filename, "w")
            f.write(json.dumps(view, indent=2))
            f.close()
            click.edit(filename=filename)
            f = open(filename, "r")
            view = json.loads(f.read())
            f.close()
            os.remove(filename)

        view_md5_after = utils.generate_nexus_payload_checksum(view, debug=True)
        if view_md5_before == view_md5_after:
            print("No change in view, aborting update.")
        else:
            nxs.views.update_es(esview=view, rev=current_revision)
            print("View updated.")
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 2
0
def _list(_from, size, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.organizations.list(pagination_from=_from,
                                          pagination_size=size)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            table = PrettyTable(['Label', 'Description', 'Id', 'Deprecated'])
            table.align["Label"] = "l"
            table.align["Description"] = "l"
            table.align["Id"] = "l"
            table.align["Deprecated"] = "l"
            for r in response["_results"]:
                if "description" in r:
                    table.add_row([
                        r["_label"], r["description"], r["@id"],
                        r["_deprecated"]
                    ])
                else:
                    table.add_row(
                        [r["_label"], "", r["@id"], r["_deprecated"]])
            print(table)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 3
0
def show_identities(_json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.identities.fetch()
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            columns = ["Id", "Type", "Realm", "User", "Group"]
            table = PrettyTable(columns)
            for c in columns:
                table.align[c] = "l"
            for i in response["identities"]:
                realm = ""
                if "realm" in i:
                    realm = i["realm"]

                user = ""
                if "subject" in i:
                    user = i["subject"]

                group = ""
                if "group" in i:
                    realm = i["group"]

                table.add_row([i["@id"], i["@type"], realm, user, group])
            print(table)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 4
0
def view_token():
    """Show token for current profile."""
    config = utils.get_cli_config()

    _token = None
    selected = None
    for key in config.keys():
        if nexuscli.config.SELECTED_KEY in config[key] and config[key][
                nexuscli.config.SELECTED_KEY] is True:
            selected = key
            if TOKEN_KEY in config[key]:
                _token = config[key][TOKEN_KEY]
                print(_token)

                decoded = jwt.decode(_token, verify=False)
                print("\nDecoded token:")
                utils.print_json(decoded, colorize=True)
                expiry_utc = datetime.utcfromtimestamp(decoded['exp'])
                expires_in = expiry_utc.timestamp() - datetime.now().timestamp(
                )
                if expires_in > 0:
                    when = "in %s" % utils.print_time(expires_in)
                    message_color = 'green'
                else:
                    when = "%s ago" % utils.print_time(abs(expires_in))
                    message_color = 'red'
                msg = "\nExpiry: %s (%s)" % (
                    utils.datetime_from_utc_to_local(expiry_utc), when)
                click.echo(click.style(msg, fg=message_color))

    if _token is None:
        if selected is None:
            utils.error("You haven't selected a profile.")
        else:
            utils.error('No tokens in selected profile: %s' % selected)
Ejemplo n.º 5
0
def _list(_org_label, _prj_label, deprecated, _from, size, _type, _json,
          pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        response = nxs.views.list(org_label=_org_label,
                                  project_label=_prj_label,
                                  pagination_from=_from,
                                  pagination_size=size,
                                  deprecated=deprecated,
                                  type=_type)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            table = PrettyTable(['Id', 'Type', 'Revision', 'Deprecated'])
            table.align["Id"] = "l"
            table.align["Type"] = "l"
            table.align["Revision"] = "l"
            table.align["Deprecated"] = "l"
            for r in response["_results"]:
                types = utils.format_json_field(r, "@type")
                table.add_row([r["@id"], types, r["_rev"], r["_deprecated"]])
            print(table)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 6
0
def query_sparql(_org_label, _prj_label, id, _payload, file, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        default_query = "SELECT * WHERE { ?s ?p ?o } LIMIT 10"
        data = get_query_from_payload_xor_data_otherwise_editor(
            _payload, file, default_query, file_prefix="query-sparql")
        response = nxs.views.query_sparql(org_label=_org_label,
                                          project_label=_prj_label,
                                          query=data,
                                          view_id=id)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            vars = response["head"]["vars"]
            table = PrettyTable(vars)
            for v in vars:
                table.align[v] = "l"
            for b in response["results"]["bindings"]:
                cells = []
                for v in vars:
                    cells.append(b[v]["value"])
                table.add_row(cells)
            print(table)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 7
0
def create(_org_label, _prj_label, id, file, _type, _payload, format, idcolumn, idnamespace, mergewith, mergeon, max_connections, schema, _json, pretty):


    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = {}
        if _payload is not None and file is not None:
            utils.error("--data and --file are mutually exclusive.")
        if _payload is not None:
            data = json.loads(_payload)
        if file is not None:
            if format == "json":
                with open(file) as f:
                    data = json.load(f)
                if len(data) == 0:
                    utils.error("You must give a non empty payload")

                response = nxs.resources.create(org_label=_org_label, project_label=_prj_label, data=data,
                                                schema_id=schema, resource_id=id)
                print("Resource created (id: %s)" % response["@id"])
                if _json:
                    utils.print_json(response, colorize=pretty)
            elif format == "csv":

               utils.load_csv(_org_label, _prj_label, schema, file_path=file, merge_with=mergewith, merge_on=mergeon, _type=_type, id_colum=idcolumn, id_namespace=idnamespace, max_connections=max_connections)
               print("Finished loading.")


    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 8
0
def update(id, _org_label, _prj_label, _payload):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = nxs.resources.fetch(org_label=_org_label, project_label=_prj_label, schema_id='_', resource_id=id)
        data_md5_before = utils.generate_nexus_payload_checksum(data)
        current_revision = data["_rev"]

        if _payload is not None:
            data = json.loads(_payload)
        else:
            # If no payload given, load up the entry in a text file and open default editor
            new_file, filename = tempfile.mkstemp()
            print("Opening an editor: %s" % filename)
            f = open(filename, "w")
            f.write(json.dumps(data, indent=2))
            f.close()
            click.edit(filename=filename)
            f = open(filename, "r")
            data = json.loads(f.read())
            f.close()
            os.remove(filename)

        data_md5_after = utils.generate_nexus_payload_checksum(data)
        if data_md5_before == data_md5_after:
            print("No change in resource, aborting update.")
        else:
            nxs.resources.update(resource=data, rev=current_revision)
            print("Resource updated.")
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 9
0
def create(label, _org_label, description, base, vocab, _api_mapping, _json,
           pretty):
    _org_label = utils.get_organization_label(_org_label)
    try:
        mappings = None
        if _api_mapping is not None:
            mappings = []
            for am in _api_mapping:
                if "=" not in am:
                    utils.error(
                        "Invalid API Mapping, it should be in the format <prefix>=<URL>: %s"
                        % am)
                key, value = am.split("=", 1)
                entry = {"prefix": key, "namespace": value}
                mappings.append(entry)

        nxs = utils.get_nexus_client()
        response = nxs.projects.create(org_label=_org_label,
                                       project_label=label,
                                       description=description,
                                       api_mappings=mappings,
                                       vocab=vocab,
                                       base=base)
        print("Project created (id: %s)" % response["@id"])
        if _json:
            utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 10
0
def make_public(_org_label, _prj_label, _replace, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        path = _org_label + '/' + _prj_label

        utils.warn("You are about to make the data in your project public to the world.")
        input("Press <ENTER> to continue, CTRL+C to cancel...")

        response = nxs.acls.fetch(subpath=path)
        count = len(response["_results"])
        if count > 1:
            utils.error("More than one ACL matching: %d" % count)
        elif count == 0:
            utils.warn("No ACL found specifically for this organization '%s' and project '%s'." % (_org_label, _prj_label))
            current_rev = 0
        else:
            current_rev = response["_results"][0]['_rev']

        _identities = [_ANONYMOUS_]
        _permissions = [_PROJECTS_READ_, _RESOURCES_READ_, _VIEWS_QUERY_]
        if _replace:
            print("Replacing existing ACLs on project '%s' in organization '%s'" % (_prj_label, _org_label))
            response = nxs.acls.replace(subpath=path, identities=_identities, permissions=[_permissions],
                                        rev=current_rev)
        else:
            print("Adding to existing ACLs on project '%s' in organization '%s'" % (_prj_label, _org_label))
            response = nxs.acls.append(subpath=path, identities=_identities, permissions=[_permissions],
                                       rev=current_rev)
        if _json:
            utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 11
0
def create(_org_label, _prj_label, id, _projects, _identities, _priority,
           _resources_types, _type, _payload, file, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = {}
        if _payload is not None and file is not None:
            utils.error("--data and --file are mutually exclusive.")

        if _priority is not None and _identities is not None and _projects is not None:
            response = nxs.resolvers.create(org_label=_org_label,
                                            project_label=_prj_label,
                                            projects=_projects,
                                            identities=_identities,
                                            _priority=_priority,
                                            _id=id,
                                            resources_types=_resources_types)
        else:
            if _payload is not None:
                data = json.loads(_payload)

            if file is not None:
                with open(file) as f:
                    data = json.load(f)
                if len(data) == 0:
                    utils.error(
                        "The provided file %s should contain a non empty json payload"
                        % file)

            if not data:
                # If no payload given, load up the entry in a text file and open default editor
                new_file, filename = tempfile.mkstemp()
                print("Opening an editor: %s" % filename)
                f = open(filename, "w")
                f.write(json.dumps(data, indent=2))
                f.close()
                click.edit(filename=filename)
                f = open(filename, "r")
                data = json.loads(f.read())
                f.close()
                os.remove(filename)
            if data:
                full_url = nexussdk_http._full_url(
                    path=[nxs.resolvers.SEGMENT, _org_label, _prj_label],
                    use_base=False)
                response = nxs.resolvers.create_(path=full_url,
                                                 payload=data,
                                                 id=id)
            else:
                utils.error(
                    "--data, --file or (--priority, --identities, --projects) are required for creating a resolver."
                )

        print("Resolver created (id: %s)" % response["@id"])
        if _json:
            utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 12
0
def fetch(label, revision, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.fetch(label, revision)
        utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 13
0
def update(label, data, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.replace_(label, data, data['_rev'])
        if _json:
            utils.print_json(response, colorize=pretty)
        utils.success("Realm updated.")
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 14
0
def create(label, name, _open_id_config, logo, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.create(label, name, _open_id_config, logo)
        if _json:
            utils.print_json(response, colorize=pretty)
        utils.success("Realm created.")
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 15
0
def _list():
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.list()
        utils.print_json(response, colorize=True)
        for r in response["_results"]:
            print(r["name"], r["_deprecated"])
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 16
0
def fetch(label, revision, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.organizations.fetch(org_label=label, rev=revision)
        if revision is not None and response["_rev"] != revision:
            utils.error("Revision '%s' does not exist" % revision)
        utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 17
0
def fetch(id, _org_label, _prj_label, schema, revision, tag, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        response = nxs.resources.fetch(org_label=_org_label, project_label=_prj_label, schema_id=schema,
                                       resource_id=id, rev=revision, tag=tag)
        utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 18
0
def _list(_org_label, _prj_label, deprecated, _from, size, search, _json,
          pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        response = nxs.schemas.list(org_label=_org_label,
                                    project_label=_prj_label,
                                    pagination_from=_from,
                                    pagination_size=size,
                                    deprecated=deprecated,
                                    full_text_search_query=search)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            columns = [
                'Id', 'Types', 'Label', 'Imports', 'NodeShapes',
                'PropertyShapes', 'Revision', 'Deprecated'
            ]
            table = PrettyTable(columns)
            for c in columns:
                table.align[c] = "l"

            for r in response["_results"]:
                types = utils.format_json_field(r, "@type")

                # Get extra info from the schema itself
                schema = nxs.schemas.fetch(org_label=_org_label,
                                           project_label=_prj_label,
                                           schema_id=r["@id"])
                imports = utils.format_json_field(schema, "imports")
                node_shapes = get_shapes_id_by_node_kind(
                    schema, ["sh:NodeShape", "NodeShape"])
                property_shapes = get_shapes_id_by_node_kind(
                    schema, ["sh:PropertyShapes", "PropertyShapes"])
                dummy_payload = {
                    "nodes": node_shapes,
                    "properties": property_shapes
                }
                nodes = utils.format_json_field(dummy_payload, "nodes")
                properties = utils.format_json_field(dummy_payload,
                                                     "properties")
                label = ""
                if "label" in schema:
                    label = schema["label"]

                table.add_row([
                    r["@id"], types, label, imports, nodes, properties,
                    r["_rev"], r["_deprecated"]
                ])
            print(table)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 19
0
def deprecate(label, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.deprecate(label)
        if _json:
            utils.print_json(response, colorize=pretty)

        utils.success("Realm deprecated.")
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 20
0
def select(label, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.realms.fetch(label)
        if _json:
            utils.print_json(response, colorize=pretty)
        utils.set_default_realm(label, response['_issuer'])
        utils.success("Realm selected.")
    except nxs.HTTPError as e:
        print(e.response.json())
        utils.error(str(e))
Ejemplo n.º 21
0
def create(label, description, _json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.organizations.create(org_label=label,
                                            description=description)
        print("Organization created (id: %s)" % response["@id"])
        if _json:
            utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 22
0
def statistics(_org_label, _prj_label, id, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        response = nxs.views.stats(org_label=_org_label,
                                   project_label=_prj_label,
                                   view_id=id)
        utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 23
0
def update(id, _org_label, _prj_label, _projects, _identities, _priority,
           _resources_types, _type, _payload):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = nxs.resolvers.fetch(org_label=_org_label,
                                   project_label=_prj_label,
                                   id=id)
        current_revision = data["_rev"]
        data_md5_before = utils.generate_nexus_payload_checksum(data)
        if _priority is not None and _identities is not None and _projects is not None:
            response = nxs.resolvers.update(org_label=_org_label,
                                            project_label=_prj_label,
                                            projects=_projects,
                                            identities=_identities,
                                            _priority=_priority,
                                            id=id,
                                            rev=current_revision,
                                            resources_types=_resources_types)
        else:
            if _payload is not None:
                data = json.loads(_payload)
            else:
                # If no payload given, load up the entry in a text file and open default editor
                new_file, filename = tempfile.mkstemp()
                print("Opening an editor: %s" % filename)
                f = open(filename, "w")
                f.write(json.dumps(data, indent=2))
                f.close()
                click.edit(filename=filename)
                f = open(filename, "r")
                data = json.loads(f.read())
                f.close()
                os.remove(filename)

            data_md5_after = utils.generate_nexus_payload_checksum(data)
            if data_md5_before == data_md5_after:
                print("No change in resolver, aborting update.")
            else:
                encoded_id = encode_url(id)
                nxs.resolvers.update_(path=[
                    nxs.resolvers.SEGMENT, _org_label, _prj_label, encoded_id
                ],
                                      payload=data,
                                      rev=current_revision)
                print("Resolver updated.")

    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 24
0
def select(label):
    nxs = utils.get_nexus_client()
    try:
        nxs.organizations.fetch(org_label=label)
    except nxs.HTTPError as e:
        if e.response.status_code == 404:
            utils.error("Could not find organization with label '%s'." % label)
        else:
            # unexpected error
            utils.print_json(e.response.json(), colorize=True)
            utils.error(str(e))

    utils.set_default_organization(label)
    print("organization selected.")
Ejemplo n.º 25
0
def show_permissions(_json, pretty):
    nxs = utils.get_nexus_client()
    try:
        response = nxs.permissions.fetch()
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            table = PrettyTable(['Permissions'])
            table.align['Permissions'] = "l"
            for p in response["permissions"]:
                table.add_row([p])
            print(table)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 26
0
def select(label, _org_label):
    _org_label = utils.get_organization_label(_org_label)
    try:
        nxs = utils.get_nexus_client()
        nxs.projects.fetch(org_label=_org_label, project_label=label)
    except nxs.HTTPError as e:
        if e.response.status_code == 404:
            utils.error("Could not find project with label '%s' under organization '%s'." % (label, _org_label))
        else:
            # unexpected error
            utils.print_json(e.response.json(), colorize=True)
            utils.error(str(e))

    utils.set_default_project(label)
    print("Project selected.")
Ejemplo n.º 27
0
def create(_org_label, _prj_label, id, _payload, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = {}
        if _payload is not None:
            data = json.loads(_payload)
        response = nxs.views.create_es(org_label=_org_label, project_label=_prj_label, view_data=data, view_id=id)
        print("View created (id: %s)" % response["@id"])
        if _json:
            utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 28
0
def create(_org_label, _prj_label, id, _payload, file, dir, _schemas_base_dir,
           _schemas_ns, _strategy, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = {}
        if _payload is not None and file is not None:
            utils.error("--data and --file are mutually exclusive.")
        if _payload is not None:
            data = json.loads(_payload)
        if file is not None:
            with open(file) as f:
                data = json.load(f)
        if dir is not None:
            if _schemas_base_dir:
                print(_schemas_base_dir)
                _schemas_base_dir = json.loads(_schemas_base_dir)
            imported, not_imported = schemahelper.import_schemas(
                dir, _org_label, _prj_label, _schemas_base_dir, _schemas_ns,
                _strategy)

            if len(not_imported) > 0:
                with open("schema-import-errors.log", "w") as file:
                    for (schema_file_path, exception_name,
                         error_message) in not_imported:
                        file.write(
                            "schema={} exception_name={} message={}\n".format(
                                schema_file_path, exception_name,
                                error_message))
                utils.error(
                    "\nFailed to import {} schemas. See 'schema-import-errors.log' for details."
                    .format(len(not_imported)))

        if data:
            response = nxs.schemas.create(org_label=_org_label,
                                          project_label=_prj_label,
                                          schema_obj=data,
                                          schema_id=id)
            print("Schema created (id: %s)" % response["@id"])
            if _json:
                utils.print_json(response, colorize=pretty)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))
Ejemplo n.º 29
0
def query_es(_org_label, _prj_label, id, _payload, file, _json, pretty):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        default_query = {"query": {"query_string": {"query": "*"}}}
        data = get_query_from_payload_xor_data_otherwise_editor(
            _payload, file, default_query, file_prefix="query-es")
        response = nxs.views.query_es(org_label=_org_label,
                                      project_label=_prj_label,
                                      view_id=id,
                                      query=data)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            table = PrettyTable(['Id', 'Type', 'Revision', 'Deprecated'])
            table.align["Id"] = "l"
            table.align["Type"] = "l"
            table.align["Revision"] = "l"
            table.align["Deprecated"] = "l"
            for r in response["hits"]["hits"]:
                types = ""
                if "_source" in r and "@type" in r["_source"]:
                    if type(r["_source"]["@type"]) is str:
                        types = r["_source"]["@type"]
                    elif isinstance(r["_source"]["@type"],
                                    collections.Sequence):
                        for t in r["_source"]["@type"]:
                            types += t + "\n"
                    else:
                        utils.warn("Unsupported type: " +
                                   type(r["_source"]["@type"]))
                        types = r["_source"]["@type"]
                else:
                    types = '-'

                table.add_row([
                    r["_source"]["@id"], types, r["_source"]["_rev"],
                    r["_source"]["_deprecated"]
                ])
            print(table)
    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 30
0
def _list(_org_label, _prj_label, subpath, _ancestor, _self, _json, pretty, verbose):
    if _org_label != '*':
        _org_label = utils.get_organization_label(_org_label)
    if _prj_label != '*':
        _prj_label = utils.get_project_label(_prj_label)

    nxs = utils.get_nexus_client()
    try:
        path = _org_label + '/' + _prj_label
        if subpath is not None:
            path += '/' + subpath
        if verbose:
            print("subpath: %s" % path)
            print("self: %s" % _self)
            print("ancestors: %s" % _ancestor)
        response = nxs.acls.list(subpath=path, ancestors=_ancestor, self=_self)
        if _json:
            utils.print_json(response, colorize=pretty)
        else:
            columns = ['Path', 'Identity', 'Permissions']
            table = PrettyTable(columns)
            for c in columns:
                table.align[c] = "l"
            for _acl in response["_results"]:
                for entry in _acl["acl"]:
                    i = entry["identity"]
                    _type = i["@type"]
                    printed_identity = _type
                    if _type == "User":
                        printed_identity = "%s: %s (realm: %s)" % (_type, i["subject"], i["realm"])
                    elif _type == "Group":
                        printed_identity = "%s: %s (realm: %s)" % (_type, i["group"], i["realm"])
                    elif _type == "Authenticated":
                        printed_identity = "%s (realm: %s)" % (_type, i["realm"])

                    _permissions = "\n".join(entry["permissions"])
                    table.add_row([_acl["_path"], printed_identity, _permissions])
            print(table)
    except nxs.HTTPError as e:
        utils.print_json(e.response.json(), colorize=True)
        utils.error(str(e))