text:
from io import BytesIO
import os
import re
import warnings

from datetime import timedelta

from django.conf import settings

try:  # pragma: no cover
  from django.contrib.auth import get_user_model
  User = get_user_model()
except ImportError, e:
  from django.contrib.auth.models import User

from django.core import mail
from django.core.exceptions import ValidationError
from django.utils import timezone

import plata
from plata.contact.models import Contact
from plata.discount.models import Discount
from plata.product.stock.models import Period, StockTransaction
from plata.shop.models import Order, OrderPayment

from .base import PlataTest, get_request

Product = plata.product_model()

class ViewTest(PlataTest):
    def setUp(self):
        self.ORIG_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
        settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)

    def tearDown(self):
        settings.TEMPLATE_DIRS = self.ORIG_TEMPLATE_DIRS

    def test_01_cart_empty(self):
        """Test cart is empty redirects work properly"""
        self.assertContains(self.client.get('/cart/'), 'Cart is empty')
        self.assertRedirects(self.client.get('/checkout/'), '/cart/')
        self.assertRedirects(self.client.get('/discounts/'), '/cart/')
        self.assertRedirects(self.client.get('/confirmation/'), '/cart/')

    def test_02_authenticated_user_has_contact(self):
        """Test shop.contact_from_user works correctly"""
        user = User.objects.create_user('test', 'test@example.com',
            'testing')
        self.client.login(username='test', password='testing')

        contact = Contact.objects.create(user=user)
        shop = plata.shop_instance()

        request = get_request(user=user)

        self.assertEqual(shop.contact_from_user(request.user), contact)

    def test_03_product_detail(self):
        """Test product detail view and cart handling methods"""
        # Removed everything -- the minimal add to cart form is really,
        # really stupid. Nothing to test here.

    def test_04_shopping(self):
        """Test shopping, checkout and order PDF generation in one go"""
        self.assertEqual(Order.objects.count(), 0)
        p1 = self.create_product()
        p2 = self.create_product()
        p2.name = 'Test Product 2'
        p2.save()

        p1.stock_transactions.create(type=StockTransaction.PURCHASE, change=100)
        p2.stock_transactions.create(type=StockTransaction.PURCHASE, change=100)
        self.assertEqual(Product.objects.filter(items_in_stock=0).count(), 0)

        self.assertContains(self.client.get(p1.get_absolute_url()),
            p1.name)

        self.client.post(p1.get_absolute_url(), {
            'quantity': 5,
            })
        self.client.post(p2.get_absolute_url(), {
            'quantity': 3,
            })

        self.assertEqual(Order.objects.count(), 1)
        self.assertContains(self.client.get('/cart/'), 'value="5"')

        order = Order.objects.all()[0]
        i1 = order.modify_item(p1, 0)
        i2 = order.modify_item(p2, 0)

        self.assertRedirects(self.client.post('/cart/', {
            'items-INITIAL_FORMS': 2,
            'items-TOTAL_FORMS': 2,
            'items-MAX_NUM_FORMS': 2,

            'items-0-id': i1.id,
            'items-0-quantity': 6, # one additional item

            'items-1-id': i2.id,
            'items-1-quantity': i2.quantity,
            }), '/cart/')

        self.assertEqual(order.modify_item(p1, 0).quantity, 6)

        self.assertRedirects(self.client.post('/cart/', {
            'checkout': True,

            'items-INITIAL_FORMS': 2,
            'items-TOTAL_FORMS': 2,
            'items-MAX_NUM_FORMS': 2,

            'items-0-id': i1.id,
            'items-0-quantity': 6, # one additional item

            'items-1-id': i2.id,
            'items-1-quantity': 0,
            }), '/checkout/')

        self.assertEqual(order.modify_item(p1, 0).quantity, 6)
        self.assertEqual(order.items.count(), 1)

        self.client.post(p2.get_absolute_url(), {
            'quantity': 5,
            })
        self.assertEqual(order.items.count(), 2)

        # TODO test what happens when a product has been deleted from the
        # shop in the meantime (and orderitem.product = None)

        self.assertEqual(Order.objects.get().status, Order.CART)
        self.assertRedirects(self.client.post('/cart/', {
            'checkout': True,

            'items-INITIAL_FORMS': 2,
            'items-TOTAL_FORMS': 2,
            'items-MAX_NUM_FORMS': 2,

            'items-0-id': i1.id,
            'items-0-quantity': 6,
            'items-0-DELETE': True,

            'items-1-id': i2.id,
            'items-1-quantity': 5,
            }), '/checkout/')
        self.assertEqual(order.items.count(), 1)

        self.client.get('/checkout/')
        self.assertEqual(Order.objects.get().status, Order.CHECKOUT)

        self.assertEqual(self.client.post('/checkout/', {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Hans',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            #'order-shipping_same_as_billing': True, # billing information is missing...
            'order-email': 'something@example.com',
            'order-currency': 'CHF',
            }).status_code, 200) # ... therefore view does not redirect

        self.assertRedirects(self.client.post('/checkout/', {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Hans',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            'order-shipping_same_as_billing': True,
            'order-email': 'something@example.com',
            'order-currency': 'CHF',
            'order-notes': 'Test\n\nJust testing.',
            }), '/confirmation/')

        Discount.objects.create(
            is_active=True,
            type=Discount.PERCENTAGE_VOUCHER,
            code='asdf',
            name='Percentage discount',
            value=30)

        self.assertContains(self.client.post('/discounts/', {
            'code': 'something-invalid',
            }), 'not validate')

        self.assertRedirects(self.client.post('/discounts/', {
            'code': 'asdf',
            }), '/discounts/')

        self.assertRedirects(self.client.post('/discounts/', {
            'proceed': 'True',
            }), '/confirmation/')

        self.assertEqual(self.client.post('/confirmation/', {}).status_code, 200)
        self.assertEqual(Order.objects.get(pk=order.id).status, Order.CHECKOUT)

        self.assertContains(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'postfinance',
            }), 'SHASign')

        self.assertContains(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'paypal',
            }), 'cgi-bin/webscr')

        self.assertRedirects(self.client.post(p2.get_absolute_url(), {
            'quantity': 42,
            }), '/cart/', target_status_code=302)
        self.assertRedirects(self.client.post('/cart/', {
            'items-INITIAL_FORMS': 1,
            'items-TOTAL_FORMS': 1,
            'items-MAX_NUM_FORMS': 1,

            'items-0-id': i2.id,
            'items-0-quantity': 43,
            'items-0-DELETE': False,
            }), '/confirmation/?confirmed=1')
        self.assertTrue(Order.objects.all()[0].items.get(product=p2).quantity != 42)

        # Test this view works at all
        self.client.get('/order/payment_failure/')

        self.assertEqual(len(mail.outbox), 0)
        self.assertRedirects(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'cod',
            }), '/order/success/')
        self.assertEqual(len(mail.outbox), 2) # invoice and packing slip
        self.assertEqual(Order.objects.get(pk=order.id).status, Order.PAID)

        # Clear order
        self.assertRedirects(self.client.get('/order/new/?next=%s' % p1.get_absolute_url()),
            p1.get_absolute_url())
        # Can call URL several times without change in behavior
        self.assertRedirects(self.client.get('/order/new/'), '/',
            target_status_code=302)

        # Cart is empty
        self.assertRedirects(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'cod',
            }), '/cart/')

        self.assertRedirects(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'paypal',
            }), '/cart/')

        user = User.objects.create_superuser('admin', 'admin@example.com', 'password')

        self.client.login(username='admin', password='password')
        self.assertEqual(self.client.get('/reporting/invoice_pdf/%s/' % order.id)['Content-Type'],
            'application/pdf')
        self.assertEqual(self.client.get('/reporting/packing_slip_pdf/%s/' % order.id)['Content-Type'],
            'application/pdf')
        self.assertEqual(self.client.get('/reporting/product_xls/')['Content-Type'],
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    def test_05_creation(self):
        """Test creation of orders through the shop object"""
        shop = plata.shop_instance()
        request = get_request()

        order = shop.order_from_request(request)
        self.assertEqual(order, None)

        order = shop.order_from_request(request, create=True)
        self.assertEqual(Order.objects.count(), 1)
        self.assertEqual(order.user, None)

    def test_06_postfinance_ipn(self):
        """Test Postfinance server-to-server request handling"""
        shop = plata.shop_instance()
        request = get_request()

        product = self.create_product()

        Period.objects.create(name='Test period')
        product.stock_transactions.create(type=StockTransaction.PURCHASE, change=10)
        self.client.post(product.get_absolute_url(), {
            'quantity': 5,
            })

        response = self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'postfinance',
            })
        self.assertContains(response, 'SHASign')
        self.assertContains(response, '721735bc3876094bb7e5ff075de8411d85494a66')

        self.assertEqual(StockTransaction.objects.count(), 2)
        self.assertEqual(Order.objects.get().status, Order.CONFIRMED)
        self.assertEqual(OrderPayment.objects.count(), 1)

        self.client.get('/order/payment_failure/')
        # payment process reservation should have been removed now,
        # this does not change anything else though
        self.assertEqual(StockTransaction.objects.count(), 1)
        self.assertEqual(Order.objects.get().status, Order.CHECKOUT)

        self.assertContains(self.client.post('/payment/postfinance/ipn/', {
            }), 'Missing data', status_code=403)

        order = Order.objects.get(pk=1)

        ipn_data = {
            'orderID': 'Order-1-1',
            'currency': order.currency,
            'amount': order.balance_remaining,
            'PM': 'Postfinance',
            'ACCEPTANCE': 'xxx',
            'STATUS': '5', # Authorized
            'CARDNO': 'xxxxxxxxxxxx1111',
            'PAYID': '123456789',
            'NCERROR': '',
            'BRAND': 'VISA',
            'SHASIGN': 'this-value-is-invalid',
            }

        self.assertContains(self.client.post('/payment/postfinance/ipn/', ipn_data),
            'Hash did not validate', status_code=403)

        ipn_data['SHASIGN'] = '4b4cf5f9a5f0b54cc119be3696f43f81139232ae'

        self.assertContains(self.client.post('/payment/postfinance/ipn/', ipn_data),
            'OK', status_code=200)

        order = Order.objects.get(pk=1)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            self.assertTrue(order.is_paid())
            self.assertEqual(len(w), 1)
            self.assertTrue(
                'Order.is_paid() has been deprecated' in str(w[-1]))
        self.assertTrue(order.status >= Order.PAID)

        self.assertEqual(StockTransaction.objects.count(), 2)

        # Manipulate paid amount
        order.paid -= 10
        order.save()
        self.assertRedirects(self.client.get('/cart/'), '/confirmation/?confirmed=1')

        self.assertContains(self.client.get('/order/success/'),
            '
Order has been partially paid.
')

        # Revert manipulation
        order.paid += 10
        order.save()
        self.assertRedirects(self.client.get('/checkout/'), '/order/success/')

    def test_07_paypal_ipn(self):
        """Test PayPal Instant Payment Notification handler"""
        paypal_ipn_data = {
            'txn_id': '123456789',
            'invoice': 'Order-1-1',
            'mc_currency': 'CHF',
            'mc_gross': '1234',
            'payment_status': 'Completed',
            'last_name': u'H\xe5konsen',
        }

        from plata.payment.modules import paypal
        import cgi
        def mock_urlopen(*args, **kwargs):
            qs = cgi.parse_qs(args[1].encode('ascii'))
            self.assertEqual(qs['cmd'][0], '_notify-validate')
            for k, v in paypal_ipn_data.iteritems():
                self.assertEqual(unicode(qs[k][0], 'utf-8'), v)
            s = BytesIO('VERIFIED')
            return s
        paypal.urllib2.urlopen = mock_urlopen

        shop = plata.shop_instance()
        request = get_request()

        product = self.create_product()
        product.stock_transactions.create(type=StockTransaction.PURCHASE, change=10)
        self.client.post(product.get_absolute_url(), {
            'quantity': 5,
            })

        response = self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'paypal',
            })
        self.assertContains(response, 'sandbox')

        self.assertEqual(StockTransaction.objects.count(), 2)
        self.assertEqual(Order.objects.count(), 1)
        self.assertEqual(OrderPayment.objects.count(), 1)

        self.assertContains(
            self.client.post('/payment/paypal/ipn/', paypal_ipn_data),
            'Ok'
        )

        # test windows-1252 encoded IPN also:
        self.assertContains(
            self.client.post(
                '/payment/paypal/ipn/',
                dict(
                    map(
                        lambda (k,v): (k, v.encode('windows-1252')),
                        dict(paypal_ipn_data, charset='windows-1252').items()
                    )
                ),
            ),
            'Ok'
        )

        order = Order.objects.get(pk=1)
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            self.assertTrue(order.is_paid())
            self.assertEqual(len(w), 1)
            self.assertTrue(
                'Order.is_paid() has been deprecated' in str(w[-1]))

        self.assertEqual(
            set((
                StockTransaction.PURCHASE,
                StockTransaction.SALE,
                StockTransaction.PAYMENT_PROCESS_RESERVATION,
            )), set(StockTransaction.objects.values_list('type', flat=True)))

    def test_08_checkout_preexisting_user(self):
        """Test checkout behavior using already existing user without contact"""
        User.objects.create_user('else', 'else@example.com', 'test')

        user = User.objects.create_user('test', 'test@example.com', 'test')
        self.client.login(username='test', password='test')

        p1 = self.create_product(stock=100)
        self.client.post(p1.get_absolute_url(), {'quantity': 5})

        response = self.client.get('/checkout/')
        self.assertContains(response, 'Checkout')
        self.assertNotContains(response, 'login-username')

        checkout_data = {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Hans',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            'order-shipping_same_as_billing': True,
            'order-email': 'else@example.com',
            'order-currency': 'CHF',
            'order-create_account': True,
            }

        self.assertContains(self.client.post('/checkout/', checkout_data),
            'This e-mail address belongs to a different account')

        self.assertEqual(len(mail.outbox), 0)
        checkout_data['order-email'] = 'something@example.com'
        self.assertRedirects(self.client.post('/checkout/', checkout_data),
            '/confirmation/')
        self.assertEqual(len(mail.outbox), 1)

        # There should be exactly one contact object now
        contact = Contact.objects.get()
        self.assertEqual(contact.user.orders.count(), 1)
        self.assertEqual(contact.billing_city, 'Beispielstadt')

        # User e-mail address is unchanged
        self.assertEqual(contact.user.email, 'test@example.com')

    def test_09_checkout_create_user(self):
        """Test checkout behavior without existing user or contact"""
        User.objects.create_user('else', 'else@example.com', 'test')

        p1 = self.create_product(stock=100)
        self.client.post(p1.get_absolute_url(), {'quantity': 5})

        response = self.client.get('/checkout/')
        self.assertContains(response, 'Checkout')
        self.assertContains(response, 'login-username')

        checkout_data = {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Hans',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            'order-shipping_same_as_billing': True,
            'order-email': 'else@example.com',
            'order-currency': 'CHF',
            'order-create_account': True,
            }

        self.assertContains(self.client.post('/checkout/', checkout_data),
            'This e-mail address might belong to you, but we cannot know for sure because you are not authenticated yet')

        self.assertEqual(len(mail.outbox), 0)
        checkout_data['order-email'] = 'something@example.com'
        self.assertRedirects(self.client.post('/checkout/', checkout_data),
            '/confirmation/')
        self.assertEqual(len(mail.outbox), 1)

        # There should be exactly one contact object now
        contact = Contact.objects.get()
        self.assertEqual(contact.user.orders.count(), 1)
        self.assertEqual(contact.billing_city, 'Beispielstadt')

        self.assertEqual(contact.user.email, 'something@example.com')

        # New order
        self.client.post(p1.get_absolute_url(), {'quantity': 5})
        response = self.client.get('/checkout/')

        self.assertContains(response, 'value="something@example.com"')
        self.assertContains(response, 'value="Beispielstadt"')

    def test_10_login_in_checkout_preexisting_contact(self):
        """Test checkout behavior using already existing contact and user"""
        Contact.objects.create(
            user=User.objects.create_user('else@example.com', 'else@example.com', 'test'),
            currency='CHF',
            billing_first_name='Hans',
            billing_last_name='Muster',
            )

        p1 = self.create_product(stock=100)
        self.client.post(p1.get_absolute_url(), {'quantity': 5})

        response = self.client.get('/checkout/')
        self.assertContains(response, 'Checkout')
        self.assertContains(response, 'login-username')

        self.assertRedirects(self.client.post('/checkout/', {
            '_login': 1,
            'login-username': 'else@example.com',
            'login-password': 'test',
            }), '/checkout/')

        # Test that the order is still active after logging in
        response = self.client.get('/checkout/')
        self.assertContains(response, 'value="else@example.com"')
        self.assertContains(response, 'value="Muster"')

        checkout_data = {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Fritz',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            'order-shipping_same_as_billing': True,
            'order-email': 'else@example.com',
            'order-currency': 'CHF',
            'order-create_account': True,
            }

        self.assertEqual(len(mail.outbox), 0)
        self.assertRedirects(self.client.post('/checkout/', checkout_data),
            '/confirmation/')
        self.assertEqual(len(mail.outbox), 0)

        contact = Contact.objects.get()
        # First name should be updated in checkout processing
        self.assertEqual(contact.billing_first_name, 'Fritz')
        self.assertEqual(unicode(contact), 'else@example.com') # Username

        # Order should be assigned to contact
        self.assertEqual(Order.objects.count(), 1)
        self.assertEqual(contact.user.orders.count(), 1)

    def test_11_login_in_checkout_create_contact(self):
        """Test checkout using already existing user, but no contact"""
        User.objects.create_user('else@example.com', 'else@example.com', 'test')

        p1 = self.create_product(stock=100)
        self.client.post(p1.get_absolute_url(), {'quantity': 5})

        response = self.client.get('/checkout/')
        self.assertContains(response, 'Checkout')
        self.assertContains(response, 'login-username')

        self.assertRedirects(self.client.post('/checkout/', {
            '_login': 1,
            'login-username': 'else@example.com',
            'login-password': 'test',
            }), '/checkout/')

        checkout_data = {
            '_checkout': 1,
            'order-billing_company': u'BigCorp',
            'order-billing_first_name': u'Fritz',
            'order-billing_last_name': u'Muster',
            'order-billing_address': u'Musterstrasse 42',
            'order-billing_zip_code': u'8042',
            'order-billing_city': u'Beispielstadt',
            'order-billing_country': u'CH',
            'order-shipping_same_as_billing': True,
            'order-email': 'else@example.com',
            'order-currency': 'CHF',
            'order-create_account': True,
            }

        # If order wasn't active after logging in anymore, this would not work
        self.assertRedirects(self.client.post('/checkout/', checkout_data),
            '/confirmation/')

        contact = Contact.objects.get()
        self.assertEqual(contact.billing_first_name, 'Fritz')

        # Order should be assigned to contact
        self.assertEqual(Order.objects.count(), 1)
        self.assertEqual(contact.user.orders.count(), 1)

    def test_12_insufficient_stock(self):
        """Test insufficient stock handling in checkout process"""
        p1 = self.create_product(stock=10)
        self.client.post(p1.get_absolute_url(), {'quantity': 9})

        p1.stock_transactions.create(type=StockTransaction.SALE, change=-5)

        response = self.client.get('/checkout/')
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], 'http://testserver/cart/?e=1')

        self.assertContains(self.client.get('/cart/'),
            'Not enough stock available for')

    def test_13_expired_reservation(self):
        """Test payment process reservation expiration"""
        p1 = self.create_product(stock=10)

        self.assertEqual(
            p1.__class__.objects.get(pk=p1.pk).items_in_stock,
            10)

        p1.stock_transactions.create(
            type=StockTransaction.PAYMENT_PROCESS_RESERVATION,
            change=-7)

        # Payment process reservation stock transactions should not modify
        # the items_in_stock field
        self.assertEqual(
            p1.__class__.objects.get(pk=p1.pk).items_in_stock,
            10)

        self.assertEqual(StockTransaction.objects.items_in_stock(p1), 10)
        self.assertEqual(StockTransaction.objects.items_in_stock(p1,
            include_reservations=True), 3)

        StockTransaction.objects.update(created=timezone.now()-timedelta(minutes=10))
        self.assertEqual(StockTransaction.objects.items_in_stock(p1), 10)
        self.assertEqual(StockTransaction.objects.items_in_stock(p1,
            include_reservations=True), 3)

        StockTransaction.objects.update(created=timezone.now()-timedelta(minutes=20))
        self.assertEqual(StockTransaction.objects.items_in_stock(p1,
            include_reservations=True), 10)
        self.assertEqual(StockTransaction.objects.items_in_stock(p1), 10)

        order = self.create_order()
        order.modify_item(p1, relative=5)
        order.validate(order.VALIDATE_ALL)

        StockTransaction.objects.update(created=timezone.now()-timedelta(minutes=10))
        self.assertRaises(ValidationError, order.validate, order.VALIDATE_ALL)

    def test_14_remaining_discount(self):
        """Test that a new discount is created when there is an amount remaining"""
        p1 = self.create_product(stock=10)
        self.client.post(p1.get_absolute_url(), {'quantity': 5})

        discount = Discount.objects.create(
            name='Testname',
            type=Discount.AMOUNT_VOUCHER_INCL_TAX,
            value=1000,
            config='{"all":{}}',
            tax_class=self.tax_class,
            currency='CHF',
            )

        self.assertRedirects(self.client.post('/discounts/', {
            'code': discount.code,
            'proceed': 'True',
            }), '/confirmation/')

        self.assertRedirects(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'cod',
            }), '/order/success/')

        self.assertEqual(Discount.objects.count(), 2)

        order = Order.objects.get()
        new_discount = Discount.objects.exclude(code=discount.code).get()

        self.assertAlmostEqual(
            discount.value - sum(item.subtotal for item in order.items.all()),
            new_discount.value * (1 + self.tax_class.rate / 100))

        self.client.get('/order/new/')

        self.client.post(p1.get_absolute_url(), {'quantity': 1})
        self.assertRedirects(self.client.post('/discounts/', {
            'code': new_discount.code,
            'proceed': 'True',
            }), '/confirmation/')

        self.assertRedirects(self.client.post('/confirmation/', {
            'terms_and_conditions': True,
            'payment_method': 'cod',
            }), '/order/success/')

        self.client.get('/order/new/')
        self.client.get('/order/new/') # Should not do anything the second time
        self.client.post(p1.get_absolute_url(), {'quantity': 1})
        self.assertContains(self.client.post('/discounts/', {
            'code': new_discount.code,
            'proceed': 'True',
            }), 'Allowed uses for this discount has already been reached.')

        # Stock transactions must be created for orders which are paid from the start
        # 10 purchase, -5 sale, -1 sale
        self.assertEqual(StockTransaction.objects.count(), 3)
        p1 = Product.objects.get(pk=p1.pk)
        self.assertEqual(p1.items_in_stock, 4)


text:
package org.processmining.models.graphbased.directedhypergraph;

import java.util.Set;

/**
 * represents edges going from a source towards multiple targets
 *
 * @author bfvdonge
 *
 * @param <S>
 * @param <T>
 */
public interface DirectedOutgoingHyperedge<S extends DirectedHypergraphNode, T extends DirectedHypergraphNode> extends
		DirectedHypergraphElement {

	S getSource();

	Set<T> getTargets();

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef HEADLESS

#include <stdlib.h>
#include <string.h>

#include "sun_java2d_SunGraphics2D.h"

#include "jlong.h"
#include "jni_util.h"
#include "OGLContext.h"
#include "OGLRenderQueue.h"
#include "OGLSurfaceData.h"
#include "GraphicsPrimitiveMgr.h"
#include "Region.h"

/**
 * The following methods are implemented in the windowing system (i.e. GLX
 * and WGL) source files.
 */
extern jboolean OGLSD_InitOGLWindow(JNIEnv *env, OGLSDOps *oglsdo);
extern OGLContext *OGLSD_MakeOGLContextCurrent(JNIEnv *env,
                                               OGLSDOps *srcOps,
                                               OGLSDOps *dstOps);

/**
 * This table contains the standard blending rules (or Porter-Duff compositing
 * factors) used in glBlendFunc(), indexed by the rule constants from the
 * AlphaComposite class.
 */
OGLBlendRule StdBlendRules[] = {
    { GL_ZERO,                GL_ZERO                }, /* 0 - Nothing      */
    { GL_ZERO,                GL_ZERO                }, /* 1 - RULE_Clear   */
    { GL_ONE,                 GL_ZERO                }, /* 2 - RULE_Src     */
    { GL_ONE,                 GL_ONE_MINUS_SRC_ALPHA }, /* 3 - RULE_SrcOver */
    { GL_ONE_MINUS_DST_ALPHA, GL_ONE                 }, /* 4 - RULE_DstOver */
    { GL_DST_ALPHA,           GL_ZERO                }, /* 5 - RULE_SrcIn   */
    { GL_ZERO,                GL_SRC_ALPHA           }, /* 6 - RULE_DstIn   */
    { GL_ONE_MINUS_DST_ALPHA, GL_ZERO                }, /* 7 - RULE_SrcOut  */
    { GL_ZERO,                GL_ONE_MINUS_SRC_ALPHA }, /* 8 - RULE_DstOut  */
    { GL_ZERO,                GL_ONE                 }, /* 9 - RULE_Dst     */
    { GL_DST_ALPHA,           GL_ONE_MINUS_SRC_ALPHA }, /*10 - RULE_SrcAtop */
    { GL_ONE_MINUS_DST_ALPHA, GL_SRC_ALPHA           }, /*11 - RULE_DstAtop */
    { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA }, /*12 - RULE_AlphaXor*/
};

/** Evaluates to "front" or "back", depending on the value of buf. */
#define OGLC_ACTIVE_BUFFER_NAME(buf) \
    (buf == GL_FRONT || buf == GL_COLOR_ATTACHMENT0_EXT) ? "front" : "back"

/**
 * Initializes the viewport and projection matrix, effectively positioning
 * the origin at the top-left corner of the surface.  This allows Java 2D
 * coordinates to be passed directly to OpenGL, which is typically based on
 * a bottom-right coordinate system.  This method also sets the appropriate
 * read and draw buffers.
 */
static void
OGLContext_SetViewport(OGLSDOps *srcOps, OGLSDOps *dstOps)
{
    jint width = dstOps->width;
    jint height = dstOps->height;

    J2dTraceLn4(J2D_TRACE_INFO,
                "OGLContext_SetViewport: w=%d h=%d read=%s draw=%s",
                width, height,
                OGLC_ACTIVE_BUFFER_NAME(srcOps->activeBuffer),
                OGLC_ACTIVE_BUFFER_NAME(dstOps->activeBuffer));

    // set the viewport and projection matrix
    j2d_glViewport(dstOps->xOffset, dstOps->yOffset,
                   (GLsizei)width, (GLsizei)height);
    j2d_glMatrixMode(GL_PROJECTION);
    j2d_glLoadIdentity();
    j2d_glOrtho(0.0, (GLdouble)width, (GLdouble)height, 0.0, -1.0, 1.0);

    // set the active read and draw buffers
    j2d_glReadBuffer(srcOps->activeBuffer);
    j2d_glDrawBuffer(dstOps->activeBuffer);

    // set the color mask to enable alpha channel only when necessary
    j2d_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, (GLboolean)!dstOps->isOpaque);
}

/**
 * Initializes the alpha channel of the current surface so that it contains
 * fully opaque alpha values.
 */
static void
OGLContext_InitAlphaChannel()
{
    GLboolean scissorEnabled;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_InitAlphaChannel");

    // it is possible for the scissor test to be enabled at this point;
    // if it is, disable it temporarily since it can affect the glClear() op
    scissorEnabled = j2d_glIsEnabled(GL_SCISSOR_TEST);
    if (scissorEnabled) {
        j2d_glDisable(GL_SCISSOR_TEST);
    }

    // set the color mask so that we only affect the alpha channel
    j2d_glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);

    // clear the color buffer so that the alpha channel is fully opaque
    j2d_glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    j2d_glClear(GL_COLOR_BUFFER_BIT);

    // restore the color mask (as it was set in OGLContext_SetViewport())
    j2d_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);

    // re-enable scissor test, only if it was enabled earlier
    if (scissorEnabled) {
        j2d_glEnable(GL_SCISSOR_TEST);
    }
}

/**
 * Fetches the OGLContext associated with the given destination surface,
 * makes the context current for those surfaces, updates the destination
 * viewport, and then returns a pointer to the OGLContext.
 */
OGLContext *
OGLContext_SetSurfaces(JNIEnv *env, jlong pSrc, jlong pDst)
{
    OGLSDOps *srcOps = (OGLSDOps *)jlong_to_ptr(pSrc);
    OGLSDOps *dstOps = (OGLSDOps *)jlong_to_ptr(pDst);
    OGLContext *oglc = NULL;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_SetSurfaces");

    if (srcOps == NULL || dstOps == NULL) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_SetSurfaces: ops are null");
        return NULL;
    }

    J2dTraceLn2(J2D_TRACE_VERBOSE, "  srctype=%d dsttype=%d",
                srcOps->drawableType, dstOps->drawableType);

    if (dstOps->drawableType == OGLSD_TEXTURE) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_SetSurfaces: texture cannot be used as destination");
        return NULL;
    }

    if (dstOps->drawableType == OGLSD_UNDEFINED) {
        // initialize the surface as an OGLSD_WINDOW
        if (!OGLSD_InitOGLWindow(env, dstOps)) {
            J2dRlsTraceLn(J2D_TRACE_ERROR,
                "OGLContext_SetSurfaces: could not init OGL window");
            return NULL;
        }
    }

    // make the context current
    oglc = OGLSD_MakeOGLContextCurrent(env, srcOps, dstOps);
    if (oglc == NULL) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_SetSurfaces: could not make context current");
        return NULL;
    }

    // update the viewport
    OGLContext_SetViewport(srcOps, dstOps);

    // perform additional one-time initialization, if necessary
    if (dstOps->needsInit) {
        if (dstOps->isOpaque) {
            // in this case we are treating the destination as opaque, but
            // to do so, first we need to ensure that the alpha channel
            // is filled with fully opaque values (see 6319663)
            OGLContext_InitAlphaChannel();
        }
        dstOps->needsInit = JNI_FALSE;
    }

    return oglc;
}

/**
 * Resets the current clip state (disables both scissor and depth tests).
 */
void
OGLContext_ResetClip(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_ResetClip");

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    j2d_glDisable(GL_SCISSOR_TEST);
    j2d_glDisable(GL_DEPTH_TEST);
}

