GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — dropbox-sdk-java/generator/java.stoneg.py at master · JavaScriptBach/dropbox-sdk-java Expand file tree/ Copy pathjava.stoneg.pyMore file actions 4378 lines (3639 loc) · 173 KB / Copy pathjava.stoneg.pyFile metadata and controls4378 lines (3639 loc) · 173 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 from __future__ import absolute_import, division, print_function, unicode_literals import abc import argparse import json import os import re import six import sys import types from collections import defaultdict, OrderedDict, Sequence from contextlib import contextmanager from functools import ( partial, total_ordering, wraps, ) from itertools import chain from stone.ir import ( Api, ApiNamespace, ApiRoute, DataType, Field, Int32, is_boolean_type, is_bytes_type, is_composite_type, is_list_type, is_map_type, is_nullable_type, is_numeric_type, is_primitive_type, is_string_type, is_struct_type, is_timestamp_type, is_union_type, is_user_defined_type, is_void_type, StructField, TagRef, Union, UnionField, unwrap_nullable, Void, ) from stone.backend import CodeBackend @six.add_metaclass(abc.ABCMeta) class StoneType: pass StoneType.register(ApiNamespace) StoneType.register(ApiRoute) StoneType.register(DataType) StoneType.register(Field) def cached(f): cache = {} @wraps(f) def wrapper(*args, **kwargs): key = tuple(args) + tuple(entry for entry in sorted(kwargs.items())) if key in cache: return cache[key] else: val = f(*args, **kwargs) cache[key] = val return val return wrapper class cached_property(object): """ Decorator similar to @property, but which caches the results permanently. """ def __init__(self, func): self._func = func self._attr_name = func.__name__ def __get__(self, instance, owner): if instance is None: return self else: val = self._func(instance) instance.__dict__[self._attr_name] = val return val def _fixreserved(s): if s in _RESERVED_KEYWORDS: s += '_' return s def _capwords(s): words = s.replace('/', '_').split('_') return ''.join(w[:1].upper() + w[1:] for w in words) def _camelcase(s): s = _capwords(s) return s[:1].lower() + s[1:] def _allcaps(s): return s.replace('/', '_').upper() def capwords(s): return _fixreserved(_capwords(s)) def camelcase(s): return _fixreserved(_camelcase(s)) def allcaps(s): return _fixreserved(_allcaps(s)) def collapse_whitespace(s): return "\n".join( line.strip() for line in s.strip().splitlines() ) def split_paragraphs(s): paragraph = [] for line in s.splitlines(): line = line.strip() if line == '': if paragraph: yield "\n".join(paragraph) del paragraph[:] else: paragraph.append(line) if paragraph: yield "\n".join(paragraph) def split_stone_name(stone_fq_name, max_parts): assert isinstance(stone_fq_name, six.text_type), repr(stone_fq_name) assert max_parts > 0, "max_parts must be positive" parts = stone_fq_name.split('.') if len(parts) > max_parts: raise ValueError('Malformed Stone reference: %s' % stone_fq_name) else: filler = (None,) * (max_parts - len(parts)) return filler + tuple(parts) def sanitize_pattern(pattern): return pattern.replace('\\', '\\\\').replace('"', '\\"') _JAVADOC_REPLACEMENT_CHARS = ( ('&', '&'), ('<', '<'), ('>', '>'), ) def sanitize_javadoc(doc): # sanitize &, <, > characters for char, code in _JAVADOC_REPLACEMENT_CHARS: doc = doc.replace(char, code) return doc def unsanitize_javadoc(doc): for char, code in _JAVADOC_REPLACEMENT_CHARS: doc = doc.replace(code, char) return doc def oxford_comma_list(values, conjunction='and'): if not values: return None elif len(values) == 1: return values[0] elif len(values) == 2: return '%s %s %s' % (values[0], conjunction, values[1]) else: return '%s, %s %s' % (', '.join(values[:-1]), conjunction, values[-1]) def classname(s): return capwords(s) def get_ancestors(data_type): """Return list of (tag, data_type) pairs. The first pair is the root and always has tag None. The last pair represents the argument. The tag is only present if the data_type in that pair has an ancestor and is a member of that ancestore's enumerated subtypes. Suppose we have the following tree: struct A struct B extends A struct C extends B Without enumerated subtypes: - get_ancestors(C) returns [(None, A), (None, B), (None, C)] - get_ancestors(B) returns [(None, A), (None, B)] - get_ancestors(A) returns [(None, A)] Now add enumerated subtypes, so the tree becomes: struct A union b B struct B extends A union c C struct C extends B Now the return values are: - get_ancestors(C) returns [(None, A), ('b', B), ('c', C)] - get_ancestors(B) returns [(None, A), ('b', B)] - get_ancestors(A) returns [(None, A)] """ assert isinstance(data_type, DataType), repr(data_type) ancestors = [] while data_type is not None: parent_type = data_type.parent_type tag = None if parent_type is not None and parent_type.has_enumerated_subtypes(): for field in parent_type.get_enumerated_subtypes(): if field.data_type is data_type: tag = field.name break else: assert False, "Type %s not found in subtypes of ancestor %s" % (data_type.name, parent_type.name) ancestors.append((tag, data_type)) data_type = parent_type ancestors.reverse() return ancestors def get_enumerated_subtypes_recursively(data_type): """ Returns a list of (tag, DataType) pairs. This method searches for all possible enumerated subtypes of the given data type. In the example: struct A union b B c C struct B extends A union d D e E struct C extends A union f F struct D extends B struct E extends B struct F extends C The following value would be returned: - get_enumerated_subtypes_recursively(A): [('b', B), ('c', C), ('b.d', D), ('b.e', E), ('c.f', F)] - get_enumerated_subtypes_recursively(B): [('b.d', D), ('b.e', E)] - get_enumerated_subtypes_recursively(C): [('c.f', F)] - get_enumerated_subtypes_recursively(D): [] """ assert isinstance(data_type, DataType), repr(data_type) if not data_type.has_enumerated_subtypes(): return [] subtypes = [] def add_subtype(data_type): subtypes.append(data_type) if data_type.has_enumerated_subtypes(): for subtype in data_type.get_enumerated_subtypes(): add_subtype(subtype.data_type) add_subtype(data_type) result = [] for subtype in subtypes: tag = '.'.join(name for name, _ in get_ancestors(subtype) if name) result.append((tag, subtype)) return result def get_underlying_type(data_type, allow_data_structures=True): assert isinstance(data_type, DataType), repr(data_type) while True: if allow_data_structures and is_list_type(data_type): data_type = data_type.data_type elif allow_data_structures and is_map_type(data_type): data_type = data_type.value_data_type elif is_nullable_type(data_type): data_type = data_type.data_type else: break return data_type def union_create_with_method_name(data_type, value_fields_subset): if len(value_fields_subset) > 0: method_suffix = 'And%s' % _capwords(value_fields_subset[0].name) else: method_suffix = '' return 'withTag%s' % method_suffix @total_ordering class JavaClass(object): """ Represents a Java class name. This class is a convenience for handling Java classes. This class lets you reference a Java class explicitly by its fully-qualified name or its short-name. :ivar str fq_name: Fully-qualified Java class name """ def __init__(self, fq_name, generics=()): assert isinstance(fq_name, six.text_type), repr(fq_name) assert isinstance(generics, Sequence), repr(generics) self._fq_name = fq_name self._generics = generics for g in generics: assert isinstance(g, (JavaClass, six.text_type)), repr(generics) if isinstance(g, six.text_type): assert '.' not in g, repr(generics) package_parts = fq_name.split('.') # Handle nested classes, like: # # com.foo.Bar.Wop # # name => Wop # package => com.foo # static_name => Bar.Wop # import_name => com.foo.Bar # self._name = package_parts[-1] for i, part in enumerate(package_parts): is_last = i == len(package_parts) - 1 is_class_name = (part and part[0].isupper()) if is_last or is_class_name: self._package = '.'.join(package_parts[:i]) self._static_name = '.'.join(package_parts[i:]) self._import_name = '.'.join(package_parts[:i+1]) break @classmethod def from_str(cls, val): """ Returns an instance of JavaClass from its string representation produced using str(..). """ matcher = re.match(r'^(?P<fq_name>[^< ]+)(?:<(?P<generics>.*)>)?$', val) if matcher is None: raise ValueError("Malformed Java class: %s" % val) fq_name = matcher.group('fq_name') generics_group = matcher.group('generics') generics = [] if generics_group is not None: for gtype in generics_group.split(','): gtype = gtype.strip() if not gtype: raise ValueError("Malformed Java class: %s" % val) if '.' in gtype: generics.append(cls.from_str(gtype)) else: generics.append(gtype) return JavaClass(fq_name, generics=generics) @property def fq(self): """ Fully-qualified Java class name. Example: com.foo.Bar.Wop => com.foo.Bar.Wop :rtype: str """ return self._fq_name @property def name(self): """ Short name of Java class. Example: com.foo.Bar.Wop => Wop :rtype: str """ return self._name @property def name_with_generics(self): if self._generics and all('.' in g for g in self._generics): return '%s<%s>' % (self._name, ', '.join(self._generics)) else: return self._name def resolved_name(self, current_class, imports, generics=False): """ Returns the appropriate name to use when referencing this class from within the given class. Examples: current_class => JavaClass("com.dropbox.files.C") imports => {JavaClass("com.dropbox.common.A"), JavaClass("java.util.B")} "com.dropbox.files.D" => "D" # package local "com.dropbox.common.E" => "com.dropbox.common.E" # not imported "com.dropbox.common.A" => "A" # already imported "com.dropbox.files.C.X" => "X" # nested inner class "java.util.B.Y" => "B.Y" # nested class outside current class Args: current_class(JavaClass): class that will reference this class imports(set[JavaClass]): set of full-qualified classes that have been imported :rtype: str """ resolved = self._resolved_name(current_class, imports) if generics and self._generics: resolved_generics = ', '.join( g.resolved_name(current_class, imports, generics) if isinstance(g, JavaClass) else g for g in self._generics ) return '%s<%s>' % (resolved, resolved_generics) else: return resolved def _resolved_name(self, current_class, imports): # no package, so just return the name if not self._package: return self._name assert isinstance(current_class, JavaClass), repr(current_class) assert imports is not None # inner class? (e.g. com.foo.CommitInfo.Builder) if self._fq_name.startswith(current_class._fq_name + '.'): return self._fq_name[len(current_class._fq_name) + 1:] # package-local class? we don't need to import these if self._package == current_class.package: return self._static_name # check if we already imported this name into our current context if self.import_class in imports: return self._static_name # last resort, display fully-qualified name return self._fq_name @property def package(self): """ Name of package containing this Java class. Example: com.foo.Bar.Wop => com.foo :rtype: str """ return self._package @property def is_nested(self): """ Whether or not this class is nested within another Java class. :rtype: bool """ return self._static_name != self._name @property def import_class(self): """ Returns the root class containing this nested class. Example: com.foo.Bar => com.foo.Bar com.foo.Bar.A => com.foo.Bar com.foo.Bar.A.B => com.foo.Bar The returned class is the class you would import if you needed access to this class. :rtype: JavaClass """ return JavaClass(self._import_name) def __repr__(self): return '%s(%s)' % (type(self), str(self)) def __str__(self): if self._generics: return '%s<%s>' % (self._fq_name, ', '.join(str(g) for g in self._generics)) else: return self._fq_name def __hash__(self): return hash(self._fq_name) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if isinstance(other, JavaClass): return self._fq_name == other._fq_name return False def __lt__(self, other): assert isinstance(other, type(self)), repr(other) return self._fq_name < other._fq_name @total_ordering class Visibility(object): def __init__(self, rank, name, modifier): self._rank = rank self._name = name self._modifier = modifier @property def name(self): return self._name @property def is_visible(self): return self._modifier is not None @property def modifier(self): if not self.is_visible: raise ValueError("Not visible") return self._modifier @classmethod def from_name(cls, name): for value in cls._VALUES: if value.name == name: return value raise ValueError("Unrecognized name: %s" % name) def __repr__(self): return self._name def __hash__(self): return self._rank def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if isinstance(other, type(self)): return self._rank == other._rank return False def __lt__(self, other): assert isinstance(other, type(self)), repr(other) return self._rank < other._rank Visibility.NONE = Visibility(0, 'NONE', None) Visibility.PRIVATE = Visibility(1, 'PRIVATE', 'private') Visibility.PACKAGE = Visibility(2, 'PACKAGE', '') Visibility.PUBLIC = Visibility(3, 'PUBLIC', 'public') Visibility._VALUES = (Visibility.NONE, Visibility.PRIVATE, Visibility.PACKAGE, Visibility.PUBLIC) _CMDLINE_PARSER = argparse.ArgumentParser(prog='java-generator') _CMDLINE_PARSER.add_argument('--package', type=six.text_type, required=True, help='base package name') _CMDLINE_PARSER.add_argument('--client-class', type=six.text_type, default='StoneClient', help='Name of client class to generate.') _CMDLINE_PARSER.add_argument('--client-javadoc', type=six.text_type, default='Auto-generated Stone client', help='Class Javadoc to use for auto-generated client.') _CMDLINE_PARSER.add_argument('--requests-classname-prefix', type=six.text_type, default=None, help=('Prefix to prepend to the per-namespace requests classes. ' 'Defaults to using the name of the client class.')) _CMDLINE_PARSER.add_argument('--data-types-only', action="store_true", default=False, help='Generate all data types but no routes or clients.') _CMDLINE_PARSER.add_argument('--javadoc-refs', type=six.text_type, default=None, help='Path to Javadoc references file. If a file exists at this ' + 'path, it will be loaded and used for generating correct Javadoc ' + 'references based off previous generator runs. This is useful when ' + 'generating multiple clients for a single project. ' + 'If this argument is specified, an update Javadoc references file ' + 'will be saved to the given location. It is OK if this file does not ' + 'exist.') _CMDLINE_PARSER.add_argument('--unused-classes-to-generate', default=None, help='Specify types ' + 'that we want to generate regardless of whether they are used.') class JavaCodeGenerator(CodeBackend): cmdline_parser = _CMDLINE_PARSER def generate(self, api): """ Toplevel code generation method. This is called by stone.cli. """ generator = JavaCodeGenerationInstance(self, api) if self.args.data_types_only: assert self.args.javadoc_refs is None, "Cannot specify --javadoc-refs with --data-types-only" generator.generate_data_types() else: generator.generate_all() class JavaImporter(object): def __init__(self, current_class, j): assert isinstance(current_class, JavaClass), repr(current_class) assert isinstance(j, JavaApi), repr(j) self._class = current_class self._j = j self._imports = set() @property def imports(self): return frozenset(self._imports) def add_imports(self, *imports): """ Adds the fully-qualified Java class names to the set of imports for the currently generated class. Imports must be fully-qualified class name strings (e.g. ``"com.foo.Bar"``) or JavaClass instances. """ assert all(isinstance(i, (six.text_type, JavaClass)) for i in imports), repr(imports) def convert(val): if isinstance(val, JavaClass): return val elif isinstance(val, six.string_types): return JavaClass(val) else: raise AssertionError(repr(type(val))) # convert all imports to JavaClass instances imports = [convert(i) for i in imports] # remove imports that are missing package (e.g. long, Integer, # etc) and imports from java.lang imports = [ i for i in imports if i.package and i.package != 'java.lang' ] current_class_prefix = self._class.fq + '.' existing_names = {i.name: i for i in self._imports} # avoid issues where we import a class with the same name as us existing_names[self._class.name] = self._class for import_ in imports: # resolve nested classes to their root containing class import_ = import_.import_class # already imported or local name (not fully qualified) if import_ in self._imports or not import_.package: continue # ignore nested classes inside our current class if import_ == self._class: continue # is this import in our existing names? make sure we choose the most "valid" import # between the two: if import_.name in existing_names: # we always prefer package-local imports, otherwise we can't determine at name # resolution time whether a package-local class needs to be fully-qualified or # not. This means we essentially block all imports that clash with package-local # class names. if import_.package == self._class.package: existing_import = existing_names[import_.name] self._imports.remove(existing_import) existing_names[import_.name] = import_ self._imports.add(import_) else: # leave the existing import alone pass else: # new import existing_names[import_.name] = import_ self._imports.add(import_) def add_imports_for_namespace(self, namespace): assert isinstance(namespace, ApiNamespace), repr(namespace) self.add_imports( 'com.dropbox.core.DbxException', 'com.dropbox.core.DbxWrappedException', 'com.dropbox.core.http.HttpRequestor', 'com.dropbox.core.v2.DbxRawClientV2', 'java.util.HashMap', 'java.util.Map', ) for route in namespace.routes: self.add_imports_for_route(route) def add_imports_for_route(self, route): assert isinstance(route, ApiRoute), repr(route) j = self._j self._add_imports_for_data_type(route.arg_data_type) self._add_imports_for_data_type(route.result_data_type) self._add_imports_for_data_type_exception(route.error_data_type) if j.has_builder(route) and j.has_arg(route) and j.has_builder(route.arg_data_type): self._add_imports_for_data_type_builder(route.arg_data_type) if is_struct_type(route.arg_data_type): if j.has_builder(route): fields = route.arg_data_type.all_required_fields else: fields = route.arg_data_type.all_fields for field in fields: self.add_imports_for_field(field) if j.request_style(route) == 'upload': self.add_imports('com.dropbox.core.DbxUploader') if j.has_builder(route): self.add_imports('com.dropbox.core.v2.DbxUploadStyleBuilder') elif j.request_style(route) == 'download': self.add_imports( 'com.dropbox.core.DbxDownloader', 'com.dropbox.core.v2.DbxDownloadStyleBuilder', 'java.util.Collections', 'java.util.List', 'java.util.Map', ) def add_imports_for_route_builder(self, route): assert isinstance(route, ApiRoute), repr(route) j = self._j assert j.has_builder(route), repr(route) if j.has_arg(route) and j.has_builder(route.arg_data_type): self._add_imports_for_data_type_builder(route.arg_data_type) self._add_imports_for_data_type(route.result_data_type) self._add_imports_for_data_type_exception(route.error_data_type) namespace = j.route_namespace(route) route_auth = j.auth_style(route) if j.auth_style(route) != 'noauth' else 'user' self.add_imports( j.java_class(namespace), 'com.dropbox.core.DbxException', ) for field in route.arg_data_type.all_optional_fields: self.add_imports_for_field(field) if j.request_style(route) == 'download': self.add_imports( 'com.dropbox.core.v2.DbxDownloadStyleBuilder', 'com.dropbox.core.DbxDownloader', ) elif j.request_style(route) == 'upload': self.add_imports('com.dropbox.core.v2.DbxUploadStyleBuilder') def add_imports_for_route_uploader(self, route): self.add_imports( 'com.dropbox.core.DbxWrappedException', 'com.dropbox.core.DbxUploader', 'com.dropbox.core.http.HttpRequestor', 'java.io.IOException', ) self._add_imports_for_data_type(route.result_data_type) self._add_imports_for_data_type_exception(route.error_data_type) def add_imports_for_data_type(self, data_type, include_serialization=True): assert isinstance(data_type, DataType), repr(data_type) assert is_user_defined_type(data_type), repr(data_type) j = self._j # for hash code computation if data_type.fields or (is_union_type(data_type) and not j.is_enum(data_type)): self.add_imports('java.util.Arrays') self._add_imports_for_data_type(data_type) if include_serialization: self._add_imports_for_data_type_serializers(data_type) for field in data_type.all_fields: self.add_imports_for_field(field) # for regex pattern validation if is_string_type(field.data_type) and field.data_type.pattern is not None: self.add_imports('java.util.regex.Pattern') # check if we need to import parent type if is_struct_type(data_type) and data_type.parent_type: self._add_imports_for_data_type(data_type.parent_type) def add_imports_for_exception_type(self, data_type): j = self._j self.add_imports( 'com.dropbox.core.DbxApiException', 'com.dropbox.core.LocalizedText', j.java_class(data_type), ) def add_imports_for_field(self, field): self._add_imports_for_data_type(field.data_type) def _add_imports_for_data_type(self, data_type): j = self._j if is_user_defined_type(data_type): self.add_imports(j.java_class(data_type)) else: java_type = _TYPE_MAP_UNBOXED.get(data_type.name) if java_type and '.' in java_type: self.add_imports(java_type) if is_list_type(data_type) or is_nullable_type(data_type): self._add_imports_for_data_type(data_type.data_type) elif is_map_type(data_type): self._add_imports_for_data_type(data_type.value_data_type) elif is_timestamp_type(data_type): self.add_imports('com.dropbox.core.util.LangUtil') def _add_imports_for_data_type_builder(self, data_type): assert isinstance(data_type, DataType), repr(data_type) j = self._j self.add_imports(j.builder_class(data_type)) def _add_imports_for_data_type_exception(self, data_type): j = self._j if is_void_type(data_type): self.add_imports('com.dropbox.core.DbxApiException') else: self.add_imports( j.java_class(data_type), j.exception_class(data_type), ) def _add_imports_for_data_type_serializers(self, data_type): self.add_imports( 'java.io.IOException', 'com.fasterxml.jackson.core.JsonGenerationException', 'com.fasterxml.jackson.core.JsonGenerator', 'com.fasterxml.jackson.core.JsonParseException', 'com.fasterxml.jackson.core.JsonParser', 'com.fasterxml.jackson.core.JsonToken', 'com.dropbox.core.stone.StoneSerializers', ) if is_struct_type(data_type): self.add_imports('com.dropbox.core.stone.StructSerializer') elif is_union_type(data_type): self.add_imports('com.dropbox.core.stone.UnionSerializer') def __repr__(self): return '%s(class=%s,imports=%s)' % (type(self).__name__, self._class, self._imports) class JavaClassWriter(object): def __init__(self, g, j, refs, java_class, stone_element=None, package_doc=None): assert isinstance(java_class, JavaClass), repr(java_class) assert java_class.package, repr(java_class) self.importer = JavaImporter(java_class, j) self._g = g self._j = j self._refs = refs self._class = java_class self._stone_element = stone_element self._package_doc = package_doc if package_doc: assert java_class.name == 'package-info', "Only package-info.java files can contain package Javadoc" def _mkdirs(self, path): if not os.path.isdir(path): self._g.logger.info('Creating directory %s', path) os.makedirs(path) def __enter__(self): components = self._class.import_class.fq.split('.') path = os.path.join(*components) self._mkdirs(os.path.dirname(path)) self._enter_ctx = self._g.output_to_relative_path(path + '.java') self._enter_ctx.__enter__() self._emit_header() if self._package_doc: self.javadoc(self._package_doc) self.out('package %s;', self._class.package) self.out('') return self def __exit__(self, exc_type, exc_value, traceback): ret = self._enter_ctx.__exit__(exc_type, exc_value, traceback) self._enter_ctx = None return ret def fmt(self, fmt_str, *args, **kwargs): assert isinstance(fmt_str, six.text_type), repr(fmt_str) generics = kwargs.get('generics', True) # resolve JavaClass to appropriate names based on our current imports resolved_args = tuple( self.resolved_class(a, generics=generics) if isinstance(a, JavaClass) else a for a in args ) return fmt_str % resolved_args def out(self, fmt_str, *args, **kwargs): self._g.emit(self.fmt(fmt_str, *args), **kwargs) def block(self, fmt_str, *args, **kwargs): return self._g.block(self.fmt(fmt_str, *args).strip(), **kwargs) @contextmanager def conditional_block(self, predicate, fmt_str, *args): if predicate: with self.block(fmt_str, *args): yield else: yield def class_block(self, element, visibility=Visibility.PUBLIC, parent_class=None): assert isinstance(element, (JavaClass, StoneType)), repr(element) assert visibility.is_visible, repr((element, visibility)) j = self._j java_class = j.java_class(element) if isinstance(element, StoneType) else element modifiers = [visibility.modifier] class_type = 'class' class_name = java_class.name_with_generics inheritance = parent_class if java_class.is_nested: modifiers.append('static') if isinstance(element, DataType): data_type = element if j.is_enum(data_type): class_type = 'enum' elif is_union_type(data_type): modifiers.append('final') elif is_struct_type(data_type) and data_type.parent_type: assert parent_class is None, repr((data_type, parent_class)) inheritance = j.java_class(data_type.parent_type) if inheritance: return self.block('%s %s %s extends %s', ' '.join(modifiers), class_type, class_name, inheritance) else: return self.block('%s %s %s', ' '.join(modifiers), class_type, class_name) def resolved_class(self, val, generics=True): if isinstance(val, six.text_type): val = JavaClass(val) else: assert isinstance(val, JavaClass), repr(val) return val.resolved_name(self._class, self.importer.imports, generics=generics) def _emit_header(self): j = self._j filenames = j.get_spec_filenames(self._stone_element) if self._stone_element else None self.out('/* DO NOT EDIT */') if filenames: self.out('/* This file was generated from %s */' % ', '.join(filenames)) else: self.out('/* This file was generated by Stone */') self.out('') def write_imports(self): # start off will all imports, then group into categories imports = self.importer.imports # remove package-local imports imports = { import_ for import_ in imports |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |