Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

#!/usr/bin/env python 

""" 

@file ion/core/object/gpb_wrapper.py 

@brief Wrapper for Google Protocol Buffer Message Classes. 

These classes are the lowest level of the object management stack 

@author David Stuebe 

@author  

TODO: 

""" 

 

from ion.core.object.object_utils import get_type_from_obj, sha1bin, sha1hex,\ 

    sha1_to_hex, ObjectUtilException, create_type_identifier, get_gpb_class_from_type_id, OOIObjectError 

 

import StringIO 

 

from ion.core.object.object_utils import CDM_GROUP_TYPE, CDM_DATASET_TYPE, CDM_ATTRIBUTE_TYPE, CDM_DIMENSION_TYPE, CDM_VARIABLE_TYPE 

 

# Get the object decorators used on all wrapper methods! 

from ion.core.object.object_utils import _gpb_source, _gpb_source_root 

 

import struct 

 

from google.protobuf import message 

from google.protobuf.internal import containers 

from google.protobuf import descriptor 

 

from ion.core.object.cdm_methods import dataset 

from ion.core.object.cdm_methods import variables 

from ion.core.object.cdm_methods import attribute 

from ion.core.object.cdm_methods import group 

from ion.core.object.cdm_methods import attribute_merge 

 

import ion.util.ionlog 

from ion.core import ioninit 

 

CONF = ioninit.config(__name__) 

log = ion.util.ionlog.getLogger(__name__) 

 

STRUCTURE_ELEMENT_TYPE = create_type_identifier(object_id=1, version=1) 

LINK_TYPE = create_type_identifier(object_id=3, version=1) 

 

class WrappedEnum(object): 

    """ Data descriptor (like a property) for passing through GPB enums from the Wrapper. """ 

 

    def __init__(self, val, doc=None): 

        self.val = val 

        if doc: self.__doc__ = doc 

 

    def __get__(self, obj, objtype=None): 

        return self.val 

 

    def __set__(self, obj, value): 

        raise AttributeError('Enums are read-only.') 

 

    def __delete__(self, wrapper): 

        raise AttributeError('Can not delete a Wrapper property for an ION Object field') 

 

 

class EnumType(type): 

    """ 

    Metaclass that automatically generates subclasses of Wrapper with corresponding enums and 

    pass-through properties for each field in the protobuf descriptor. 

    """ 

 

    _type_cache = {} 

 

    def __call__(cls, enum_type_descriptor, *args, **kwargs): 

        # Cache the custom-built classes 

 

        assert isinstance(enum_type_descriptor, descriptor.EnumDescriptor) 

 

        clsType = None 

        enum_name = enum_type_descriptor.name 

        enum_full_name = enum_type_descriptor.full_name 

 

        if enum_full_name in EnumType._type_cache: 

            clsType = EnumType._type_cache[enum_full_name] 

        else: 

            clsName = '%s_%s' % (cls.__name__, enum_name) 

            clsDict = {} 

 

            lookup = {} 

            clsDict['lookup'] = lookup 

 

            for name, val_desc in enum_type_descriptor.values_by_name.items(): 

                prop = WrappedEnum(val_desc.number) 

 

                clsDict[name] = prop 

 

                lookup[val_desc.number] = name 

 

            clsType = EnumType.__new__(EnumType, clsName, (cls,), clsDict) 

 

            # Also set the enum descriptors _after_ building the class so the descriptor doesn't go away 

            #if hasattr(descriptor, 'enum_values_by_name'): 

            #    for k,v in descriptor.enum_values_by_name.iteritems(): 

            #        setattr(clsType, k, WrappedEnum(v.number)) 

 

            EnumType._type_cache[enum_full_name] = clsType 

 

        # Finally allow the instantiation to occur, but slip in our new class type 

        obj = super(EnumType, clsType).__call__(enum_type_descriptor, *args, **kwargs) 

        return obj 

 

 

class EnumObject(object): 

    ''' 

    A Class for GPB Enum access 

    ''' 

 

    __metaclass__ = EnumType 

 

    def __init__(self, enum_type_descriptor): 

        """ 

        Instantiate a class with properties to get GPB Enum Values 

        """ 

 

 

class WrappedProperty(object): 

    def __init__(self, name, doc=None, field_type=None, field_enum=None): 

        self.name = name 

        if doc: self.__doc__ = doc 

 

        if field_type is None: 

            pass 

        elif field_type == 8: 

            self.field_type = "TYPE_BOOL" 

        elif field_type == 12: 

            self.field_type = "TYPE_BYTES" 

        elif field_type == 1: 

            self.field_type = "TYPE_DOUBLE" 

        elif field_type == 14: 

            self.field_type = "TYPE_ENUM" 

        elif field_type == 7: 

            self.field_type = "TYPE_FIXED32" 

        elif field_type == 6: 

            self.field_type = "TYPE_FIXED64" 

        elif field_type == 2: 

            self.field_type = "TYPE_FLOAT" 

        elif field_type == 10: 

            self.field_type = "TYPE_GROUP" 

        elif field_type == 5: 

            self.field_type = "TYPE_INT32" 

        elif field_type == 3: 

            self.field_type = "TYPE_INT64" 

        elif field_type == 2: 

            self.field_type = "TYPE_FLOAT" 

        elif field_type == 11: 

            self.field_type = 'TYPE_MESSAGE' 

        elif field_type == 15: 

            self.field_type = 'TYPE_SFIXED32' 

        elif field_type == 16: 

            self.field_type = 'TYPE_SFIXED64' 

        elif field_type == 17: 

            self.field_type = 'TYPE_SINT32' 

        elif field_type == 18: 

            self.field_type = 'TYPE_SINT64' 

        elif field_type == 9: 

            self.field_type = 'TYPE_STRING' 

        elif field_type == 13: 

            self.field_type = 'TYPE_UINT32' 

        elif field_type == 4: 

            self.field_type = 'TYPE_UINT64' 

        else: 

            raise OOIObjectError('Unknow field type "%s" in property constructor.' % field_type) 

 

        self.field_enum = field_enum 

 

    def __get__(self, wrapper, objtype=None): 

        raise NotImplementedError('Abstract base class for property wrappers: __get__') 

 

    def _get_backdoor(self, wrapper): 

        raise NotImplementedError('Abstract base class for property wrappers: _get_backdoor') 

 

    def __set__(self, wrapper, value): 

        raise NotImplementedError('Abstract base class for property wrappers: __set__') 

 

 

    def __delete__(self, wrapper): 

        raise NotImplementedError('Abstrat base class for property wrappers: __delete__') 

 

 

class WrappedMessageProperty(WrappedProperty): 

    """ Data descriptor (like a property) for passing through GPB properties of Type Message from the Wrapper. """ 

 

    def __get__(self, wrapper, objtype=None): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not get message (composite) property - %s - in a wrapper which is invalidated.' % self.name) 

            # This may be the result we were looking for, in the case of a simple scalar field 

        field = getattr(wrapper.GPBMessage, self.name) 

        result = wrapper._rewrap(field) 

 

        if result.ObjectType == LINK_TYPE: 

            result = wrapper.Repository.get_linked_object(result) 

 

        return result 

 

    def _get_backdoor(self, wrapper): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not get message (composite) property - %s -in a wrapper which is invalidated.' % self.name) 

            # This may be the result we were looking for, in the case of a simple scalar field 

        field = getattr(wrapper.GPBMessage, self.name) 

        result = wrapper._rewrap(field) 

 

        return result 

 

 

    def __set__(self, wrapper, value): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not set message (composite) property - %s - in a wrapper which is invalidated.' % self.name) 

 

        if wrapper.ReadOnly: 

            raise OOIObjectError('This object wrapper is read only!') 

 

        wrapper.SetLinkByName(self.name, value) 

        wrapper._set_parents_modified() 

 

        return None 

 

    def __delete__(self, wrapper): 

        raise AttributeError('Can not delete a Wrapper property for an ION Object field') 

 

 

class WrappedRepeatedScalarProperty(WrappedProperty): 

    """ Data descriptor (like a property) for passing through GPB properties of Type Repeated Scalar from the Wrapper. """ 

 

    def __get__(self, wrapper, objtype=None): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not get repeated scalar property - %s - in a wrapper which is invalidated.'% self.name) 

            # This may be the result we were looking for, in the case of a simple scalar field 

        field = getattr(wrapper.GPBMessage, self.name) 

 

        return ScalarContainerWrapper.factory(wrapper, field) 

 

    def __set__(self, wrapper, value): 

        raise AttributeError('Assignment is not allowed for field name "%s" of type Repeated Scalar in ION Object' % self.name) 

 

    def __delete__(self, wrapper): 

        raise AttributeError('Can not delete a Wrapper property for an ION Object field') 

 

 

class WrappedRepeatedCompositeProperty(WrappedProperty): 

    """ Data descriptor (like a property) for passing through GPB properties of Type Repeated Composite from the Wrapper. """ 

 

    def __get__(self, wrapper, objtype=None): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not "get" from a repeated composite property - %s - in a wrapper which is invalidated.' % self.name) 

 

        # This may be the result we were looking for, in the case of a simple scalar field 

        field = getattr(wrapper.GPBMessage, self.name) 

 

        return ContainerWrapper.factory(wrapper, field) 

 

    def _get_backdoor(self, wrapper, objtype=None): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError( 

                'Can not get_backdoor from a repeated composite property - %s - in a wrapper which is invalidated.' % self.name) 

 

        # This may be the result we were looking for, in the case of a simple scalar field 

        field = getattr(wrapper.GPBMessage, self.name) 

 

        return ContainerWrapper.factory(wrapper, field) 

 

    def __set__(self, wrapper, value): 

        raise AttributeError( 

            'Assignment is not allowed for field name - "%s" - of type Repeated Composite in ION Object' % self.name) 

 

    def __delete__(self, wrapper): 

        raise AttributeError('Can not delete a Wrapper property for an ION Object field') 

 

 

class WrappedScalarProperty(WrappedProperty): 

    """ Data descriptor (like a property) for passing through GPB properties of Type Scalar from the Wrapper. """ 

 

    def __get__(self, wrapper, objtype=None): 

        # This may be the result we were looking for, in the case of a simple scalar field 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not get scalar property - %s - in a wrapper which is invalidated.' % self.name) 

 

        return getattr(wrapper.GPBMessage, self.name) 

 

    def __set__(self, wrapper, value): 

        if wrapper.Invalid: 

            log.error(wrapper.Debug()) 

            raise OOIObjectError('Can not set scalar property - %s -in a wrapper which is invalidated.' % self.name) 

 

        if wrapper.ReadOnly: 

            raise OOIObjectError('This object wrapper is read only!') 

 

        setattr(wrapper.GPBMessage, self.name, value) 

 

        # Set this object and it parents to be modified 

        wrapper._set_parents_modified() 

 

        return None 

 

    def __delete__(self, wrapper): 

        raise AttributeError('Can not delete a Wrapper property for an ION Object field') 

 

 

class CommitCounter(object): 

    """ 

    Class used to count the number of recursive calls to commit a data structure 

    """ 

    count = 0 

 

 

class WrapperType(type): 

    """ 

    Metaclass that automatically generates subclasses of Wrapper with corresponding enums and 

    pass-through properties for each field in the protobuf descriptor. 

     

    This approach is generally applicable to wrap data structures. It is extremely powerful! 

    """ 

 

    _type_cache = {} 

 

    recurse_counter = CommitCounter() 

 

 

    def __call__(cls, gpbMessage, *args, **kwargs): 

        # Cache the custom-built classes 

        msgType, clsType = type(gpbMessage), None 

 

        if msgType in WrapperType._type_cache: 

            clsType = WrapperType._type_cache[msgType] 

        else: 

            # Check that the object we are wrapping is a Google Message object 

            if not isinstance(gpbMessage, message.Message): 

                raise OOIObjectError('Wrapper init argument must be an instance of a GPB message') 

 

            # Get the class name 

            clsName = '%s_%s' % (cls.__name__, msgType.__name__) 

            clsDict = {} 

            properties = {} 

            enums = {} 

 

            clsDict['_GPBClass'] = gpbMessage.__class__ 

            clsDict['_Properties'] = properties 

            clsDict['_Enums'] = enums 

 

            clsDict['recurse_count'] = WrapperType.recurse_counter 

 

            # Now setup the properties to map through to the GPB object 

            descriptor = msgType.DESCRIPTOR 

 

            # Add the enums of the message class 

            if hasattr(descriptor, 'enum_types_by_name'): 

                for enum_name, enum_desc in descriptor.enum_types_by_name.iteritems(): 

                    enum_obj = EnumObject(enum_desc) 

                    clsDict[enum_name] = enum_obj 

                    enums[enum_name] = enum_obj 

 

            # Add the property wrappers for each of the fields of the message 

            for fieldName, field_desc in descriptor.fields_by_name.items(): 

                fieldType = getattr(msgType, fieldName) 

 

                # Add any enums for the fields the message contains 

                enum_desc = field_desc.enum_type 

                field_enum = None 

                if enum_desc: 

                    field_enum = EnumObject(enum_desc) 

                    clsDict[enum_desc.name] = field_enum 

                    enums[enum_desc.name] = field_enum 

 

                field_type = field_desc.type 

 

                prop = None 

                if field_desc.label == field_desc.LABEL_REPEATED: 

                    if field_desc.cpp_type == field_desc.CPPTYPE_MESSAGE: 

                        prop = WrappedRepeatedCompositeProperty(fieldName, doc=fieldType.__doc__, field_type=field_type, 

                                                                field_enum=field_enum) 

                    else: 

                        prop = WrappedRepeatedScalarProperty(fieldName, doc=fieldType.__doc__, field_type=field_type, 

                                                             field_enum=field_enum) 

                else: 

                    if field_desc.cpp_type == field_desc.CPPTYPE_MESSAGE: 

                        prop = WrappedMessageProperty(fieldName, doc=fieldType.__doc__, field_type=field_type, 

                                                      field_enum=field_enum) 

                    else: 

                        prop = WrappedScalarProperty(fieldName, doc=fieldType.__doc__, field_type=field_type, 

                                                     field_enum=field_enum) 

 

                clsDict[fieldName] = prop 

                properties[fieldName] = prop 

 

            # Set the object type: 

            if clsDict.has_key('_MessageTypeIdentifier'): 

                mti = clsDict['_MessageTypeIdentifier'] 

                obj_type = create_type_identifier(object_id=mti._ID,\ 

                                                  version=mti._VERSION) 

            else: 

                obj_type = create_type_identifier(object_id=-99,\ 

                                                  version=1) 

            clsDict['_gpb_type'] = obj_type 

            # the obj_type can now be used for adding special methods to the Wrapper for certain types 

 

            # Special methods for certain object types: 

            WrapperType._add_specializations(cls, obj_type, clsDict) 

 

            VALIDATE_ATTRS = CONF.getValue('VALIDATE_ATTRS', True) 

            if VALIDATE_ATTRS: 

                def obj_setter(self, k, v): 

                    if self._init and not hasattr(self, k): 

                        raise AttributeError(\ 

                            '''Cant add properties to the ION object wrapper for object Class "%s".\n''' 

                            '''Unknown property name - "%s"; value - "%s"''' % (self._GPBClass, k, v)) 

                    super(Wrapper, self).__setattr__(k, v) 

 

                clsDict['__setattr__'] = obj_setter 

 

            clsDict['_init'] = False 

 

            clsType = WrapperType.__new__(WrapperType, clsName, (cls,), clsDict) 

 

            WrapperType._type_cache[msgType] = clsType 

 

 

        # Finally allow the instantiation to occur, but slip in our new class type 

        obj = super(WrapperType, clsType).__call__(gpbMessage, *args, **kwargs) 

 

        return obj 

 

 

    def _add_specializations(cls, obj_type, clsDict): 

        #--------------------------------------------------------------# 

        # Attach specialized methods to object class dictionaries here # 

        #--------------------------------------------------------------# 

        if obj_type == LINK_TYPE: 

            @_gpb_source 

            def obj_setlink(self, value, ignore_copy_errors=False): 

 

                self.Repository.set_linked_object(self, value, ignore_copy_errors=ignore_copy_errors) 

                if not self.Modified: 

                    self._set_parents_modified() 

                return 

 

            clsDict['SetLink'] = obj_setlink 

 

            @_gpb_source 

            def copy_link(self,link): 

 

                if link.ObjectType != LINK_TYPE: 

                    log.error(link.Debug()) 

                    log.error(self.Debug()) 

                    raise OOIObjectError('Can not copy_link from an object that is not a link!') 

 

                self.GPBMessage.CopyFrom(link.GPBMessage) 

 

                self.ChildLinks.add(self) 

 

                try: 

                    obj = self.Repository.get_linked_object(link) 

                    obj.AddParentLink(link) 

                except KeyError: 

                    log.warn('Copy Link does not have the linked object!') 

 

            clsDict['CopyLink'] = copy_link 

 

        elif obj_type == CDM_DATASET_TYPE: 

            clsDict['MakeRootGroup'] = dataset._make_root_group 

            clsDict['ShowVariableNames'] = dataset._get_variable_names 

            clsDict['ShowGlobalAttributes'] = dataset._get_group_attributes_for_display 

            clsDict['ShowVariableAttributes'] = dataset._get_variable_attributes_for_display 

 

        elif obj_type == CDM_GROUP_TYPE: 

            clsDict['AddGroup'] = group._add_group_to_group 

            clsDict['AddAttribute'] = group._add_attribute 

            clsDict['AddDimension'] = group._add_dimension 

            clsDict['AddVariable'] = group._add_variable 

            clsDict['FindGroupByName'] = group._find_group_by_name 

            clsDict['FindAttributeByName'] = group._find_attribute_by_name 

            clsDict['FindDimensionByName'] = group._find_dimension_by_name 

            clsDict['FindVariableByName'] = group._find_variable_by_name 

            clsDict['FindVariableIndexByName'] = group._find_variable_index_by_name 

            clsDict['FindAttributeIndexByName'] = group._find_attribute_index_by_name 

            clsDict['HasAttribute'] = group._cdm_resource_has_attribute 

            clsDict['RemoveAttribute'] = group._remove_attribute 

            clsDict['SetAttribute'] = group._set_attribute 

            clsDict['SetDimension'] = group._set_dimension 

 

            clsDict['MergeAttSrc'] = attribute_merge.MergeAttSrc 

            clsDict['MergeAttDst'] = attribute_merge.MergeAttDst 

            clsDict['MergeAttGreater'] = attribute_merge.MergeAttGreater 

            clsDict['MergeAttLesser'] = attribute_merge.MergeAttLesser 

            clsDict['MergeAttDstOver'] = attribute_merge.MergeAttDstOver 

            clsDict['_GetNumericValue'] = attribute_merge._GetNumericValue 

 

 

 

 

            # Allow the DataType enum to be accessible by this Wrapper... 

            #------------------------------------------------------------------------# 

            # Additional helper methods for attaching specialized attributes/methods # 

            #------------------------------------------------------------------------# 

            def __add_data_type_enum(clsDict): 

                # Get a handle to the data_type field from the variable class 

                VAR_CLASS = get_gpb_class_from_type_id(CDM_VARIABLE_TYPE) 

                field_desc = None 

                for name, desc in VAR_CLASS.DESCRIPTOR.fields_by_name.items(): 

                    if name == "data_type": 

                        field_desc = desc 

 

                # Add the enum definitions from the data_type field (can only be one - DataType) 

                enum_desc = field_desc.enum_type 

                if enum_desc and not enum_desc.name in clsDict: 

                    clsDict[enum_desc.name] = EnumObject(enum_desc) 

 

 

            __add_data_type_enum(clsDict) 

 

 

        elif obj_type == CDM_ATTRIBUTE_TYPE: 

            clsDict['GetValue'] = attribute._get_attribute_value_by_index 

            clsDict['GetValues'] = attribute._get_attribute_values 

            # clsDict['SetValue'] = _get_attribute_values 

            # clsDict['SetValues'] = _get_attribute_values 

            clsDict['GetLength'] = attribute._get_attribute_values_length 

            clsDict['GetDataType'] = attribute._get_attribute_data_type 

            clsDict['IsSameType'] = attribute._attribute_is_same_type 

 

 

 

 

        elif obj_type == CDM_VARIABLE_TYPE: 

            clsDict['GetUnits'] = variables._get_var_units 

            clsDict['GetStandardName'] = variables._get_var_std_name 

            clsDict['GetNumDimensions'] = variables._get_var_num_dims 

            clsDict['GetNumBoundedArrays'] = variables._get_var_num_ba 

            clsDict['AddAttribute'] = group._add_attribute 

            clsDict['FindAttributeByName'] = group._find_attribute_by_name 

            clsDict['FindDimensionByName'] = group._find_dimension_by_name 

            clsDict['FindAttributeIndexByName'] = group._find_attribute_index_by_name 

            clsDict['HasAttribute'] = group._cdm_resource_has_attribute 

            clsDict['RemoveAttribute'] = group._remove_attribute 

            clsDict['SetAttribute'] = group._set_attribute 

            clsDict['SetDimension'] = group._set_dimension 

 

            clsDict['GetValue'] = variables.GetValue 

 

            clsDict['MergeAttSrc'] = attribute_merge.MergeAttSrc 

            clsDict['MergeAttDst'] = attribute_merge.MergeAttDst 

            clsDict['MergeAttGreater'] = attribute_merge.MergeAttGreater 

            clsDict['MergeAttLesser'] = attribute_merge.MergeAttLesser 

            clsDict['MergeAttDstOver'] = attribute_merge.MergeAttDstOver 

            clsDict['_GetNumericValue'] = attribute_merge._GetNumericValue 

 

 

class Wrapper(object): 

    ''' 

    A Wrapper class for intercepting access to protocol buffers message fields. 

    For instance, in the example below I can create a wrapper which is 

    read-only. 

 

    To make the wrapper general - apply to more than one kind of protobuffer - 

    we can not use descriptors (properties) to transparently intercept a get or 

    set request because they are class attributes - shared between all instances 

    of the wrapper class. If we add properties each time we create a wrapper 

    instance for a new kind of protobuf, new properties will be added to all 

    wrapper instances. 

 

    The solution I can up with is clunky! Override the __getattribute__ and 

    _setattr__ method to preemptively check a list of fields to get from the 

    protocol buffer message. If the key is in the list get/set the deligated 

    protocol buffer rather than the wrapper class. The problem is that now we 

    can not use the default get/set to initialize our own class or get the list 

    of fields! 

 

    Organization: 

    The meat of the class is at the top - Init and class methods are at the top 

    along with overrides for __getattribute__ and __setattr__ which are the heart 

    of the wrapper. 

 

    Below that are all of the methods of protobuffers exposed by the wrapper. 

 

    TODO: 

    What about name conflicts between wrapper methods and GPB Fields? 

 

 

    ''' 

 

    __metaclass__ = WrapperType 

 

 

    def __init__(self, gpbMessage): 

        """ 

        Initialize the Wrapper class and set up it message type. 

 

        """ 

 

        self._gpbMessage = gpbMessage 

        """ 

        The gpbMessage is the data object which this instance of wrapper provides 

        proxy access to. This wrapper controls both the message object and its 

        nested child objects in the case of a composite message. Each child in 

        the nested object is returned as a wrapped object all of which are subordinate 

        to the wrapper for the root of the composite message. 

        """ 

 

        self._root = None 

        """ 

        A reference to the root object wrapper for this protobuffer 

        A composit protobuffer object may return 

        """ 

 

        self._invalid = None 

        """ 

        Used to determine whether the wrapper is a currently valid object in the 

        version framework. Invalid states can be created when old references to 

        an object remain after a differnt version is checked out - similar to 

        having a file or directory open that does not exist in the currently 

        checked out branch of a source repository. 

        """ 

 

        # This filed now comes from the metaclass 

        #self._gpb_type = None 

        """ 

        The Type ID object for the wrapped object of this class 

        """ 

 

        self._bytes = None 

        """ 

        Used in _load_element to create a proxy object. The bytes are not loaded 

        parsed until the object is needed! 

        """ 

 

        self._parent_links = None 

        """ 

        A list of all the other wrapper objects which link to me 

        """ 

 

        self._child_links = None 

        """ 

        A list of my child link wrappers 

        """ 

 

        self._derived_wrappers = None 

        """ 

        A container for all the wrapper objects which are rewrapped, derived 

        from a root object wrapper 

        """ 

 

        self._myid = None # only exists in the root object 

        """ 

        The name for this object - the SHA1 if it is already hashed or the object 

        counter value if it is still in the workspace. 

        """ 

 

        self._modified = None # only exists in the root object 

        """ 

        Is this wrapper object modified or commited 

        """ 

 

        self._read_only = None # only exists in the root object 

        """ 

        Set this to be a read only wrapper! 

        Used for commit objects and a history checkout... it is only set in the root object 

        """ 

 

        self._repository = None # only exists in the root object 

        """ 

        Need to carry a reference to the repository I am in. 

        """ 

 

        self._source = self 

        """ 

        To avoid invalidating during when there is a hash conflict in the workspace - set the twin... 

        """ 

 

        self.__no_string = CONF.getValue('STR_GPBS', False) 

 

        # Hack to prevent setting properties in a class instance 

        self._init = True 

 

        #frame = sys._getframe(2) 

        #frames = [] 

        #for i in range(6): 

        #    frames.append(frame) 

        #    frame = frame.f_back 

        #print 'Name: %s, Caller names: ' % type(self), [frame.f_code.co_name for frame in frames] 

 

 

    GPBSource = _gpb_source 

 

    GPBSourceRoot = _gpb_source_root 

 

 

    @classmethod 

    def _create_object(cls, msgtype): 

        """ 

        This is a convience method to create unattached wrapper objects. 

        Generally this method should not be used - it is a hook for testing. 

        """ 

 

        gpbMessage = get_gpb_class_from_type_id(msgtype)() 

 

        obj = cls(gpbMessage) 

        obj._repository = None 

        obj._root = obj 

        obj._parent_links = set() 

        obj._child_links = set() 

        obj._derived_wrappers = {} 

        obj._read_only = False 

        obj._myid = '-1' 

        obj._modified = True 

        obj._invalid = False 

 

        return obj 

 

    @property 

    def Invalid(self): 

        return self._source._invalid 

 

    def noisy_invalidate(self): 

        pass 

 

    def Invalidate(self, other=None): 

 

 

        self.noisy_invalidate() 

        if other is not None: 

 

            #log.debug('Invalidating self:\n%s' % self.Debug()) 

 

            #log.debug('Invalidating self with Other:\n%s \n\n' % other.Debug()) 

 

            if self.ObjectType != other.ObjectType: 

                log.error(self.Debug()) 

                raise OOIObjectError('Can not invalidate by merge when two objects are not the same type') 

 

            if self._invalid: 

                log.error(self.Debug()) 

                raise OOIObjectError('It is unexpected to try and invalidate an object with a new source a second time') 

 

            if self._source is not self: 

                log.error(self.Debug()) 

                raise OOIObjectError( 

                    'It is unexpected to try and invalidate an object which already has an alternate source') 

 

            if self.Repository is not other.Repository: 

                log.error(self.Debug()) 

                raise OOIObjectError('Can not invalidate by passing a wrapper from another repository') 

 

            if other.Invalid: 

                log.error('Error while invalidating self - other is invalid too!\nSelf: %s\nOther: %s'% (self.Debug(), other.Debug())) 

                raise OOIObjectError('Can not invalidate self with other when other is already invalid') 

 

        else: 

            #log.debug('Invalidating self:\n%s' % self.Debug()) 

 

            other = self 

 

            #if self._invalid: 

            if self.Invalid: 

                return 

 

        if other is not self: 

            # If we are doing an invalidate to other... 

            self._merge_derived_wrappers(other._source) 

 

 

        elif self.IsRoot: 

            # If this is a straight invalidation - clear the derived wrappers if root 

            for item in self.DerivedWrappers.values(): 

                item.Invalidate() 

 

        # Source must always be set to self or another gpb_wrapper object! 

        self._source = other._source 

 

        self._derived_wrappers = None 

        self._gpbMessage = None 

        self._parent_links = None 

        self._child_links = None 

        self._myid = None 

        self._bytes = None 

 

        # Do not clear root or Repository 

 

        self._invalid = True 

 

 

    def _merge_derived_wrappers(self, other): 

        for name, prop in self._Properties.iteritems(): 

            if prop.field_type == 'TYPE_MESSAGE': 

                self_obj = prop._get_backdoor(self) 

 

                other_obj = prop._get_backdoor(other) 

                if self_obj is other_obj: 

                    raise OOIObjectError('The back door property getter failed!') 

 

 

                log.debug('Invalidating message property: %s' % prop.name) 

                if isinstance(self_obj, ContainerWrapper): 

                    # Make sure to get the derive object not what it links to! 

                    for gpb_item_self, gpb_item_other in zip(self_obj._gpbcontainer, other_obj._gpbcontainer): 

 

                        item_self = self_obj._wrapper._rewrap(gpb_item_self) 

                        item_other = other_obj._wrapper._rewrap(gpb_item_other) 

 

                        item_self.Invalidate(other = item_other) 

 

                else: 

                    self_obj.Invalidate(other = other_obj) 

 

 

    @property 

    @GPBSource 

    def ObjectClass(self): 

        return self._GPBClass 

 

    @property 

    @GPBSource 

    def DESCRIPTOR(self): 

        return self._gpbMessage.DESCRIPTOR 

 

    @property 

    @GPBSourceRoot 

    def Root(self): 

        """ 

        Access to the root object of the nested GPB object structure 

        """ 

        return self 

 

    @property 

    @GPBSource 

    def IsRoot(self): 

        """ 

        Is this wrapped object the root of a GPB Message? 

        GPBs are also tree structures and each element must be wrapped 

        """ 

        return self is self._root 

 

    @property 

    @GPBSource 

    def ObjectType(self): 

        """ 

        Could just replace the attribute with the capital name? 

        """ 

        return self._gpb_type 

 

    @property 

    @GPBSource 

    def GPBMessage(self): 

        """ 

        If this is a proxy object which references its serialized value load it! 

        """ 

        bytes = self._bytes 

        if  bytes != None: 

            self.ParseFromString(bytes) 

            self._bytes = None 

        return self._gpbMessage 

 

    @property 

    @GPBSourceRoot 

    def Repository(self): 

        return self._repository 

 

    @property 

    @GPBSourceRoot 

    def DerivedWrappers(self): 

        return self._derived_wrappers 

 

    @GPBSourceRoot 

    def _get_myid(self): 

        return self._myid 

 

    @GPBSourceRoot 

    def _set_myid(self, value): 

        assert isinstance(value, str), 'myid is a string property' 

        self._myid = value 

 

    MyId = property(_get_myid, _set_myid) 

 

 

    @GPBSourceRoot 

    def _get_parent_links(self): 

        """ 

        A list of all the wrappers which link to me 

        """ 

        return self._parent_links 

 

    @GPBSourceRoot 

    def _set_parent_links(self, value): 

        """ 

        A list of all the wrappers which link to me 

        """ 

 

        self._parent_links = value 

 

    ParentLinks = property(_get_parent_links, _set_parent_links) 

 

    @GPBSourceRoot 

    def _get_child_links(self): 

        """ 

        A list of all the wrappers which I link to 

        """ 

        return self._child_links 

 

    @GPBSourceRoot 

    def _set_child_links(self, value): 

        """ 

        A list of all the wrappers which I link to 

        """ 

        self._child_links = value 

 

    ChildLinks = property(_get_child_links, _set_child_links) 

 

    @GPBSourceRoot 

    def _get_readonly(self): 

        return self._read_only 

 

    @GPBSourceRoot 

    def _set_readonly(self, value): 

        assert isinstance(value, bool), 'readonly is a boolen property' 

        self._read_only = value 

 

    ReadOnly = property(_get_readonly, _set_readonly) 

 

    @GPBSourceRoot 

    def _get_modified(self): 

        return self._modified 

 

    @GPBSourceRoot 

    def _set_modified(self, value): 

        assert isinstance(value, bool), 'modified is a boolen property' 

        self._modified = value 

 

    Modified = property(_get_modified, _set_modified) 

 

 

    @GPBSource 

    def SetLinkByName(self, linkname, value): 

        link = self.GetLink(linkname) 

        link.SetLink(value) 

 

    @GPBSource 

    def GetLink(self, linkname): 

        gpb = self.GPBMessage 

        link = getattr(gpb, linkname) 

        link = self._rewrap(link) 

 

        if not link.ObjectType == LINK_TYPE: 

            raise OOIObjectError('The field "%s" is not a link!' % linkname) 

        return link 

 

    @GPBSource 

    def InParents(self, value): 

        ''' 

        Check recursively to make sure the object is not already its own parent! 

        ''' 

        if not value.IsRoot: 

            raise OOIObjectError('Can not test lineage of object that is not a root object') 

 

        for item in self.ParentLinks: 

            if item.Root is value: 

                return True 

            if item.InParents(value): 

                return True 

        return False 

 

    @GPBSource 

    def SetStructureReadOnly(self): 

        """ 

        Set these objects to be read only 

        """ 

 

        self.ReadOnly = True 

        for link in self.ChildLinks: 

            try: 

                child = self.Repository.get_linked_object(link) 

                child.SetStructureReadOnly() 

            except KeyError: 

                # we're just setting things read only, don't worry if we couldn't get part of it. 

                # this is intentionally happening in ingestion 

                pass 

 

    @GPBSource 

    def SetStructureReadWrite(self): 

        """ 

        Set these object to be read write! 

        """ 

 

        self.ReadOnly = False 

        for link in self.ChildLinks: 

            child = self.Repository.get_linked_object(link) 

            child.SetStructureReadWrite() 

 

    @GPBSource 

    def RecurseCommit(self, structure): 

        """ 

        Recursively build up the serialized structure elements which are needed 

        to commit this wrapper and reset all the links using its CAS name. 

        """ 

 

        # Should this error if called on a non root object? 

        if not self.IsRoot: 

            raise OOIObjectError('Can not call Recurse Commit on a non root object wrapper.') 

 

        self.recurse_count.count += 1 

        local_cnt = self.recurse_count.count 

        log.debug('Entering Recurse Commit: recurse counter - %d, Object Type - %s, child links - %d, objects to commit - %d, Modified - %s' % 

              (local_cnt, type(self), len(self.ChildLinks), len(structure), self.Modified)) 

 

        if not  self.Modified: 

            # This object is already committed! 

            log.debug('Exiting Recurse Commit: recurse counter - %d' % local_cnt) 

 

            return 

 

        # Create the Structure Element in which the binary blob will be stored 

        se = StructureElement() 

        repo = self.Repository 

 

        for link in  self.ChildLinks: 

 

            if link.Invalid: 

                log.error('Link in child links is invalid!') 

                log.debug('Current Wrapper: %s' % self.Debug()) 

                log.debug('Invalid Link %s' % link.Debug()) 

 

            # Test to see if it is already serialized! 

            child_se = repo.index_hash.get(link.key, structure.get(link.key, None)) 

            #child_se = repo.index_hash.get(link.key, None) 

 

            #log.debug('Setting child Link: %s' % str(child_se)) 

            if  child_se is not None: 

                # Set the links is leaf property 

                link.isleaf = child_se.isleaf 

 

            else: 

                # if isleaf set, type set, and the key is an actual SHA1 - we don't need to recurse into it or do anything, really. 

                if link.IsFieldSet('isleaf') and link.IsFieldSet('type') and len(link.key) == 20: 

                    log.debug('Disregarding un-index-hashed link %s' % link.key) 

                    pass 

                else: 

                    child = repo.get_linked_object(link) 

 

                    # Determine whether this is a leaf node 

                    if len(child.ChildLinks) == 0: 

                        link.isleaf = True 

                    else: 

                        link.isleaf = False 

 

                    child.RecurseCommit(structure) 

 

            # Save the link info as a convience for sending! 

            se.ChildLinks.add(link.key) 

 

        se.value = self.SerializeToString() 

        #se.key = sha1hex(se.value) 

 

        # Structure element wrapper provides for setting type! 

        se.type = self.ObjectType 

 

        # Calculate the sha1 from the serialized value and type! 

        # Sha1 is a property - not a method... 

        se.key = se.sha1 

 

        # Determine whether I am a leaf 

        if len(self.ChildLinks) is 0: 

            se.isleaf = True 

        else: 

            se.isleaf = False 

 

        # Done setting up the Structure Element 

        structure[se.key] = se 

        # It does not matter if we are replacing an existing se with the same key - the content - including the child links must be identical! 

 

 

        # This will be true for any object which is not a core object such as a commit 

        # We don't want to worry about what is in the workspace - that is the repositories job. 

        # if I am currently in the work space the commited version of me should be too! 

        if repo._workspace.has_key(self.MyId): 

            # Remove my old name 

            del repo._workspace[self.MyId] 

 

            # Now deal with some nastyness 

            # Possible DAG structure created by hash conflict - two wrappers of the same type with the same value in one data structure 

            if se.key in repo._workspace: 

                # If this is true we have just done a lot of extra work to create the Structure element - but there is no way to know before creating it! 

 

                # Get the other object with the same name that is already committed... 

                other = repo._workspace[se.key] 

 

                #print "Self Plinks:",self.ParentLinks 

                #print "Other Plinks:",other.ParentLinks 

                other.ParentLinks.update(self.ParentLinks) 

 

                #print "Other Plinks After:",other.ParentLinks 

 

                # Invalidate ourself 

                self.Invalidate(other) 

 

            else: 

                # Now add it back the workspace under the new name 

                repo._workspace[se.key] = self 

 

        # Test to see if we need to set MyId - don't mess up the case where self now points to another source which is already commited. 

        if self.MyId != se.key: 

            self.MyId = se.key 

            self.Modified = False 

 

        # Set the key value for parent links! 

        # This will only be reached once for a given child object. Set all parents 

        # now and the child will return as unmodified when the other parents ask it 

        # to recurse commit. 

 

        #log.debug('Current Wrapper: %s' % self.Debug()) 

 

        #cnt = 1 

        #for link in self.ParentLinks: 

        #    log.debug('Parrent Link # %d \n%s' % (cnt, link.Debug())) 

        #    cnt += 1 

 

 

        for link in self.ParentLinks: 

            if link.Invalid: 

                log.error('Link in parent links is invalid!') 

                log.debug('Current Wrapper: %s' % self.Debug()) 

                log.debug('Invalid Link %s' % link.Debug()) 

 

 

            if link.key != se.key: 

                link.key = se.key 

 

        log.debug('Exiting Recurse Commit: recurse counter - %d' % local_cnt) 

 

 

    @GPBSource 

    def FindChildLinks(self): 

        """ 

        Find all of the links in this composit structure 

        All of the objects worked on in this method are raw proto buffers messages! 

        """ 

 

        gpb = self.GPBMessage 

        # For each field in the protobuffer message 

        for field in gpb.DESCRIPTOR.fields: 

            # if the field is a composite - another message 

            if field.message_type: 

                # Get the field of type message 

                gpb_field = getattr(gpb, field.name) 

 

 

                # If it is a repeated container type 

                if isinstance(gpb_field, containers.RepeatedCompositeFieldContainer): 

                    for item in gpb_field: 

                        wrapped_item = self._rewrap(item) 

                        if wrapped_item.ObjectType == LINK_TYPE: 

                            self.ChildLinks.add(wrapped_item) 

                        else: 

                            wrapped_item.FindChildLinks() 

 

                # IF it is a standard message field 

                else: 

                    if not gpb_field.IsInitialized(): 

                        # if it is an optional field which is not initialized 

                        # it can not hold any links! 

                        continue 

 

                    item = self._rewrap(gpb_field) 

                    if item.ObjectType == LINK_TYPE: 

                        self.ChildLinks.add(item) 

                    else: 

                        item.FindChildLinks() 

 

    @GPBSource 

    def AddParentLink(self, link): 

        #if self.Invalid: 

 

        for parent in self.ParentLinks: 

            if parent.GPBMessage is link.GPBMessage: 

                break 

        else: 

            self.ParentLinks.add(link) 

 

    @GPBSource 

    def _rewrap(self, gpbMessage): 

        ''' 

        Factory method to return a new instance of wrapper for a gpbMessage 

        from self - used for access to composite structures, it has all the same 

        shared variables as the parent wrapper 

        ''' 

 

        # Check the root wrapper objects list of derived wrappers 

        if gpbMessage in self.DerivedWrappers: 

            return self.DerivedWrappers[gpbMessage] 

 

        # Else make a new one... 

        inst = Wrapper(gpbMessage) 

        inst._root = self.Root 

        inst._invalid=False 

 

        # Add it to the list of objects which derive from the root wrapper 

        self.DerivedWrappers[gpbMessage] = inst 

 

        return inst 

 

    @GPBSource 

    def _set_parents_modified(self): 

        """ 

        This method recursively changes an objects parents to a modified state 

        All links are reset as they are no longer hashed values 

        """ 

 

        if self.Modified: 

            # Be clear about what we are doing here! 

            # If it has already been modified we are done. 

            return 

        else: 

            self.Modified = True 

 

            # Get the repository 

            repo = self.Repository 

 

            new_id = repo.new_id() 

            repo._workspace[new_id] = self.Root 

 

            if repo._workspace.has_key(self.MyId): 

                del repo._workspace[self.MyId] 

            self.MyId = new_id 

 

            # When you hit the commit ref - stop! 

            if self.Root is repo._workspace_root: 

                # The commit is no longer really your parent! 

                self.ParentLinks = set() 

 

            else: 

                for link in self.ParentLinks: 

                    # Tricky - set the message directly and call modified! 

                    #link.GPBMessage.key = self.MyId 

                    link.GPBMessage.key = self.MyId 

                    #link._set_parents_modified() 

                    link._set_parents_modified() 

 

    @GPBSource 

    def __eq__(self, other): 

        if not isinstance(other, Wrapper): 

            return False 

 

        if self is other: 

            return True 

 

        return self.GPBMessage == other.GPBMessage 

 

    @GPBSource 

    def __ne__(self, other): 

        # Can't just say self != other_msg, since that would infinitely recurse. :) 

        return not self == other 

 

    def __str__(self): 

        """ 

        Since str is used in debugging it should never return an exception - no matter the state of the wrapper object 

        """ 

 

        ''' 

        # Too complex - don't do things that might raise errors in str method! 

        if self._gpb_type == LINK_TYPE: 

            key = self._gpbMessage.key 

            try: 

                key = sha1_to_hex(self._gpbMessage.key) 

            except struct.error, er: 

                pass 

            msg = '\nkey: %s \ntype { %s }' % (key, self._gpbMessage.type) 

        else: 

            msg = '\n' +self._gpbMessage.__str__() 

        ''' 

 

        if not self.__no_string: 

            return 'GPB NO STRING!' 

 

        #log.critical('HOLY SHIT STILL HERE!') 

 

        if self._source is self: 

            msg = '\n %s \n' % str(self._gpbMessage) 

        else: 

            msg = '\n %s \n' % str(self._source._gpbMessage) 

 

        return msg 

 

    def Debug(self): 

        """ 

        Since Debug is for debugging it should never return an exception - no matter the state of the wrapper object 

        """ 

        output = '================== GPB Wrapper ====================\n' 

 

        key = self._myid 

        try: 

            key = sha1_to_hex(key) 

        except struct.error, er: 

            pass 

 

        output += 'Wrapper ID: %s \n' % key 

        output += 'Wrapper repr: %s \n' % repr(self) 

        output += 'Wrapper Invalid: %s \n' % self._invalid 

        output += 'Wrapper ReadOnly: %s \n' % self._read_only 

        output += 'Wrapper IsRoot: %s \n' % str(self._root is self) 

 

        # This is dangerous - this can result in an exception loop! 

        if hasattr(self._repository, '_dotgit') and not self._repository._dotgit.Invalid: 

            output += 'Repository: %s \n' % str(self._repository.repository_key) 

        else: 

            output += 'Repository: %s \n' % str(self._repository) 

 

        if self._root: 

            output += 'Wrapper ParentLinks: %s \n' % str(self._parent_links) 

            output += 'Wrapper ChildLinks: %s \n' % str(self._child_links) 

            output += 'Wrapper Modified: %s \n' % self._root._modified 

 

        output += 'Wrapper Type: %s \n' % str(self._gpb_type) 

        # DO NOT UNCOMMENT THE FOLLOWING LINES unless you know what you are doing and you will recomment them! 

        # They are more expensive than you can possibly imagine 

        #output += 'Wrapper current value:\n' 

        #output += str(self) + '\n' 

        if self._source is not self: 

            output += '================== Has Other source! =========================\n' 

            output += self._source.Debug() 

            output += '================== end source! =========================\n' 

        else: 

            output += 'Source is Self!\n' 

        output += '================== Wrapper Complete =========================\n' 

        return output 

 

    @GPBSource 

    def IsInitialized(self): 

        """Checks if the message is initialized. 

 

        Returns: 

            The method returns True if the message is initialized (i.e. all of its 

        required fields are set). 

        """ 

        return self.GPBMessage.IsInitialized() 

 

    @GPBSource 

    def SerializeToString(self): 

        """Serializes the protocol message to a binary string. 

 

        Returns: 

          A binary string representation of the message if all of the required 

        fields in the message are set (i.e. the message is initialized). 

 

        Raises: 

          message.EncodeError if the message isn't initialized. 

        """ 

 

        try: 

            serialized = self.GPBMessage.SerializeToString() 

        except message.EncodeError, ex: 

            log.info(ex) 

            raise OOIObjectError( 

                'Could not serialize object - likely due to unset required field in a core object: %s' % str(self)) 

 

        return serialized 

 

    @GPBSource 

    def ParseFromString(self, serialized): 

        """Clear the message and read from serialized.""" 

 

        # Do not use the GPBMessage method - it will recurse! 

        self._gpbMessage.ParseFromString(serialized) 

 

    @GPBSource 

    def ListSetFields(self): 

        """Returns a list of (FieldDescriptor, value) tuples for all 

        fields in the message which are not empty.  A singular field is non-empty 

        if IsFieldSet() would return true, and a repeated field is non-empty if 

        it contains at least one element.  The fields are ordered by field 

        number""" 

 

        field_list = self.GPBMessage.ListFields() 

        fnames = [] 

        for desc, val in field_list: 

            fnames.append(desc.name) 

        return fnames 

 

    @GPBSource 

    def IsFieldSet(self, field_name): 

        GPBMessage = self.GPBMessage 

        # Get the raw GPB field 

        try: 

            GPBField = getattr(GPBMessage, field_name) 

        except AttributeError, ex: 

            raise OOIObjectError('The "%s" object definition does not have a field named "%s"' %\ 

                                 (str(self.ObjectClass), field_name)) 

 

        if isinstance(GPBField, containers.RepeatedScalarFieldContainer): 

            return len(GPBField) > 0 

 

        elif isinstance(GPBField, containers.RepeatedCompositeFieldContainer): 

            if len(GPBField) == 0: 

                return False 

            for item in GPBField: 

                if len(item.ListFields()) > 0: 

                    return True 

            else: 

                return False 

 

        else: 

            return GPBMessage.HasField(field_name) 

 

    def HasField(self, field_name): 

        log.warn('HasField is depricated because the name is confusing. Use IsFieldSet') 

        return self.IsFieldSet(field_name) 

 

    @GPBSource 

    def ClearField(self, field_name): 

        GPBMessage = self.GPBMessage 

 

        #if not GPBMessage.IsFieldSet(field_name): 

        #    # Nothing to clear 

        #    return 

 

        # Get the raw GPB field 

        try: 

            GPBField = getattr(GPBMessage, field_name) 

        except AttributeError, ex: 

            raise OOIObjectError('The "%s" object definition does not have a field named "%s"' %\ 

                                 (str(self.ObjectClass), field_name)) 

 

        if isinstance(GPBField, containers.RepeatedScalarFieldContainer): 

            del self.DerivedWrappers[GPBField] 

            # Nothing to do - just clear the field. It can not contain a link 

 

        elif isinstance(GPBField, containers.RepeatedCompositeFieldContainer): 

            for item in GPBField: 

                wrapped_field = self._rewrap(item) 

                wrapped_field._clear_derived_message() 

 

                del self.DerivedWrappers[item] 

 

            del self.DerivedWrappers[GPBField] 

 

        elif isinstance(GPBField, message.Message): 

            wrapped_field = self._rewrap(GPBField) 

            wrapped_field._clear_derived_message() 

 

            del self.DerivedWrappers[GPBField] 

 

        # Nothing to be done for scalar fields - just clear it. 

 

        #Now clear the field 

        self.GPBMessage.ClearField(field_name) 

        # Set this object and it parents to be modified 

        self._set_parents_modified() 

 

    @GPBSource 

    def _clear_derived_message(self): 

        """ 

        Helper method for ClearField 

        """ 

        if self.ObjectType == LINK_TYPE: 

            child_obj = self.Repository.get_linked_object(self) 

            # Remove this link from the list of parents 

            child_obj.ParentLinks.remove(self) 

 

            # This is the only one, remove it as a child 

            self.ChildLinks.remove(self) 

 

        for field_name in self.DESCRIPTOR.fields_by_name.keys(): 

            # Recursively remove all 

            self.ClearField(field_name) 

 

    #def HasExtension(self, extension_handle): 

    #    return self.GPBMessage.HasExtension(extension_handle) 

 

    #def ClearExtension(self, extension_handle): 

    #    return self.GPBMessage.ClearExtension(extension_handle) 

 

    @GPBSource 

    def ByteSize(self): 

        """Returns the serialized size of this message. 

        Recursively calls ByteSize() on all contained messages. 

        """ 

        return self.GPBMessage.ByteSize() 

 

    @GPBSource 

    def PPrint(self, offset=''): 

 

        fid = StringIO.StringIO() 

 

        fid.write('%s%s\n' % (offset, self.ObjectClass)) 

 

        try: 

            for name, field in self._Properties.iteritems(): 

                try: 

                    field_val = field.__get__(self) 

                except KeyError, ke: 

                    log.debug('KeyError during get field: %s' % ke) 

 

                    fid.write('''%s{Field Name - "%s" : Field Type - %s : %s} \n''' % ( 

                    offset, name, field.field_type, 'KeyError - object not found in local workbench')) 

                    continue 

 

                if isinstance(field, WrappedMessageProperty): 

                    try: 

                        val = 'Field Value - \n%s \n%s' % (field_val.PPrint(offset=offset + '  '), offset) 

                    except AttributeError, ae: 

                        log.debug('Unset CasRef Field Name: %s: Catching Attribute Error: %s ' % (name, ae)) 

                        val = 'Field Value - None' 

                    except Exception, ex: 

                        log.exception('Unexpected state in a WrappedMessageProperty.') 

                        fid.write('%s Exception while printing field name - %s, Exception - %s\n' % (offset, name, ex)) 

                        continue 

 

                elif isinstance(field, WrappedRepeatedCompositeProperty): 

                    try: 

                        val = 'Field Value - \n%s \n%s' % (field_val.PPrint(offset=offset + '  ', name=name), offset) 

                    except Exception, ex: 

                        log.exception('Unexpected state in a WrappedRepeatedCompositeProperty.') 

                        fid.write('%s Exception while printing field name - %s, Exception - %s\n' % (offset, name, ex)) 

                        continue 

 

                elif isinstance(field, WrappedRepeatedScalarProperty): 

                    scalars = field_val 

                    if len(scalars) > 20: 

                        val = '# of Values - %i: Field Values - "%s"... truncated at 20 values!' % ( 

                        len(scalars), str(scalars[:20])) 

                    else: 

                        val = '# of Values - %i: Field Values - "%s"' % (len(scalars), str(scalars[:])) 

 

                else: 

                    item = field_val 

                    if field.field_type == 'TYPE_ENUM': 

                        item = field.field_enum.lookup.get(item, 'Invalid Enum Value!') 

 

                    val = 'Field Value - "%s"' % str(item) 

 

                fid.write('''%s{Field Name - "%s" : Field Type - %s : %s} \n''' % (offset, name, field.field_type, val)) 

        except Exception, ex: 

            log.exception('Unexpected Exception in PPrint Wrapper!') 

            fid.write('Exception! %s' % ex) 

 

        finally: 

            msg = fid.getvalue() 

            fid.close() 

 

        return msg 

 

 

class ContainerWrapper(object): 

    """ 

    This class is only for use with containers.RepeatedCompositeFieldContainer 

    It is not needed for repeated scalars! 

    """ 

 

    def __init__(self, wrapper, gpbcontainer): 

        # Be careful - this is a hard link 

        self._wrapper = wrapper 

        if not isinstance(gpbcontainer, containers.RepeatedCompositeFieldContainer): 

            raise OOIObjectError('The Container Wrapper is only for use with Repeated Composite Field Containers') 

        self._gpbcontainer = gpbcontainer 

        self.Repository = wrapper.Repository 

        self._source = self 

 

    def GPBSourceCW(func): 

        def call_func(self, *args, **kwargs): 

            func_name = func.__name__ 

            ''' 

            print 'GPB INVALID CW' 

            print 'func name', func_name, func 

            print 'args', args 

            print 'kwargs', kwargs 

            ''' 

            wrapper = self._wrapper._source 

            if wrapper._invalid: 

                log.error(wrapper.Debug()) 

                raise OOIObjectError('Can not access Invalidated Container Wrapper Object in function "%s"' % func_name) 

 

            source = self._source 

 

            return func(source, *args, **kwargs) 

 

        return call_func 

 

 

    @classmethod 

    def factory(cls, wrapper, gpbcontainer): 

        #print cls, type(wrapper), type(gpbcontainer) 

        #objhash = hash(gpbcontainer) 

        dw = wrapper.DerivedWrappers 

        if gpbcontainer in dw: 

            return dw[gpbcontainer] 

 

        inst = cls(wrapper, gpbcontainer) 

 

        # Add it to the list of objects which derive from the root wrapper 

        dw[gpbcontainer] = inst 

        return inst 

 

 

    @property 

    def Root(self): 

        return self._wrapper._root 

 

 

    @property 

    def Invalid(self): 

        return self.Root.Invalid 

 

    def Invalidate(self, source=None): 

        self._gpbcontainer = None 

        if source is not None: 

            self._source = source 

 

    @GPBSourceCW 

    def __setitem__(self, key, value): 

        """ 

        Sets the item in the specified position. 

        """ 

 

        if not isinstance(value, Wrapper): 

            raise OOIObjectError('To set an item in a repeated field container, the value must be a Wrapper') 

 

        item = self._gpbcontainer.__getitem__(key) 

        item = self._wrapper._rewrap(item) 

        if item.ObjectType == LINK_TYPE: 

            self.Repository.set_linked_object(item, value) 

        else: 

            raise OOIObjectError( 

                'It is illegal to set a value of a repeated composite field unless it is a CASRef - Link') 

 

        self._wrapper._set_parents_modified() 

 

 

    @GPBSourceCW 

    def SetLink(self, key, value, ignore_copy_errors=False): 

        if not isinstance(value, Wrapper): 

            raise OOIObjectError('To set an item in a repeated field container, the value must be a Wrapper') 

 

        item = self._gpbcontainer.__getitem__(key) 

        item = self._wrapper._rewrap(item) 

        if item.ObjectType == LINK_TYPE: 

            self.Repository.set_linked_object(item, value, ignore_copy_errors) 

        else: 

            raise OOIObjectError( 

                'It is illegal to set a value of a repeated composit field unless it is a CASRef - Link') 

 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceCW 

    def __getitem__(self, key): 

        """Retrieves item by the specified key.""" 

 

        value = self._gpbcontainer.__getitem__(key) 

        value = self._wrapper._rewrap(value) 

        if value.ObjectType == LINK_TYPE: 

            value = self.Repository.get_linked_object(value) 

        return value 

 

    @GPBSourceCW 

    def GetLink(self, key): 

        link = self._gpbcontainer.__getitem__(key) 

        link = self._wrapper._rewrap(link) 

        assert link.ObjectType == LINK_TYPE, 'The field "%s" is not a link!' % link.ObjectClass 

        return link 

 

    @GPBSourceCW 

    def GetLinks(self): 

        wrapper_list = [] 

        links = self._gpbcontainer[:] # Get all the links! 

        for link in links: 

            link = self._wrapper._rewrap(link) 

            assert link.ObjectType == LINK_TYPE, 'The field "%s" is not a link!' % link.ObjectClass 

            wrapper_list.append(link) 

        return wrapper_list 

 

    @GPBSourceCW 

    def __len__(self): 

        """Returns the number of elements in the container.""" 

 

        return self._gpbcontainer.__len__() 

 

    @GPBSourceCW 

    def __ne__(self, other): 

        """Checks if another instance isn't equal to this one.""" 

 

        return not self._gpbcontainer == other._gpbcontainer 

 

    @GPBSourceCW 

    def __eq__(self, other): 

        """Compares the current instance with another one.""" 

 

        if self is other: 

            return True 

 

        if not isinstance(other, self.__class__): 

            raise OOIObjectError('Can only compare repeated composite fields against other repeated composite fields.') 

        return self._gpbcontainer == other._gpbcontainer 

 

    @GPBSourceCW 

    def __str__(self): 

        """Need to improve this!""" 

 

        return self._gpbcontainer.__str__() 

 

 

    # Composite specific methods: 

    @GPBSourceCW 

    def add(self): 

        new_element = self._gpbcontainer.add() 

 

        self._wrapper._set_parents_modified() 

        return self._wrapper._rewrap(new_element) 

 

    @GPBSourceCW 

    def __getslice__(self, start, stop): 

        """Retrieves the subset of items from between the specified indices.""" 

 

        wrapper_list = [] 

        for index in range(0, len(self))[start:stop]: 

            wrapper_list.append(self.__getitem__(index)) 

 

        # Does it make sense to return a list? 

        return wrapper_list 

 

    @GPBSourceCW 

    def __delitem__(self, key): 

        """Deletes the item at the specified position.""" 

 

        self._wrapper._set_parents_modified() 

 

        item = self._gpbcontainer.__getitem__(key) 

        item = self._wrapper._rewrap(item) 

 

        item._clear_derived_message() 

 

        self._gpbcontainer.__delitem__(key) 

 

    @GPBSourceCW 

    def __delslice__(self, start, stop): 

        """Deletes the subset of items from between the specified indices.""" 

 

        i_range = range(0, len(self))[start:stop] 

        for index in reversed(i_range): 

            self.__delitem__(index) 

 

 

    @GPBSourceCW 

    def __iter__(self): 

        for i in range(len(self)): 

            yield self[i] 

 

    @GPBSourceCW 

    def PPrint(self, offset='', name='items'): 

 

        length = len(self) 

 

        if length is 0: 

            return '%s[ ]' % offset 

        else: 

            fid = StringIO.StringIO() 

            fid.write('%s[ # of %s - %i \n' % (offset, name, length)) 

 

 

        try: 

 

                #n = min(10, length) 

 

            # Print all repeated composites 

            for i in range(length): 

                #log.debug('Printing field # %d' % i) 

                try: 

                    val = self[i].PPrint(offset=offset + '  ') 

                    fid.write('''%s%s# %i - %s  \n''' % (offset, name, i, val)) 

 

                except AttributeError, ae: 

                    log.debug('Attribute error while calling pprint on repeated composite: %s' % ae) 

                    fid.write('''%s%s# %i - %s  \n''' % (offset, name, i, 'Repeated Link Not Set!')) 

 

                except KeyError, ke: 

                    log.debug('KeyError while calling pprint on repeated composite: %s' % ke) 

                    fid.write('''%s%s# %i - %s  \n''' % (offset, name, i, 'Repeated Link object not found!!')) 

 

                except Exception, ex: 

                    log.exception('Unexpected Exception while calling pprint on repeated composite') 

                    fid.write('''%s%s# %i - Exception: %s  \n''' % (offset, name, i, ex)) 

 

 

                    #if length > 10: 

            #    msg += offset + '... truncated printing list at 10 items!\n' 

 

 

            fid.write(offset + '] ') 

 

        except Exception, ex: 

            log.exception('Unexpected Exception in PPrint CompositeContainer!') 

            fid.write('Exception! %s' % ex) 

 

        finally: 

            msg = fid.getvalue() 

            fid.close() 

 

        return msg 

 

 