/**
 * Sets the OpenGL scissor bounds to the provided rectangular clip bounds.
 */
void
OGLContext_SetRectClip(OGLContext *oglc, OGLSDOps *dstOps,
                       jint x1, jint y1, jint x2, jint y2)
{
    jint width = x2 - x1;
    jint height = y2 - y1;

    J2dTraceLn4(J2D_TRACE_INFO,
                "OGLContext_SetRectClip: x=%d y=%d w=%d h=%d",
                x1, y1, width, height);

    RETURN_IF_NULL(dstOps);
    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    if ((width < 0) || (height < 0)) {
        // use an empty scissor rectangle when the region is empty
        width = 0;
        height = 0;
    }

    j2d_glDisable(GL_DEPTH_TEST);
    j2d_glEnable(GL_SCISSOR_TEST);

    // the scissor rectangle is specified using the lower-left
    // origin of the clip region (in the framebuffer's coordinate
    // space), so we must account for the x/y offsets of the
    // destination surface
    j2d_glScissor(dstOps->xOffset + x1,
                  dstOps->yOffset + dstOps->height - (y1 + height),
                  width, height);
}

/**
 * Sets up a complex (shape) clip using the OpenGL depth buffer.  This
 * method prepares the depth buffer so that the clip Region spans can
 * be "rendered" into it.  The depth buffer is first cleared, then the
 * depth func is setup so that when we render the clip spans,
 * nothing is rendered into the color buffer, but for each pixel that would
 * be rendered, a non-zero value is placed into that location in the depth
 * buffer.  With depth test enabled, pixels will only be rendered into the
 * color buffer if the corresponding value at that (x,y) location in the
 * depth buffer differs from the incoming depth value.
 */
void
OGLContext_BeginShapeClip(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_BeginShapeClip");

    RETURN_IF_NULL(oglc);
    RESET_PREVIOUS_OP();

    j2d_glDisable(GL_SCISSOR_TEST);

    // enable depth test and clear depth buffer so that depth values are at
    // their maximum; also set the depth func to GL_ALWAYS so that the
    // depth values of the clip spans are forced into the depth buffer
    j2d_glEnable(GL_DEPTH_TEST);
    j2d_glClearDepth(1.0);
    j2d_glClear(GL_DEPTH_BUFFER_BIT);
    j2d_glDepthFunc(GL_ALWAYS);

    // disable writes into the color buffer while we set up the clip
    j2d_glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

    // save current transform
    j2d_glMatrixMode(GL_MODELVIEW);
    j2d_glPushMatrix();

    // use identity transform plus slight translation in the z-axis when
    // setting the clip spans; this will push the clip spans (which would
    // normally be at z=0) to the z=1 plane to give them some depth
    j2d_glLoadIdentity();
    j2d_glTranslatef(0.0f, 0.0f, 1.0f);
}

/**
 * Finishes setting up the shape clip by resetting the depth func
 * so that future rendering operations will once again be written into the
 * color buffer (while respecting the clip set up in the depth buffer).
 */
void
OGLContext_EndShapeClip(OGLContext *oglc, OGLSDOps *dstOps)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_EndShapeClip");

    RETURN_IF_NULL(dstOps);
    RETURN_IF_NULL(oglc);
    RESET_PREVIOUS_OP();

    // restore transform
    j2d_glPopMatrix();

    // re-enable writes into the color buffer
    j2d_glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, (GLboolean)!dstOps->isOpaque);

    // enable the depth test so that only fragments within the clip region
    // (i.e. those fragments whose z-values are >= the values currently
    // stored in the depth buffer) are rendered
    j2d_glDepthFunc(GL_GEQUAL);
}

/**
 * Initializes the OpenGL state responsible for applying extra alpha.  This
 * step is only necessary for any operation that uses glDrawPixels() or
 * glCopyPixels() with a non-1.0f extra alpha value.  Since the source is
 * always premultiplied, we apply the extra alpha value to both alpha and
 * color components using GL_*_SCALE.
 */
void
OGLContext_SetExtraAlpha(jfloat ea)
{
    J2dTraceLn1(J2D_TRACE_INFO, "OGLContext_SetExtraAlpha: ea=%f", ea);

    j2d_glPixelTransferf(GL_ALPHA_SCALE, ea);
    j2d_glPixelTransferf(GL_RED_SCALE, ea);
    j2d_glPixelTransferf(GL_GREEN_SCALE, ea);
    j2d_glPixelTransferf(GL_BLUE_SCALE, ea);
}

/**
 * Resets all OpenGL compositing state (disables blending and logic
 * operations).
 */
void
OGLContext_ResetComposite(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_ResetComposite");

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    // disable blending and XOR mode
    if (oglc->compState == sun_java2d_SunGraphics2D_COMP_ALPHA) {
        j2d_glDisable(GL_BLEND);
    } else if (oglc->compState == sun_java2d_SunGraphics2D_COMP_XOR) {
        j2d_glDisable(GL_COLOR_LOGIC_OP);
        j2d_glDisable(GL_ALPHA_TEST);
    }

    // set state to default values
    oglc->compState = sun_java2d_SunGraphics2D_COMP_ISCOPY;
    oglc->extraAlpha = 1.0f;
}

/**
 * Initializes the OpenGL blending state.  XOR mode is disabled and the
 * appropriate blend functions are setup based on the AlphaComposite rule
 * constant.
 */
void
OGLContext_SetAlphaComposite(OGLContext *oglc,
                             jint rule, jfloat extraAlpha, jint flags)
{
    J2dTraceLn1(J2D_TRACE_INFO,
                "OGLContext_SetAlphaComposite: flags=%d", flags);

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    // disable XOR mode
    if (oglc->compState == sun_java2d_SunGraphics2D_COMP_XOR) {
        j2d_glDisable(GL_COLOR_LOGIC_OP);
        j2d_glDisable(GL_ALPHA_TEST);
    }

    // we can safely disable blending when:
    //   - comp is SrcNoEa or SrcOverNoEa, and
    //   - the source is opaque
    // (turning off blending can have a large positive impact on
    // performance)
    if ((rule == RULE_Src || rule == RULE_SrcOver) &&
        (extraAlpha == 1.0f) &&
        (flags & OGLC_SRC_IS_OPAQUE))
    {
        J2dTraceLn1(J2D_TRACE_VERBOSE,
                    "  disabling alpha comp: rule=%d ea=1.0 src=opq", rule);
        j2d_glDisable(GL_BLEND);
    } else {
        J2dTraceLn2(J2D_TRACE_VERBOSE,
                    "  enabling alpha comp: rule=%d ea=%f", rule, extraAlpha);
        j2d_glEnable(GL_BLEND);
        j2d_glBlendFunc(StdBlendRules[rule].src, StdBlendRules[rule].dst);
    }

    // update state
    oglc->compState = sun_java2d_SunGraphics2D_COMP_ALPHA;
    oglc->extraAlpha = extraAlpha;
}

/**
 * Initializes the OpenGL logic op state to XOR mode.  Blending is disabled
 * before enabling logic op mode.  The XOR pixel value will be applied
 * later in the OGLContext_SetColor() method.
 */
void
OGLContext_SetXorComposite(OGLContext *oglc, jint xorPixel)
{
    J2dTraceLn1(J2D_TRACE_INFO,
                "OGLContext_SetXorComposite: xorPixel=%08x", xorPixel);

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    // disable blending mode
    if (oglc->compState == sun_java2d_SunGraphics2D_COMP_ALPHA) {
        j2d_glDisable(GL_BLEND);
    }

    // enable XOR mode
    j2d_glEnable(GL_COLOR_LOGIC_OP);
    j2d_glLogicOp(GL_XOR);

    // set up the alpha test so that we discard transparent fragments (this
    // is primarily useful for rendering text in XOR mode)
    j2d_glEnable(GL_ALPHA_TEST);
    j2d_glAlphaFunc(GL_NOTEQUAL, 0.0f);

    // update state
    oglc->compState = sun_java2d_SunGraphics2D_COMP_XOR;
    oglc->xorPixel = xorPixel;
    oglc->extraAlpha = 1.0f;
}

/**
 * Resets the OpenGL transform state back to the identity matrix.
 */
void
OGLContext_ResetTransform(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_ResetTransform");

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    j2d_glMatrixMode(GL_MODELVIEW);
    j2d_glLoadIdentity();
}

/**
 * Initializes the OpenGL transform state by setting the modelview transform
 * using the given matrix parameters.
 *
 * REMIND: it may be worthwhile to add serial id to AffineTransform, so we
 *         could do a quick check to see if the xform has changed since
 *         last time... a simple object compare won't suffice...
 */
void
OGLContext_SetTransform(OGLContext *oglc,
                        jdouble m00, jdouble m10,
                        jdouble m01, jdouble m11,
                        jdouble m02, jdouble m12)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_SetTransform");

    RETURN_IF_NULL(oglc);
    CHECK_PREVIOUS_OP(OGL_STATE_CHANGE);

    if (oglc->xformMatrix == NULL) {
        size_t arrsize = 16 * sizeof(GLdouble);
        oglc->xformMatrix = (GLdouble *)malloc(arrsize);
        memset(oglc->xformMatrix, 0, arrsize);
        oglc->xformMatrix[10] = 1.0;
        oglc->xformMatrix[15] = 1.0;
    }

    // copy values from AffineTransform object into native matrix array
    oglc->xformMatrix[0] = m00;
    oglc->xformMatrix[1] = m10;
    oglc->xformMatrix[4] = m01;
    oglc->xformMatrix[5] = m11;
    oglc->xformMatrix[12] = m02;
    oglc->xformMatrix[13] = m12;

    J2dTraceLn3(J2D_TRACE_VERBOSE, "  [%lf %lf %lf]",
                oglc->xformMatrix[0], oglc->xformMatrix[4],
                oglc->xformMatrix[12]);
    J2dTraceLn3(J2D_TRACE_VERBOSE, "  [%lf %lf %lf]",
                oglc->xformMatrix[1], oglc->xformMatrix[5],
                oglc->xformMatrix[13]);

    j2d_glMatrixMode(GL_MODELVIEW);
    j2d_glLoadMatrixd(oglc->xformMatrix);
}

