Beispiel #1
0
    def test_datetime_with_time_zone(self):
        oldDefaultTimeZone = TimeZone.getDefault()
        try:
            TimeZone.setDefault(TimeZone.getTimeZone("GMT+4"))
            c = tWithDateTimeZCursor(self.context)

            zoneId = ZoneId.of("GMT+2")
            #This is the datetime we will insert
            localDateTime = LocalDateTime.of(2017, Month.DECEMBER, 31, 22, 0,
                                             0)
            zonedDateTime = ZonedDateTime.of(localDateTime, zoneId)
            #This is the datetime we expect the database to receive
            utcDateTime = LocalDateTime.of(2018, Month.JANUARY, 1, 0, 0, 0)

            c.eventDate = zonedDateTime
            c.insert()
            c.clear()

            c.first()

            zoneIdAfterSelect = ZoneId.of("GMT+4")
            self.assertEquals(utcDateTime, c.eventDate.toLocalDateTime())
            self.assertEquals(zoneIdAfterSelect, c.eventDate.getZone())

        finally:
            TimeZone.setDefault(oldDefaultTimeZone)
Beispiel #2
0
    def test_mat_view_date_rounding(self):
        tableCursor = table3Cursor(self.context)
        mViewCursor = mView4Cursor(self.context)

        tableCursor.deleteAll()
        self.assertEquals(0, mViewCursor.count())

        datetime1 = LocalDateTime.of(2000, Month.AUGUST, 5, 10, 5, 32)
        date1 = datetime1.truncatedTo(ChronoUnit.DAYS)

        tableCursor.numb = 5
        tableCursor.date = Timestamp.valueOf(datetime1)
        tableCursor.insert()
        tableCursor.clear()

        datetime2 = LocalDateTime.of(2000, Month.AUGUST, 5, 22, 5, 32)
        tableCursor.numb = 2
        tableCursor.date = Timestamp.valueOf(datetime2)
        tableCursor.insert()
        tableCursor.clear()

        datetime3 = LocalDateTime.of(2000, Month.AUGUST, 6, 10, 5, 32)
        date2 = datetime3.truncatedTo(ChronoUnit.DAYS)
        tableCursor.numb = 5
        tableCursor.date = Timestamp.valueOf(datetime3)
        tableCursor.insert()
        tableCursor.clear()

        self.assertEquals(2, mViewCursor.count())
        mViewCursor.get(Timestamp.valueOf(date1))
        self.assertEquals(7, mViewCursor.s)

        mViewCursor.get(Timestamp.valueOf(date2))
        self.assertEquals(5, mViewCursor.s)
Beispiel #3
0
 def onConfigure(self):
     self.withArgs([
         DateTimeType("dateTime").withDateTime().withMinValue(
             LocalDateTime.of(2020, 1, 1, 0, 0)).withMaxValue(
                 LocalDateTime.of(2030, 1, 1, 0, 0)),
         DateTimeType("dateTimeZone").withDateTimeZone(),
         DateTimeType("date").withDate().withFormat("yyyy-MM-dd"),
         DateTimeType("time").withTime().withFormat("HH:mm:ss"),
         DateTimeType("instant").withInstant()
     ]).withResult(ListType(DynamicType()))
Beispiel #4
0
    def test_getdate_in_view(self):
        tableCursor = getDateForViewCursor(self.context)
        tableCursor.deleteAll()

        viewCursor = viewWithGetDateCursor(self.context)
        self.assertEquals(0, viewCursor.count())

        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().minusDays(1))
        tableCursor.insert()
        self.assertEquals(0, viewCursor.count())

        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        tableCursor.insert()
        self.assertEquals(1, viewCursor.count())
Beispiel #5
0
def jdatetime(t):
    """
    Convert python date to joda DateTime.
    
    :param t: Python date
    
    :returns: Joda DateTime
    """
    if isinstance(t, (list, tuple)):
        r = []
        for tt in t:
            r.append(LocalDateTime.of(tt.year, tt.month, tt.day, tt.hour, tt.minute, tt.second, tt.microsecond / 1000))
        return r
    else:
        return LocalDateTime.of(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond / 1000)
Beispiel #6
0
    def _testInFilterWithAdditionalLookup(self, a, b, g):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)
        gTableCursor = gFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()
        gTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        self._fillTablesForTestInFilterWithRangeOnOtherCursor(aTableCursor, bTableCursor, timestamp)

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 5
        gTableCursor.num2 = -30
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 6
        gTableCursor.num2 = -40
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 1
        gTableCursor.num2 = -41
        gTableCursor.insert()
        gTableCursor.clear()

        gTableCursor.createDate = timestamp
        gTableCursor.num1 = 1
        gTableCursor.num2 = -42
        gTableCursor.insert()
        gTableCursor.clear()


        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")
        additionalLookup = lookup.and(g).add("date", "createDate").add("number1", "num1")

        self.assertEquals(3, a.count())

        b.setRange('numb2', -40)
        self.assertEquals(2, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)

        a.navigate('>')
        self.assertEquals(6, a.number1)
        self.assertEquals(-20, a.number2)

        g.setRange('num2', -30)
        self.assertEquals(1, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)
Beispiel #7
0
    def _testInFilterWithRangeInOtherCursorAfterSetIn(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        self._fillTablesForTestInFilterWithRangeOnOtherCursor(aTableCursor, bTableCursor, timestamp)


        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")

        self.assertEquals(3, a.count())

        b.setRange('numb2', -40)
        self.assertEquals(2, a.count())

        a.first()
        self.assertEquals(5, a.number1)
        self.assertEquals(-10, a.number2)

        a.navigate('>')
        self.assertEquals(6, a.number1)
        self.assertEquals(-20, a.number2)
Beispiel #8
0
    def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        status_attribute_value = userService.getCustomAttribute(find_user_by_uid, "gluuStatus")
        if status_attribute_value != None:
            user_status = status_attribute_value.getValue()
            if StringHelper.equals(user_status, "inactive"):
                print "Basic (lock account). Lock user. User '%s' locked already" % user_name
                return
        
        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "inactive")
        updated_user = userService.updateUser(find_user_by_uid)

        object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':'))

        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs")

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
    def unLockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService = CdiUtil.bean(CacheService)

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        object_to_store = json.dumps(
            {
                'locked': False,
                'created': LocalDateTime.now().toString()
            },
            separators=(',', ':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime),
                         "lock_user_" + user_name, object_to_store)

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus",
                                       "active")
        userService.setCustomAttribute(find_user_by_uid,
                                       self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)

        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
Beispiel #10
0
    def parse_local_date_time(self,t):
        '''
        Return LocalDateTime

        Input is a java.lang.String parsed to LocalDateTime
        '''
        return LocalDateTime.parse(t,self.fb)