class ScalarContainerWrapper(object): 

    """ 

    This class is only for use with containers.RepeatedCompositeFieldContainer 

    It is not needed for repeated scalars! 

    """ 

 

    def __init__(self, wrapper, gpbcontainer): 

        # Be careful - this is a hard link 

        self._wrapper = wrapper 

        if not isinstance(gpbcontainer, containers.RepeatedScalarFieldContainer): 

            raise OOIObjectError('The Container Wrapper is only for use with Repeated Composit Field Containers') 

        self._gpbcontainer = gpbcontainer 

        self.Repository = wrapper.Repository 

 

    @classmethod 

    def factory(cls, wrapper, gpbcontainer): 

        # Check the root wrapper objects list of derived wrappers before making a new one 

        #objhash = hash(gpbcontainer) 

        dw = wrapper.DerivedWrappers 

        if gpbcontainer in dw: 

            return dw[gpbcontainer] 

 

        inst = cls(wrapper, gpbcontainer) 

 

        # Add it to the list of objects which derive from the root wrapper 

        dw[gpbcontainer] = inst 

        return inst 

 

 

    def GPBSourceSCW(func): 

        def call_func(self, *args, **kwargs): 

            func_name = func.__name__ 

            ''' 

            print 'GPB INVALID CW' 

            print 'func name', func_name, func 

            print 'args', args 

            print 'kwargs', kwargs 

            ''' 

            wrapper = self._wrapper._source 

            if wrapper._invalid: 

                log.error(wrapper.Debug()) 

                raise OOIObjectError( 

                    'Can not access Invalidated Scalar Container Wrapper Object in function "%s"' % func_name) 

 

            return func(self, *args, **kwargs) 

 

        return call_func 

 

    @property 

    def Root(self): 

        return self._wrapper._root 

 

    @property 

    def Invalid(self): 

        return self.Root.Invalid 

 

    def Invalidate(self, source=None): 

        self._gpbcontainer = None 

        if source is not None: 

            self._source = source 

 

    @GPBSourceSCW 

    def append(self, value): 

        """Appends an item to the list. Similar to list.append().""" 

 

        self._gpbcontainer.append(value) 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def insert(self, key, value): 

        """Inserts the item at the specified position. Similar to list.insert().""" 

 

        self._gpbcontainer.insert(key, value) 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def extend(self, elem_seq): 

        """Extends by appending the given sequence. Similar to list.extend().""" 

 

        self._gpbcontainer.extend(elem_seq) 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def remove(self, elem): 

        """Removes an item from the list. Similar to list.remove().""" 

 

        self._gpbcontainer.remove(elem) 

        self._wrapper._set_parents_modified() 

 

 

    @GPBSourceSCW 

    def __getslice__(self, start, stop): 

        """Retrieves the subset of items from between the specified indices.""" 

 

        return self._gpbcontainer._values[start:stop] 

 

 

    @GPBSourceSCW 

    def __len__(self): 

        """Returns the number of elements in the container.""" 

 

        return len(self._gpbcontainer._values) 

 

 

    @GPBSourceSCW 

    def __getitem__(self, key): 

        """Retrieves the subset of items from between the specified indices.""" 

 

        return self._gpbcontainer._values[key] 

 

 

    @GPBSourceSCW 

    def __setitem__(self, key, value): 

        """Sets the item on the specified position.""" 

        self._gpbcontainer.__setitem__(key, value) 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def __setslice__(self, start, stop, values): 

        """Sets the subset of items from between the specified indices.""" 

 

        self._gpbcontainer.__setslice__(start, stop, values) 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def __delitem__(self, key): 

        """Deletes the item at the specified position.""" 

 

        del self._gpbcontainer._values[key] 

        self._gpbcontainer._message_listener.Modified() 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def __delslice__(self, start, stop): 

        """Deletes the subset of items from between the specified indices.""" 

 

        self._gpbcontainer._values.__delslice__(start, stop) 

        self._gpbcontainer._message_listener.Modified() 

        self._wrapper._set_parents_modified() 

 

    @GPBSourceSCW 

    def __eq__(self, other): 

        """Compares the current instance with another one.""" 

 

        if self is other: 

            return True 

            # Special case for the same type which should be common and fast. 

        if isinstance(other, self.__class__): 

            return other._gpbcontainer._values == self._gpbcontainer._values 

            # We are presumably comparing against some other sequence type. 

        return other == self._gpbcontainer._values 

 

    @GPBSourceSCW 

    def __ne__(self, other): 

        """Checks if another instance isn't equal to this one.""" 

        # The concrete classes should define __eq__. 

        return not self == other 

 

    @GPBSourceSCW 

    def __str__(self): 

        return str(self._gpbcontainer._values) 

 

    @GPBSourceSCW 

    def __iter__(self): 

        for i in range(len(self)): 

            yield self[i] 

 

 