/**
 * Creates a 2D texture of the given format and dimensions and returns the
 * texture object identifier.  This method is typically used to create a
 * temporary texture for intermediate work, such as in the
 * OGLContext_InitBlitTileTexture() method below.
 */
GLuint
OGLContext_CreateBlitTexture(GLenum internalFormat, GLenum pixelFormat,
                             GLuint width, GLuint height)
{
    GLuint texID;
    GLint sp, sr, rl, align;
    GLclampf priority = 1.0f;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_CreateBlitTexture");

    j2d_glGenTextures(1, &texID);
    j2d_glBindTexture(GL_TEXTURE_2D, texID);
    j2d_glPrioritizeTextures(1, &texID, &priority);
    j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    OGLSD_RESET_TEXTURE_WRAP(GL_TEXTURE_2D);

    // save pixel store parameters (since this method could be invoked after
    // the caller has already set up its pixel store parameters)
    j2d_glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &sp);
    j2d_glGetIntegerv(GL_UNPACK_SKIP_ROWS, &sr);
    j2d_glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rl);
    j2d_glGetIntegerv(GL_UNPACK_ALIGNMENT, &align);

    // set pixel store parameters to default values
    j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    j2d_glTexImage2D(GL_TEXTURE_2D, 0, internalFormat,
                     width, height, 0,
                     pixelFormat, GL_UNSIGNED_BYTE, NULL);

    // restore pixel store parameters
    j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, sp);
    j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, sr);
    j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, rl);
    j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, align);

    return texID;
}

/**
 * Initializes a small texture tile for use with tiled blit operations (see
 * OGLBlitLoops.c and OGLMaskBlit.c for usage examples).  The texture ID for
 * the tile is stored in the given OGLContext.  The tile is initially filled
 * with garbage values, but the tile is updated as needed (via
 * glTexSubImage2D()) with real RGBA values used in tiled blit situations.
 * The internal format for the texture is GL_RGBA8, which should be sufficient
 * for storing system memory surfaces of any known format (see PixelFormats
 * for a list of compatible surface formats).
 */
jboolean
OGLContext_InitBlitTileTexture(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_InitBlitTileTexture");

    oglc->blitTextureID =
        OGLContext_CreateBlitTexture(GL_RGBA8, GL_RGBA,
                                     OGLC_BLIT_TILE_SIZE,
                                     OGLC_BLIT_TILE_SIZE);

    return JNI_TRUE;
}

/**
 * Destroys the OpenGL resources associated with the given OGLContext.
 * It is required that the native context associated with the OGLContext
 * be made current prior to calling this method.
 */
void
OGLContext_DestroyContextResources(OGLContext *oglc)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_DestroyContextResources");

    if (oglc->xformMatrix != NULL) {
        free(oglc->xformMatrix);
    }

    if (oglc->blitTextureID != 0) {
        j2d_glDeleteTextures(1, &oglc->blitTextureID);
    }
}

/**
 * Returns JNI_TRUE if the given extension name is available for the current
 * GraphicsConfig; JNI_FALSE otherwise.  An extension is considered available
 * if its identifier string is found amongst the space-delimited GL_EXTENSIONS
 * string.
 *
 * Adapted from the OpenGL Red Book, pg. 506.
 */
jboolean
OGLContext_IsExtensionAvailable(const char *extString, char *extName)
{
    jboolean ret = JNI_FALSE;
    char *p = (char *)extString;
    char *end;

    if (extString == NULL) {
        J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsExtensionAvailable");
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_IsExtensionAvailable: extension string is null");
        return JNI_FALSE;
    }

    end = p + strlen(p);

    while (p < end) {
        size_t n = strcspn(p, " ");

        if ((strlen(extName) == n) && (strncmp(extName, p, n) == 0)) {
            ret = JNI_TRUE;
            break;
        }

        p += (n + 1);
    }

    J2dRlsTraceLn2(J2D_TRACE_INFO,
                   "OGLContext_IsExtensionAvailable: %s=%s",
                   extName, ret ? "true" : "false");

    return ret;
}

/**
 * Returns JNI_TRUE only if all of the following conditions are met:
 *   - the GL_EXT_framebuffer_object extension is available
 *   - FBO support has been enabled via the system property
 *   - we can successfully create an FBO with depth capabilities
 */
static jboolean
OGLContext_IsFBObjectExtensionAvailable(JNIEnv *env,
                                        const char *extString)
{
    jboolean isFBObjectEnabled = JNI_FALSE;
    GLuint fbobjectID, textureID, depthID;
    jint width = 1, height = 1;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsFBObjectExtensionAvailable");

    // first see if the fbobject extension is available
    if (!OGLContext_IsExtensionAvailable(extString,
                                         "GL_EXT_framebuffer_object"))
    {
        return JNI_FALSE;
    }

    // next see if the fbobject system property has been enabled
    isFBObjectEnabled =
        JNU_GetStaticFieldByName(env, NULL,
                                 "sun/java2d/opengl/OGLSurfaceData",
                                 "isFBObjectEnabled", "Z").z;
    if (!isFBObjectEnabled) {
        J2dRlsTraceLn(J2D_TRACE_INFO,
            "OGLContext_IsFBObjectExtensionAvailable: disabled via flag");
        return JNI_FALSE;
    }

    // finally, create a dummy fbobject with depth capabilities to see
    // if this configuration is supported by the drivers/hardware
    // (first we initialize a color texture object that will be used to
    // construct the dummy fbobject)
    j2d_glGenTextures(1, &textureID);
    j2d_glBindTexture(GL_TEXTURE_2D, textureID);
    j2d_glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                     width, height, 0,
                     GL_RGB, GL_UNSIGNED_BYTE, NULL);
    j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    // initialize framebuffer object using color texture created above
    if (!OGLSD_InitFBObject(&fbobjectID, &depthID,
                            textureID, GL_TEXTURE_2D,
                            width, height))
    {
        J2dRlsTraceLn(J2D_TRACE_INFO,
            "OGLContext_IsFBObjectExtensionAvailable: fbobject unsupported");
        j2d_glDeleteTextures(1, &textureID);
        return JNI_FALSE;
    }

    // delete the temporary resources
    j2d_glDeleteTextures(1, &textureID);
    j2d_glDeleteRenderbuffersEXT(1, &depthID);
    j2d_glDeleteFramebuffersEXT(1, &fbobjectID);

    J2dRlsTraceLn(J2D_TRACE_INFO,
        "OGLContext_IsFBObjectExtensionAvailable: fbobject supported");

    return JNI_TRUE;
}

/**
 * Returns JNI_TRUE only if all of the following conditions are met:
 *   - the GL_ARB_fragment_shader extension is available
 *   - the LCD text shader codepath has been enabled via the system property
 *   - the hardware supports the minimum number of texture units
 */
static jboolean
OGLContext_IsLCDShaderSupportAvailable(JNIEnv *env,
                                       jboolean fragShaderAvailable)
{
    jboolean isLCDShaderEnabled = JNI_FALSE;
    GLint maxTexUnits;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsLCDShaderSupportAvailable");

    // first see if the fragment shader extension is available
    if (!fragShaderAvailable) {
        return JNI_FALSE;
    }

    // next see if the lcdshader system property has been enabled
    isLCDShaderEnabled =
        JNU_GetStaticFieldByName(env, NULL,
                                 "sun/java2d/opengl/OGLSurfaceData",
                                 "isLCDShaderEnabled", "Z").z;
    if (!isLCDShaderEnabled) {
        J2dRlsTraceLn(J2D_TRACE_INFO,
            "OGLContext_IsLCDShaderSupportAvailable: disabled via flag");
        return JNI_FALSE;
    }

    // finally, check to see if the hardware supports the required number
    // of texture units
    j2d_glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &maxTexUnits);
    if (maxTexUnits < 4) {
        J2dRlsTraceLn1(J2D_TRACE_INFO,
          "OGLContext_IsLCDShaderSupportAvailable: not enough tex units (%d)",
          maxTexUnits);
    }

    J2dRlsTraceLn(J2D_TRACE_INFO,
        "OGLContext_IsLCDShaderSupportAvailable: LCD text shader supported");

    return JNI_TRUE;
}

/**
 * Returns JNI_TRUE only if all of the following conditions are met:
 *   - the GL_ARB_fragment_shader extension is available
 *   - the BufferedImageOp shader codepath has been enabled via the
 *     system property
 */
static jboolean
OGLContext_IsBIOpShaderSupportAvailable(JNIEnv *env,
                                        jboolean fragShaderAvailable)
{
    jboolean isBIOpShaderEnabled = JNI_FALSE;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsBIOpShaderSupportAvailable");

    // first see if the fragment shader extension is available
    if (!fragShaderAvailable) {
        return JNI_FALSE;
    }

    // next see if the biopshader system property has been enabled
    isBIOpShaderEnabled =
        JNU_GetStaticFieldByName(env, NULL,
                                 "sun/java2d/opengl/OGLSurfaceData",
                                 "isBIOpShaderEnabled", "Z").z;
    if (!isBIOpShaderEnabled) {
        J2dRlsTraceLn(J2D_TRACE_INFO,
            "OGLContext_IsBIOpShaderSupportAvailable: disabled via flag");
        return JNI_FALSE;
    }

    /*
     * Note: In theory we should probably do some other checks here, like
     * linking a sample shader to see if the hardware truly supports our
     * shader programs.  However, our current BufferedImageOp shaders were
     * designed to support first-generation shader-level hardware, so the
     * assumption is that if our shaders work on those GPUs, then they'll
     * work on newer ones as well.  Also, linking a fragment program can
     * cost valuable CPU cycles, which is another reason to avoid these
     * checks at startup.
     */

    J2dRlsTraceLn(J2D_TRACE_INFO,
        "OGLContext_IsBIOpShaderSupportAvailable: BufferedImageOp shader supported");

    return JNI_TRUE;
}

/**
 * Returns JNI_TRUE only if all of the following conditions are met:
 *   - the GL_ARB_fragment_shader extension is available
 *   - the Linear/RadialGradientPaint shader codepath has been enabled via the
 *     system property
 */