Beispiel #11
0
    def _testInFilterForIndices(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        aTableCursor.date = timestamp
        aTableCursor.number1 = 5
        aTableCursor.number2 = -10
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = timestamp
        aTableCursor.number1 = 1
        aTableCursor.number2 = -20
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        aTableCursor.number2 = -30
        aTableCursor.insert()
        aTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 2
        bTableCursor.numb2 = -40
        bTableCursor.insert()
        bTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 5
        bTableCursor.numb2 = -50
        bTableCursor.insert()
        bTableCursor.clear()

        lookup = a.setIn(b).add("date", "created")
        self.assertEquals(2, a.count())

        lookup = a.setIn(b).add("date", "created").add("number1", "numb1")
        self.assertEquals(1, a.count())

        a.setIn(b).add("date", "created").add("number1", "numb1").add("number2", "numb2")
        self.assertEquals(0, a.count())
Beispiel #12
0
 def dt_gen(inc_days):
     with jvm():
         from java.time import LocalDateTime
         from java.time.format import DateTimeFormatter
         dt = LocalDateTime.of(2019, 11, 26, 16, 30, 0)
         dtfmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
         for inc in range(1, inc_days + 1):
             yield dt.plusDays(inc).format(dtfmt)
Beispiel #13
0
 def onCall(self, type):
     if type == "string":
         return DynamicValue("text", StringType())
     elif type == "boolean":
         return DynamicValue(True, BooleanType())
     elif type == "datetime":
         return DynamicValue(LocalDateTime.now(), DateTimeType().withTime().withFormat("HH:mm"))
     else:
         return None
Beispiel #14
0
 def onConfigure(self):
     self.withLabel("Action with a date/time argument")
     self.withArg(
         DateTimeType("dateTime").withDateTime().withFormat(
             "yyyy-MM-dd HH:mm").withMinValue(
                 LocalDateTime.of(2020, 1, 1, 0,
                                  0)).withLabel("Date and time"))
     self.withResult(StringType().withLabel("Formatted text"))
     self.withFeature("icon", "timer")
Beispiel #15
0
def jdate(t):
    """
    Convert python date to java LocalDateTime.
    
    :param t: Python date
    
    :returns: Java date
    """
    if isinstance(t, list):
        r = []
        for tt in t:
            t = LocalDateTime.of(tt.year, tt.month, tt.day, tt.hour, tt.minute, tt.second)
            #cal.set(Calendar.MILLISECOND, 0)
            r.append(t)
        return r
    else:
        t = LocalDateTime.of(t.year, t.month, t.day, t.hour, t.minute, t.second)
        #cal.set(Calendar.MILLISECOND, 0)
        return t
Beispiel #16
0
    def _testInFilterWithRangeInMainCursor(self, a, b):
        aTableCursor = aFilterCursor(self.context)
        bTableCursor = bFilterCursor(self.context)

        aTableCursor.deleteAll()
        bTableCursor.deleteAll()

        timestamp = Timestamp.valueOf(LocalDateTime.now())

        aTableCursor.date = timestamp
        aTableCursor.number1 = 5
        aTableCursor.number2 = -10
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = timestamp
        aTableCursor.number1 = 1
        aTableCursor.number2 = -20
        aTableCursor.insert()
        aTableCursor.clear()

        aTableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        aTableCursor.number2 = -30
        aTableCursor.insert()
        aTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 2
        bTableCursor.numb2 = -40
        bTableCursor.insert()
        bTableCursor.clear()

        bTableCursor.created = timestamp
        bTableCursor.numb1 = 5
        bTableCursor.numb2 = -50
        bTableCursor.insert()
        bTableCursor.clear()

        a.setRange('number1', 5)
        lookup = a.setIn(b).add("date", "created")
        self.assertEquals(1, a.count())
        a.first()
Beispiel #17
0
    def addLog(self, messageInfo, toolFlag, time, row, operationName):

        self.panel.getLogTableModel().getLogArray().add(
            Log(
                LocalDateTime.now(), self._callbacks.getToolName(toolFlag),
                self._callbacks.saveBuffersToTempFiles(messageInfo),
                self._helpers.analyzeRequest(messageInfo).getUrl(),
                self._helpers.analyzeResponse(
                    messageInfo.getResponse()).getStatusCode(), operationName,
                time))
        self.panel.getLogTableModel().fireTableRowsInserted(row, row)
Beispiel #18
0
    def test_getXRec(self):
        cursor = tXRecCursor(self.context)
        cursor.deleteAll()

        id = 1
        num = 10
        cost = 10.2
        title = 'product'
        isActive = True
        created = Timestamp.valueOf(
            LocalDateTime.of(2018, Month.of(1), 11, 19, 15))

        cursor.num = num
        cursor.cost = cost
        cursor.title = title
        cursor.isActive = isActive
        cursor.created = created

        xRec = cursor.getXRec()
        self._assertXRecCursorFields(xRec, None, None, None, None, None, None)
        cursor.insert()

        self._assertXRecCursorFields(xRec, None, None, None, None, None, None)
        cursor.clear()

        xRec = cursor.getXRec()
        self._assertXRecCursorFields(xRec, None, None, None, None, None, None)

        cursor.get(1)
        self._assertXRecCursorFields(xRec, id, num, cost, title, isActive,
                                     created)

        cursor.num = num + 1
        cursor.cost = cost + 1
        cursor.title = title + 'asd'
        cursor.isActive = False
        cursor.created = Timestamp.valueOf(
            LocalDateTime.of(2017, Month.of(1), 11, 19, 15))

        self._assertXRecCursorFields(xRec, id, num, cost, title, isActive,
                                     created)
Beispiel #19
0
    def onConfigure(self):
        self.withLabel("Type date-time arg action")
        self.withArgs([
            DateTimeType("arg").withLabel("Date-time non nullable").withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argNullable").withLabel("Date-time nullable").withNullable(),
            DateTimeType("argDefault").withLabel("Date-time with default").withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argReadOnlyNullable").withLabel("Date-time read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argReadOnlyNonNullable").withLabel("Date-time read only non nullable").withReadOnly()
                .withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),

            DateTimeType("argDate").withDate().withLabel("Date non nullable").withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateNullable").withDate().withLabel("Date nullable").withNullable(),
            DateTimeType("argDateDefault").withDate().withLabel("Date with default").withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateReadOnlyNullable").withDate().withLabel("Date read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateReadOnlyNonNullable").withDate().withLabel("Date read only non nullable").withReadOnly()
                .withDefaultValue(LocalDate.of(2020, 1, 1)),

            DateTimeType("argTime").withTime().withFormat("HH:mm").withLabel("Time non nullable").withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeNullable").withTime().withFormat("HH:mm").withLabel("Time nullable").withNullable(),
            DateTimeType("argTimeDefault").withTime().withFormat("HH:mm").withLabel("Time with default").withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeReadOnlyNullable").withTime().withFormat("HH:mm").withLabel("Time read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeReadOnlyNonNullable").withTime().withFormat("HH:mm").withLabel("Time read only non nullable").withReadOnly()
                .withDefaultValue(LocalTime.of(12, 0)),

            DateTimeType("argDateTimeZoneReadOnlyNullable").withDateTimeZone().withLabel("Date-time-zone read only nullable").withReadOnly().withNullable()
                .withDefaultValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit"))),
            DateTimeType("argDateTimeZoneReadOnlyNonNullable").withDateTimeZone().withLabel("Date-time-zone read only non nullable").withReadOnly()
                .withDefaultValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit"))),

            DateTimeType("argInstantReadOnlyNullable").withInstant().withLabel("Instant read only nullable").withReadOnly().withNullable()
                .withDefaultValue(Instant.now()),
            DateTimeType("argInstantReadOnlyNonNullable").withInstant().withLabel("Instant read only non nullable").withReadOnly()
                .withDefaultValue(Instant.now()),

            # DATE_TIME_ZONE and INSTANT editing is not supported yet.
        ]).withResult(StringType())
Beispiel #20
0
	def __init__(self,uuid,url,title,dateTime):    

		'''HistoryDataElements must have at least one UUID, URL, Title, & DateTime '''
		valid = (type(uuid) is UUID) and (isinstance(url,str))	and (isinstance(title,str)) and (type(dateTime) is LocalDateTime)

		if not valid:
			from InvalidHistoryDataElementException import InvalidHistoryDataElementException
			raise InvalidHistoryDataElementException()
		else:
			super(HistoryDataElement,self).add(0, uuid)
			super(HistoryDataElement,self).add(1, url)
			super(HistoryDataElement,self).add(2, title)
			super(HistoryDataElement,self).add(3, dateTime)
			print("Log: HistoryDataElement object constructed @ " +  str(LocalDateTime.now()) + " with UUID: " + str(self.get(0)))