class StructureElementError(Exception): 

    """ 

    An error class for structure elements 

    """ 

 

 

class StructureElement(object): 

    """ 

    @brief Wrapper for the container structure element. These are the objects 

    stored in the hashed elements table. Mostly convience methods are provided 

    here. A set provides references to the child objects so that the content 

    need not be decoded to find them. 

    """ 

 

    def __init__(self, se=None): 

        if se: 

            self._element = se 

        else: 

            self._element = get_gpb_class_from_type_id(STRUCTURE_ELEMENT_TYPE)() 

        self.ChildLinks = set() 

 

    @classmethod 

    def parse_structure_element(cls, blob): 

        se = get_gpb_class_from_type_id(STRUCTURE_ELEMENT_TYPE)() 

        se.ParseFromString(blob) 

 

        instance = cls(se) 

 

        if instance.key != instance.sha1: 

            log.error('The sha1 key does not match the value. The data is corrupted! \n' +\ 

                      'Element key %s, Calculated key %s' % (sha1_to_hex(instance.key), sha1_to_hex(instance.sha1))) 

            raise StructureElementError('Error reading serialized structure element. Sha1 value does not match.') 

 

        return instance 

 

    @property 

    def sha1(self): 

        """ 

        Make the sha1 safe for empty contents but also type safe. 

        Take use the sha twice so that we don't need to concatinate long strings! 

        """ 

        ################# 

        ## This is the method that you can compare in Java 

        ################# 

        ## Get the length of the binary arrays 

        #sha_len = 20 

        #type_len = self.type.ByteSize() 

        # 

        ## Convert to signed integer bytes 

        #fmt = '!%db' % type_len 

        #type_bytes = struct.unpack('!%db' % type_len , self.type.SerializeToString()) 

        # 

        ## Convert the sha1 of the content to signed integer bytes 

        #c_sha_bytes = struct.unpack('!20b', sha1bin(self.value)) 

        # 

        ## Concatinate the the byte arrays as integers 

        #cat_bytes = list(c_sha_bytes) + list(type_bytes) 

        # 

        ## Get the length of the concatination and convert to byte array 

        #fmt = '!%db' % (type_len+sha_len) 

        #sha_cat = struct.pack(fmt, *cat_bytes) 

        # 

        ##print 'sha1hex(sha_cat):',sha1hex(sha_cat) 

        ##print 'sha1hex(sha1bin(self.value) + self.type.SerializeToString()):',sha1hex(sha1bin(self.value) + self.type.SerializeToString()) 

        # 

        ## Return the sha1 of the byte array 

        #return sha1bin(sha_cat) 

        ################# 

        # This does the same thing much faster and shorter! 

        ################# 

        return sha1bin(sha1bin(self.value) + self.type.SerializeToString()) 

 

    #@property 

    def _get_type(self): 

        return self._element.type 

 

    #@type.setter 

    def _set_type(self, obj_type): 

        self._element.type.object_id = obj_type.object_id 

        self._element.type.version = obj_type.version 

 

    type = property(_get_type, _set_type) 

 

    #@property 

    def _get_value(self): 

        return self._element.value 

 

    #@value.setter 

    def _set_value(self, value): 

        self._element.value = value 

 

    value = property(_get_value, _set_value) 

 

    #@property 

    def _get_key(self): 

        #return sha1_to_hex(self._element.key) 

        return self._element.key 

 

    #@key.setter 

    def _set_key(self, value): 

        self._element.key = value 

 

    key = property(_get_key, _set_key) 

 

    def _set_isleaf(self, value): 

        self._element.isleaf = value 

 

    def _get_isleaf(self): 

        return self._element.isleaf 

 

    isleaf = property(_get_isleaf, _set_isleaf) 

 

    def __str__(self): 

        msg = '' 

        if len(self._element.key) == 20: 

            msg =   'Key:    ' + sha1_to_hex(self._element.key) + '\n' 

        msg = msg + 'Type:   ' + str(self._element.type) + '\n' 

        msg = msg + 'IsLeaf: ' + str(self._element.isleaf) + '\n' 

        msg = msg + 'El Len: ' + str(self.__sizeof__()) 

        return msg 

 

    def serialize(self): 

        return self._element.SerializeToString() 

 

 

    def __sizeof__(self): 

        #size = len(self._element.value) + 34 

        #print 'Esimtate: ', size 

        #print 'GPB Size: ', self._element.ByteSize() 

 

        return self._element.ByteSize()