static jboolean
OGLContext_IsGradShaderSupportAvailable(JNIEnv *env,
                                        jboolean fragShaderAvailable)
{
    jboolean isGradShaderEnabled = JNI_FALSE;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsGradShaderSupportAvailable");

    // first see if the fragment shader extension is available
    if (!fragShaderAvailable) {
        return JNI_FALSE;
    }

    // next see if the gradshader system property has been enabled
    isGradShaderEnabled =
        JNU_GetStaticFieldByName(env, NULL,
                                 "sun/java2d/opengl/OGLSurfaceData",
                                 "isGradShaderEnabled", "Z").z;
    if (!isGradShaderEnabled) {
        J2dRlsTraceLn(J2D_TRACE_INFO,
            "OGLContext_IsGradShaderSupportAvailable: disabled via flag");
        return JNI_FALSE;
    }

    J2dRlsTraceLn(J2D_TRACE_INFO,
        "OGLContext_IsGradShaderSupportAvailable: Linear/RadialGradientPaint shader supported");

    return JNI_TRUE;
}

/**
 * Checks for the presence of the optional extensions used by
 * the Java 2D OpenGL pipeline.  The given caps bitfield is updated
 * to reflect the availability of these extensions.
 */
void
OGLContext_GetExtensionInfo(JNIEnv *env, jint *caps)
{
    jint vcap = OGLC_VENDOR_OTHER;
    const char *vendor = (char *)j2d_glGetString(GL_VENDOR);
    const char *e = (char *)j2d_glGetString(GL_EXTENSIONS);
    jboolean fragShaderAvail =
        OGLContext_IsExtensionAvailable(e, "GL_ARB_fragment_shader");

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_GetExtensionInfo");

    if (OGLContext_IsExtensionAvailable(e, "GL_ARB_multitexture")) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_MULTITEXTURE;
    }
    if (OGLContext_IsExtensionAvailable(e, "GL_ARB_texture_non_power_of_two")){
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_TEXNONPOW2;
    }
    if (OGLContext_IsExtensionAvailable(e, "GL_ARB_texture_rectangle")) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_TEXRECT;
    }
    if (OGLContext_IsFBObjectExtensionAvailable(env, e)) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_FBOBJECT;
    }
    if (OGLContext_IsLCDShaderSupportAvailable(env, fragShaderAvail)) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_LCD_SHADER;
    }
    if (OGLContext_IsBIOpShaderSupportAvailable(env, fragShaderAvail)) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_BIOP_SHADER;
    }
    if (OGLContext_IsGradShaderSupportAvailable(env, fragShaderAvail)) {
        *caps |= sun_java2d_opengl_OGLContext_CAPS_EXT_GRAD_SHADER;
    }

    // stuff vendor descriptor in the upper bits of the caps
    if (vendor != NULL) {
        if (strncmp(vendor, "ATI", 3) == 0) {
            vcap = OGLC_VENDOR_ATI;
        } else if (strncmp(vendor, "NVIDIA", 6) == 0) {
            vcap = OGLC_VENDOR_NVIDIA;
        } else if (strncmp(vendor, "Sun", 3) == 0) {
            vcap = OGLC_VENDOR_SUN;
        }
    }
    *caps |= ((vcap & OGLC_VCAP_MASK) << OGLC_VCAP_OFFSET);
}

/**
 * Returns JNI_TRUE if the given GL_VERSION string meets the minimum
 * requirements (>= 1.2); JNI_FALSE otherwise.
 */
jboolean
OGLContext_IsVersionSupported(const unsigned char *versionstr)
{
    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_IsVersionSupported");

    if (versionstr == NULL) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_IsVersionSupported: version string is null");
        return JNI_FALSE;
    }

    // note that this check allows for OpenGL 2.x
    return ((versionstr[0] == '1' && versionstr[2] >= '2') ||
            (versionstr[0] >= '2'));
}

/**
 * Compiles and links the given fragment shader program.  If
 * successful, this function returns a handle to the newly created shader
 * program; otherwise returns 0.
 */
GLhandleARB
OGLContext_CreateFragmentProgram(const char *fragmentShaderSource)
{
    GLhandleARB fragmentShader, fragmentProgram;
    GLint success;
    int infoLogLength = 0;

    J2dTraceLn(J2D_TRACE_INFO, "OGLContext_CreateFragmentProgram");

    // create the shader object and compile the shader source code
    fragmentShader = j2d_glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
    j2d_glShaderSourceARB(fragmentShader, 1, &fragmentShaderSource, NULL);
    j2d_glCompileShaderARB(fragmentShader);
    j2d_glGetObjectParameterivARB(fragmentShader,
                                  GL_OBJECT_COMPILE_STATUS_ARB,
                                  &success);

    // print the compiler messages, if necessary
    j2d_glGetObjectParameterivARB(fragmentShader,
                                  GL_OBJECT_INFO_LOG_LENGTH_ARB,
                                  &infoLogLength);
    if (infoLogLength > 1) {
        char infoLog[1024];
        j2d_glGetInfoLogARB(fragmentShader, 1024, NULL, infoLog);
        J2dRlsTraceLn2(J2D_TRACE_WARNING,
            "OGLContext_CreateFragmentProgram: compiler msg (%d):\n%s",
                       infoLogLength, infoLog);
    }

    if (!success) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_CreateFragmentProgram: error compiling shader");
        j2d_glDeleteObjectARB(fragmentShader);
        return 0;
    }

    // create the program object and attach it to the shader
    fragmentProgram = j2d_glCreateProgramObjectARB();
    j2d_glAttachObjectARB(fragmentProgram, fragmentShader);

    // it is now safe to delete the shader object
    j2d_glDeleteObjectARB(fragmentShader);

    // link the program
    j2d_glLinkProgramARB(fragmentProgram);
    j2d_glGetObjectParameterivARB(fragmentProgram,
                                  GL_OBJECT_LINK_STATUS_ARB,
                                  &success);

    // print the linker messages, if necessary
    j2d_glGetObjectParameterivARB(fragmentProgram,
                                  GL_OBJECT_INFO_LOG_LENGTH_ARB,
                                  &infoLogLength);
    if (infoLogLength > 1) {
        char infoLog[1024];
        j2d_glGetInfoLogARB(fragmentProgram, 1024, NULL, infoLog);
        J2dRlsTraceLn2(J2D_TRACE_WARNING,
            "OGLContext_CreateFragmentProgram: linker msg (%d):\n%s",
                       infoLogLength, infoLog);
    }

    if (!success) {
        J2dRlsTraceLn(J2D_TRACE_ERROR,
            "OGLContext_CreateFragmentProgram: error linking shader");
        j2d_glDeleteObjectARB(fragmentProgram);
        return 0;
    }

    return fragmentProgram;
}

#endif /* !HEADLESS */


text:
v0.5.6

  * add reporters spec, list, tap

v0.5.5

  * support coffee-script
  * support file with shebang `#!/usr/bin/node`

v0.5.2

  * fix require() patch, loading `.json`, `.node` module now is fine
  * fix out reporter: summary
  * fix --coverage param:  --coverage 80,85,95
  * fix parse .covignore bug


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.cmmn.engine.impl.runtime;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.flowable.cmmn.api.migration.ActivatePlanItemDefinitionMapping;
import org.flowable.cmmn.api.migration.MoveToAvailablePlanItemDefinitionMapping;
import org.flowable.cmmn.api.migration.RemoveWaitingForRepetitionPlanItemDefinitionMapping;
import org.flowable.cmmn.api.migration.TerminatePlanItemDefinitionMapping;
import org.flowable.cmmn.api.migration.WaitingForRepetitionPlanItemDefinitionMapping;
import org.flowable.cmmn.api.repository.CaseDefinition;
import org.flowable.cmmn.api.runtime.PlanItemInstanceState;
import org.flowable.cmmn.engine.impl.persistence.entity.PlanItemInstanceEntity;

public class CaseInstanceChangeState {

    protected String caseInstanceId;
    protected CaseDefinition caseDefinitionToMigrateTo;
    protected Map<String, Object> caseVariables = new HashMap<>();
    protected Map<String, List<PlanItemInstanceEntity>> currentPlanItemInstances;
    protected Set<ActivatePlanItemDefinitionMapping> activatePlanItemDefinitions;
    protected Set<MoveToAvailablePlanItemDefinitionMapping> changePlanItemToAvailables;
    protected Set<TerminatePlanItemDefinitionMapping> terminatePlanItemDefinitions;
    protected Set<WaitingForRepetitionPlanItemDefinitionMapping> waitingForRepetitionPlanItemDefinitions;
    protected Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> removeWaitingForRepetitionPlanItemDefinitions;
    protected Map<String, Map<String, Object>> childInstanceTaskVariables = new HashMap<>();
    protected Map<String, PlanItemInstanceEntity> createdStageInstances = new HashMap<>();
    protected Map<String, PlanItemInstanceEntity> terminatedPlanItemInstances = new HashMap<>();

    public CaseInstanceChangeState() {
    }

    public String getCaseInstanceId() {
        return caseInstanceId;
    }

    public CaseInstanceChangeState setCaseInstanceId(String caseInstanceId) {
        this.caseInstanceId = caseInstanceId;
        return this;
    }

    public CaseDefinition getCaseDefinitionToMigrateTo() {
        return caseDefinitionToMigrateTo;
    }

    public CaseInstanceChangeState setCaseDefinitionToMigrateTo(CaseDefinition caseDefinitionToMigrateTo) {
        this.caseDefinitionToMigrateTo = caseDefinitionToMigrateTo;
        return this;
    }

    public Map<String, Object> getCaseVariables() {
        return caseVariables;
    }

    public CaseInstanceChangeState setCaseVariables(Map<String, Object> caseVariables) {
        this.caseVariables = caseVariables;
        return this;
    }

    public Map<String, List<PlanItemInstanceEntity>> getCurrentPlanItemInstances() {
        return currentPlanItemInstances;
    }

    public void setCurrentPlanItemInstances(Map<String, List<PlanItemInstanceEntity>> currentPlanItemInstances) {
        this.currentPlanItemInstances = currentPlanItemInstances;
    }

    public PlanItemInstanceEntity getRuntimePlanItemInstance(String planItemDefinitionId) {
        if (currentPlanItemInstances != null && currentPlanItemInstances.containsKey(planItemDefinitionId)) {
            List<PlanItemInstanceEntity> currentPlanItemInstanceList = currentPlanItemInstances.get(planItemDefinitionId);
            for (PlanItemInstanceEntity planItemInstance : currentPlanItemInstanceList) {
                if (!PlanItemInstanceState.TERMINAL_STATES.contains(planItemInstance.getState())) {
                    return planItemInstance;
                }
            }
        }

        return null;
    }