Beispiel #21
0
    def test_count_with_getdate_condition(self):
        tableCursor = countGetDateCondCursor(self.context)
        tableCursor.deleteAll()

        viewCursor = viewCountGetDateCondCursor(self.context)
        viewCursor.first()
        self.assertEquals(0, viewCursor.c)

        tableCursor.insert()
        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(
            LocalDateTime.now().minusSeconds(2))
        tableCursor.insert()

        viewCursor.first()
        self.assertEquals(0, viewCursor.c)

        tableCursor.clear()
        tableCursor.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        tableCursor.insert()

        viewCursor.first()
        self.assertEquals(1, viewCursor.c)
Beispiel #22
0
 def onCall(self, type):
     if type == "nonNullable":
         return DynamicValue(LocalDateTime.of(2020, 1, 1, 12, 0), DateTimeType().withLabel("Date-time non nullable"))
     elif type == "nullable":
         return DynamicValue(None, DateTimeType().withLabel("Date-time nullable").withNullable())
     elif type == "readOnlyNullable":
         return DynamicValue(None, DateTimeType().withLabel("Date-time read only nullable").withReadOnly().withNullable())
     elif type == "readOnlyNonNullable":
         return DynamicValue(LocalDateTime.of(2020, 1, 1, 12, 0), DateTimeType().withLabel("Date-time read only non nullable").withReadOnly())
     if type == "dateNonNullable":
         return DynamicValue(LocalDate.of(2020, 1, 1), DateTimeType().withDate().withLabel("Date non nullable"))
     elif type == "dateNullable":
         return DynamicValue(None, DateTimeType().withDate().withLabel("Date nullable").withNullable())
     elif type == "dateReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withDate().withLabel("Date read only nullable").withReadOnly().withNullable())
     elif type == "dateReadOnlyNonNullable":
         return DynamicValue(LocalDate.of(2020, 1, 1), DateTimeType().withDate().withLabel("Date-time read only non nullable").withReadOnly())
     if type == "timeNonNullable":
         return DynamicValue(LocalTime.of(12, 0), DateTimeType().withTime().withFormat("HH:mm").withLabel("Time non nullable"))
     elif type == "timeNullable":
         return DynamicValue(None, DateTimeType().withTime().withFormat("HH:mm").withLabel("Time nullable").withNullable())
     elif type == "timeReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withTime().withFormat("HH:mm").withLabel("Time read only nullable").withReadOnly().withNullable())
     elif type == "timeReadOnlyNonNullable":
         return DynamicValue(LocalTime.of(12, 0), DateTimeType().withTime().withFormat("HH:mm").withLabel("Time read only non nullable").withReadOnly())
     if type == "dateTimeZoneReadOnlyNullable":
         return DynamicValue(None,
                             DateTimeType().withDateTimeZone().withLabel("Date-time-zone read only nullable").withReadOnly().withNullable())
     elif type == "dateTimeZoneReadOnlyNonNullable":
         return DynamicValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit")),
                             DateTimeType().withDateTimeZone().withLabel("Date-time-zone read only non nullable").withReadOnly())
     if type == "instantReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withInstant().withLabel("Instant read only nullable").withReadOnly().withNullable())
     elif type == "instantReadOnlyNonNullable":
         return DynamicValue(Instant.now(), DateTimeType().withInstant().withLabel("Instant read only non nullable").withReadOnly())
     else:
         return None
    def unLockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        object_to_store = json.dumps({'locked': False, 'created': LocalDateTime.now().toString()}, separators=(',',':'))
        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);

        userService.setCustomAttribute(find_user_by_uid, "gluuStatus", "active")
        userService.setCustomAttribute(find_user_by_uid, self.invalidLoginCountAttribute, None)
        updated_user = userService.updateUser(find_user_by_uid)


        print "Basic (lock account). Lock user. User '%s' unlocked" % user_name
Beispiel #24
0
def saveverifyfile(filename, vtables, times=None):
    """
    Save verification result cvs file.
    
    :param filename: (*string*) Output file name.
    :param vtables: (*list or VerifyTable*) Verification table list.
    :param times: (*list or datetime*) Times corresponding to virification tables.
    """
    if not isinstance(vtables, list):
        vtables = [vtables]
        if not times is None:
            times = [times]
    if times is None:
        VerifyStat.writeVerifyFile(vtables, filename)
    else:
        dates = []
        for t in times:
            d = LocalDateTime.of(t.year, t.month, t.day, t.hour, t.minute, t.second)
            dates.append(d)
        VerifyStat.writeVerifyFile(vtables, dates, filename)