    public Map<String, List<PlanItemInstanceEntity>> getActivePlanItemInstances() {
        Map<String, List<PlanItemInstanceEntity>> activePlanItemInstanceMap = new HashMap<>();
        if (currentPlanItemInstances != null) {
            for (String planItemDefinitionId : currentPlanItemInstances.keySet()) {
                List<PlanItemInstanceEntity> planItemInstances = currentPlanItemInstances.get(planItemDefinitionId);
                List<PlanItemInstanceEntity> activePlanItemInstances = null;
                for (PlanItemInstanceEntity planItemInstance : planItemInstances) {
                    if (PlanItemInstanceState.ACTIVE_STATES.contains(planItemInstance.getState())) {
                        if (activePlanItemInstances == null) {
                            activePlanItemInstances = new ArrayList<>();
                        }

                        activePlanItemInstances.add(planItemInstance);
                    }
                }

                if (activePlanItemInstances != null) {
                    activePlanItemInstanceMap.put(planItemDefinitionId, activePlanItemInstances);
                }
            }
        }

        return activePlanItemInstanceMap;
    }

    public Map<String, List<PlanItemInstanceEntity>> getRuntimePlanItemInstances() {
        Map<String, List<PlanItemInstanceEntity>> runtimePlanItemInstanceMap = new HashMap<>();
        if (currentPlanItemInstances != null) {
            for (String planItemDefinitionId : currentPlanItemInstances.keySet()) {
                List<PlanItemInstanceEntity> planItemInstances = currentPlanItemInstances.get(planItemDefinitionId);
                List<PlanItemInstanceEntity> runtimePlanItemInstances = null;
                for (PlanItemInstanceEntity planItemInstance : planItemInstances) {
                    if (!PlanItemInstanceState.TERMINAL_STATES.contains(planItemInstance.getState())) {
                        if (runtimePlanItemInstances == null) {
                            runtimePlanItemInstances = new ArrayList<>();
                        }

                        runtimePlanItemInstances.add(planItemInstance);
                    }
                }

                if (runtimePlanItemInstances != null) {
                    runtimePlanItemInstanceMap.put(planItemDefinitionId, runtimePlanItemInstances);
                }
            }
        }

        return runtimePlanItemInstanceMap;
    }

    public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() {
        return activatePlanItemDefinitions;
    }

    public CaseInstanceChangeState setActivatePlanItemDefinitions(Set<ActivatePlanItemDefinitionMapping> planItemDefinitionMappings) {
        this.activatePlanItemDefinitions = planItemDefinitionMappings;
        return this;
    }

    public Set<MoveToAvailablePlanItemDefinitionMapping> getChangePlanItemDefinitionsToAvailable() {
        return changePlanItemToAvailables;
    }

    public CaseInstanceChangeState setChangePlanItemDefinitionsToAvailable(Set<MoveToAvailablePlanItemDefinitionMapping> planItemDefinitionMappings) {
        this.changePlanItemToAvailables = planItemDefinitionMappings;
        return this;
    }

    public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() {
        return terminatePlanItemDefinitions;
    }

    public CaseInstanceChangeState setTerminatePlanItemDefinitions(Set<TerminatePlanItemDefinitionMapping> planItemDefinitionMappings) {
        this.terminatePlanItemDefinitions = planItemDefinitionMappings;
        return this;
    }

    public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() {
        return waitingForRepetitionPlanItemDefinitions;
    }

    public CaseInstanceChangeState setWaitingForRepetitionPlanItemDefinitions(Set<WaitingForRepetitionPlanItemDefinitionMapping> waitingForRepetitionPlanItemDefinitions) {
        this.waitingForRepetitionPlanItemDefinitions = waitingForRepetitionPlanItemDefinitions;
        return this;
    }

    public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() {
        return removeWaitingForRepetitionPlanItemDefinitions;
    }

    public CaseInstanceChangeState setRemoveWaitingForRepetitionPlanItemDefinitions(Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> removeWaitingForRepetitionPlanItemDefinitions) {
        this.removeWaitingForRepetitionPlanItemDefinitions = removeWaitingForRepetitionPlanItemDefinitions;
        return this;
    }

    public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
        return childInstanceTaskVariables;
    }

    public CaseInstanceChangeState setChildInstanceTaskVariables(Map<String, Map<String, Object>> childInstanceTaskVariables) {
        this.childInstanceTaskVariables = childInstanceTaskVariables;
        return this;
    }

    public Map<String, PlanItemInstanceEntity> getCreatedStageInstances() {
        return createdStageInstances;
    }

    public CaseInstanceChangeState setCreatedStageInstances(HashMap<String, PlanItemInstanceEntity> createdStageInstances) {
        this.createdStageInstances = createdStageInstances;
        return this;
    }

    public void addCreatedStageInstance(String key, PlanItemInstanceEntity planItemInstance) {
        this.createdStageInstances.put(key, planItemInstance);
    }

    public Map<String, PlanItemInstanceEntity> getTerminatedPlanItemInstances() {
        return terminatedPlanItemInstances;
    }

    public CaseInstanceChangeState setTerminatedPlanItemInstances(HashMap<String, PlanItemInstanceEntity> terminatedPlanItemInstances) {
        this.terminatedPlanItemInstances = terminatedPlanItemInstances;
        return this;
    }

    public void addTerminatedPlanItemInstance(String key, PlanItemInstanceEntity planItemInstance) {
        this.terminatedPlanItemInstances.put(key, planItemInstance);
    }
}


text:
import threading
import time
import datetime
from assistant import Assistant as TestEquipment
from target import TARGET
import subprocess

class TPlanMessageHandler():
    """
     This class handle messages from UI
    """

    def __init__(self, bridge):

        self.bridge = bridge
        self.stop_event = threading.Event()
        self.dev = TestEquipment(self.on_dev_disconnected)

        self.exit_auto = threading.Event()

        self.message_thread = threading.Thread(target=self.handle_message)

    def run_auto_test(self):

        while not self.exit_auto.is_set():
            targets = self.dev.wait_for_target(2)
            if not targets:
                continue

            board = self.bridge.getBoard()
            target = TARGET[board](self.dev)
            self.bridge.log('\n============= search target =============')
            start_time = datetime.datetime.now()
            mask = 0
            for i in range(4):
                if targets & (1 << i):
                    self.bridge.log('find target %d' % (i + 1))
                    self.bridge.setBoardState(i, 1)
                else:
                    self.bridge.setBoardState(i, 0)

            mask = targets
            for i in range(4):
                if mask & (1 << i) == 0:
                    continue

                self.dev.select_target(i)

                time.sleep(0.1)
                # To do

                self.bridge.log('----------- test target %d -----------' % (i + 1))
                print('......... test target %d .........' % (i + 1))

                try:
                    has_error = False
                    while True:
                        if target.find_device():
                            self.bridge.log('skip writing interface firmware')
                        else:
                            self.bridge.log('write interface firmware...')
                            if target.write_interface():
                                has_error = True
                                break

                        self.bridge.log('write bootloader...')
                        if target.write_bootloader():
                            has_error = True
                            break

                        self.bridge.log('write test program...')
                        if target.write_test():
                            has_error = True
                            break

                        self.bridge.log('ok')
                        time.sleep(2)
                        self.bridge.log('read test result...')
                        io_result, io_result_description, voltage_result, voltage_result_description = target.test()
                        if io_result:
                            self.bridge.log('IO test: ok')
                        else:
                            self.bridge.log('IO test: failed')
                            self.bridge.log(io_result_description)

                            has_error = True
                            break

                        if voltage_result:
                            self.bridge.log('Voltage test: ok')
                        else:
                            self.bridge.log('Voltage test: failed')
                            self.bridge.log(voltage_result_description)

                            has_error = True
                            break

                        # self.bridge.log('write product program...')
                        # target.write_product()

                        break

                    if has_error:
                        self.bridge.log('failed')
                        self.bridge.setBoardState(i, 3)
                    else:
                        self.bridge.log('......... test target %d done .........' % (i + 1))
                        self.bridge.setBoardState(i, 2)
                except subprocess.CalledProcessError as e:
                    self.bridge.log('failed')
                    self.bridge.log(e)
                    self.bridge.setBoardState(i, 3)

                self.dev.power_off_targets(i)

            end_time = datetime.datetime.now()
            self.bridge.log('\ntime lapsed: %d' % (end_time - start_time).seconds)

    def handle_message(self):
        while True:
            message = self.bridge.get()
            print(message)
            if message == 'start':
                if self.dev.connect():
                    self.auto_test_thread = threading.Thread(target=self.run_auto_test)
                    self.exit_auto.clear()
                    self.auto_test_thread.start()
            elif message == 'stop':
                self.exit_auto.set()
            elif message == 'quit':
                self.exit_auto.set()
                self.stop_event.set()
                break
            else:
                if self.dev.connect():
                    board = self.bridge.getBoard()
                    target = TARGET[board](self.dev)
                    index = self.bridge.getBoardId() - 1
                    self.dev.select_target(index)
                    time.sleep(3)
                    self.bridge.log('-------- %s --------' % message)
                    try:
                        has_error = False
                        if message == 'write interface':
                            if target.write_interface():
                                has_error = True
                        elif message == 'write bootloader':
                            if target.write_bootloader():
                                has_error = True
                        elif message == 'write program':
                            if target.write_test():
                                has_error = True
                        elif message == 'test target':
                            io_result, io_result_description, voltage_result, voltage_result_description = target.test()
                            if not io_result:
                                self.bridge.log('IO test: failed')
                                self.bridge.log(io_result_description)

                                has_error = True

                            if not voltage_result:
                                self.bridge.log('Voltage test: failed')
                                self.bridge.log(voltage_result_description)

                                has_error = True
                        elif message == 'write product':
                            target.write_product()

                        if has_error:
                            self.bridge.log('failed')
                        else:
                            self.bridge.log('ok')
                    except subprocess.CalledProcessError as e:
                        self.bridge.log('failed')
                        self.bridge.log(e)

                        # self.dev.deselect_target(index)

    def start(self):
        self.message_thread.start()

    def join(self):
        self.exit_auto.set()
        self.stop_event.set()
        self.dev.disconnect()
        self.message_thread.join()

    def on_dev_disconnected(self):
        self.exit_auto.set()
        self.bridge.disconnect('device is disconnected')


text:
/*
 *  Super-Bits.com CODE CNPJ 20.019.971/0001-90

 */
package com.super_bits.modulosSB.webPaginas.controller.soap;

import com.super_bits.modulosSB.SBCore.modulos.Controller.SBWS_Client;
import com.super_bits.modulosSB.SBCore.modulos.TratamentoDeErros.FabErro;
import javax.xml.ws.Endpoint;

/**
 *
 * @author Salvio
 */
public abstract class SBWS_IO<T> extends SBWS_Client<T> {

    public static boolean ativo = false;

    public boolean ativaServidor(Class implementacaoWebservice) {

        try {
            try {
                System.out.println("iniciando publicação de " + getUrl());
                Endpoint.publish("http://" + getDnsName() + ":" + getporta().toString() + "/ws/" + getNomeServico(), implementacaoWebservice.newInstance());
                System.out.println("WebService Publicado em:" + getUrlWsdl());
                return true;

            } catch (InstantiationException e) {
                FabErro.SOLICITAR_REPARO.paraDesenvolvedor("Erro ao instanciar a Classe do servidor, certifique que a classe seja uma classe sem parametros de constructor e que implemente a Interface do webservice", e);
                return false;
            }
        } catch (Exception e) {
            FabErro.SOLICITAR_REPARO.paraDesenvolvedor("Erro ao iniciar WS Soap", e);
            return false;
        }

    }
}


text:
import sys

_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2

# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2

DESCRIPTOR = _descriptor.FileDescriptor(
    name="google/cloud/oslogin/common/common.proto",
    package="google.cloud.oslogin.common",
    syntax="proto3",
    serialized_pb=_b(
        '\n(google/cloud/oslogin/common/common.proto\x12\x1bgoogle.cloud.oslogin.common\x1a\x1cgoogle/api/annotations.proto"\xa8\x01\n\x0cPosixAccount\x12\x0f\n\x07primary\x18\x01 \x01(\x08\x12\x10\n\x08username\x18\x02 \x01(\t\x12\x0b\n\x03uid\x18\x03 \x01(\x03\x12\x0b\n\x03gid\x18\x04 \x01(\x03\x12\x16\n\x0ehome_directory\x18\x05 \x01(\t\x12\r\n\x05shell\x18\x06 \x01(\t\x12\r\n\x05gecos\x18\x07 \x01(\t\x12\x11\n\tsystem_id\x18\x08 \x01(\t\x12\x12\n\naccount_id\x18\t \x01(\t"N\n\x0cSshPublicKey\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x1c\n\x14\x65xpiration_time_usec\x18\x02 \x01(\x03\x12\x13\n\x0b\x66ingerprint\x18\x03 \x01(\tB\xae\x01\n\x1f\x63om.google.cloud.oslogin.commonB\x0cOsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\xaa\x02\x1bGoogle.Cloud.OsLogin.Common\xca\x02\x1bGoogle\\Cloud\\OsLogin\\Commonb\x06proto3'
    ),
    dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR],
)

_POSIXACCOUNT = _descriptor.Descriptor(
    name="PosixAccount",
    full_name="google.cloud.oslogin.common.PosixAccount",
    filename=None,
    file=DESCRIPTOR,
    containing_type=None,
    fields=[
        _descriptor.FieldDescriptor(
            name="primary",
            full_name="google.cloud.oslogin.common.PosixAccount.primary",
            index=0,
            number=1,
            type=8,
            cpp_type=7,
            label=1,
            has_default_value=False,
            default_value=False,
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="username",
            full_name="google.cloud.oslogin.common.PosixAccount.username",
            index=1,
            number=2,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="uid",
            full_name="google.cloud.oslogin.common.PosixAccount.uid",
            index=2,
            number=3,
            type=3,
            cpp_type=2,
            label=1,
            has_default_value=False,
            default_value=0,
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="gid",
            full_name="google.cloud.oslogin.common.PosixAccount.gid",
            index=3,
            number=4,
            type=3,
            cpp_type=2,
            label=1,
            has_default_value=False,
            default_value=0,
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="home_directory",
            full_name="google.cloud.oslogin.common.PosixAccount.home_directory",
            index=4,
            number=5,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="shell",
            full_name="google.cloud.oslogin.common.PosixAccount.shell",
            index=5,
            number=6,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="gecos",
            full_name="google.cloud.oslogin.common.PosixAccount.gecos",
            index=6,
            number=7,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="system_id",
            full_name="google.cloud.oslogin.common.PosixAccount.system_id",
            index=7,
            number=8,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="account_id",
            full_name="google.cloud.oslogin.common.PosixAccount.account_id",
            index=8,
            number=9,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
    ],
    extensions=[],
    nested_types=[],
    enum_types=[],
    options=None,
    is_extendable=False,
    syntax="proto3",
    extension_ranges=[],
    oneofs=[],
    serialized_start=104,
    serialized_end=272,
)

_SSHPUBLICKEY = _descriptor.Descriptor(
    name="SshPublicKey",
    full_name="google.cloud.oslogin.common.SshPublicKey",
    filename=None,
    file=DESCRIPTOR,
    containing_type=None,
    fields=[
        _descriptor.FieldDescriptor(
            name="key",
            full_name="google.cloud.oslogin.common.SshPublicKey.key",
            index=0,
            number=1,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="expiration_time_usec",
            full_name="google.cloud.oslogin.common.SshPublicKey.expiration_time_usec",
            index=1,
            number=2,
            type=3,
            cpp_type=2,
            label=1,
            has_default_value=False,
            default_value=0,
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
        _descriptor.FieldDescriptor(
            name="fingerprint",
            full_name="google.cloud.oslogin.common.SshPublicKey.fingerprint",
            index=2,
            number=3,
            type=9,
            cpp_type=9,
            label=1,
            has_default_value=False,
            default_value=_b("").decode("utf-8"),
            message_type=None,
            enum_type=None,
            containing_type=None,
            is_extension=False,
            extension_scope=None,
            options=None,
        ),
    ],
    extensions=[],
    nested_types=[],
    enum_types=[],
    options=None,
    is_extendable=False,
    syntax="proto3",
    extension_ranges=[],
    oneofs=[],
    serialized_start=274,
    serialized_end=352,
)

DESCRIPTOR.message_types_by_name["PosixAccount"] = _POSIXACCOUNT
DESCRIPTOR.message_types_by_name["SshPublicKey"] = _SSHPUBLICKEY
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

PosixAccount = _reflection.GeneratedProtocolMessageType(
    "PosixAccount",
    (_message.Message,),
    dict(
        DESCRIPTOR=_POSIXACCOUNT,
        __module__="google.cloud.oslogin.common.common_pb2",
        __doc__="""The POSIX account information associated with a Google account.

  Attributes:
      primary:
          Only one POSIX account can be marked as primary.
      username:
          The username of the POSIX account.
      uid:
          The user ID.
      gid:
          The default group ID.
      home_directory:
          The path to the home directory for this account.
      shell:
          The path to the logic shell for this account.
      gecos:
          The GECOS (user information) entry for this account.
      system_id:
          System identifier for which account the username or uid
          applies to. By default, the empty value is used.
      account_id:
          Output only. A POSIX account identifier.
  """,
        # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.PosixAccount)
    ),
)
_sym_db.RegisterMessage(PosixAccount)

SshPublicKey = _reflection.GeneratedProtocolMessageType(
    "SshPublicKey",
    (_message.Message,),
    dict(
        DESCRIPTOR=_SSHPUBLICKEY,
        __module__="google.cloud.oslogin.common.common_pb2",
        __doc__="""The SSH public key information associated with a Google account.

  Attributes:
      key:
          Public key text in SSH format, defined by RFC4253 section 6.6.
      expiration_time_usec:
          An expiration time in microseconds since epoch.
      fingerprint:
          Output only. The SHA-256 fingerprint of the SSH public key.
  """,
        # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.SshPublicKey)
    ),
)
_sym_db.RegisterMessage(SshPublicKey)

DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(
    descriptor_pb2.FileOptions(),
    _b(
        "\n\037com.google.cloud.oslogin.commonB\014OsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\252\002\033Google.Cloud.OsLogin.Common\312\002\033Google\\Cloud\\OsLogin\\Common"
    ),
)
# @@protoc_insertion_point(module_scope)


text:
require 'rack/ssl-enforcer'

class BaseApp < App
  use Rack::SslEnforcer, only_environments: 'production'

  set :public_folder, File.join(APP_ROOT, '..', 'public')
  set :views, File.join(APP_ROOT, 'app', 'views')

  set :assets_paths, %w(../../client/assets)
  set :assets_precompile, %w(*.css *.png *.svg)
  set :assets_host, "cdn.citylines.co"
  set :assets_protocol, :https

  register Sinatra::AssetPipeline

  helpers I18nHelpers
  helpers WebpackHelpers
  helpers SEOHelpers

  before do
    cache_control :no_store
    @locale = set_locale(params, request)
  end

  get '/robots.txt' do
    "Sitemap: #{AWS_HOST}sitemaps/sitemap.xml.gz"
  end

  # Pre-render title and description for Compare
  get '/compare' do
    @title, @description = compare_title_and_description(params)
    @url = canonical_url(request.url, allowed_params = ['cities', 'locale'])

    erb :index
  end

  # Pre-render title and description for Data
  get '/data' do
    @title, @description = data_title_and_description
    @url = canonical_url(request.url, allowed_params = ['locale'])

    erb :index
  end

  # Pre-render title and description for User
  get '/user/:user_id' do |user_id|
    if user = User[user_id]
      @title, @description = user_title_and_description(user)
    end

    @url = canonical_url(request.url, allowed_params = ['locale'])

    erb :index
  end

  # Pre-render title and description for cities and systems
  get '/:url_name' do |url_name|
    @url = canonical_url(request.url, allowed_params = ['system_id', 'locale'])

    @title, @description = if params[:system_id] and system = System[params[:system_id]]
                             system_title_and_description(system)
                           elsif city = City[url_name: url_name]
                             city_title_and_description(city)
                           else
                             title_and_description
                           end

    erb :index
  end

  get '/*' do
    @title, @description = title_and_description
    @url = canonical_url(request.url, allowed_params = ['locale'])

    erb :index
  end
end