Beispiel #25
0
    def _fillTablesForTestInFilterWithRangeOnOtherCursor(self, a, b, timestamp):
        a.date = timestamp
        a.number1 = 5
        a.number2 = -10
        a.insert()
        a.clear()

        a.date = timestamp
        a.number1 = 6
        a.number2 = -20
        a.insert()
        a.clear()

        a.date = timestamp
        a.number1 = 1
        a.number2 = -20
        a.insert()
        a.clear()

        a.date = Timestamp.valueOf(LocalDateTime.now().plusDays(1))
        a.number2 = -30
        a.insert()
        a.clear()

        b.created = timestamp
        b.numb1 = 6
        b.numb2 = -40
        b.insert()
        b.clear()

        b.created = timestamp
        b.numb1 = 5
        b.numb2 = -40
        b.insert()
        b.clear()

        b.created = timestamp
        b.numb1 = 1
        b.numb2 = -41
        b.insert()
        b.clear()
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)


            logged_in = False
            if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if logged_in:
                self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))
            else:
                countInvalidLoginArributeValue = self.getUserAttributeValue(user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % ( user_name, userSatus )

                countInvalidLogin = StringHelper.toInteger(countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % ( remainingAttempts, user_name )

                    self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(FacesMessage.SEVERITY_INFO, StringHelper.toString(remainingAttempts)+" more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and ((userSatus == None) or (userSatus == "active")):
                    print "Basic (lock account). Locking '%s' for '%s' seconds" % ( user_name, self.lockExpirationTime)
                    self.lockUser(user_name)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and userSatus == "inactive":
                    print "Basic (lock account). User '%s' is locked. Checking if we can unlock him" % user_name
                    
                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "Basic (lock account). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details['created']
                        user_lock_details_created_date = LocalDateTime.parse(user_lock_details_created, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(user_lock_details_created_date, LocalDateTime.now()).getSeconds()
                        print "Basic (lock account). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % ( user_name, user_lock_details_locked, user_lock_details_created, user_lock_details_created_diff )

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "Basic (lock account). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(0))
                        logged_in = authenticationService.authenticate(user_name, user_password)
                        if not logged_in:
                            # Update number of attempts 
                            self.setUserAttributeValue(user_name, self.invalidLoginCountAttribute, StringHelper.toString(1))
                            if self.maximumInvalidLoginAttemps == 1:
                                # Lock user if maximum count login attempts is 1 
                                self.lockUser(user_name)
                                return False


            return logged_in
        else:
            return False
Beispiel #27
0
    def show(self):
        #Root Pane
        root = VBox()
        #FXML Loader
        fxmlLoader = FXMLLoader()

        #TextArea
        from javafx.scene.control import TextArea
        textArea = TextArea("Loading . . .")

        #Configure Text Area
        textArea.setEditable(False)
        textArea.setPrefHeight(600)

        #Bottom Bar, Current Stylesheet
        if self.app.getCurrentTheme() == "Dark":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_dark.fxml").toURI().
                toURL())  #For some odd reason this is broken?
            bottom_bar = self.app.bottom_bar_dt
        elif self.app.getCurrentTheme() == "Light":
            fxmlLoader.setLocation(
                File("../resources/fxml/history_url_tab_light.fxml").toURI().
                toURL())
            bottom_bar = ImageView(
                Image(
                    String(
                        File('../resources/icons/bottom_bar_lt.png').toURI().
                        toString()), True))
        #Think about future themes
        else:
            pass

        #URL Bar
        try:
            url_bar = fxmlLoader.load(
            )  #BROKEN - For some reason this breaks after a couple toggles.
        except LoadException as e:
            print('Log: Exception: An FXML Load Exception has occured.' +
                  str(e.getCause()))

        #Add Children to root pane
        root.getChildren().addAll(url_bar, textArea, bottom_bar)

        #Fill Width, assume Theme of Main Stage
        root.setFillWidth(True)

        #Set scene, title
        scene = Scene(root, 1350, 625)

        #We are leaving the default controls for now.

        #Make sure the Text Area's scroll bar is always visible.
        scene.getStylesheets().add(
            File("../resources/themes/text-area_scroll-pane.css").toURI().
            toString())
        self.stage.setScene(scene)
        self.stage.setTitle("History - EmeraldFX")

        #Position History Stage
        self.stage.setX(self.app.getMainStage().getX())
        self.stage.setY(self.app.getMainStage().getY() + 52)

        #Display History Stage
        self.stage.show()

        #It is CSV, let us display as plain text.
        history_csv = File("../resources/history/HISTORY.csv")
        history_txt = File("../resources/history/HISTORY.txt")

        #Delete text copy if it exists
        history_txt.delete() if history_txt.exists() else None

        #Copy
        Files.copy(history_csv.toPath(), history_txt.toPath())

        #Prevent Resizing
        self.stage.setResizable(False)

        #Flush Stream
        self.BS.triggerHistoryWrite()

        #GetController instance
        controller = fxmlLoader.getController()
        ''' Failed Attempts '''

        #WebView
        # webView = WebView()
        #Grab Web Engine
        # webEng = webView.getEngine()
        #Enable JS
        # webEng.setJavaScriptEnabled(True)

        #Attempt #1 - Start scrolling from the bottom - FAILED
        # webEng.executeScript("window.scrollTo(" + "0" + ", " + "600" + ");")

        #Attempt #2 - Scroll Pane - FAILED
        # from javafx.scene.control import ScrollPane
        # wv_scroll = ScrollPane()
        # wv_scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS)
        # wv_scroll.setContent(webView)
        # wv_scroll.setFitToWidth(True)
        # wv_scroll.setFitToHeight(True)
        # wv_scroll.setVvalue(wv_scroll.getVmin())

        #Load History
        # try:
        # webEng.load(history_txt.toURI().toString())
        # except Exception as e:
        # print ('Log: Load Exception: Error Loading History: ' + str(e.getCause()))
        # return

        #Attempt #3 - Execute Script for Scroll Bar - FAILD
        # webEng.executeScript(
        # "function scrollDown() { window.scrollTo(0,400); }" +
        # "scrollDown();"
        # )

        #Set Position of Scroll Bar
        class AnonInnerCL_TA(ChangeListener):
            """Inner Class for Scrolling Down"""
            def __init__(self, textArea):
                self.textArea = textArea

            #@Override
            def changed(self, observable, old, new):
                if new > old:
                    from java.lang import Double
                    self.textArea.setScrollTop(Double.MAX_VALUE)
                else:
                    pass

        textArea.textProperty().addListener(AnonInnerCL_TA(textArea))

        #Show History after it is loaded
        if self.stage.isShowing(
        ):  #May or may not be broken. If there is litle to no delay, "Loading . . ." will not be noticed.
            #Load History on separate thread.
            #Clear initial text: Loading . . .
            textArea.clear()
            #Instantate Service
            service = HistoryService(history_txt, textArea)
            #Algorithm improved. Start service
            service.start()
        '''Add resources to controller'''
        #Theme Resources
        controller.addThemeResources(
            self.app.getMainStage(), self.stage,
            self.app.getMainStage().getScene(), self.app.getCurrentTheme(),
            textArea
        )  #(Stage mainStage, Stage histStage, Scene scene, String theme, TextArea textArea)
        #Clear Resource
        controller.addClearResources(self.BS.isHistoryCleared())  #(boolean)
        #Quit Resources
        controller.addQuitResources(
            self.app.getAllStages(),
            self.BS.getHistoryWriter())  #(List<Stages>, PrintWriter)
        #Media Resources
        MMC = self.app.getMediaControls()
        controller.addMediaResources(MMC)

        #Create Bidirectional Bindings between Main Stage's media controls and history's controls
        from javafx.beans.binding import Bindings

        MMC_IT = MMC.listIterator()
        HMC = controller.getMediaControls()

        #Set history media controls to current state
        class HMCC(Consumer):
            def __init__(self, MMC_IT):
                self.MMC_IT = MMC_IT

            #@Override
            def accept(self, button):
                button.setDisabled(MMC_IT.next().isDisabled())

        HMC.forEach(HMCC(MMC_IT))

        #Fails - first arg cannot be coerced into Consumer? Odd.
        # history_media_controls.forEach(lambda button: button.setDisabled( main_media_controls.forEach(lambda button: button.isDisabled()) ) )

        #Play
        #Won't work -- read only property does not inherit Property, seperate API.
        # Bindings.bindBidirectional(history_media_controls.get(0).disabledProperty(), main_media_controls[0].disabledProperty() )
        #Stop
        # Bindings.bindBidirectional(history_media_controls.get(1).disabledProperty(), main_media_controls[1].disabledProperty() )
        #Previous
        # Bindings.bindBidirectional(history_media_controls.get(2).disabledProperty(), main_media_controls[2].disabledProperty() )
        #Next
        # Bindings.bindBidirectional(history_media_controls.get(3).disabledProperty(), main_media_controls[3].disabledProperty() )

        #Shortcut Keys Allowed for History (CTRL + D, CTRL + Q, CTRL + T)
        scene.addEventFilter(
            KeyEvent.KEY_PRESSED, lambda event: self.handleHistoryShortcuts(
                event, self.BS, controller.getToggleTheme(),
                controller.getClearHistory()))

        #Python needs to fix lambdas so we don't have to resort to wrapping inner classes in collections. Yuck.
        class HistoryClosed:
            @staticmethod
            def printClosed():
                print("Log: Quit Action: History just closed.")

        #Switch back to the main stage
        self.stage.setOnCloseRequest(lambda event: [
            self.app.getMainStage().toFront(),
            self.stage.close(),
            HistoryClosed.printClosed()
        ])

        #Log
        print('Log: History Notification: History data displayed @ ' +
              str(LocalDateTime.now()))
Beispiel #28
0
from mil.army.usace.hec.vortex.math import Normalizer
from mil.army.usace.hec.vortex.io import DataReader

from java.time import ZonedDateTime
from java.time import LocalDateTime
from java.time import ZoneId
from java.time import Duration

source = "C:/Temp/qpe.dss"
normals = "C:/Temp/prism.dss"

sourceGrids = DataReader.getVariables(source)
normalGrids = DataReader.getVariables(normals)

start = ZonedDateTime.of(LocalDateTime.of(2017, 1, 1, 0, 0), ZoneId.of("UTC"))
end = ZonedDateTime.of(LocalDateTime.of(2017, 1, 3, 0, 0), ZoneId.of("UTC"))
interval = Duration.ofDays(1)

destination = 'C:/Temp/normalized.dss'

options = {'partF': 'my normalized grids'}

normalizer = Normalizer.builder() \
    .startTime(start) \
    .endTime(end) \
    .interval(interval) \
    .pathToSource(source) \
    .sourceVariables(sourceGrids) \
    .pathToNormals(normals) \
    .normalsVariables(normalGrids) \
    .destination(destination) \
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        if step == 1:
            print "Basic (lock account). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            user_password = credentials.getPassword()
            cacheService = CdiUtil.bean(CacheService)
            userService = CdiUtil.bean(UserService)

            logged_in = False
            if (StringHelper.isNotEmptyString(user_name)
                    and StringHelper.isNotEmptyString(user_password)):
                try:
                    logged_in = authenticationService.authenticate(
                        user_name, user_password)
                except AuthenticationException:
                    print "Basic (lock account). Authenticate. Failed to authenticate user '%s'" % user_name

            if logged_in:
                self.setUserAttributeValue(user_name,
                                           self.invalidLoginCountAttribute,
                                           StringHelper.toString(0))
            else:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % (user_name,
                                                            userSatus)

                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % (
                        remainingAttempts, user_name)

                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and (
                    (userSatus == None) or (userSatus == "active")):
                    print "Basic (lock account). Locking '%s' for '%s' seconds" % (
                        user_name, self.lockExpirationTime)
                    self.lockUser(user_name)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps
                    ) and userSatus == "inactive":
                    print "Basic (lock account). User '%s' is locked. Checking if we can unlock him" % user_name

                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(
                        None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "Basic (lock account). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details[
                            'created']
                        user_lock_details_created_date = LocalDateTime.parse(
                            user_lock_details_created,
                            DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(
                            user_lock_details_created_date,
                            LocalDateTime.now()).getSeconds()
                        print "Basic (lock account). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % (
                            user_name, user_lock_details_locked,
                            user_lock_details_created,
                            user_lock_details_created_diff)

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "Basic (lock account). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(
                            user_name, self.invalidLoginCountAttribute,
                            StringHelper.toString(0))
                        logged_in = authenticationService.authenticate(
                            user_name, user_password)
                        if not logged_in:
                            # Update number of attempts
                            self.setUserAttributeValue(
                                user_name, self.invalidLoginCountAttribute,
                                StringHelper.toString(1))
                            if self.maximumInvalidLoginAttemps == 1:
                                # Lock user if maximum count login attempts is 1
                                self.lockUser(user_name)
                                return False

            return logged_in
        else:
            return False
Beispiel #30
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        authenticationService = CdiUtil.bean(AuthenticationService)

        identity = CdiUtil.bean(Identity)
        credentials = identity.getCredentials()

        self.setRequestScopedParameters(identity)

        if step == 1:

            #############################################
            ### LOCKOUT
            print "OTP (with lockout). Authenticate for step 1"
            facesMessages = CdiUtil.bean(FacesMessages)
            facesMessages.setKeepMessages()
            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()
            user_name = credentials.getUsername()
            cacheService = CdiUtil.bean(CacheService)

            print "OTP (with lockout). Authenticate for step 1"
            authenticated_user = self.processBasicAuthentication(credentials)

            if authenticated_user != None:
                self.setUserAttributeValue(user_name,
                                           self.invalidLoginCountAttribute,
                                           StringHelper.toString(0))
            elif user_name != self.no_lockout_admin:
                countInvalidLoginArributeValue = self.getUserAttributeValue(
                    user_name, self.invalidLoginCountAttribute)
                userSatus = self.getUserAttributeValue(user_name, "gluuStatus")
                print "Current user '%s' status is '%s'" % (user_name,
                                                            userSatus)

                countInvalidLogin = StringHelper.toInteger(
                    countInvalidLoginArributeValue, 0)

                if countInvalidLogin < self.maximumInvalidLoginAttemps:
                    countInvalidLogin = countInvalidLogin + 1
                    remainingAttempts = self.maximumInvalidLoginAttemps - countInvalidLogin

                    print "Remaining login count attempts '%s' for user '%s'" % (
                        remainingAttempts, user_name)

                    self.setUserAttributeValue(
                        user_name, self.invalidLoginCountAttribute,
                        StringHelper.toString(countInvalidLogin))
                    if remainingAttempts > 0 and userSatus == "active":
                        facesMessages.add(
                            FacesMessage.SEVERITY_INFO,
                            StringHelper.toString(remainingAttempts) +
                            " more attempt(s) before account is LOCKED!")

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps) and (
                    (userSatus == None) or (userSatus == "active")):
                    print "OTP (with lockout). Locking '%s' for '%s' seconds" % (
                        user_name, self.lockExpirationTime)
                    self.lockUser(user_name, self.maximumInvalidLoginAttemps)
                    return False

                if (countInvalidLogin >= self.maximumInvalidLoginAttemps
                    ) and userSatus == "inactive":
                    print "OTP (with lockout). User '%s' is locked. Checking if we can unlock him" % user_name

                    unlock_and_authenticate = False

                    object_from_store = cacheService.get(
                        None, "lock_user_" + user_name)
                    if object_from_store == None:
                        # Object in cache was expired. We need to unlock user
                        print "OTP (with lockout). User locking details for user '%s' not exists" % user_name
                        unlock_and_authenticate = True
                    else:
                        # Analyze object from cache
                        user_lock_details = json.loads(object_from_store)

                        user_lock_details_locked = user_lock_details['locked']
                        user_lock_details_created = user_lock_details[
                            'created']
                        user_lock_details_created_date = LocalDateTime.parse(
                            user_lock_details_created,
                            DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                        user_lock_details_created_diff = Duration.between(
                            user_lock_details_created_date,
                            LocalDateTime.now()).getSeconds()
                        print "OTP (with lockout). Get user '%s' locking details. locked: '%s', Created: '%s', Difference in seconds: '%s'" % (
                            user_name, user_lock_details_locked,
                            user_lock_details_created,
                            user_lock_details_created_diff)

                        if user_lock_details_locked and user_lock_details_created_diff >= self.lockExpirationTime:
                            print "OTP (with lockout). Unlocking user '%s' after lock expiration" % user_name
                            unlock_and_authenticate = True

                    if unlock_and_authenticate:
                        self.unLockUser(user_name)
                        self.setUserAttributeValue(
                            user_name, self.invalidLoginCountAttribute,
                            StringHelper.toString(0))
                        ### TODO: Fix free attempt after unlock
                        authenticated_user = self.processBasicAuthentication(
                            credentials)
                        if authenticated_user == None:
                            self.setUserAttributeValue(
                                user_name, self.invalidLoginCountAttribute,
                                StringHelper.toString(1))

            if authenticated_user == None:
                return False
            ### LOCKOUT
            #############################################

            # Check the otp_group user membership
            if (self.use_otp_group):
                print "OTP (with lockout). Authenticate for step 1. Checking if user '%s' belongs to otp_group" % authenticated_user.getUserId(
                )
                is_member_otp_group = self.isUserMemberOfGroup(
                    authenticated_user, self.audit_attribute, self.otp_group)
                if not is_member_otp_group:
                    print "OTP (with lockout). Authenticate for step 1. User '%s' not a member of otp group, skipping OTP" % authenticated_user.getUserId(
                    )
                    identity.setWorkingParameter("otp_count_login_steps", 1)
                    return True
                else:
                    print "OTP (with lockout). Authenticate for step 1. User '%s' is a member of otp group, continue to OTP" % authenticated_user.getUserId(
                    )

            otp_auth_method = "authenticate"
            # Uncomment this block if you need to allow user second OTP registration
            #enrollment_mode = ServerUtil.getFirstValue(requestParameters, "loginForm:registerButton")
            #if StringHelper.isNotEmpty(enrollment_mode):
            #    otp_auth_method = "enroll"

            if otp_auth_method == "authenticate":
                user_enrollments = self.findEnrollments(
                    authenticated_user.getUserId())
                if len(user_enrollments) == 0:
                    otp_auth_method = "enroll"
                    print "OTP (with lockout). Authenticate for step 1. There is no OTP enrollment for user '%s'. Changing otp_auth_method to '%s'" % (
                        authenticated_user.getUserId(), otp_auth_method)

            if otp_auth_method == "enroll":
                print "OTP (with lockout). Authenticate for step 1. Setting count steps: '%s'" % 3
                identity.setWorkingParameter("otp_count_login_steps", 3)

            print "OTP (with lockout). Authenticate for step 1. otp_auth_method: '%s'" % otp_auth_method
            identity.setWorkingParameter("otp_auth_method", otp_auth_method)

            return True
        elif step == 2:
            print "OTP (with lockout). Authenticate for step 2"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP (with lockout). Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method == 'enroll':
                auth_result = ServerUtil.getFirstValue(requestParameters,
                                                       "auth_result")
                if not StringHelper.isEmpty(auth_result):
                    print "OTP (with lockout). Authenticate for step 2. User not enrolled OTP"
                    return False

                print "OTP (with lockout). Authenticate for step 2. Skipping this step during enrollment"
                return True

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP (with lockout). Authenticate for step 2. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        elif step == 3:
            print "OTP (with lockout). Authenticate for step 3"

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if user == None:
                print "OTP (with lockout). Authenticate for step 2. Failed to determine user name"
                return False

            session_id_validation = self.validateSessionId(identity)
            if not session_id_validation:
                return False

            # Restore state from session
            otp_auth_method = identity.getWorkingParameter("otp_auth_method")
            if otp_auth_method != 'enroll':
                return False

            otp_auth_result = self.processOtpAuthentication(
                requestParameters, user.getUserId(), identity, otp_auth_method)
            print "OTP (with lockout). Authenticate for step 3. OTP authentication result: '%s'" % otp_auth_result

            return otp_auth_result
        else:
            return False