text
stringlengths
7
1.01M
package com.fasterxml.jackson.databind.deser.jdk; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.InvalidFormatException; import com.fasterxml.jackson.databind.exc.MismatchedInputException; /** * Additional `java.util.Date` deserialization tests for cases where `ObjectMapper` * is configured to use timezone different from UTC. */ @SuppressWarnings("javadoc") public class DateDeserializationTZTest extends BaseMapTest { private static final String LOCAL_TZ = "GMT+2"; private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); static class Annot_TimeZone { @JsonFormat(timezone="GMT+4") java.util.Date date; } static class Annot_Pattern { @JsonFormat(pattern="'*'d MMM yyyy HH:mm:ss'*'") java.util.Date pattern; @JsonFormat(pattern="'*'d MMM yyyy HH:mm:ss'*'", locale="FR") java.util.Date pattern_FR; @JsonFormat(pattern="'*'d MMM yyyy HH:mm:ss'*'", timezone="GMT+4") java.util.Date pattern_GMT4; @JsonFormat(pattern="'*'d MMM yyyy HH:mm:ss'*'", locale="FR", timezone="GMT+4") java.util.Date pattern_FR_GMT4; } static class DateAsStringBean { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/") public Date date; } static class DateAsStringBeanGermany { @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/", locale="fr_FR") public Date date; } private ObjectMapper MAPPER; @Override protected void setUp() throws Exception { super.setUp(); // Create an ObjectMapper with its timezone set to something other than the default (UTC). // This way we can verify that serialization and deserialization actually consider the time // zone set on the mapper. ObjectMapper m = new ObjectMapper(); m.setTimeZone(TimeZone.getTimeZone(LOCAL_TZ)); MAPPER = m; FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } /* /********************************************************** /* Test methods /********************************************************** */ /** * Test the various timezone/offset representations */ public void testDateUtilISO8601_Timezone() throws Exception { // Complete offset, with ':' between hours and minutes verify( MAPPER, "2000-01-02T03:04:05.678+01:00", judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1")); // Complete offset, without ':' between hours and minutes verify( MAPPER, "2000-01-02T03:04:05.678+0100", judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1")); // Hour offset (no minutes) verify( MAPPER, "2000-01-02T03:04:05.678+01", judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1")); // 'zulu' offset verify( MAPPER, "2000-01-02T03:04:05.678Z", judate(2000, 1, 2, 3, 4, 5, 678, "UTC")); // --------------------------------------------------------------------------------------------- // WARNING: // According to ISO8601, hours and minutes of the offset must be expressed with 2 digits // (not more, not less), i.e. Z or +hh:mm or -hh:mm. See https://www.w3.org/TR/NOTE-datetime. // // The forms below are therefore ILLEGAL and must be refused. // --------------------------------------------------------------------------------------------- failure( MAPPER, "2000-01-02T03:04:05.678+"); failure( MAPPER, "2000-01-02T03:04:05.678+1"); failure( MAPPER, "2000-01-02T03:04:05.678+001"); failure( MAPPER, "2000-01-02T03:04:05.678+00:"); failure( MAPPER, "2000-01-02T03:04:05.678+00:001"); failure( MAPPER, "2000-01-02T03:04:05.678+001:001"); failure( MAPPER, "2000-01-02T03:04:05.678+1:"); failure( MAPPER, "2000-01-02T03:04:05.678+00:1"); } /** * Test the millis */ public void testDateUtilISO8601_DateTimeMillis() throws Exception { // WITH timezone (from 4 to 0 digits) failure(MAPPER, "2000-01-02T03:04:05.0123456789+01:00"); // at most 9 digits for the millis verify( MAPPER, "2000-01-02T03:04:05.6789+01:00", judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1")); verify( MAPPER, "2000-01-02T03:04:05.678+01:00", judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1")); verify( MAPPER, "2000-01-02T03:04:05.67+01:00", judate(2000, 1, 2, 3, 4, 5, 670, "GMT+1")); verify( MAPPER, "2000-01-02T03:04:05.6+01:00", judate(2000, 1, 2, 3, 4, 5, 600, "GMT+1")); verify( MAPPER, "2000-01-02T03:04:05+01:00", judate(2000, 1, 2, 3, 4, 5, 000, "GMT+1")); // WITH timezone Z (from 4 to 0 digits) failure(MAPPER, "2000-01-02T03:04:05.0123456789Z"); // at most 9 digits for the millis verify( MAPPER, "2000-01-02T03:04:05.6789Z", judate(2000, 1, 2, 3, 4, 5, 678, "UTC")); verify( MAPPER, "2000-01-02T03:04:05.678Z", judate(2000, 1, 2, 3, 4, 5, 678, "UTC")); verify( MAPPER, "2000-01-02T03:04:05.67Z", judate(2000, 1, 2, 3, 4, 5, 670, "UTC")); verify( MAPPER, "2000-01-02T03:04:05.6Z", judate(2000, 1, 2, 3, 4, 5, 600, "UTC")); verify( MAPPER, "2000-01-02T03:04:05Z", judate(2000, 1, 2, 3, 4, 5, 0, "UTC")); // WITHOUT timezone (from 4 to 0 digits) failure(MAPPER, "2000-01-02T03:04:05.0123456789"); // at most 9 digits for the millis verify( MAPPER, "2000-01-02T03:04:05.6789", judate(2000, 1, 2, 3, 4, 5, 678, LOCAL_TZ)); verify( MAPPER, "2000-01-02T03:04:05.678", judate(2000, 1, 2, 3, 4, 5, 678, LOCAL_TZ)); verify( MAPPER, "2000-01-02T03:04:05.67", judate(2000, 1, 2, 3, 4, 5, 670, LOCAL_TZ)); verify( MAPPER, "2000-01-02T03:04:05.6", judate(2000, 1, 2, 3, 4, 5, 600, LOCAL_TZ)); verify( MAPPER, "2000-01-02T03:04:05", judate(2000, 1, 2, 3, 4, 5, 000, LOCAL_TZ)); // --------------------------------------------------------------------------------------------- // WARNING: // RFC339 includes an Internet profile of the ISO 8601 standard for representation of dates // and times using the Gregorian calendar (https://tools.ietf.org/html/rfc3339). // // The RFC defines a partial time with the following BNF notation (chapter 5.6): // time-hour = 2DIGIT ; 00-23 // time-minute = 2DIGIT ; 00-59 // time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second rules // time-secfrac = "." 1*DIGIT // partial-time = time-hour ":" time-minute ":" time-second [time-secfrac] // // The second fraction (ie the millis) is optional and can be omitted. However, a fraction // with only a dot (.) and no digit is not allowed. // // The forms below are therefore ILLEGAL and must be refused. // --------------------------------------------------------------------------------------------- // millis part with only a dot (.) and no digits failure( MAPPER, "2000-01-02T03:04:05.+01:00"); failure( MAPPER, "2000-01-02T03:04:05."); failure( MAPPER, "2000-01-02T03:04:05.Z"); } /** * Date+Time representations * * NOTE: millis are not tested here since they are covered by another test case */ public void testDateUtilISO8601_DateTime() throws Exception { // Full representation with a timezone verify(MAPPER, "2000-01-02T03:04:05+01:00", judate(2000, 1, 2, 3, 4, 5, 0, "GMT+1")); // No timezone --> the one configured on the ObjectMapper must be used verify(MAPPER, "2000-01-02T03:04:05", judate(2000, 1, 2, 3, 4, 5, 0, LOCAL_TZ)); // Hours, minutes are mandatory but seconds are optional failure(MAPPER, "2000-01-02T"); failure(MAPPER, "2000-01-02T03"); failure(MAPPER, "2000-01-02T03:"); verify(MAPPER, "2000-01-02T03:04", judate(2000, 1, 2, 3, 4, 0, 0, LOCAL_TZ)); failure(MAPPER, "2000-01-02T03:04:"); // Hours, minutes are mandatory but seconds are optional - test with a TZ failure(MAPPER, "2000-01-02T+01:00"); failure(MAPPER, "2000-01-02T03+01:00"); failure(MAPPER, "2000-01-02T03:+01:00"); verify( MAPPER, "2000-01-02T03:04+01:00", judate(2000, 1, 2, 3, 4, 0, 0, "GMT+1")); failure(MAPPER, "2000-01-02T03:04:+01:00"); failure(MAPPER, "2000-01-02TZ"); failure(MAPPER, "2000-01-02T03Z"); failure(MAPPER, "2000-01-02T03:Z"); verify(MAPPER, "2000-01-02T03:04Z", judate(2000, 1, 2, 3, 4, 0, 0, "UTC")); failure(MAPPER, "2000-01-02T03:04:Z"); // --------------------------------------------------------------------------------------------- // WARNING: // ISO8601 (https://en.wikipedia.org/wiki/ISO_8601#Times) and its RFC339 profile // (https://tools.ietf.org/html/rfc3339, chapter 5.6) seem to require 2 DIGITS for // the hours, minutes and seconds. // // The following forms should therefore be refused but are accepted by Jackson (and // java.text.SimpleDateFormat). They are verified here to detect any changes in future // releases. // // --------------------------------------------------------------------------------------------- // FIXME As highlighted in the tests below, the behaviour is not consistent and largely // depends on wether a timezone and or millis are specified or not. // The tests assert the behavior with different number of digits for hour, min and sec. // Behavior should be the SAME whatever the timezone and/or the millis. // seconds (no TZ) failure( MAPPER, "2000-01-02T03:04:5"); failure( MAPPER, "2000-01-02T03:04:5.000"); failure(MAPPER, "2000-01-02T03:04:005"); // seconds (+01:00) failure(MAPPER, "2000-01-02T03:04:5+01:00"); failure(MAPPER, "2000-01-02T03:04:5.000+01:00"); failure(MAPPER, "2000-01-02T03:04:005+01:00"); // seconds (Z) failure(MAPPER, "2000-01-02T03:04:5Z"); failure( MAPPER, "2000-01-02T03:04:5.000Z"); failure(MAPPER, "2000-01-02T03:04:005Z"); // minutes (no TZ) failure( MAPPER, "2000-01-02T03:4:05"); failure( MAPPER, "2000-01-02T03:4:05.000"); failure(MAPPER, "2000-01-02T03:004:05"); // minutes (+01:00) failure(MAPPER, "2000-01-02T03:4:05+01:00"); failure(MAPPER, "2000-01-02T03:4:05.000+01:00"); failure(MAPPER, "2000-01-02T03:004:05+01:00"); // minutes (Z) failure( MAPPER, "2000-01-02T03:4:05Z"); failure( MAPPER, "2000-01-02T03:4:05.000Z"); failure( MAPPER, "2000-01-02T03:004:05Z"); // hour (no TZ) failure( MAPPER, "2000-01-02T3:04:05"); failure( MAPPER, "2000-01-02T3:04:05.000"); failure(MAPPER, "2000-01-02T003:04:05"); // hour (+01:00) failure(MAPPER, "2000-01-02T3:04:05+01:00"); failure(MAPPER, "2000-01-02T3:04:05.000+01:00"); failure(MAPPER, "2000-01-02T003:04:05+01:00"); // hour (Z) failure( MAPPER, "2000-01-02T3:04:05Z"); failure( MAPPER, "2000-01-02T3:04:05.000Z"); failure( MAPPER, "2000-01-02T003:04:05Z"); } /** * Date-only representations (no Time part) * * NOTE: time part is not tested here since they it is covered by another test case */ public void testDateUtilISO8601_Date() throws Exception { // Date is constructed with the timezone of the ObjectMapper. Time part is set to zero. verify(MAPPER, "2000-01-02", judate(2000, 1, 2, 0, 0, 0, 0, LOCAL_TZ)); // --------------------------------------------------------------------------------------------- // WARNING: // ISO8601 (https://en.wikipedia.org/wiki/ISO_8601#Times) and its RFC339 profile // (https://tools.ietf.org/html/rfc3339, chapter 5.6) seem to require 2 DIGITS for // the month and dayofweek but 4 DIGITS for the year. // // The following forms should therefore be refused but are accepted by Jackson (and // java.text.SimpleDateFormat). They are verified here to detect any changes in future // releases. // --------------------------------------------------------------------------------------------- // day failure( MAPPER, "2000-01-2"); failure( MAPPER, "2000-01-002"); // month failure( MAPPER, "2000-1-02"); failure( MAPPER, "2000-001-02"); // year failure( MAPPER, "20000-01-02"); failure( MAPPER, "200-01-02" ); failure( MAPPER, "20-01-02" ); failure( MAPPER, "2-01-02"); } /** * DateTime as numeric representation */ public void testDateUtil_Numeric() throws Exception { { long now = 123456789L; verify( MAPPER, now, new java.util.Date(now) ); // as a long verify( MAPPER, Long.toString(now), new java.util.Date(now) ); // as a string } { // should be ok to pass as JSON String, as long // as it is plain timestamp (all numbers, 64-bit) long now = 1321992375446L; verify( MAPPER, now, new java.util.Date(now) ); // as a long verify( MAPPER, Long.toString(now), new java.util.Date(now) ); // as a string } { // #267: should handle negative timestamps too; like 12 hours before 1.1.1970 long now = - (24 * 3600 * 1000L); verify( MAPPER, now, new java.util.Date(now) ); // as a long verify( MAPPER, Long.toString(now), new java.util.Date(now) ); // as a string } // value larger than a long (Long.MAX_VALUE+1) BigInteger tooLarge = BigInteger.valueOf(Long.MAX_VALUE).add( BigInteger.valueOf(1) ); failure(MAPPER, tooLarge, InvalidFormatException.class); failure(MAPPER, tooLarge.toString(), InvalidFormatException.class); // decimal value failure(MAPPER, 0.0, MismatchedInputException.class); failure(MAPPER, "0.0", InvalidFormatException.class); } /** * Note: may be these cases are already covered by {@link #testDateUtil_Annotation_PatternAndLocale()} */ public void testDateUtil_Annotation() throws Exception { // Build the input JSON and expected value String json = aposToQuotes("{'date':'/2005/05/25/'}"); java.util.Date expected = judate(2005, 05, 25, 0, 0, 0, 0, LOCAL_TZ); // Read it to make sure the format specified by the annotation is taken into account { DateAsStringBean result = MAPPER.readValue(json, DateAsStringBean.class); assertNotNull(result); assertEquals( expected, result.date ); } { DateAsStringBean result = MAPPER.readerFor(DateAsStringBean.class) .with(Locale.GERMANY) .readValue(json); assertNotNull(result); assertEquals( expected, result.date ); } // or, via annotations { DateAsStringBeanGermany result = MAPPER.readerFor(DateAsStringBeanGermany.class) .readValue(json); assertNotNull(result); assertEquals( expected, result.date ); } } /** * Test a POJO annotated with @JsonFormat to force an pattern. * Alternate with different combination of Locale and TimeZone. */ public void testDateUtil_Annotation_PatternAndLocale() throws Exception { // Change the default locale set on the ObjectMapper to something else than the default. // This way we know if the default is correctly taken into account ObjectMapper mapper = MAPPER.copy(); mapper.setLocale( Locale.ITALY ); // Build the JSON string. This is a mixed of ITALIAN and FRENCH (no ENGLISH because this // would be the default). String json = aposToQuotes("{ 'pattern': '*1 giu 2000 01:02:03*', 'pattern_FR': '*01 juin 2000 01:02:03*', 'pattern_GMT4': '*1 giu 2000 01:02:03*', 'pattern_FR_GMT4': '*1 juin 2000 01:02:03*'}"); Annot_Pattern result = mapper.readValue(json, Annot_Pattern.class); assertNotNull(result); assertEquals( judate(2000, 6, 1, 1, 2, 3, 0, LOCAL_TZ), result.pattern ); assertEquals( judate(2000, 6, 1, 1, 2, 3, 0, LOCAL_TZ), result.pattern_FR ); assertEquals( judate(2000, 6, 1, 1, 2, 3, 0, "GMT+4"), result.pattern_GMT4 ); assertEquals( judate(2000, 6, 1, 1, 2, 3, 0, "GMT+4"), result.pattern_FR_GMT4 ); } /** * Test a POJO annotated with @JsonFormat to force a default TimeZone * other than the one set on the ObjectMapper when the JSON doesn't contain any. */ public void testDateUtil_Annotation_TimeZone() throws Exception { // WITHOUT timezone { String json = aposToQuotes("{ 'date': '2000-01-02T03:04:05.678' }"); Annot_TimeZone result = MAPPER.readValue(json, Annot_TimeZone.class); assertNotNull(result); assertEquals( judate(2000, 1, 2, 3, 4, 5, 678, "GMT+4"), result.date); } // WITH timezone // --> the annotation acts as the "default" timezone. The timezone specified // in the JSON should be considered first. { String json = aposToQuotes("{ 'date': '2000-01-02T03:04:05.678+01:00' }"); Annot_TimeZone result = MAPPER.readValue(json, Annot_TimeZone.class); assertNotNull(result); assertEquals( judate(2000, 1, 2, 3, 4, 5, 678, "GMT+1"), result.date); } } /** * ObjectMapper configured with a custom date format that does NOT handle the TIMEZONE. * Dates must be constructed with the time zone set on the ObjectMapper. */ public void testDateUtil_customDateFormat_withoutTZ() throws Exception { // FIXME // // The general rule with the StdDateFormat is: // the TimeZone of the ObjectMapper is used if the JSON doesn't hold // any timezone/offset information. // // This rule remains valid with the @JsonFormat annotation unless it forces // an explicit timezeone, in which case the latter takes precedence. // // One would expect the same behavior when the StdDateFormat is replaced by a // custom DateFormat on the ObjectMapper. In other words, the timezone of the // DateFormat is of no importance: the ObjectMapper's default should be used // whenever it is needed. // Test first with a non default TZ on the ObjectMapper // --> OK: the mapper's default TZ is used to parse the date. { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); df.setTimeZone( TimeZone.getTimeZone("GMT+4") ); // TZ different from mapper's default ObjectMapper mapper = new ObjectMapper(); mapper.setTimeZone( TimeZone.getTimeZone(LOCAL_TZ) ); mapper.setDateFormat(df); // The mapper's default TZ is used... verify(mapper, "2000-01-02X04:00:00", judate(2000, 1, 2, 4, 00, 00, 00, LOCAL_TZ)); } // Test a second time with the default TZ on the ObjectMapper // Note it is important NOT TO CALL mapper.setTimeZone(...) in this test.. // --> KO: the custom format's TZ is used instead of the mapper's default as above. // { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss"); df.setTimeZone( TimeZone.getTimeZone("GMT+4") ); // TZ different from mapper's default ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); // FIXME mapper's default TZ should have been used verify(mapper, "2000-01-02X04:00:00", judate(2000, 1, 2, 4, 00, 00, 00, "GMT+4")); } } /** * ObjectMapper configured with a custom date format that DOES handle the TIMEZONE. * Dates must be constructed from the timezone of the input, regardless of the one * of the ObjectMapper. */ public void testDateUtil_customDateFormat_withTZ() throws Exception { ObjectMapper mapper = new ObjectMapper(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ssZ"); df.setTimeZone(TimeZone.getTimeZone("GMT+4")); // use a timezone different than the ObjectMapper and the system default mapper.setDateFormat(df); verify(mapper, "2000-01-02X03:04:05+0300", judate(2000, 1, 2, 3, 4, 5, 00, "GMT+3")); } /* /********************************************************** /* Helper methods /********************************************************** */ /** * Create a {@link java.util.Date} with all the fields set to the given value. * * @param year year * @param month month (1-12) * @param day day of month (1-31) * @param hour hour (0-23) * @param minutes minutes (0-59) * @param seconds seconds (0-59) * @param millis millis * @param tz timezone id as accepted by {@link TimeZone#getTimeZone(String)} * @return a new {@link Date} instance */ private static Date judate(int year, int month, int day, int hour, int minutes, int seconds, int millis, String tz) { Calendar cal = Calendar.getInstance(); cal.setLenient(false); cal.set(year, month-1, day, hour, minutes, seconds); cal.set(Calendar.MILLISECOND, millis); cal.setTimeZone(TimeZone.getTimeZone(tz)); return cal.getTime(); } private static void verify(ObjectMapper mapper, Object input, Date expected) throws Exception { // Deserialize using the supplied ObjectMapper Date actual = read(mapper, input, java.util.Date.class); // Test against the expected if( expected==null && actual==null) { return; } if( expected==null && actual != null) { fail("Failed to deserialize "+input+", actual: '"+FORMAT.format(actual)+"', expected: <null>'"); } if( expected != null && actual == null ) { fail("Failed to deserialize "+input+", actual: <null>, expected: '"+FORMAT.format(expected)+"'"); } if( actual.getTime() != expected.getTime() ) { fail("Failed to deserialize "+input+", actual: '"+FORMAT.format(actual)+"', expected: '"+FORMAT.format(expected)+"'"); } } private static void failure(ObjectMapper mapper, Object input) throws Exception { failure(mapper, input, MismatchedInputException.class); } private static void failure(ObjectMapper mapper, Object input, Class<? extends Exception> exceptionType) throws Exception { try { Date date = read(mapper, input, java.util.Date.class); fail("Input "+input+" should not have been accepted but was deserialized into "+FORMAT.format(date)); } catch (Exception e) { // Is it the expected exception ? if (!exceptionType.isAssignableFrom(e.getClass()) ) { fail("Wrong exception thrown when reading "+input+", actual: "+e.getClass().getName() + "("+e.getMessage()+"), expected: "+exceptionType.getName()); } } } private static <T> T read(ObjectMapper mapper, Object input, Class<T> type) throws Exception { // Construct the json representation from the input String json = input.toString(); if( !(input instanceof Number) ) { json = "\""+json+"\""; } // Deserialize using the supplied ObjectMapper return (T) mapper.readValue(json, type); } }
package com.ruoyi.system.service; import java.util.List; import java.util.Set; import com.ruoyi.common.core.domain.TreeSelect; import com.ruoyi.common.core.domain.entity.SysMenu; import com.ruoyi.system.domain.vo.RouterVo; /** * 菜单 业务层 * * @author zhulm7 */ public interface ISysMenuService { /** * 根据用户查询系统菜单列表 * * @param userId 用户ID * @return 菜单列表 */ public List<SysMenu> selectMenuList(Long userId); /** * 根据用户查询系统菜单列表 * * @param menu 菜单信息 * @param userId 用户ID * @return 菜单列表 */ public List<SysMenu> selectMenuList(SysMenu menu, Long userId); /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ public Set<String> selectMenuPermsByUserId(Long userId); /** * 根据用户ID查询菜单树信息 * * @param userId 用户ID * @return 菜单列表 */ public List<SysMenu> selectMenuTreeByUserId(Long userId); /** * 根据角色ID查询菜单树信息 * * @param roleId 角色ID * @return 选中菜单列表 */ public List<Integer> selectMenuListByRoleId(Long roleId); /** * 构建前端路由所需要的菜单 * * @param menus 菜单列表 * @return 路由列表 */ public List<RouterVo> buildMenus(List<SysMenu> menus); /** * 构建前端所需要树结构 * * @param menus 菜单列表 * @return 树结构列表 */ public List<SysMenu> buildMenuTree(List<SysMenu> menus); /** * 构建前端所需要下拉树结构 * * @param menus 菜单列表 * @return 下拉树结构列表 */ public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus); /** * 根据菜单ID查询信息 * * @param menuId 菜单ID * @return 菜单信息 */ public SysMenu selectMenuById(Long menuId); /** * 是否存在菜单子节点 * * @param menuId 菜单ID * @return 结果 true 存在 false 不存在 */ public boolean hasChildByMenuId(Long menuId); /** * 查询菜单是否存在角色 * * @param menuId 菜单ID * @return 结果 true 存在 false 不存在 */ public boolean checkMenuExistRole(Long menuId); /** * 新增保存菜单信息 * * @param menu 菜单信息 * @return 结果 */ public int insertMenu(SysMenu menu); /** * 修改保存菜单信息 * * @param menu 菜单信息 * @return 结果 */ public int updateMenu(SysMenu menu); /** * 删除菜单管理信息 * * @param menuId 菜单ID * @return 结果 */ public int deleteMenuById(Long menuId); /** * 校验菜单名称是否唯一 * * @param menu 菜单信息 * @return 结果 */ public String checkMenuNameUnique(SysMenu menu); }
/** * Description: * Created By xxm */ public class Solution { public TreeNode insertIntoBST(TreeNode root, int val) { // 找到空的节点插入val if (root == null) return new TreeNode(val); // 如果val大于root的值, 则在右子树中寻找合适位置 if (val > root.val) { root.right = insertIntoBST(root.right, val); } // 如果val小于root的值, 则在左子树中寻找合适位置 if (val < root.val) { root.left = insertIntoBST(root.left, val); } return root; } }
/** * @author AnkitMittal, JavaMadeSoEasy.com * Copyright (c), AnkitMittal . All Contents are copyrighted and must not be * reproduced in any form. * This class provides custom implementation of HashMap(without using java api's)- * which allows us to store data in key-value pair form. * insertion order of key-value pairs is not maintained. * @param <K> * @param <V> */ class HashMapCustom<K, V> { private Entry<K,V>[] table; //Array of Entry. private int capacity= 4; //Initial capacity of HashMap static class Entry<K, V> { K key; V value; Entry<K,V> next; public Entry(K key, V value, Entry<K,V> next){ this.key = key; this.value = value; this.next = next; } } @SuppressWarnings("unchecked") public HashMapCustom(){ table = new Entry[capacity]; } /** * Method allows you put key-value pair in HashMapCustom. * If the map already contains a mapping for the key, the old value is replaced. * Note: method does not allows you to put null key though it allows null values. * Implementation allows you to put custom objects as a key as well. * Key Features: implementation provides you with following features:- * >provide complete functionality how to override equals method. * >provide complete functionality how to override hashCode method. * @param newKey * @param data */ public void put(K newKey, V data){ if(newKey==null) return; //does not allow to store null. //calculate hash of key. int hash=hash(newKey); //create new entry. Entry<K,V> newEntry = new Entry<K,V>(newKey, data, null); //if table location does not contain any entry, store entry there. if(table[hash] == null){ table[hash] = newEntry; } else{ Entry<K,V> previous = null; Entry<K,V> current = table[hash]; while(current != null){ //we have reached last entry of bucket. if(current.key.equals(newKey)){ // key is the same, need to replace if(previous==null){ //node has to be insert on first of bucket. newEntry.next=current.next; table[hash]=newEntry; return; } else{ newEntry.next=current.next; previous.next=newEntry; return; } } previous=current; current = current.next; } previous.next = newEntry; // It's a different key, insert at the end. } } /** * Method returns value corresponding to key. * @param key */ public V get(K key){ int hash = hash(key); if(table[hash] == null){ return null; }else{ Entry<K,V> temp = table[hash]; while(temp!= null){ if(temp.key.equals(key)) return temp.value; temp = temp.next; //return value corresponding to key. } return null; //returns null if key is not found. } } /** * Method removes key-value pair from HashMapCustom. * @param key */ public boolean remove(K deleteKey){ int hash=hash(deleteKey); if(table[hash] == null){ return false; }else{ Entry<K,V> previous = null; Entry<K,V> current = table[hash]; while(current != null){ //we have reached last entry node of bucket. if(current.key.equals(deleteKey)){ if(previous==null){ //delete first entry node. table[hash]=table[hash].next; return true; } else{ previous.next=current.next; return true; } } previous=current; current = current.next; } return false; } } /** * Method displays all key-value pairs present in HashMapCustom., * insertion order is not guaranteed, for maintaining insertion order * refer LinkedHashMapCustom. * @param key */ public void display(){ for(int i=0;i<capacity;i++){ if(table[i]!=null){ Entry<K, V> entry=table[i]; while(entry!=null){ System.out.print("{"+entry.key+"="+entry.value+"}" +" "); entry=entry.next; } } } } /** * Method implements hashing functionality, which helps in finding the appropriate * bucket location to store our data. * This is very important method, as performance of HashMapCustom is very much * dependent on this method's implementation. * @param key */ private int hash(K key){ return Math.abs(key.hashCode()) % capacity; } } /** * Main class- to test HashMap functionality. */ public class HashMapCustomApp { public static void main(String[] args) { HashMapCustom<Integer, Integer> hashMapCustom = new HashMapCustom<Integer, Integer>(); hashMapCustom.put(21, 12); hashMapCustom.put(25, 121); hashMapCustom.put(30, 151); hashMapCustom.put(33, 15); hashMapCustom.put(35, 89); System.out.println("value corresponding to key 21=" + hashMapCustom.get(21)); System.out.println("value corresponding to key 51=" + hashMapCustom.get(51)); System.out.print("Displaying : "); hashMapCustom.display(); System.out.println("\n\nvalue corresponding to key 21 removed: " + hashMapCustom.remove(21)); System.out.println("value corresponding to key 51 removed: " + hashMapCustom.remove(51)); System.out.print("Displaying : "); hashMapCustom.display(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** * @author Alexander T. Simbirtsev */ package javax.swing.plaf.basic; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.SwingTestCase; import javax.swing.border.EmptyBorder; public class BasicOptionPaneUI_ButtonAreaLayoutTest extends SwingTestCase { protected BasicOptionPaneUI.ButtonAreaLayout layout; public static void main(String[] args) { junit.textui.TestRunner.run(BasicOptionPaneUI_ButtonAreaLayoutTest.class); } /* * @see TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); } public void testButtonAreaLayout() { int padding1 = 100; int padding2 = 200; boolean syncAll1 = true; boolean syncAll2 = false; layout = new BasicOptionPaneUI.ButtonAreaLayout(syncAll1, padding1); assertEquals("syncAll", syncAll1, layout.getSyncAllWidths()); assertEquals("padding", padding1, layout.getPadding()); assertTrue("CentersChildren", layout.getCentersChildren()); layout = new BasicOptionPaneUI.ButtonAreaLayout(syncAll2, padding2); assertEquals("syncAll", syncAll2, layout.getSyncAllWidths()); assertEquals("padding", padding2, layout.getPadding()); assertTrue("CentersChildren", layout.getCentersChildren()); } public void testSetGetSyncAllWidths() { boolean syncAll1 = true; boolean syncAll2 = false; layout = new BasicOptionPaneUI.ButtonAreaLayout(syncAll1, 0); assertEquals("syncAll", syncAll1, layout.getSyncAllWidths()); layout.setSyncAllWidths(syncAll2); assertEquals("syncAll", syncAll2, layout.getSyncAllWidths()); } public void testSetGetPadding() { int padding1 = 100; int padding2 = 200; layout = new BasicOptionPaneUI.ButtonAreaLayout(true, padding1); assertEquals("padding", padding1, layout.getPadding()); layout.setPadding(padding2); assertEquals("padding", padding2, layout.getPadding()); } public void testSetGetCentersChildren() { boolean centersChildren1 = true; boolean centersChildren2 = false; layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 0); assertTrue("CentersChildren", layout.getCentersChildren()); layout.setCentersChildren(centersChildren1); assertEquals("CentersChildren", centersChildren1, layout.getCentersChildren()); layout.setCentersChildren(centersChildren2); assertEquals("CentersChildren", centersChildren2, layout.getCentersChildren()); } public void testAddLayoutComponent() { Container container = new JPanel(); JComponent component1 = new JPanel(); JComponent component2 = new JPanel(); JComponent component3 = new JPanel(); JComponent component4 = new JPanel(); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 10); container.add(component1); container.add(component2); layout.addLayoutComponent("aaa", component1); layout.addLayoutComponent("bbb", component2); component1.setMinimumSize(new Dimension(50, 50)); component2.setMinimumSize(new Dimension(70, 80)); component3.setMinimumSize(new Dimension(90, 70)); component4.setMinimumSize(new Dimension(80, 120)); assertEquals("Sizes ", new Dimension(30, 10), layout.minimumLayoutSize(container)); container.add(component3); assertEquals("Sizes ", new Dimension(50, 10), layout.minimumLayoutSize(container)); layout.addLayoutComponent("asd", component3); assertEquals("Sizes ", new Dimension(50, 10), layout.minimumLayoutSize(container)); container.add(component4); assertEquals("Sizes ", new Dimension(70, 10), layout.minimumLayoutSize(container)); layout.addLayoutComponent("dsa", component4); assertEquals("Sizes ", new Dimension(70, 10), layout.minimumLayoutSize(container)); } public void testLayoutContainer() { JComponent container = new JPanel(); JComponent component1 = new JButton(); JComponent component2 = new JButton(); JComponent component3 = new JButton(); JComponent component4 = new JButton(); component4.setMinimumSize(new Dimension(41, 26)); component3.setMinimumSize(new Dimension(48, 26)); component2.setMinimumSize(new Dimension(55, 26)); component1.setMinimumSize(new Dimension(62, 26)); component4.setPreferredSize(new Dimension(41, 26)); component3.setPreferredSize(new Dimension(48, 26)); component2.setPreferredSize(new Dimension(55, 26)); component1.setPreferredSize(new Dimension(62, 26)); component4.setMaximumSize(new Dimension(41, 26)); component3.setMaximumSize(new Dimension(48, 26)); component2.setMaximumSize(new Dimension(55, 26)); component1.setMaximumSize(new Dimension(62, 26)); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 10); container.setLayout(layout); container.setBorder(new EmptyBorder(20, 20, 20, 20)); container.add(component1); container.add(component2); container.add(component3); container.add(component4); JDialog window = new JDialog(); window.getContentPane().add(container); window.pack(); assertEquals("Container's minimum requirements", new Dimension(276, 66), layout .minimumLayoutSize(container)); assertEquals("Container's preferred requirements", new Dimension(276, 66), layout .preferredLayoutSize(container)); assertEquals("Component1 location ", new Point(20, 20), component1.getLocation()); assertEquals("Component1 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component2 location ", new Point(92, 20), component2.getLocation()); assertEquals("Component2 size ", new Dimension(55, 26), component2.getSize()); assertEquals("Component3 location ", new Point(157, 20), component3.getLocation()); assertEquals("Component3 size ", new Dimension(48, 26), component3.getSize()); assertEquals("Component4 location ", new Point(215, 20), component4.getLocation()); assertEquals("Component4 size ", new Dimension(41, 26), component4.getSize()); container.setPreferredSize(new Dimension(1000, 100)); window.pack(); assertEquals("Container's minimum requirements", new Dimension(276, 66), layout .minimumLayoutSize(container)); assertEquals("Container's preferred requirements", new Dimension(276, 66), layout .preferredLayoutSize(container)); assertEquals("Component1 location ", new Point(382, 20), component1.getLocation()); assertEquals("Component1 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component2 location ", new Point(454, 20), component2.getLocation()); assertEquals("Component2 size ", new Dimension(55, 26), component2.getSize()); assertEquals("Component3 location ", new Point(519, 20), component3.getLocation()); assertEquals("Component3 size ", new Dimension(48, 26), component3.getSize()); assertEquals("Component4 location ", new Point(577, 20), component4.getLocation()); assertEquals("Component4 size ", new Dimension(41, 26), component4.getSize()); layout.setCentersChildren(false); container.setPreferredSize(new Dimension(1200, 100)); window.pack(); assertEquals("Container's minimum requirements", new Dimension(276, 66), layout .minimumLayoutSize(container)); assertEquals("Container's preferred requirements", new Dimension(276, 66), layout .preferredLayoutSize(container)); assertEquals("Component1 location ", new Point(20, 20), component1.getLocation()); assertEquals("Component1 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component2 location ", new Point(390, 20), component2.getLocation()); assertEquals("Component2 size ", new Dimension(55, 26), component2.getSize()); assertEquals("Component3 location ", new Point(753, 20), component3.getLocation()); assertEquals("Component3 size ", new Dimension(48, 26), component3.getSize()); assertEquals("Component4 location ", new Point(1109, 20), component4.getLocation()); assertEquals("Component4 size ", new Dimension(41, 26), component4.getSize()); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 30); container.setLayout(layout); container.setBorder(new EmptyBorder(20, 20, 20, 20)); container.setPreferredSize(null); window.pack(); assertEquals("Container's minimum requirements", new Dimension(378, 66), layout .minimumLayoutSize(container)); assertEquals("Container's preferred requirements", new Dimension(378, 66), layout .preferredLayoutSize(container)); int offset = isHarmony() ? 20 : 0; assertEquals("Component1 location ", new Point(offset + 0, 20), component1 .getLocation()); assertEquals("Component1 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component2 location ", new Point(offset + 92, 20), component2 .getLocation()); assertEquals("Component2 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component3 location ", new Point(offset + 184, 20), component3 .getLocation()); assertEquals("Component3 size ", new Dimension(62, 26), component1.getSize()); assertEquals("Component4 location ", new Point(offset + 276, 20), component4 .getLocation()); assertEquals("Component4 size ", new Dimension(62, 26), component1.getSize()); } public void testMinimumLayoutSize() { JComponent container = new JPanel(); JComponent component1 = new JPanel(); JComponent component2 = new JPanel(); JComponent component3 = new JPanel(); JComponent component4 = new JPanel(); component1.setMinimumSize(new Dimension(41, 26)); component2.setMinimumSize(new Dimension(48, 26)); component3.setMinimumSize(new Dimension(55, 26)); component4.setMinimumSize(new Dimension(62, 26)); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 25); container.add(component1); container.add(component2); assertEquals("Minimum size: ", new Dimension(45, 10), layout .minimumLayoutSize(container)); assertEquals("Minimum size: ", new Dimension(45, 10), layout .preferredLayoutSize(container)); component1.setMinimumSize(new Dimension(50, 50)); component2.setMinimumSize(new Dimension(70, 120)); component3.setMinimumSize(new Dimension(90, 150)); component4.setMinimumSize(new Dimension(80, 90)); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 30); assertEquals("Minimum size: ", new Dimension(50, 10), layout .minimumLayoutSize(container)); container.add(component3); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 40); assertEquals("Minimum size: ", new Dimension(110, 10), layout .minimumLayoutSize(container)); container.add(component4); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 60); assertEquals("Minimum size: ", new Dimension(220, 10), layout .minimumLayoutSize(container)); container = new JPanel(); container.add(component1); container.add(component2); component1.setAlignmentX(0.75f); component2.setAlignmentY(0.75f); component3.setAlignmentX(0.25f); component4.setAlignmentY(0.25f); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 10); assertEquals("Minimum size: ", new Dimension(30, 10), layout .minimumLayoutSize(container)); container.add(component3); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 0); assertEquals("Minimum size: ", new Dimension(30, 10), layout .minimumLayoutSize(container)); container.add(component4); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 0); container.setBorder(new EmptyBorder(20, 20, 20, 20)); assertEquals("Minimum size: ", new Dimension(80, 50), layout .minimumLayoutSize(container)); } public void testPreferredLayoutSize() { JComponent container = new JPanel(); JComponent component1 = new JPanel(); JComponent component2 = new JPanel(); JComponent component3 = new JPanel(); JComponent component4 = new JPanel(); component1.setPreferredSize(new Dimension(41, 26)); component2.setPreferredSize(new Dimension(48, 26)); component3.setPreferredSize(new Dimension(55, 26)); component4.setPreferredSize(new Dimension(62, 26)); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 30); container.add(component1); container.add(component2); assertEquals("Preferred size: ", new Dimension(119, 26), layout .preferredLayoutSize(container)); assertEquals("Preferred size: ", new Dimension(119, 26), layout .minimumLayoutSize(container)); component1.setPreferredSize(new Dimension(50, 50)); component2.setPreferredSize(new Dimension(70, 120)); component3.setPreferredSize(new Dimension(90, 150)); component4.setPreferredSize(new Dimension(80, 90)); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 40); assertEquals("Preferred size: ", new Dimension(180, 120), layout .preferredLayoutSize(container)); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 40); assertEquals("Preferred size: ", new Dimension(160, 120), layout .preferredLayoutSize(container)); container.add(component3); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 25); assertEquals("Preferred size: ", new Dimension(260, 150), layout .preferredLayoutSize(container)); layout.setCentersChildren(true); assertEquals("Preferred size: ", new Dimension(260, 150), layout .preferredLayoutSize(container)); container.add(component4); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 20); assertEquals("Preferred size: ", new Dimension(350, 150), layout .preferredLayoutSize(container)); container = new JPanel(); container.add(component1); container.add(component2); component1.setAlignmentX(0.75f); component2.setAlignmentY(0.75f); component3.setAlignmentX(0.25f); component4.setAlignmentY(0.25f); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 20); assertEquals("Preferred size: ", new Dimension(140, 120), layout .preferredLayoutSize(container)); container.add(component3); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 20); assertEquals("Preferred size: ", new Dimension(250, 150), layout .preferredLayoutSize(container)); container.add(component4); layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 20); container.setBorder(new EmptyBorder(20, 20, 20, 20)); assertEquals("Preferred size: ", new Dimension(390, 190), layout .preferredLayoutSize(container)); } // Regression for HARMONY-2900 public void testPreferedLayoutSize() { layout = new BasicOptionPaneUI.ButtonAreaLayout(false, 20); assertEquals(new Dimension(), layout.preferredLayoutSize(null)); // no exception expected } public void testRemoveLayoutComponent() { Container container = new JPanel(); JComponent component1 = new JPanel(); JComponent component2 = new JPanel(); JComponent component3 = new JPanel(); JComponent component4 = new JPanel(); layout = new BasicOptionPaneUI.ButtonAreaLayout(true, 20); container.add(component1); container.add(component2); container.add(component3); container.add(component4); component1.setMinimumSize(new Dimension(50, 50)); component2.setMinimumSize(new Dimension(70, 80)); component3.setMinimumSize(new Dimension(90, 70)); component4.setMinimumSize(new Dimension(80, 120)); assertEquals("Sizes ", new Dimension(100, 10), layout.minimumLayoutSize(container)); container.remove(component4); assertEquals("Sizes ", new Dimension(70, 10), layout.minimumLayoutSize(container)); container.add(component4); layout.removeLayoutComponent(component4); container.remove(component4); assertEquals("Sizes ", new Dimension(70, 10), layout.minimumLayoutSize(container)); container.remove(component3); assertEquals("Sizes ", new Dimension(40, 10), layout.minimumLayoutSize(container)); container.add(component3); layout.removeLayoutComponent(component3); assertEquals("Sizes ", new Dimension(70, 10), layout.minimumLayoutSize(container)); } }
package cn.threefishes.cloudrepository.dao; import cn.threefishes.cloudrepository.entity.WeixinUser; import cn.threefishes.cloudrepository.entity.WeixinUserExample; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; public interface WeixinUserMapper { long countByExample(WeixinUserExample example); int deleteByExample(WeixinUserExample example); int deleteByPrimaryKey(Integer userId); int insert(WeixinUser record); int insertSelective(WeixinUser record); List<WeixinUser> selectByExampleWithRowbounds(WeixinUserExample example, RowBounds rowBounds); List<WeixinUser> selectByExample(WeixinUserExample example); WeixinUser selectByPrimaryKey(Integer userId); int updateByExampleSelective(@Param("record") WeixinUser record, @Param("example") WeixinUserExample example); int updateByExample(@Param("record") WeixinUser record, @Param("example") WeixinUserExample example); int updateByPrimaryKeySelective(WeixinUser record); int updateByPrimaryKey(WeixinUser record); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 opennlp.tools.formats.convert; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.DetokenizerParameter; import opennlp.tools.formats.DetokenizerSampleStreamFactory; import opennlp.tools.formats.NameSampleDataStreamFactory; import opennlp.tools.namefind.NameSample; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class NameToTokenSampleStreamFactory extends DetokenizerSampleStreamFactory<TokenSample> { protected <P> NameToTokenSampleStreamFactory(Class<P> params) { super(params); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(TokenSample.class, "namefinder", new NameToTokenSampleStreamFactory(Parameters.class)); } public ObjectStream<TokenSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); ObjectStream<NameSample> nameSampleStream = StreamFactoryRegistry.getFactory( NameSample.class, StreamFactoryRegistry.DEFAULT_FORMAT).create( ArgumentParser.filter(args, NameSampleDataStreamFactory.Parameters.class)); return new NameToTokenSampleStream(createDetokenizer(params), nameSampleStream); } interface Parameters extends NameSampleDataStreamFactory.Parameters, DetokenizerParameter { } }
/* * Copyright (C) 2018 The Android Open Source Project * * 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 android.view; import android.annotation.FloatRange; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SuppressLint; import android.graphics.Insets; import android.view.WindowInsets.Type.InsetsType; import android.view.WindowInsetsAnimation.Bounds; /** * Controller for app-driven animation of system windows. * <p> * {@code WindowInsetsAnimationController} lets apps animate system windows such as * the {@link android.inputmethodservice.InputMethodService IME}. The animation is * synchronized, such that changes the system windows and the app's current frame * are rendered at the same time. * <p> * Control is obtained through {@link WindowInsetsController#controlWindowInsetsAnimation}. */ @SuppressLint("NotCloseable") public interface WindowInsetsAnimationController { /** * Retrieves the {@link Insets} when the windows this animation is controlling are fully hidden. * <p> * Note that these insets are always relative to the window, which is the same as being relative * to {@link View#getRootView} * <p> * If there are any animation listeners registered, this value is the same as * {@link Bounds#getLowerBound()} that is being be passed into the root view of the * hierarchy. * * @return Insets when the windows this animation is controlling are fully hidden. * * @see Bounds#getLowerBound() */ @NonNull Insets getHiddenStateInsets(); /** * Retrieves the {@link Insets} when the windows this animation is controlling are fully shown. * <p> * Note that these insets are always relative to the window, which is the same as being relative * to {@link View#getRootView} * <p> * If there are any animation listeners registered, this value is the same as * {@link Bounds#getUpperBound()} that is being passed into the root view of hierarchy. * * @return Insets when the windows this animation is controlling are fully shown. * * @see Bounds#getUpperBound() */ @NonNull Insets getShownStateInsets(); /** * Retrieves the current insets. * <p> * Note that these insets are always relative to the window, which is the same as * being relative * to {@link View#getRootView} * @return The current insets on the currently showing frame. These insets will change as the * animation progresses to reflect the current insets provided by the controlled window. */ @NonNull Insets getCurrentInsets(); /** * Returns the progress as previously set by {@code fraction} in {@link #setInsetsAndAlpha} * * @return the progress of the animation, where {@code 0} is fully hidden and {@code 1} is * fully shown. * <p> * Note: this value represents raw overall progress of the animation * i.e. the combined progress of insets and alpha. * <p> */ @FloatRange(from = 0f, to = 1f) float getCurrentFraction(); /** * Current alpha value of the window. * @return float value between 0 and 1. */ float getCurrentAlpha(); /** * @return The {@link InsetsType}s this object is currently controlling. */ @InsetsType int getTypes(); /** * Modifies the insets for the frame being drawn by indirectly moving the windows around in the * system that are causing window insets. * <p> * Note that these insets are always relative to the window, which is the same as being relative * to {@link View#getRootView} * <p> * Also note that this will <b>not</b> inform the view system of a full inset change via * {@link View#dispatchApplyWindowInsets} in order to avoid a full layout pass during the * animation. If you'd like to animate views during a window inset animation, register a * {@link WindowInsetsAnimation.Callback} by calling * {@link View#setWindowInsetsAnimationCallback(WindowInsetsAnimation.Callback)} that will be * notified about any insets change via {@link WindowInsetsAnimation.Callback#onProgress} during * the animation. * <p> * {@link View#dispatchApplyWindowInsets} will instead be called once the animation has * finished, i.e. once {@link #finish} has been called. * Note: If there are no insets, alpha animation is still applied. * * @param insets The new insets to apply. Based on the requested insets, the system will * calculate the positions of the windows in the system causing insets such that * the resulting insets of that configuration will match the passed in parameter. * Note that these insets are being clamped to the range from * {@link #getHiddenStateInsets} to {@link #getShownStateInsets}. * If you intend on changing alpha only, pass null or {@link #getCurrentInsets()}. * @param alpha The new alpha to apply to the inset side. * @param fraction instantaneous animation progress. This value is dispatched to * {@link WindowInsetsAnimation.Callback}. * * @see WindowInsetsAnimation.Callback * @see View#setWindowInsetsAnimationCallback(WindowInsetsAnimation.Callback) */ void setInsetsAndAlpha(@Nullable Insets insets, @FloatRange(from = 0f, to = 1f) float alpha, @FloatRange(from = 0f, to = 1f) float fraction); /** * Finishes the animation, and leaves the windows shown or hidden. * <p> * After invoking {@link #finish}, this instance is no longer {@link #isReady ready}. * <p> * Note: Finishing an animation implicitly {@link #setInsetsAndAlpha sets insets and alpha} * according to the requested end state without any further animation. * * @param shown if {@code true}, the windows will be shown after finishing the * animation. Otherwise they will be hidden. */ void finish(boolean shown); /** * Returns whether this instance is ready to be used to control window insets. * <p> * Instances are ready when passed in {@link WindowInsetsAnimationControlListener#onReady} * and stop being ready when it is either {@link #isFinished() finished} or * {@link #isCancelled() cancelled}. * * @return {@code true} if the instance is ready, {@code false} otherwise. */ default boolean isReady() { return !isFinished() && !isCancelled(); } /** * Returns whether this instance has been finished by a call to {@link #finish}. * * @see WindowInsetsAnimationControlListener#onFinished * @return {@code true} if the instance is finished, {@code false} otherwise. */ boolean isFinished(); /** * Returns whether this instance has been cancelled by the system, or by invoking the * {@link android.os.CancellationSignal} passed into * {@link WindowInsetsController#controlWindowInsetsAnimation}. * * @see WindowInsetsAnimationControlListener#onCancelled * @return {@code true} if the instance is cancelled, {@code false} otherwise. */ boolean isCancelled(); /** * @hide * @return {@code true} when controller controls IME and IME has no insets (floating, * fullscreen or non-overlapping). */ boolean hasZeroInsetsIme(); }
package mil.nga.giat.geowave.core.cli.api; /** * The default operation prevents implementors from having to implement the * 'prepare' function, if they don't want to. */ public class DefaultOperation implements Operation { public boolean prepare( OperationParams params ) { return true; } }
package net.leanix.api; import net.leanix.api.common.ApiClient; import net.leanix.api.common.ApiException; import net.leanix.api.common.Configuration; import net.leanix.api.common.Pair; import net.leanix.api.models.TodoData; import net.leanix.api.models.TodoListResponse; import net.leanix.api.models.TodoResponse; import java.util.*; public class TodosApi { private ApiClient apiClient; public TodosApi() { this(Configuration.getDefaultApiClient()); } public TodosApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * createTodo * Saves a todo in the database * * @param body Creates a new Todo item (optional) * @param workspaceId ID of the Workspace that the Todo shall be created in. (optional) * @return TodoResponse * @throws ApiException if fails to make API call */ public TodoResponse createTodo(TodoData body, UUID workspaceId) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/todos".replaceAll("\\{format\\}", "json"); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "workspaceId", workspaceId)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"token"}; return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarAccept, localVarContentType, localVarAuthNames, TodoResponse.class); } /** * deleteTodo * deletes a todo item based on provided id. * * @param id the id of the todo item (required) * @param workspaceId the workspaceId in case that the SYSTEM deletes the todo (optional) * @throws ApiException if fails to make API call */ public void deleteTodo(UUID id, UUID workspaceId) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling deleteTodo"); } // create path and map variables String localVarPath = "/todos/{id}".replaceAll("\\{format\\}", "json") .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "workspaceId", workspaceId)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"token"}; apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarAccept, localVarContentType, localVarAuthNames, null); } /** * getTodo * Retrieves a todo by ID * * @param id (required) * @return TodoResponse * @throws ApiException if fails to make API call */ public TodoResponse getTodo(UUID id) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling getTodo"); } // create path and map variables String localVarPath = "/todos/{id}".replaceAll("\\{format\\}", "json") .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"token"}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarAccept, localVarContentType, localVarAuthNames, TodoResponse.class); } /** * getTodos * Retrieves all todos a user can read. * * @param type Specifies the todo type (optional) * @param status Specifies the todo status (optional) * @param factSheetId Specifies the ID of the Fact Sheet the todo is connected to - only works with manual Todos (optional) * @param userId Specify the user Id for the user to look for (optional) * @param workspaceId Id of the workspace to get the TodoItems from. (optional) * @param getArchived If set to true, then todos associated with archived factsheets are retrieved as well (optional, default to false) * @param size Specifies the number of Todos to get, (optional, default to 10) * @param page Specifies the page of Todos to get, (optional, default to 1) * @return TodoListResponse * @throws ApiException if fails to make API call */ public TodoListResponse getTodos(String type, String status, UUID factSheetId, UUID userId, UUID workspaceId, Boolean getArchived, Integer size, Integer page) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/todos".replaceAll("\\{format\\}", "json"); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "type", type)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "status", status)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "factSheetId", factSheetId)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "userId", userId)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "workspaceId", workspaceId)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "getArchived", getArchived)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "size", size)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "page", page)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"token"}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarAccept, localVarContentType, localVarAuthNames, TodoListResponse.class); } /** * updateTodo * Updates a todo stored in the database. * * @param id (required) * @param workspaceId ID of the Workspace that the Todo shall be updated in in case that the user is not assigned to one workspace (optional) * @param body todo (optional) * @return TodoResponse * @throws ApiException if fails to make API call */ public TodoResponse updateTodo(UUID id, UUID workspaceId, TodoData body) throws ApiException { Object localVarPostBody = body; // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling updateTodo"); } // create path and map variables String localVarPath = "/todos/{id}".replaceAll("\\{format\\}", "json") .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "workspaceId", workspaceId)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[]{"token"}; return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarAccept, localVarContentType, localVarAuthNames, TodoResponse.class); } }
package org.adempiere.ad.validationRule.impl; import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; import org.adempiere.ad.validationRule.AbstractJavaValidationRule; import org.adempiere.ad.validationRule.IValidationContext; import org.adempiere.ad.validationRule.IValidationRule; import org.adempiere.ad.validationRule.IValidationRuleFactory; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.test.AdempiereTestHelper; import org.compiere.model.I_AD_Column; import org.compiere.model.I_AD_Ref_Table; import org.compiere.model.I_AD_Reference; import org.compiere.model.I_AD_Table; import org.compiere.model.I_AD_Val_Rule; import org.compiere.model.X_AD_Val_Rule; import org.compiere.util.NamePair; import org.compiere.util.ValueNamePair; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableSet; import de.metas.util.Services; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2017 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class RegisteredValidationRuleTest { private final static String param1 = "Param1"; private final static String param2 = "Param2"; private final static String tableNameForValRule = "TableNameForValRule"; private final static String tableNameForTestValRule = "TableNameForTestTable"; private final static String columnNameForRegisteredValRule = "ColumnNameForRegisteredValRule"; @Before public void init() { AdempiereTestHelper.get().init(); } @Test public void registerValidationRule_ParametersTest() { final I_AD_Table tableForValRule = createTable(tableNameForValRule); final I_AD_Table tableToTestValrule = createTable(tableNameForTestValRule); final I_AD_Column columnForValRule = createColumn(tableToTestValrule, columnNameForRegisteredValRule); final I_AD_Reference referenceValue = createTableReferenceValue(tableForValRule); columnForValRule.setAD_Reference_Value(referenceValue); InterfaceWrapperHelper.save(columnForValRule); Services.get(IValidationRuleFactory.class).registerTableValidationRule(tableNameForValRule, ValRuleTest.instance); final IValidationRule validationRule = Services.get(IValidationRuleFactory.class).create(tableNameForValRule, 0, tableNameForValRule, columnNameForRegisteredValRule); assertThat(validationRule.getAllParameters()).containsOnly(param1, param2); } @Test public void registerValidationRuleException_NoRegisteredValRuleTest() { final I_AD_Table tableForValRule = createTable(tableNameForValRule); final I_AD_Table tableToTestValrule = createTable(tableNameForTestValRule); final I_AD_Column columnForValRule = createColumn(tableToTestValrule, columnNameForRegisteredValRule); final I_AD_Reference referenceValue = createTableReferenceValue(tableForValRule); columnForValRule.setAD_Reference_Value(referenceValue); InterfaceWrapperHelper.save(columnForValRule); final IValidationRule validationRule = Services.get(IValidationRuleFactory.class).create(tableNameForValRule, 0, tableNameForValRule, columnNameForRegisteredValRule); assertThat(validationRule).isInstanceOf(NullValidationRule.class); assertThat(validationRule.getExceptionTableAndColumns()).isEmpty(); } /** * This test is mocking the general validation rule for the table M_Warehouse, which applies to all the columns that point to the table M_Warehouse. * This validation rule has an exception for the M_ReceiptSchedule.M_Warehouse_Dest_ID. * * In this test, the validation Rule is build built for M_ReceiptSchedule.M_Warehouse_Dest_ID, which fits the exception, so the validation rule should be not applied */ @Test public void registerValidationRuleException_WithExceptions_ExceptionTableAndColumnTest() { final I_AD_Table M_Warehouse = createTable("M_Warehouse"); final I_AD_Table M_InOut = createTable("M_InOut"); final I_AD_Table M_ReceiptSchedule = createTable("M_ReceiptSchedule"); final I_AD_Reference referenceValue = createTableReferenceValue(M_Warehouse); final I_AD_Column inout_M_Warehouse_ID = createColumn(M_InOut, "inout_M_Warehouse_ID"); final I_AD_Column rs_Warehouse_Dest_ID = createColumn(M_ReceiptSchedule, "rs_Warehouse_Dest_ID"); inout_M_Warehouse_ID.setAD_Reference_Value(referenceValue); rs_Warehouse_Dest_ID.setAD_Reference_Value(referenceValue); InterfaceWrapperHelper.save(inout_M_Warehouse_ID); InterfaceWrapperHelper.save(rs_Warehouse_Dest_ID); Services.get(IValidationRuleFactory.class).registerTableValidationRule(M_Warehouse.getTableName(), ValRuleTest.instance); Services.get(IValidationRuleFactory.class).registerValidationRuleException(ValRuleTest.instance, M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName(), "test"); final IValidationRule validationRule = Services.get(IValidationRuleFactory.class).create(M_Warehouse.getTableName(), 0, M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName()); // If a validation rule has no registered rules it is considered NullValidationRule assertThat(validationRule).isInstanceOf(NullValidationRule.class); assertThat(validationRule.getExceptionTableAndColumns()).isEmpty(); } /** * * This test is mocking the general validation rule for the table M_Warehouse, which applies to all the columns that point to the table M_Warehouse. * This validation rule has an exception for the M_ReceiptSchedule.M_Warehouse_Dest_ID. * * In this test, the validation Rule is build built for M_ReceiptSchedule.M_Warehouse_Dest_ID, which fits the exception, so the validation rule should be not applied * The column M_ReceiptSchedule.M_Warehouse_Dest_ID has an SQL validation rule. This one will be applied so the final ValidationRule will be of type SQL */ @Test public void registerValidationRuleException_WithExceptions_ExceptionTableAndColumn_ExistingValRuleInDatabase() { final I_AD_Table M_Warehouse = createTable("M_Warehouse"); final I_AD_Table M_InOut = createTable("M_InOut"); final I_AD_Table M_ReceiptSchedule = createTable("M_ReceiptSchedule"); final I_AD_Reference referenceValue = createTableReferenceValue(M_Warehouse); final I_AD_Column inout_M_Warehouse_ID = createColumn(M_InOut, "inout_M_Warehouse_ID"); final I_AD_Column rs_Warehouse_Dest_ID = createColumn(M_ReceiptSchedule, "rs_Warehouse_Dest_ID"); final I_AD_Val_Rule databaseValRule = createSQLValRule("Database ValRule Code"); rs_Warehouse_Dest_ID.setAD_Val_Rule(databaseValRule); inout_M_Warehouse_ID.setAD_Reference_Value(referenceValue); rs_Warehouse_Dest_ID.setAD_Reference_Value(referenceValue); InterfaceWrapperHelper.save(inout_M_Warehouse_ID); InterfaceWrapperHelper.save(rs_Warehouse_Dest_ID); Services.get(IValidationRuleFactory.class).registerTableValidationRule(M_Warehouse.getTableName(), ValRuleTest.instance); Services.get(IValidationRuleFactory.class).registerValidationRuleException(ValRuleTest.instance, M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName(), "test"); final IValidationRule validationRule = Services.get(IValidationRuleFactory.class).create(M_Warehouse.getTableName(), databaseValRule.getAD_Val_Rule_ID(), M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName()); // If a validation rule has no registered rules it is considered NullValidationRule assertThat(validationRule).isInstanceOf(SQLValidationRule.class); assertThat(validationRule.getExceptionTableAndColumns()).isEmpty(); } /** * This test is mocking the general validation rule for the table M_Warehouse, which applies to all the columns that point to the table M_Warehouse. * This validation rule has an exception for the M_ReceiptSchedule.M_Warehouse_Dest_ID. * * In this test, the validation Rule is build built for M_InOut.M_Warehouse_ID, which doesn't fit the exception, so the validation rule should be applied */ @Test public void registerValidationRuleException_WithExceptions_GeneralCaseTest() { final I_AD_Table M_Warehouse = createTable("M_Warehouse"); final I_AD_Table M_InOut = createTable("M_InOut"); final I_AD_Table M_ReceiptSchedule = createTable("M_ReceiptSchedule"); final I_AD_Reference referenceValue = createTableReferenceValue(M_Warehouse); final I_AD_Column inout_M_Warehouse_ID = createColumn(M_InOut, "inout_M_Warehouse_ID"); final I_AD_Column rs_Warehouse_Dest_ID = createColumn(M_ReceiptSchedule, "rs_Warehouse_Dest_ID"); inout_M_Warehouse_ID.setAD_Reference_Value(referenceValue); rs_Warehouse_Dest_ID.setAD_Reference_Value(referenceValue); InterfaceWrapperHelper.save(inout_M_Warehouse_ID); InterfaceWrapperHelper.save(rs_Warehouse_Dest_ID); Services.get(IValidationRuleFactory.class).registerTableValidationRule(M_Warehouse.getTableName(), ValRuleTest.instance); Services.get(IValidationRuleFactory.class).registerValidationRuleException(ValRuleTest.instance, M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName(), "test"); final IValidationRule validationRule = Services.get(IValidationRuleFactory.class).create(M_Warehouse.getTableName(), 0, M_InOut.getTableName(), inout_M_Warehouse_ID.getColumnName()); final ValueNamePair tableAndColumnException = ValueNamePair.of(M_ReceiptSchedule.getTableName(), rs_Warehouse_Dest_ID.getColumnName(), "test"); assertThat(validationRule).isInstanceOf(ValRuleTest.class); assertThat(validationRule.getExceptionTableAndColumns()).containsOnly(tableAndColumnException); } private static final class ValRuleTest extends AbstractJavaValidationRule { private static final transient ValRuleTest instance = new ValRuleTest(); private ValRuleTest() { super(); } @Override public Set<String> getParameters() { return ImmutableSet.of(param1, param2); } @Override public boolean accept(IValidationContext evalCtx, NamePair item) { return false; // always reject } } private I_AD_Reference createTableReferenceValue(final I_AD_Table tableForReference) { final I_AD_Reference reference = InterfaceWrapperHelper.newInstance(I_AD_Reference.class); InterfaceWrapperHelper.save(reference); final I_AD_Ref_Table refTable = InterfaceWrapperHelper.newInstance(I_AD_Ref_Table.class); refTable.setAD_Table_ID(tableForReference.getAD_Table_ID()); InterfaceWrapperHelper.save(refTable); refTable.setAD_Reference_ID(reference.getAD_Reference_ID()); return reference; } private I_AD_Table createTable(final String tableName) { final I_AD_Table table = InterfaceWrapperHelper.newInstance(I_AD_Table.class); table.setTableName(tableName); InterfaceWrapperHelper.save(table); return table; } private I_AD_Column createColumn(final I_AD_Table table, final String columnName) { final I_AD_Column column = InterfaceWrapperHelper.newInstance(I_AD_Column.class); column.setColumnName(columnName); column.setAD_Table_ID(table.getAD_Table_ID()); InterfaceWrapperHelper.save(column); return column; } private I_AD_Val_Rule createSQLValRule(final String validationCode) { final I_AD_Val_Rule registeredValRule = InterfaceWrapperHelper.newInstance(I_AD_Val_Rule.class); registeredValRule.setCode(validationCode); registeredValRule.setType(X_AD_Val_Rule.TYPE_SQL); InterfaceWrapperHelper.save(registeredValRule); return registeredValRule; } }
package com.learn.thread; import com.sun.jndi.ldap.pool.Pool; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.stream.LongStream; /** * description: * * @author klaus * @date 2020/7/8 */ public class ExecutorServiceCalculatorImpl implements Calculator { private int parallism; private ExecutorService pool; public ExecutorServiceCalculatorImpl() { //获取 cpu 数量 parallism = Runtime.getRuntime().availableProcessors(); pool = Executors.newFixedThreadPool(parallism); } public static void main(String[] args) throws ExecutionException, InterruptedException { long[] longs = LongStream.rangeClosed(1, 10000000).toArray(); ExecutorServiceCalculatorImpl executor = new ExecutorServiceCalculatorImpl(); Instant start = Instant.now(); long l = executor.sumUp(longs); Instant end = Instant.now(); System.out.println(Duration.between(start, end).toMillis() + "ms"); System.out.println(l); executor.pool.shutdown(); } @Override public long sumUp(long[] num) throws ExecutionException, InterruptedException { List<Future<Long>> results = new ArrayList<>(); int part = num.length / parallism; for (int i = 0; i < parallism; i++) { int from = i * part; //开始位置 int to = (i == parallism - 1) ? num.length - 1 : (i + 1) * part - 1; //结束位置 //扔给线程池计算 results.add(pool.submit(new SumTask(num, from, to))); } long l = 0; for (Future<Long> result : results) { l += result.get(); } return l; } private static class SumTask implements Callable<Long> { private long[] numbers; private int from; private int to; public SumTask(long[] numbers, int from, int to) { this.numbers = numbers; this.from = from; this.to = to; } /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ @Override public Long call() throws Exception { long total = 0; for (int i = from; i <= to; i++) { total += numbers[i]; } return total; } } }
/* * Copyright 2013-2018 the original author or authors. * * 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 * * https://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 com.alibaba.cloud.dubbo.service; import java.util.HashMap; import java.util.Map; import org.apache.dubbo.config.annotation.DubboService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; /** * Spring MVC {@link RestService}. * * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a> */ @DubboService(version = "1.0.0") @RestController public class SpringRestService implements RestService { private Logger logger = LoggerFactory.getLogger(getClass()); @Override @GetMapping("/param") public String param(@RequestParam String param) { log("/param", param); return param; } @Override @PostMapping("/params") public String params(@RequestParam int a, @RequestParam String b) { log("/params", a + b); return a + b; } @Override @GetMapping("/headers") public String headers(@RequestHeader("h") String header, @RequestHeader("h2") String header2, @RequestParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; log("/headers", result); return result; } @Override @GetMapping("/path-variables/{p1}/{p2}") public String pathVariables(@PathVariable("p1") String path1, @PathVariable("p2") String path2, @RequestParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; log("/path-variables", result); return result; } @Override @PostMapping("/form") public String form(@RequestParam("f") String form) { return String.valueOf(form); } @Override @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_VALUE) public User requestBodyMap(@RequestBody Map<String, Object> data, @RequestParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); user.setAge((Integer) data.get("age")); log("/request/body/map", param); return user; } @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_VALUE) @Override public Map<String, Object> requestBodyUser(@RequestBody User user) { Map<String, Object> map = new HashMap<>(); map.put("id", user.getId()); map.put("name", user.getName()); map.put("age", user.getAge()); return map; } }
package pl.mmorpg.prototype.clientservercommon; public enum EquipmentPosition { NONE, HEAD, RIGHT_HAND, LEFT_HAND, CHEST, FEET }
package uk.co.compendiumdev.examples.firsttests; import uk.co.compendiumdev.examples.domain.actors.TodoMVCUser; import uk.co.compendiumdev.examples.pojo.TodoMVCPojoPage; import uk.co.compendiumdev.selenium.support.webdriver.ExecutionDriver; import uk.co.compendiumdev.todomvc.site.TodoMVCSite; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriver; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* This test uses many abstractions: - WebDriver, variables, test and method names, - annotations for test execution - ordering and 'test' identification - Hamcrest as an assertion abstraction - TodoMVCUser as a domain abstraction for the system user - A page object ApplicationPageFunctional - A Driver manager ExecutionDriver - A domain abstraction for the TodoMVCSite and environment */ public class WithAbstractionTest { @Test public void canCreateAToDo(){ WebDriver driver = new ExecutionDriver().get(); TodoMVCUser user = new TodoMVCUser(driver, new TodoMVCSite()); user.opensApplication().and().createNewToDo("new task"); TodoMVCPojoPage page = new TodoMVCPojoPage(driver, new TodoMVCSite().getURL()); assertThat(page.getCountOfTodoDoItems(), is(1)); assertThat(page.isFooterVisible(), is(true)); ExecutionDriver.closeDriver(driver); } }
package exp.libs.db.redis.bean; import exp.libs.db.redis.RedisClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <PRE> * Redis对象基类. * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: exp.lqb@foxmail.com * @since JDK 1.8+ */ abstract class _RedisObject { /** 日志器 */ protected final static Logger log = LoggerFactory.getLogger(_RedisObject.class); /** 泛型类型枚举 */ private final static int TYPE_NONE = 0, TYPE_STR = 1, TYPE_OBJ = 2; /** 当前的泛型类型 */ private int type; /** Redis连接客户端对象 */ protected RedisClient redis; /** * 构造函数 * @param redis redis客户端连接对象(需确保可用) */ protected _RedisObject(RedisClient redis) { this.type = TYPE_NONE; this.redis = (redis == null ? new RedisClient() : redis); } protected boolean typeIsNone() { return type == TYPE_NONE; } protected boolean typeIsStr() { return type == TYPE_STR; } protected boolean typeIsObj() { return type == TYPE_OBJ; } protected void setTypeStr() { this.type = TYPE_STR; } protected void setTypeObj() { this.type = TYPE_OBJ; } }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui; import com.intellij.ide.ui.VirtualFileAppearanceListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.util.LowMemoryWatcher; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.SystemProperties; import com.intellij.util.containers.FixedHashMap; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; import java.util.Map; import java.util.function.Function; public final class IconDeferrerImpl extends IconDeferrer { private static final ThreadLocal<Boolean> evaluationIsInProgress = ThreadLocal.withInitial(() -> Boolean.FALSE); private final Object LOCK = new Object(); private final Map<Object, Icon> myIconsCache = new FixedHashMap<>(SystemProperties.getIntProperty("ide.icons.deferrerCacheSize", 1000)); // guarded by LOCK private long myLastClearTimestamp; // guarded by LOCK public IconDeferrerImpl() { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(PsiModificationTracker.TOPIC, this::clearCache); // update "locked" icon connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends @NotNull VFileEvent> events) { clearCache(); } }); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { clearCache(); } }); connection.subscribe(VirtualFileAppearanceListener.TOPIC, __ -> clearCache()); LowMemoryWatcher.register(this::clearCache, connection); } @Override public void clearCache() { synchronized (LOCK) { myIconsCache.clear(); myLastClearTimestamp++; } } @Override public <T> @NotNull Icon defer(@Nullable Icon base, T param, @NotNull Function<? super T, ? extends Icon> evaluator) { return deferImpl(base, param, false, evaluator); } @Override public <T> @NotNull Icon deferAutoUpdatable(Icon base, T param, @NotNull Function<? super T, ? extends Icon> evaluator) { return deferImpl(base, param, true, evaluator); } private <T> @NotNull Icon deferImpl(Icon base, T param, final boolean autoUpdatable, @NotNull Function<? super T, ? extends Icon> evaluator) { if (evaluationIsInProgress.get().booleanValue()) { return evaluator.apply(param); } synchronized (LOCK) { Icon cached = myIconsCache.get(param); if (cached != null) { return cached; } long started = myLastClearTimestamp; Icon result = new DeferredIconImpl<>(base, param, true, autoUpdatable, evaluator, (DeferredIcon source, Icon r) -> { synchronized (LOCK) { // check if our result is not outdated yet if (started == myLastClearTimestamp) { myIconsCache.put(((DeferredIconImpl<?>)source).myParam, autoUpdatable ? source : r); } } }); myIconsCache.put(param, result); return result; } } static void evaluateDeferred(@NotNull Runnable runnable) { try { evaluationIsInProgress.set(Boolean.TRUE); runnable.run(); } finally { evaluationIsInProgress.set(Boolean.FALSE); } } @Override public boolean equalIcons(Icon icon1, Icon icon2) { return DeferredIconImpl.equalIcons(icon1, icon2); } }
/** * Copyright (c) 2015-2018, CJ Hare All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * * Neither the name of [project] nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.systematic.trading.input; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyMapOf; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.math.BigDecimal; import java.time.LocalDate; import java.util.EnumMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.systematic.trading.backtest.equity.TickerSymbol; import com.systematic.trading.backtest.input.BacktestEndDate; import com.systematic.trading.backtest.input.BacktestStartDate; import com.systematic.trading.backtest.input.DepositFrequency; import com.systematic.trading.backtest.input.TickerDataset; import com.systematic.trading.backtest.input.FileBaseOutputDirectory; import com.systematic.trading.backtest.input.OutputType; /** * Test for the BacktestLaunchArgumentParser. * * @author CJ Hare */ @RunWith(MockitoJUnitRunner.class) public class BacktestLaunchArgumentsTest { private static final String DIRCTORY_EXCEPTION_MESSAGE = "Directory exception message"; private static final String OUTPUT_EXCEPTION_MESSAGE = "Ooutput Type exception message"; private static final String OPENING_FUNDS_EXCEPTION_MESSAGE = "Opening Funds exception message"; @Mock private LaunchArgumentsParser argumentParser; @Mock private LaunchArgument<BigDecimal> interestRateArgument; @Mock private LaunchArgument<BigDecimal> openingFundsArgument; @Mock private LaunchArgument<BigDecimal> depositAmountArgument; @Mock private LaunchArgument<DepositFrequency> depositFrequencyArgument; @Mock private LaunchArgument<OutputType> outputTypeArgument; @Mock private LaunchArgument<FileBaseOutputDirectory> directoryArgument; @Mock private LaunchArgument<BacktestStartDate> startDateArgument; @Mock private LaunchArgument<BacktestEndDate> endDateArgument; @Mock private EquityArguments equityArguments; /** Launch argument parser instance being tested. */ private BacktestLaunchArguments parser; @Test public void outputType() { final String outputType = "elastic_search"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType); setUpArgumentMap(outputType); setUpOutputArgument(OutputType.ELASTIC_SEARCH); launchArguments(launchArguments); verifyOutputType(OutputType.ELASTIC_SEARCH); verifyOutputTypeArgument(outputType); } @Test public void fileOutputDirectory() { final String outputDirectory = "../../simulations"; final String outputType = "no_display"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType, outputDirectory); setUpArgumentMap(outputType, outputDirectory); setUpDirectoryArgument(outputDirectory); launchArguments(launchArguments); verifyOutputDirectory(outputDirectory); verifyOutputDirectoryArgument(outputType, outputDirectory); } @Test public void openingFunds() { final String outputDirectory = "../../simulations"; final String outputType = "no_display"; final String openingFunds = "101.67"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType, outputDirectory, openingFunds); setUpArgumentMap(outputType, outputDirectory, openingFunds); setUpOpeningFundsArgument(openingFunds); launchArguments(launchArguments); verifyOpeningFunds(openingFunds); verifyOpeningFundsArgument(outputType, outputDirectory, openingFunds); } @Test public void outputArgumentException() { final String outputType = "unmatched output type"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType); setUpOutputArgumentException(); setUpArgumentMap(outputType); launchArgumentsExpectingException(OUTPUT_EXCEPTION_MESSAGE, launchArguments); verifyOutputTypeArgument(outputType); } @Test public void fileOutputDirectoryException() { final String outputType = "unmatched output type"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType); setUpDirectoryArgumentException(); launchArguments(launchArguments); outputDirectoryExpectingException(DIRCTORY_EXCEPTION_MESSAGE); } @Test public void openingFundsException() { final String outputType = "unmatched output type"; final Map<LaunchArgumentKey, String> launchArguments = argumentMap(outputType); setUpOpeningFundsArgumentException(); launchArgumentsExpectingException(OPENING_FUNDS_EXCEPTION_MESSAGE, launchArguments); } @Test public void startDate() { final LocalDate today = LocalDate.now(); setUpStartDate(today); launchArguments(); verifyStartDate(today); verifyStartDateArgument(); } @Test public void endDate() { final LocalDate today = LocalDate.now(); setUpEndDate(today); launchArguments(); verifyEndDate(today); verifyEndDateArgument(); } @Test public void equityDataSet() { final String serviceName = "identity of the data set"; setUpEquityDataSet(serviceName); launchArguments(); verifyEquityDataSet(serviceName); } @Test public void ticketSymbol() { final String tickerSymbol = "SYMBOL"; setUpTickerSymbol(tickerSymbol); launchArguments(); verifyTickerSymbol(tickerSymbol); } @Test public void depositAmount() { final double depositAmount = 205.67; setUpDepositAmount(depositAmount); launchArguments(); verifyDepositAmount(depositAmount); } @Test public void depositFrequency() { final DepositFrequency frequency = DepositFrequency.WEEKLY; setUpDepositFrequency(frequency); launchArguments(); verifyDespoitFrequency(frequency); } @Test public void interestRate() { final double interestRate = 34.67; setUpInterestRate(interestRate); launchArguments(); verifyInterestRate(interestRate); } private void setUpDepositFrequency( final DepositFrequency frequency ) { when(depositFrequencyArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))).thenReturn(frequency); } private void setUpInterestRate( final double rate ) { when(interestRateArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(BigDecimal.valueOf(rate)); } private void setUpDepositAmount( final double amount ) { when(depositAmountArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(BigDecimal.valueOf(amount)); } private void setUpStartDate( final LocalDate startDate ) { when(startDateArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(new BacktestStartDate(startDate)); } private void setUpEndDate( final LocalDate startDate ) { when(endDateArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(new BacktestEndDate(startDate)); } private void setUpTickerSymbol( final String serviceName ) { when(equityArguments.tickerSymbol()).thenReturn(new TickerSymbol(serviceName)); } private void setUpEquityDataSet( final String serviceName ) { when(equityArguments.tickerDataset()).thenReturn(new TickerDataset(serviceName)); } private void outputDirectoryExpectingException( final String expectedMessage ) { try { parser.outputDirectory("WEEKLY_150"); fail("expecting an exception"); } catch (final IllegalArgumentException e) { assertEquals(expectedMessage, e.getMessage()); } } private void launchArgumentsExpectingException( final String expectedMessage, final Map<LaunchArgumentKey, String> arguments ) { try { launchArguments(arguments); fail("expecting an exception"); } catch (final IllegalArgumentException e) { assertEquals(expectedMessage, e.getMessage()); } } private void launchArguments( final Map<LaunchArgumentKey, String> arguments ) { parser = new BacktestLaunchArguments( outputTypeArgument, equityArguments, interestRateArgument, openingFundsArgument, depositAmountArgument, depositFrequencyArgument, startDateArgument, endDateArgument, directoryArgument, arguments); } private void launchArguments() { launchArguments(new EnumMap<>(LaunchArgumentKey.class)); } private void verifyEquityDataSet( final String expected ) { assertNotNull(parser.tickerDataset()); assertEquals(expected, parser.tickerDataset().dataset()); verify(equityArguments, atLeastOnce()).tickerDataset(); } private void verifyTickerSymbol( final String expected ) { assertNotNull(parser.tickerSymbol()); assertEquals(expected, parser.tickerSymbol().symbol()); verify(equityArguments, atLeastOnce()).tickerSymbol(); } private void verifyDepositAmount( final double expected ) { assertNotNull(parser.depositAmount()); assertEquals(BigDecimal.valueOf(expected), parser.depositAmount()); } private void verifyInterestRate( final double expected ) { assertNotNull(parser.interestRate()); assertEquals(BigDecimal.valueOf(expected), parser.interestRate()); } private void verifyDespoitFrequency( final DepositFrequency expected ) { assertNotNull(parser.depositFrequency()); assertEquals(expected, parser.depositFrequency()); } private void verifyOutputType( final OutputType expected ) { assertEquals(expected, parser.outputType()); } private void verifyOutputDirectory( final String baseDirectory ) { assertEquals(String.format("%s/WEEKLY_150/", baseDirectory), parser.outputDirectory("WEEKLY_150")); } private void verifyOpeningFunds( final String openingFunds ) { assertEquals(new BigDecimal(openingFunds), parser.openingFunds()); } private void verifyStartDate( final LocalDate expected ) { assertNotNull(parser.startDateInclusive()); assertEquals(expected, parser.startDateInclusive().date()); } private void verifyEndDate( final LocalDate expected ) { assertNotNull(parser.endDateExclusive()); assertEquals(expected, parser.endDateExclusive().date()); } private void verifyOutputDirectoryArgument( final String outputValue, final String fileBaseDirectory ) { verify(directoryArgument).get(argumentMap(outputValue, fileBaseDirectory)); verifyNoMoreInteractions(directoryArgument); } private void verifyOpeningFundsArgument( final String outputValue, final String fileBaseDirectory, final String openingFunds ) { verify(openingFundsArgument).get(argumentMap(outputValue, fileBaseDirectory, openingFunds)); verifyNoMoreInteractions(openingFundsArgument); } private void verifyStartDateArgument() { verify(startDateArgument).get(new EnumMap<>(LaunchArgumentKey.class)); verifyNoMoreInteractions(startDateArgument); } private void verifyEndDateArgument() { verify(endDateArgument).get(new EnumMap<>(LaunchArgumentKey.class)); verifyNoMoreInteractions(endDateArgument); } private void verifyOutputTypeArgument( final String outputTypeValue ) { verify(outputTypeArgument).get(argumentMap(outputTypeValue)); verifyNoMoreInteractions(outputTypeArgument); } private void setUpOutputArgument( final OutputType type ) { when(outputTypeArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))).thenReturn(type); } private void setUpDirectoryArgument( final String directory ) { when(directoryArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(new FileBaseOutputDirectory(directory)); } private void setUpOpeningFundsArgument( final String openingFunds ) { when(openingFundsArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenReturn(new BigDecimal(openingFunds)); } private void setUpOutputArgumentException() { when(outputTypeArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenThrow(new IllegalArgumentException(OUTPUT_EXCEPTION_MESSAGE)); } private void setUpDirectoryArgumentException() { when(directoryArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenThrow(new IllegalArgumentException(DIRCTORY_EXCEPTION_MESSAGE)); } private void setUpOpeningFundsArgumentException() { when(openingFundsArgument.get(anyMapOf(LaunchArgumentKey.class, String.class))) .thenThrow(new IllegalArgumentException(OPENING_FUNDS_EXCEPTION_MESSAGE)); } private void setUpArgumentMap( final String outputValue ) { when(argumentParser.parse(any(String[].class))).thenReturn(argumentMap(outputValue)); } private void setUpArgumentMap( final String outputValue, final String fileBaseDirectory ) { when(argumentParser.parse(any(String[].class))).thenReturn(argumentMap(outputValue, fileBaseDirectory)); } private void setUpArgumentMap( final String outputValue, final String fileBaseDirectory, final String openingFunds ) { when(argumentParser.parse(any(String[].class))) .thenReturn(argumentMap(outputValue, fileBaseDirectory, openingFunds)); } private Map<LaunchArgumentKey, String> argumentMap( final String outputValue ) { final Map<LaunchArgumentKey, String> arguments = new EnumMap<>(LaunchArgumentKey.class); arguments.put(LaunchArgumentKey.OUTPUT_TYPE, outputValue); return arguments; } private Map<LaunchArgumentKey, String> argumentMap( final String outputValue, final String fileBaseDirectory ) { final Map<LaunchArgumentKey, String> arguments = argumentMap(outputValue); arguments.put(LaunchArgumentKey.FILE_BASE_DIRECTORY, fileBaseDirectory); return arguments; } private Map<LaunchArgumentKey, String> argumentMap( final String outputValue, final String fileBaseDirectory, final String openingFunds ) { final Map<LaunchArgumentKey, String> arguments = argumentMap(outputValue, fileBaseDirectory); arguments.put(LaunchArgumentKey.OPENING_FUNDS, openingFunds); return arguments; } }
package ru.job4j.tracker.actions; import ru.job4j.tracker.interfaces.Input; import ru.job4j.tracker.StartUI; import ru.job4j.tracker.interfaces.ITracker; import java.util.function.Consumer; public class ExitProgramm extends BaseAction { private StartUI stop; public ExitProgramm(int key, String name, StartUI stop) { super(key, name); this.stop = stop; } @Override public void execute(Input input, ITracker tracker, Consumer<String> output) { this.stop.exit(); } }
package uk.gov.hmcts.reform.iacasepaymentsapi.domain.entities.payment; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Date; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class PaymentResponseTest { private String reference = "RC-1590-6786-1063-9996"; private Date dateCreated = new Date(); private String status = "Success"; private String paymentGroupReference = "2020-1590678609071"; private List<StatusHistories> statusHistories = Arrays.asList(new StatusHistories("Success", null, null, null, null)); private PaymentResponse paymentResponse; @BeforeEach public void setUp() { paymentResponse = new PaymentResponse( reference, dateCreated, status, paymentGroupReference, statusHistories); } @Test void should_hold_onto_values() { assertEquals(paymentResponse.getReference(), reference); assertEquals(paymentResponse.getDateCreated(), dateCreated); assertEquals(paymentResponse.getStatus(), status); assertEquals(paymentResponse.getPaymentGroupReference(), paymentGroupReference); } @Test void should_throw_required_field_exception() { paymentResponse = new PaymentResponse(null, null, null, null, null); assertThatThrownBy(paymentResponse::getReference) .isExactlyInstanceOf(NullPointerException.class); assertThatThrownBy(paymentResponse::getDateCreated) .isExactlyInstanceOf(NullPointerException.class); assertThatThrownBy(paymentResponse::getStatus) .isExactlyInstanceOf(NullPointerException.class); assertThatThrownBy(paymentResponse::getPaymentGroupReference) .isExactlyInstanceOf(NullPointerException.class); assertThatThrownBy(paymentResponse::getStatusHistories) .isExactlyInstanceOf(NullPointerException.class); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 freemarker.core; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.IOException; import java.sql.Time; import java.sql.Timestamp; import java.util.Collections; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import freemarker.cache.ConditionalTemplateConfigurationFactory; import freemarker.cache.FileNameGlobMatcher; import freemarker.template.Configuration; import freemarker.template.SimpleDate; import freemarker.template.Template; import freemarker.template.TemplateDateModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModelException; import freemarker.test.TemplateTest; public class DateFormatTest extends TemplateTest { /** 2015-09-06T12:00:00Z */ private static long T = 1441540800000L; private static TemplateDateModel TM = new SimpleDate(new Date(T), TemplateDateModel.DATETIME); @Before public void setup() { Configuration cfg = getConfiguration(); cfg.setIncompatibleImprovements(Configuration.VERSION_2_3_24); cfg.setLocale(Locale.US); cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00")); cfg.setSQLDateAndTimeTimeZone(TimeZone.getTimeZone("UTC")); cfg.setCustomDateFormats(ImmutableMap.of( "epoch", EpochMillisTemplateDateFormatFactory.INSTANCE, "loc", LocAndTZSensitiveTemplateDateFormatFactory.INSTANCE, "div", EpochMillisDivTemplateDateFormatFactory.INSTANCE, "appMeta", AppMetaTemplateDateFormatFactory.INSTANCE, "htmlIso", HTMLISOTemplateDateFormatFactory.INSTANCE)); } @Test public void testCustomFormat() throws Exception { addToDataModel("d", new Date(123456789)); assertOutput( "${d?string.@epoch} ${d?string.@epoch} <#setting locale='de_DE'>${d?string.@epoch}", "123456789 123456789 123456789"); getConfiguration().setDateTimeFormat("@epoch"); assertOutput( "<#assign d = d?datetime>" + "${d} ${d?string} <#setting locale='de_DE'>${d}", "123456789 123456789 123456789"); getConfiguration().setDateTimeFormat("@htmlIso"); assertOutput( "<#assign d = d?datetime>" + "${d} ${d?string} <#setting locale='de_DE'>${d}", "1970-01-02<span class='T'>T</span>10:17:36Z " + "1970-01-02T10:17:36Z " + "1970-01-02<span class='T'>T</span>10:17:36Z"); } @Test public void testLocaleChange() throws Exception { addToDataModel("d", new Date(123456789)); assertOutput( "${d?string.@loc} ${d?string.@loc} " + "<#setting locale='de_DE'>" + "${d?string.@loc} ${d?string.@loc} " + "<#setting locale='en_US'>" + "${d?string.@loc} ${d?string.@loc}", "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 " + "123456789@de_DE:GMT+01:00 123456789@de_DE:GMT+01:00 " + "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00"); getConfiguration().setDateTimeFormat("@loc"); assertOutput( "<#assign d = d?datetime>" + "${d} ${d?string} " + "<#setting locale='de_DE'>" + "${d} ${d?string} " + "<#setting locale='en_US'>" + "${d} ${d?string}", "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 " + "123456789@de_DE:GMT+01:00 123456789@de_DE:GMT+01:00 " + "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00"); } @Test public void testTimeZoneChange() throws Exception { addToDataModel("d", new Date(123456789)); getConfiguration().setDateTimeFormat("iso"); assertOutput( "${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal} " + "<#setting timeZone='GMT+02:00'>" + "${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal} " + "<#setting timeZone='GMT+01:00'>" + "${d?string.@loc} ${d?string.@loc} ${d?datetime?isoLocal}", "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 1970-01-02T11:17:36+01:00 " + "123456789@en_US:GMT+02:00 123456789@en_US:GMT+02:00 1970-01-02T12:17:36+02:00 " + "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 1970-01-02T11:17:36+01:00"); getConfiguration().setDateTimeFormat("@loc"); assertOutput( "<#assign d = d?datetime>" + "${d} ${d?string} " + "<#setting timeZone='GMT+02:00'>" + "${d} ${d?string} " + "<#setting timeZone='GMT+01:00'>" + "${d} ${d?string}", "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00 " + "123456789@en_US:GMT+02:00 123456789@en_US:GMT+02:00 " + "123456789@en_US:GMT+01:00 123456789@en_US:GMT+01:00"); } @Test public void testWrongFormatStrings() throws Exception { getConfiguration().setDateTimeFormat("x1"); assertErrorContains("${.now}", "\"x1\"", "'x'"); assertErrorContains("${.now?string}", "\"x1\"", "'x'"); getConfiguration().setDateTimeFormat("short"); assertErrorContains("${.now?string('x2')}", "\"x2\"", "'x'"); } @Test public void testCustomParameterized() throws Exception { Configuration cfg = getConfiguration(); addToDataModel("d", new SimpleDate(new Date(12345678L), TemplateDateModel.DATETIME)); cfg.setDateTimeFormat("@div 1000"); assertOutput("${d}", "12345"); assertOutput("${d?string}", "12345"); assertOutput("${d?string.@div_100}", "123456"); assertErrorContains("${d?string.@div_xyz}", "\"@div_xyz\"", "\"xyz\""); cfg.setDateTimeFormat("@div"); assertErrorContains("${d}", "\"datetime_format\"", "\"@div\"", "format parameter is required"); } @Test public void testUnknownCustomFormat() throws Exception { { getConfiguration().setDateTimeFormat("@noSuchFormat"); Throwable exc = assertErrorContains( "${.now}", "\"@noSuchFormat\"", "\"noSuchFormat\"", "\"datetime_format\""); assertThat(exc.getCause(), instanceOf(UndefinedCustomFormatException.class)); } { getConfiguration().setDateFormat("@noSuchFormatD"); assertErrorContains( "${.now?date}", "\"@noSuchFormatD\"", "\"noSuchFormatD\"", "\"date_format\""); } { getConfiguration().setTimeFormat("@noSuchFormatT"); assertErrorContains( "${.now?time}", "\"@noSuchFormatT\"", "\"noSuchFormatT\"", "\"time_format\""); } { getConfiguration().setDateTimeFormat(""); Throwable exc = assertErrorContains("${.now?string('@noSuchFormat2')}", "\"@noSuchFormat2\"", "\"noSuchFormat2\""); assertThat(exc.getCause(), instanceOf(UndefinedCustomFormatException.class)); } } @Test public void testNullInModel() throws Exception { addToDataModel("d", new MutableTemplateDateModel()); assertErrorContains("${d}", "nothing inside it"); assertErrorContains("${d?string}", "nothing inside it"); } @Test public void testIcIAndEscaping() throws Exception { Configuration cfg = getConfiguration(); addToDataModel("d", new SimpleDate(new Date(12345678L), TemplateDateModel.DATETIME)); testIcIAndEscapingWhenCustFormsAreAccepted(cfg); cfg.setIncompatibleImprovements(Configuration.VERSION_2_3_23); testIcIAndEscapingWhenCustFormsAreAccepted(cfg); cfg.setCustomDateFormats(Collections.<String, TemplateDateFormatFactory>emptyMap()); cfg.setDateTimeFormat("@epoch"); assertErrorContains("${d}", "\"@epoch\""); cfg.setDateTimeFormat("'@'yyyy"); assertOutput("${d}", "@1970"); cfg.setDateTimeFormat("@@yyyy"); assertOutput("${d}", "@@1970"); cfg.setIncompatibleImprovements(Configuration.VERSION_2_3_24); cfg.setDateTimeFormat("@epoch"); assertErrorContains("${d}", "custom", "\"epoch\""); cfg.setDateTimeFormat("'@'yyyy"); assertOutput("${d}", "@1970"); cfg.setDateTimeFormat("@@yyyy"); assertOutput("${d}", "@@1970"); } protected void testIcIAndEscapingWhenCustFormsAreAccepted(Configuration cfg) throws IOException, TemplateException { cfg.setDateTimeFormat("@epoch"); assertOutput("${d}", "12345678"); cfg.setDateTimeFormat("'@'yyyy"); assertOutput("${d}", "@1970"); cfg.setDateTimeFormat("@@yyyy"); assertOutput("${d}", "@@1970"); } @Test public void testEnvironmentGetters() throws Exception { Template t = new Template(null, "", getConfiguration()); Environment env = t.createProcessingEnvironment(null, null); Configuration cfg = getConfiguration(); String dateFormatStr = "yyyy.MM.dd. (Z)"; String timeFormatStr = "HH:mm"; String dateTimeFormatStr = "yyyy.MM.dd. HH:mm"; cfg.setDateFormat(dateFormatStr); cfg.setTimeFormat(timeFormatStr); cfg.setDateTimeFormat(dateTimeFormatStr); // Test that values are coming from the cache if possible for (Class dateClass : new Class[] { Date.class, Timestamp.class, java.sql.Date.class, Time.class } ) { for (int dateType : new int[] { TemplateDateModel.DATE, TemplateDateModel.TIME, TemplateDateModel.DATETIME }) { String formatString = dateType == TemplateDateModel.DATE ? cfg.getDateFormat() : (dateType == TemplateDateModel.TIME ? cfg.getTimeFormat() : cfg.getDateTimeFormat()); TemplateDateFormat expectedF = env.getTemplateDateFormat(formatString, dateType, dateClass); assertSame(expectedF, env.getTemplateDateFormat(dateType, dateClass)); // Note: Only reads the cache assertSame(expectedF, env.getTemplateDateFormat(formatString, dateType, dateClass)); assertSame(expectedF, env.getTemplateDateFormat(formatString, dateType, dateClass, cfg.getLocale())); assertSame(expectedF, env.getTemplateDateFormat(formatString, dateType, dateClass, cfg.getLocale(), cfg.getTimeZone(), cfg.getSQLDateAndTimeTimeZone())); } } String dateFormatStr2 = dateFormatStr + "'!'"; String timeFormatStr2 = timeFormatStr + "'!'"; String dateTimeFormatStr2 = dateTimeFormatStr + "'!'"; assertEquals("2015.09.06. 13:00", env.getTemplateDateFormat(TemplateDateModel.DATETIME, Date.class).formatToPlainText(TM)); assertEquals("2015.09.06. 13:00!", env.getTemplateDateFormat(dateTimeFormatStr2, TemplateDateModel.DATETIME, Date.class).formatToPlainText(TM)); assertEquals("2015.09.06. (+0100)", env.getTemplateDateFormat(TemplateDateModel.DATE, Date.class).formatToPlainText(TM)); assertEquals("2015.09.06. (+0100)!", env.getTemplateDateFormat(dateFormatStr2, TemplateDateModel.DATE, Date.class).formatToPlainText(TM)); assertEquals("13:00", env.getTemplateDateFormat(TemplateDateModel.TIME, Date.class).formatToPlainText(TM)); assertEquals("13:00!", env.getTemplateDateFormat(timeFormatStr2, TemplateDateModel.TIME, Date.class).formatToPlainText(TM)); assertEquals("2015.09.06. 13:00", env.getTemplateDateFormat(TemplateDateModel.DATETIME, Timestamp.class).formatToPlainText(TM)); assertEquals("2015.09.06. 13:00!", env.getTemplateDateFormat(dateTimeFormatStr2, TemplateDateModel.DATETIME, Timestamp.class).formatToPlainText(TM)); assertEquals("2015.09.06. (+0000)", env.getTemplateDateFormat(TemplateDateModel.DATE, java.sql.Date.class).formatToPlainText(TM)); assertEquals("2015.09.06. (+0000)!", env.getTemplateDateFormat(dateFormatStr2, TemplateDateModel.DATE, java.sql.Date.class).formatToPlainText(TM)); assertEquals("12:00", env.getTemplateDateFormat(TemplateDateModel.TIME, Time.class).formatToPlainText(TM)); assertEquals("12:00!", env.getTemplateDateFormat(timeFormatStr2, TemplateDateModel.TIME, Time.class).formatToPlainText(TM)); { String dateTimeFormatStrLoc = dateTimeFormatStr + " EEEE"; // Gets into cache: TemplateDateFormat format1 = env.getTemplateDateFormat(dateTimeFormatStrLoc, TemplateDateModel.DATETIME, Date.class); assertEquals("2015.09.06. 13:00 Sunday", format1.formatToPlainText(TM)); // Different locale (not cached): assertEquals("2015.09.06. 13:00 Sonntag", env.getTemplateDateFormat(dateTimeFormatStrLoc, TemplateDateModel.DATETIME, Date.class, Locale.GERMANY).formatToPlainText(TM)); // Different locale and zone (not cached): assertEquals("2015.09.06. 14:00 Sonntag", env.getTemplateDateFormat(dateTimeFormatStrLoc, TemplateDateModel.DATETIME, Date.class, Locale.GERMANY, TimeZone.getTimeZone("GMT+02"), TimeZone.getTimeZone("GMT+03")).formatToPlainText(TM)); // Different locale and zone (not cached): assertEquals("2015.09.06. 15:00 Sonntag", env.getTemplateDateFormat(dateTimeFormatStrLoc, TemplateDateModel.DATETIME, java.sql.Date.class, Locale.GERMANY, TimeZone.getTimeZone("GMT+02"), TimeZone.getTimeZone("GMT+03")).formatToPlainText(TM)); // Check for corrupted cache: TemplateDateFormat format2 = env.getTemplateDateFormat(dateTimeFormatStrLoc, TemplateDateModel.DATETIME, Date.class); assertEquals("2015.09.06. 13:00 Sunday", format2.formatToPlainText(TM)); assertSame(format1, format2); } addToDataModel("d", TM); assertErrorContains("${d?string('[wrong]')}", "format string", "[wrong]"); cfg.setDateFormat("[wrong d]"); cfg.setDateTimeFormat("[wrong dt]"); cfg.setTimeFormat("[wrong t]"); assertErrorContains("${d?date}", "\"date_format\"", "[wrong d]"); assertErrorContains("${d?datetime}", "\"datetime_format\"", "[wrong dt]"); assertErrorContains("${d?time}", "\"time_format\"", "[wrong t]"); } @Test public void testAlieses() throws Exception { Configuration cfg = getConfiguration(); cfg.setCustomDateFormats(ImmutableMap.of( "d", new AliasTemplateDateFormatFactory("yyyy-MMM-dd"), "m", new AliasTemplateDateFormatFactory("yyyy-MMM"), "epoch", EpochMillisTemplateDateFormatFactory.INSTANCE)); TemplateConfiguration tc = new TemplateConfiguration(); tc.setCustomDateFormats(ImmutableMap.of( "m", new AliasTemplateDateFormatFactory("yyyy-MMMM"), "i", new AliasTemplateDateFormatFactory("@epoch"))); cfg.setTemplateConfigurations(new ConditionalTemplateConfigurationFactory(new FileNameGlobMatcher("*2*"), tc)); addToDataModel("d", TM); String commonFtl = "${d?string.@d} ${d?string.@m} " + "<#setting locale='fr_FR'>${d?string.@m} " + "<#attempt>${d?string.@i}<#recover>E</#attempt>"; addTemplate("t1.ftl", commonFtl); addTemplate("t2.ftl", commonFtl); // 2015-09-06T12:00:00Z assertOutputForNamed("t1.ftl", "2015-Sep-06 2015-Sep 2015-sept. E"); assertOutputForNamed("t2.ftl", "2015-Sep-06 2015-September 2015-septembre " + T); } @Test public void testAlieses2() throws Exception { Configuration cfg = getConfiguration(); cfg.setCustomDateFormats(ImmutableMap.of( "d", new AliasTemplateDateFormatFactory("yyyy-MMM", ImmutableMap.of( new Locale("en"), "yyyy-MMM'_en'", Locale.UK, "yyyy-MMM'_en_GB'", Locale.FRANCE, "yyyy-MMM'_fr_FR'")))); cfg.setDateTimeFormat("@d"); addToDataModel("d", TM); assertOutput( "<#setting locale='en_US'>${d} " + "<#setting locale='en_GB'>${d} " + "<#setting locale='en_GB_Win'>${d} " + "<#setting locale='fr_FR'>${d} " + "<#setting locale='hu_HU'>${d}", "2015-Sep_en 2015-Sep_en_GB 2015-Sep_en_GB 2015-sept._fr_FR 2015-szept."); } /** * ?date() and such are new in 2.3.24. */ @Test public void testZeroArgDateBI() throws IOException, TemplateException { Configuration cfg = getConfiguration(); cfg.setDateFormat("@epoch"); cfg.setDateTimeFormat("@epoch"); cfg.setTimeFormat("@epoch"); addToDataModel("t", String.valueOf(T)); assertOutput( "${t?date?string.xs_u} ${t?date()?string.xs_u}", "2015-09-06Z 2015-09-06Z"); assertOutput( "${t?time?string.xs_u} ${t?time()?string.xs_u}", "12:00:00Z 12:00:00Z"); assertOutput( "${t?datetime?string.xs_u} ${t?datetime()?string.xs_u}", "2015-09-06T12:00:00Z 2015-09-06T12:00:00Z"); } @Test public void testAppMetaRoundtrip() throws IOException, TemplateException { Configuration cfg = getConfiguration(); cfg.setDateFormat("@appMeta"); cfg.setDateTimeFormat("@appMeta"); cfg.setTimeFormat("@appMeta"); addToDataModel("t", String.valueOf(T) + "/foo"); assertOutput( "${t?date} ${t?date()}", T + " " + T + "/foo"); assertOutput( "${t?time} ${t?time()}", T + " " + T + "/foo"); assertOutput( "${t?datetime} ${t?datetime()}", T + " " + T + "/foo"); } @Test public void testUnknownDateType() throws IOException, TemplateException { addToDataModel("u", new Date(T)); assertErrorContains("${u?string}", "isn't known"); assertOutput("${u?string('yyyy')}", "2015"); assertOutput("<#assign s = u?string>${s('yyyy')}", "2015"); } private static class MutableTemplateDateModel implements TemplateDateModel { private Date date; public void setDate(Date date) { this.date = date; } public Date getAsDate() throws TemplateModelException { return date; } public int getDateType() { return DATETIME; } } }
/** * Copyright Pravega Authors. * * 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 io.pravega.segmentstore.contracts.tables; import lombok.Builder; import lombok.Getter; /** * Configuration for a Table Segment. */ @Builder @Getter public class TableSegmentConfig { public static final TableSegmentConfig NO_CONFIG = TableSegmentConfig.builder().build(); @Builder.Default private final int keyLength = 0; @Override public String toString() { return String.format("KeyLength = %s", this.keyLength); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.cxf.tools.corba.processors.idl; import javax.wsdl.Definition; import javax.xml.namespace.QName; import antlr.collections.AST; import org.apache.cxf.binding.corba.wsdl.Enum; import org.apache.cxf.binding.corba.wsdl.Enumerator; import org.apache.ws.commons.schema.XmlSchema; import org.apache.ws.commons.schema.XmlSchemaEnumerationFacet; import org.apache.ws.commons.schema.XmlSchemaSimpleType; import org.apache.ws.commons.schema.XmlSchemaSimpleTypeRestriction; import org.apache.ws.commons.schema.constants.Constants; public class EnumVisitor extends VisitorBase { public EnumVisitor(Scope scope, Definition defn, XmlSchema schemaRef, WSDLASTVisitor wsdlVisitor) { super(scope, defn, schemaRef, wsdlVisitor); } public static boolean accept(AST node) { return node.getType() == IDLTokenTypes.LITERAL_enum; } public void visit(AST enumNode) { // <enum_type> ::= "enum" <identifier> "{" <enumerator> {"," <enumerator>}* "}" // <enumerator> ::= <identifier> AST enumNameNode = enumNode.getFirstChild(); Scope enumNameScope = new Scope(getScope(), enumNameNode); // xmlschema:enum XmlSchemaSimpleType enumSchemaSimpleType = new XmlSchemaSimpleType(schema, true); enumSchemaSimpleType.setName(mapper.mapToQName(enumNameScope)); XmlSchemaSimpleTypeRestriction enumSchemaSimpleTypeRestriction = new XmlSchemaSimpleTypeRestriction(); enumSchemaSimpleTypeRestriction.setBaseTypeName(Constants.XSD_STRING); //XmlSchemaSimpleTypeContent xmlSchemaSimpleTypeContent = enumSchemaSimpleTypeRestriction; enumSchemaSimpleType.setContent(enumSchemaSimpleTypeRestriction); // corba:enum Enum corbaEnum = new Enum(); corbaEnum.setQName(new QName(typeMap.getTargetNamespace(), enumNameScope.toString())); corbaEnum.setRepositoryID(enumNameScope.toIDLRepositoryID()); corbaEnum.setType(enumSchemaSimpleType.getQName()); AST node = enumNameNode.getNextSibling(); while (node != null) { // xmlschema:enumeration XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); enumeration.setValue(node.toString()); enumSchemaSimpleTypeRestriction.getFacets().add(enumeration); // corba:enumerator Enumerator enumerator = new Enumerator(); enumerator.setValue(node.toString()); corbaEnum.getEnumerator().add(enumerator); node = node.getNextSibling(); } // add corbaType typeMap.getStructOrExceptionOrUnion().add(corbaEnum); // REVISIT: are there assignments needed? setSchemaType(enumSchemaSimpleType); setCorbaType(corbaEnum); } }
package me.zhengjie.modules.finance.service.dto; import lombok.Data; import me.zhengjie.modules.basic_management.Archivesmouthsmanagement.service.dto.ArchiveDto; import me.zhengjie.modules.basic_management.Archivesmouthsmanagement.service.dto.ArchiveTreeDto; import java.io.Serializable; import java.util.List; @Data public class TreeDTO implements Serializable { /** * ID */ private Long id; /** * 名称 */ private String name; private List children; public TreeDTO(Long id, String name, List<ArchiveTreeDto> children) { this.id = id; this.name = name; this.children = children; } }
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2020 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.operator; import net.imglib2.ops.operation.real.binary.RealDifference; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.DoubleType; import org.scijava.plugin.Plugin; /** * Image Calculator plugin for {@link RealDifference} operation. * * @author Curtis Rueden */ @Deprecated @Plugin(type = CalculatorOp.class, name = "Difference", priority = OpDifference.PRIORITY) public class OpDifference<I1 extends RealType<I1>, I2 extends RealType<I2>> extends AbstractCalculatorOp<I1, I2> { public static final int PRIORITY = OpAverage.PRIORITY - 1; public OpDifference() { super(new RealDifference<I1, I2, DoubleType>()); } }
package skill.handler.subtract; import com.amazon.speech.ui.SimpleCard; import io.klerch.alexa.state.handler.AWSDynamoStateHandler; import io.klerch.alexa.state.handler.AlexaStateHandler; import io.klerch.alexa.state.utils.AlexaStateException; import io.klerch.alexa.tellask.model.AlexaInput; import io.klerch.alexa.tellask.model.AlexaOutput; import io.klerch.alexa.tellask.model.AlexaOutputSlot; import io.klerch.alexa.tellask.schema.AlexaIntentHandler; import io.klerch.alexa.tellask.schema.annotation.AlexaIntentListener; import io.klerch.alexa.tellask.schema.type.AlexaOutputFormat; import io.klerch.alexa.tellask.util.AlexaRequestHandlerException; import skill.model.Calculation; @AlexaIntentListener(customIntents = "Subtract") public class SubtractTwoIntentHandler implements AlexaIntentHandler { @Override public boolean verify(final AlexaInput input) { return input.hasSlotIsNumber("b") && input.hasSlotIsNumber("a"); } @Override public AlexaOutput handleRequest(final AlexaInput input) throws AlexaRequestHandlerException, AlexaStateException { // get state handlers for session and dynamoDB of States SDK final AlexaStateHandler sessionHandler = input.getSessionStateHandler(); final AlexaStateHandler dynamoHandler = new AWSDynamoStateHandler(sessionHandler.getSession()); // try get calculation from session first, if not there read or create in dynamo // cause we permanently save the precision a user can set final Calculation calc = sessionHandler.readModel(Calculation.class) .orElse(dynamoHandler.readModel(Calculation.class) .orElse(dynamoHandler.createModel(Calculation.class))); // number from slot (already ensured is a number in verfiy final Integer a = Integer.valueOf(input.getSlotValue("a")); // number from slot (already ensured is a number in verfiy final Integer b = Integer.valueOf(input.getSlotValue("b")); calc.subtract(a, b); final SimpleCard formulaCard = new SimpleCard(); formulaCard.setContent(a + " - " + b + " = " + calc.getResult()); // ensure model is written back to session only (in case it was read out from dynamo) // we'd like to avoid unnecessary roundtrips to dynamo at this point cause we'd only // change the result which is not saved permanently calc.setHandler(sessionHandler); return AlexaOutput.ask("SaySubtractResult") .withCard(formulaCard) .putSlot(new AlexaOutputSlot("a", a).formatAs(AlexaOutputFormat.NUMBER)) .putSlot(new AlexaOutputSlot("b", b).formatAs(AlexaOutputFormat.NUMBER)) .putState(calc) .withReprompt(true) .build(); } @Override public AlexaOutput handleError(final AlexaRequestHandlerException exception) { return AlexaOutput.tell("SaySorry").build(); } }
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.job.lite.internal.sharding; import com.dangdang.ddframe.job.executor.ShardingContexts; import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration; import com.dangdang.ddframe.job.lite.internal.config.ConfigurationService; import com.dangdang.ddframe.job.lite.internal.schedule.JobRegistry; import com.dangdang.ddframe.job.lite.internal.storage.JobNodeStorage; import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 执行作业的服务. * * @author zhangliang * @author caohao */ public final class ExecutionService { private final String jobName; private final JobNodeStorage jobNodeStorage; private final ConfigurationService configService; public ExecutionService(final CoordinatorRegistryCenter regCenter, final String jobName) { this.jobName = jobName; jobNodeStorage = new JobNodeStorage(regCenter, jobName); configService = new ConfigurationService(regCenter, jobName); } /** * 注册作业启动信息. * * @param shardingContexts 分片上下文 */ public void registerJobBegin(final ShardingContexts shardingContexts) { JobRegistry.getInstance().setJobRunning(jobName, true); if (!configService.load(true).isMonitorExecution()) { return; } for (int each : shardingContexts.getShardingItemParameters().keySet()) { jobNodeStorage.fillEphemeralJobNode(ShardingNode.getRunningNode(each), ""); } } /** * 注册作业完成信息. * * @param shardingContexts 分片上下文 */ public void registerJobCompleted(final ShardingContexts shardingContexts) { JobRegistry.getInstance().setJobRunning(jobName, false); if (!configService.load(true).isMonitorExecution()) { return; } for (int each : shardingContexts.getShardingItemParameters().keySet()) { jobNodeStorage.removeJobNodeIfExisted(ShardingNode.getRunningNode(each)); } } /** * 清除全部分片的运行状态. */ public void clearAllRunningInfo() { clearRunningInfo(getAllItems()); } /** * 清除分配分片项的运行状态. * * @param items 需要清理的分片项列表 */ public void clearRunningInfo(final List<Integer> items) { for (int each : items) { jobNodeStorage.removeJobNodeIfExisted(ShardingNode.getRunningNode(each)); } } /** * 判断分片项中是否还有执行中的作业. * * @param items 需要判断的分片项列表 * @return 分片项中是否还有执行中的作业 */ public boolean hasRunningItems(final Collection<Integer> items) { LiteJobConfiguration jobConfig = configService.load(true); if (null == jobConfig || !jobConfig.isMonitorExecution()) { return false; } for (int each : items) { if (jobNodeStorage.isJobNodeExisted(ShardingNode.getRunningNode(each))) { return true; } } return false; } /** * 判断是否还有执行中的作业. * * @return 是否还有执行中的作业 */ public boolean hasRunningItems() { return hasRunningItems(getAllItems()); } private List<Integer> getAllItems() { int shardingTotalCount = configService.load(true).getTypeConfig().getCoreConfig().getShardingTotalCount(); List<Integer> result = new ArrayList<>(shardingTotalCount); for (int i = 0; i < shardingTotalCount; i++) { result.add(i); } return result; } /** * 如果当前分片项仍在运行则设置任务被错过执行的标记. * * @param items 需要设置错过执行的任务分片项 * @return 是否错过本次执行 */ public boolean misfireIfHasRunningItems(final Collection<Integer> items) { if (!hasRunningItems(items)) { return false; } setMisfire(items); return true; } /** * 设置任务被错过执行的标记. * * @param items 需要设置错过执行的任务分片项 */ public void setMisfire(final Collection<Integer> items) { for (int each : items) { jobNodeStorage.createJobNodeIfNeeded(ShardingNode.getMisfireNode(each)); } } /** * 获取标记被错过执行的任务分片项. * * @param items 需要获取标记被错过执行的任务分片项 * @return 标记被错过执行的任务分片项 */ public List<Integer> getMisfiredJobItems(final Collection<Integer> items) { List<Integer> result = new ArrayList<>(items.size()); for (int each : items) { if (jobNodeStorage.isJobNodeExisted(ShardingNode.getMisfireNode(each))) { result.add(each); } } return result; } /** * 清除任务被错过执行的标记. * * @param items 需要清除错过执行的任务分片项 */ public void clearMisfire(final Collection<Integer> items) { for (int each : items) { jobNodeStorage.removeJobNodeIfExisted(ShardingNode.getMisfireNode(each)); } } /** * 获取禁用的任务分片项. * * @param items 需要获取禁用的任务分片项 * @return 禁用的任务分片项 */ public List<Integer> getDisabledItems(final List<Integer> items) { List<Integer> result = new ArrayList<>(items.size()); for (int each : items) { if (jobNodeStorage.isJobNodeExisted(ShardingNode.getDisabledNode(each))) { result.add(each); } } return result; } }
/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds licenses this file * to you 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.jclouds.openstack.glance.v1_0.internal; import java.util.Properties; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.openstack.glance.v1_0.GlanceAsyncApi; import com.google.common.base.Function; import com.google.inject.Module; /** * Base class for writing KeyStone Rest Api Expect tests * * @author Adrian Cole */ public class BaseGlanceAsyncApiExpectTest extends BaseGlanceExpectTest<GlanceAsyncApi> { public GlanceAsyncApi createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) { return createInjector(fn, module, props).getInstance(GlanceAsyncApi.class); } }
/* * 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 com.facebook.presto.metadata; import com.facebook.presto.client.NodeVersion; import com.facebook.presto.server.NoOpFailureDetector; import com.facebook.presto.spi.Node; import com.facebook.presto.spi.NodeManager; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import io.airlift.discovery.client.ServiceDescriptor; import io.airlift.discovery.client.ServiceSelector; import io.airlift.discovery.client.testing.StaticServiceSelector; import io.airlift.http.client.HttpClient; import io.airlift.http.client.testing.TestingHttpClient; import io.airlift.http.client.testing.TestingResponse; import io.airlift.node.NodeConfig; import io.airlift.node.NodeInfo; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import static com.facebook.presto.spi.NodeState.ACTIVE; import static com.facebook.presto.spi.NodeState.INACTIVE; import static io.airlift.discovery.client.ServiceDescriptor.serviceDescriptor; import static io.airlift.http.client.HttpStatus.OK; import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; @Test(singleThreaded = true) public class TestDiscoveryNodeManager { private final NodeInfo nodeInfo = new NodeInfo("test"); private NodeVersion expectedVersion; private List<PrestoNode> activeNodes; private List<PrestoNode> inactiveNodes; private PrestoNode coordinator; private ServiceSelector selector; private HttpClient testHttpClient; @BeforeMethod public void setup() { testHttpClient = new TestingHttpClient(input -> new TestingResponse(OK, ArrayListMultimap.create(), ACTIVE.name().getBytes())); expectedVersion = new NodeVersion("1"); coordinator = new PrestoNode(UUID.randomUUID().toString(), URI.create("https://192.0.2.8"), expectedVersion); activeNodes = ImmutableList.of( new PrestoNode(nodeInfo.getNodeId(), URI.create("http://192.0.1.1"), expectedVersion), new PrestoNode(UUID.randomUUID().toString(), URI.create("http://192.0.2.1:8080"), expectedVersion), new PrestoNode(UUID.randomUUID().toString(), URI.create("http://192.0.2.3"), expectedVersion), coordinator); inactiveNodes = ImmutableList.of( new PrestoNode(UUID.randomUUID().toString(), URI.create("https://192.0.3.9"), NodeVersion.UNKNOWN), new PrestoNode(UUID.randomUUID().toString(), URI.create("https://192.0.4.9"), new NodeVersion("2")) ); List<ServiceDescriptor> descriptors = new ArrayList<>(); for (PrestoNode node : Iterables.concat(activeNodes, inactiveNodes)) { descriptors.add(serviceDescriptor("presto") .setNodeId(node.getNodeIdentifier()) .addProperty("http", node.getHttpUri().toString()) .addProperty("node_version", node.getNodeVersion().toString()) .addProperty("coordinator", String.valueOf(node.equals(coordinator))) .build()); } selector = new StaticServiceSelector(descriptors); } @Test public void testGetAllNodes() throws Exception { DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, nodeInfo, new NoOpFailureDetector(), expectedVersion, testHttpClient); AllNodes allNodes = manager.getAllNodes(); Set<Node> activeNodes = allNodes.getActiveNodes(); assertEqualsIgnoreOrder(activeNodes, this.activeNodes); for (Node actual : activeNodes) { for (Node expected : this.activeNodes) { assertNotSame(actual, expected); } } assertEqualsIgnoreOrder(activeNodes, manager.getNodes(ACTIVE)); Set<Node> inactiveNodes = allNodes.getInactiveNodes(); assertEqualsIgnoreOrder(inactiveNodes, this.inactiveNodes); for (Node actual : inactiveNodes) { for (Node expected : this.inactiveNodes) { assertNotSame(actual, expected); } } assertEqualsIgnoreOrder(inactiveNodes, manager.getNodes(INACTIVE)); } @Test public void testGetCurrentNode() { Node expected = activeNodes.get(0); NodeInfo nodeInfo = new NodeInfo(new NodeConfig() .setEnvironment("test") .setNodeId(expected.getNodeIdentifier())); DiscoveryNodeManager manager = new DiscoveryNodeManager(selector, nodeInfo, new NoOpFailureDetector(), expectedVersion, testHttpClient); assertEquals(manager.getCurrentNode(), expected); } @Test public void testGetCoordinators() throws Exception { NodeManager manager = new DiscoveryNodeManager(selector, nodeInfo, new NoOpFailureDetector(), expectedVersion, testHttpClient); assertEquals(manager.getCoordinators(), ImmutableSet.of(coordinator)); } @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = ".* current node not returned .*") public void testGetCurrentNodeRequired() { new DiscoveryNodeManager(selector, new NodeInfo("test"), new NoOpFailureDetector(), expectedVersion, testHttpClient); } }
package com.github.stigmata.birthmarks.is; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import com.github.stigmata.Birthmark; import com.github.stigmata.BirthmarkContext; import com.github.stigmata.BirthmarkElement; import com.github.stigmata.birthmarks.BirthmarkExtractVisitor; import com.github.stigmata.birthmarks.NullBirthmarkElement; import com.github.stigmata.digger.ClassFileEntry; import com.github.stigmata.digger.ClasspathContext; import com.github.stigmata.utils.WellknownClassManager; /** * * * * @author Haruaki TAMADA */ public class InheritanceStructureBirthmarkExtractVisitor extends BirthmarkExtractVisitor{ public InheritanceStructureBirthmarkExtractVisitor(ClassVisitor visitor, Birthmark birthmark, BirthmarkContext context){ super(visitor, birthmark, context); } @Override public void visit(int version, int access, String nameInClassFormat, String signature, String superNameInClassFormat, String[] interfaces){ if((access & Opcodes.ACC_INTERFACE) != Opcodes.ACC_INTERFACE){ ClasspathContext context = getEnvironment().getClasspathContext(); String name = nameInClassFormat.replace('/', '.'); ClassFileEntry entry = context.findEntry(name); if(entry == null){ String superName = superNameInClassFormat.replace('/', '.'); ClassFileEntry parent = context.findEntry(superName); if(parent != null){ addIsBirthmark(name); addIsBirthmark(superName); } else{ addFailur(new ClassNotFoundException(superName)); } } else{ try{ Class<?> clazz = context.findClass(nameInClassFormat); addISBirthmark(clazz); } catch(ClassNotFoundException e){ addFailur(e); } } } } private void addIsBirthmark(String className){ WellknownClassManager wcm = getEnvironment().getWellknownClassManager(); BirthmarkElement element; if(wcm.isWellKnownClass(className)){ element = new BirthmarkElement(className); } else{ element = NullBirthmarkElement.getInstance(); } addElement(element); } private void addISBirthmark(Class<?> c){ Class<?> targetClass = c; WellknownClassManager wcm = getEnvironment().getWellknownClassManager(); do{ String className = c.getName(); BirthmarkElement element = null; if(wcm.isWellKnownClass(className)){ element = new BirthmarkElement(className); } else{ element = NullBirthmarkElement.getInstance(); } addElement(element); targetClass = targetClass.getSuperclass(); } while(!(c instanceof Object)); addElement(new BirthmarkElement("java.lang.Object")); } }
package mekanism.common.content.teleporter; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.Set; import java.util.UUID; import javax.annotation.Nullable; import mekanism.api.Coord4D; import mekanism.api.NBTConstants; import mekanism.api.text.EnumColor; import mekanism.common.lib.frequency.Frequency; import mekanism.common.lib.frequency.FrequencyType; import mekanism.common.lib.frequency.IColorableFrequency; import mekanism.common.util.NBTUtils; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; public class TeleporterFrequency extends Frequency implements IColorableFrequency { private final Set<Coord4D> activeCoords = new ObjectOpenHashSet<>(); private EnumColor color = EnumColor.PURPLE; /** * @param uuid Should only be null if we have incomplete data that we are loading */ public TeleporterFrequency(String n, @Nullable UUID uuid) { super(FrequencyType.TELEPORTER, n, uuid); } public TeleporterFrequency() { super(FrequencyType.TELEPORTER); } public Set<Coord4D> getActiveCoords() { return activeCoords; } @Override public int getSyncHash() { int code = super.getSyncHash(); code = 31 * code + color.ordinal(); return code; } @Override public EnumColor getColor() { return color; } @Override public void setColor(EnumColor color) { this.color = color; } @Override public void update(TileEntity tile) { super.update(tile); activeCoords.add(Coord4D.get(tile)); } @Override public void onDeactivate(TileEntity tile) { super.onDeactivate(tile); activeCoords.remove(Coord4D.get(tile)); } public Coord4D getClosestCoords(Coord4D coord) { Coord4D closest = null; for (Coord4D iterCoord : activeCoords) { if (iterCoord.equals(coord)) { continue; } if (closest == null) { closest = iterCoord; continue; } if (coord.dimension != closest.dimension && coord.dimension == iterCoord.dimension) { closest = iterCoord; } else if (coord.dimension != closest.dimension || coord.dimension == iterCoord.dimension) { if (coord.distanceTo(closest) > coord.distanceTo(iterCoord)) { closest = iterCoord; } } } return closest; } @Override protected void read(CompoundNBT nbtTags) { super.read(nbtTags); NBTUtils.setEnumIfPresent(nbtTags, NBTConstants.COLOR, EnumColor::byIndexStatic, this::setColor); } @Override protected void read(PacketBuffer dataStream) { super.read(dataStream); setColor(dataStream.readEnum(EnumColor.class)); } @Override public void write(CompoundNBT nbtTags) { super.write(nbtTags); nbtTags.putInt(NBTConstants.COLOR, color.ordinal()); } @Override public void write(PacketBuffer buffer) { super.write(buffer); buffer.writeEnum(color); } }
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 com.huawei.cookbook.util; /** * Constants for CommonOperator */ public class CommonOperationConstants { /** * CHECK_PERMISSION */ public static final int CHECK_PERMISSION = 2000; /** * START_ABILITY */ public static final int START_ABILITY = 2020; /** * CHECK_PACKAGE_INSTALLATION */ public static final int CHECK_PACKAGE_INSTALLATION = 2030; /** * OPEN_URL */ public static final int OPEN_URL = 2040; /** * get unique id */ public static final int GET_UNIQUE_ID = 2050; /** * to vmall */ public static final int TO_VMALL = 2060; /** * check register */ public static final int CHECK_REGISTER = 2070; /** * hilink register */ public static final int HILINK_REGISTER = 2080; /** * hilink register */ public static final int HW_SHARE_REGISTER = 2090; /** * SUCCESS code */ public static final int SUCCESS = 0; private CommonOperationConstants() { } }
package cn.zxJava.service; import cn.zxJava.domain.TbUser; import cn.zxJava.entity.Result; /** * 拓薪教育 -- 腾讯课程认证机构 * 樱木老师 */ public interface UserService { String sendCode(String phone) throws Exception; Result regist(TbUser tbUser, String code); }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.services.storagegateway.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * DeleteFileShareOutput * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30/DeleteFileShare" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteFileShareResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the deleted file share. * </p> */ private String fileShareARN; /** * <p> * The Amazon Resource Name (ARN) of the deleted file share. * </p> * * @param fileShareARN * The Amazon Resource Name (ARN) of the deleted file share. */ public void setFileShareARN(String fileShareARN) { this.fileShareARN = fileShareARN; } /** * <p> * The Amazon Resource Name (ARN) of the deleted file share. * </p> * * @return The Amazon Resource Name (ARN) of the deleted file share. */ public String getFileShareARN() { return this.fileShareARN; } /** * <p> * The Amazon Resource Name (ARN) of the deleted file share. * </p> * * @param fileShareARN * The Amazon Resource Name (ARN) of the deleted file share. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteFileShareResult withFileShareARN(String fileShareARN) { setFileShareARN(fileShareARN); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFileShareARN() != null) sb.append("FileShareARN: ").append(getFileShareARN()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteFileShareResult == false) return false; DeleteFileShareResult other = (DeleteFileShareResult) obj; if (other.getFileShareARN() == null ^ this.getFileShareARN() == null) return false; if (other.getFileShareARN() != null && other.getFileShareARN().equals(this.getFileShareARN()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFileShareARN() == null) ? 0 : getFileShareARN().hashCode()); return hashCode; } @Override public DeleteFileShareResult clone() { try { return (DeleteFileShareResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.springframework.boot.autoconfigure.data; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.StandardAnnotationMetadata; import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource; import org.springframework.data.repository.config.BootstrapMode; import org.springframework.data.repository.config.RepositoryConfigurationDelegate; import org.springframework.data.repository.config.RepositoryConfigurationExtension; import org.springframework.data.util.Streamable; import java.lang.annotation.Annotation; /** * Base {@link ImportBeanDefinitionRegistrar} used to auto-configure Spring Data * Repositories. * * @author Phillip Webb * @author Dave Syer * @author Oliver Gierke * @since 1.0.0 */ public abstract class AbstractRepositoryConfigurationSourceSupport implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { private ResourceLoader resourceLoader; private BeanFactory beanFactory; private Environment environment; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { new RepositoryConfigurationDelegate(getConfigurationSource(registry), this.resourceLoader, this.environment) .registerRepositoriesIn(registry, getRepositoryConfigurationExtension()); } private AnnotationRepositoryConfigurationSource getConfigurationSource( BeanDefinitionRegistry beanDefinitionRegistry) { StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getConfiguration(), true); return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(), this.resourceLoader, this.environment, beanDefinitionRegistry) { @Override public Streamable<String> getBasePackages() { return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages(); } @Override public BootstrapMode getBootstrapMode() { return AbstractRepositoryConfigurationSourceSupport.this.getBootstrapMode(); } }; } protected Streamable<String> getBasePackages() { return Streamable.of(AutoConfigurationPackages.get(this.beanFactory)); } /** * The Spring Data annotation used to enable the particular repository support. * * @return the annotation class */ protected abstract Class<? extends Annotation> getAnnotation(); /** * The configuration class that will be used by Spring Boot as a template. * * @return the configuration class */ protected abstract Class<?> getConfiguration(); /** * The {@link RepositoryConfigurationExtension} for the particular repository support. * * @return the repository configuration extension */ protected abstract RepositoryConfigurationExtension getRepositoryConfigurationExtension(); /** * The {@link BootstrapMode} for the particular repository support. Defaults to * {@link BootstrapMode#DEFAULT}. * * @return the bootstrap mode */ protected BootstrapMode getBootstrapMode() { return BootstrapMode.DEFAULT; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
package cn.kerison.sample; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
package net.gvsun.gsquestionpool.domain; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.Set; /** * The persistent class for the t_assignment database table. * */ @Entity @Table(name="t_assignment") @NamedQuery(name="TAssignment.findAll", query="SELECT t FROM TAssignment t") public class TAssignment implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Lob private String content; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_time") private Date createdTime; private String description; @Column(name="is_check_all") private Integer isCheckAll; @Column(name="is_group") private Integer isGroup; private Integer isSubmit; private Integer mins; @Column(name="need_submit") private Integer needSubmit; private Integer sequence; @Column(name="site_id") private Integer siteId; private Integer status; private String teacherFilePath; private Integer testParentId; private String title; private String type; //bi-directional many-to-one association to WkFolder @ManyToOne @JoinColumn(name="folder_id") private WkFolder wkFolder; //bi-directional many-to-one association to User @ManyToOne @JoinColumn(name="created_by") private User user; //bi-directional many-to-one association to TAssignmentAnswerAssign @OneToOne(mappedBy="TAssignment") private TAssignmentAnswerAssign TAssignmentAnswerAssign; //bi-directional many-to-one association to TAssignmentControl @OneToOne(mappedBy="TAssignment") private TAssignmentControl TAssignmentControl; //bi-directional many-to-one association to TAssignmentGrading @OneToMany(mappedBy="TAssignment") private Set<TAssignmentGrading> TAssignmentGradings; //bi-directional many-to-one association to TAssignmentItemComponent @OneToMany(mappedBy="TAssignment") private Set<TAssignmentItemComponent> TAssignmentItemComponents; //bi-directional many-to-one association to TAssignmentItemMapping @OneToMany(mappedBy="TAssignment") private Set<TAssignmentItemMapping> TAssignmentItemMappings; @ManyToOne @JoinColumn(name="exam_questionpool_id") private ExamQuestionpool examQuestionpool; //bi-directional many-to-many association to TAssignmentQuestionpool @ManyToMany @JoinTable( name="t_assignment_question" , joinColumns={ @JoinColumn(name="t_assignment_id") } , inverseJoinColumns={ @JoinColumn(name="t_question_id") } ) private Set<TAssignmentQuestionpool> TAssignmentQuestionpools; //bi-directional many-to-one association to TAssignmentSection @OneToMany(mappedBy="TAssignment", cascade = { CascadeType.REMOVE }, fetch = FetchType.EAGER) private Set<TAssignmentSection> TAssignmentSections; //bi-directional many-to-one association to TGradeObject @OneToMany(mappedBy="TAssignment") private Set<TGradeObject> TGradeObjects; @Column(name="subscribe_exam_id") private Integer subScribeExamId; public TAssignment() { } public Integer getSubScribeExamId() { return subScribeExamId; } public void setSubScribeExamId(Integer subScribeExamId) { this.subScribeExamId = subScribeExamId; } public Integer getId() { return this.id; } public void setId(int id) { this.id = id; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } public Date getCreatedTime() { return this.createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public Integer getIsCheckAll() { return this.isCheckAll; } public void setIsCheckAll(int isCheckAll) { this.isCheckAll = isCheckAll; } public Integer getIsGroup() { return this.isGroup; } public void setIsGroup(int isGroup) { this.isGroup = isGroup; } public Integer getIsSubmit() { return this.isSubmit; } public void setIsSubmit(int isSubmit) { this.isSubmit = isSubmit; } public Integer getMins() { return this.mins; } public void setMins(int mins) { this.mins = mins; } public Integer getNeedSubmit() { return this.needSubmit; } public void setNeedSubmit(int needSubmit) { this.needSubmit = needSubmit; } public Integer getSequence() { return this.sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public Integer getSiteId() { return this.siteId; } public void setSiteId(int siteId) { this.siteId = siteId; } public Integer getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public String getTeacherFilePath() { return this.teacherFilePath; } public void setTeacherFilePath(String teacherFilePath) { this.teacherFilePath = teacherFilePath; } public Integer getTestParentId() { return this.testParentId; } public void setTestParentId(int testParentId) { this.testParentId = testParentId; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public WkFolder getWkFolder() { return this.wkFolder; } public void setWkFolder(WkFolder wkFolder) { this.wkFolder = wkFolder; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } public ExamQuestionpool getExamQuestionpool() { return examQuestionpool; } public void setExamQuestionpool(ExamQuestionpool examQuestionpool) { this.examQuestionpool = examQuestionpool; } public TAssignmentAnswerAssign getTAssignmentAnswerAssign() { return this.TAssignmentAnswerAssign; } public void setTAssignmentAnswerAssign(TAssignmentAnswerAssign TAssignmentAnswerAssign) { this.TAssignmentAnswerAssign = TAssignmentAnswerAssign; } public TAssignmentControl getTAssignmentControl() { return this.TAssignmentControl; } public void setTAssignmentControl(TAssignmentControl TAssignmentControl) { this.TAssignmentControl = TAssignmentControl; } public Set<TAssignmentGrading> getTAssignmentGradings() { return this.TAssignmentGradings; } public void setTAssignmentGradings(Set<TAssignmentGrading> TAssignmentGradings) { this.TAssignmentGradings = TAssignmentGradings; } public TAssignmentGrading addTAssignmentGrading(TAssignmentGrading TAssignmentGrading) { getTAssignmentGradings().add(TAssignmentGrading); TAssignmentGrading.setTAssignment(this); return TAssignmentGrading; } public TAssignmentGrading removeTAssignmentGrading(TAssignmentGrading TAssignmentGrading) { getTAssignmentGradings().remove(TAssignmentGrading); TAssignmentGrading.setTAssignment(null); return TAssignmentGrading; } public Set<TAssignmentItemComponent> getTAssignmentItemComponents() { return this.TAssignmentItemComponents; } public void setTAssignmentItemComponents(Set<TAssignmentItemComponent> TAssignmentItemComponents) { this.TAssignmentItemComponents = TAssignmentItemComponents; } public TAssignmentItemComponent addTAssignmentItemComponent(TAssignmentItemComponent TAssignmentItemComponent) { getTAssignmentItemComponents().add(TAssignmentItemComponent); TAssignmentItemComponent.setTAssignment(this); return TAssignmentItemComponent; } public TAssignmentItemComponent removeTAssignmentItemComponent(TAssignmentItemComponent TAssignmentItemComponent) { getTAssignmentItemComponents().remove(TAssignmentItemComponent); TAssignmentItemComponent.setTAssignment(null); return TAssignmentItemComponent; } public Set<TAssignmentItemMapping> getTAssignmentItemMappings() { return this.TAssignmentItemMappings; } public void setTAssignmentItemMappings(Set<TAssignmentItemMapping> TAssignmentItemMappings) { this.TAssignmentItemMappings = TAssignmentItemMappings; } public TAssignmentItemMapping addTAssignmentItemMapping(TAssignmentItemMapping TAssignmentItemMapping) { getTAssignmentItemMappings().add(TAssignmentItemMapping); TAssignmentItemMapping.setTAssignment(this); return TAssignmentItemMapping; } public TAssignmentItemMapping removeTAssignmentItemMapping(TAssignmentItemMapping TAssignmentItemMapping) { getTAssignmentItemMappings().remove(TAssignmentItemMapping); TAssignmentItemMapping.setTAssignment(null); return TAssignmentItemMapping; } public Set<TAssignmentQuestionpool> getTAssignmentQuestionpools() { return this.TAssignmentQuestionpools; } public void setTAssignmentQuestionpools(Set<TAssignmentQuestionpool> TAssignmentQuestionpools) { this.TAssignmentQuestionpools = TAssignmentQuestionpools; } public Set<TAssignmentSection> getTAssignmentSections() { return this.TAssignmentSections; } public void setTAssignmentSections(Set<TAssignmentSection> TAssignmentSections) { this.TAssignmentSections = TAssignmentSections; } public TAssignmentSection addTAssignmentSection(TAssignmentSection TAssignmentSection) { getTAssignmentSections().add(TAssignmentSection); TAssignmentSection.setTAssignment(this); return TAssignmentSection; } public TAssignmentSection removeTAssignmentSection(TAssignmentSection TAssignmentSection) { getTAssignmentSections().remove(TAssignmentSection); TAssignmentSection.setTAssignment(null); return TAssignmentSection; } public Set<TGradeObject> getTGradeObjects() { return this.TGradeObjects; } public void setTGradeObjects(Set<TGradeObject> TGradeObjects) { this.TGradeObjects = TGradeObjects; } public TGradeObject addTGradeObject(TGradeObject TGradeObject) { getTGradeObjects().add(TGradeObject); TGradeObject.setTAssignment(this); return TGradeObject; } public TGradeObject removeTGradeObject(TGradeObject TGradeObject) { getTGradeObjects().remove(TGradeObject); TGradeObject.setTAssignment(null); return TGradeObject; } }
package com.androidadvance.topsnackbar; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; /** * Created by kurt on 2015/06/08. */ public class AnimationUtils { public static final Interpolator LINEAR_INTERPOLATOR = new LinearInterpolator(); public static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator(); public static final Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator(); AnimationUtils() { } static float lerp(float startValue, float endValue, float fraction) { return startValue + fraction * (endValue - startValue); } static int lerp(int startValue, int endValue, float fraction) { return startValue + Math.round(fraction * (float) (endValue - startValue)); } public static class AnimationListenerAdapter implements Animation.AnimationListener { public AnimationListenerAdapter() { } public void onAnimationStart(Animation animation) { } public void onAnimationEnd(Animation animation) { } public void onAnimationRepeat(Animation animation) { } } }
/** * Copyright © 2016-2021 The Thingsboard Authors * * 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.thingsboard.server.transport.lwm2m.secure; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.californium.elements.util.CertPathUtil; import org.eclipse.californium.scandium.dtls.AlertMessage; import org.eclipse.californium.scandium.dtls.CertificateMessage; import org.eclipse.californium.scandium.dtls.CertificateType; import org.eclipse.californium.scandium.dtls.CertificateVerificationResult; import org.eclipse.californium.scandium.dtls.ConnectionId; import org.eclipse.californium.scandium.dtls.DTLSSession; import org.eclipse.californium.scandium.dtls.HandshakeException; import org.eclipse.californium.scandium.dtls.HandshakeResultHandler; import org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier; import org.eclipse.californium.scandium.dtls.x509.StaticCertificateVerifier; import org.eclipse.californium.scandium.util.ServerNames; import org.eclipse.leshan.server.security.NonUniqueSecurityInfoException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode; import org.thingsboard.server.common.data.device.credentials.lwm2m.X509ClientCredentials; import org.thingsboard.server.common.msg.EncryptionUtil; import org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse; import org.thingsboard.server.common.transport.util.SslUtil; import org.thingsboard.server.queue.util.TbLwM2mTransportComponent; import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import org.thingsboard.server.transport.lwm2m.secure.credentials.LwM2MCredentials; import org.thingsboard.server.transport.lwm2m.server.store.TbEditableSecurityStore; import org.thingsboard.server.transport.lwm2m.server.store.TbLwM2MDtlsSessionStore; import javax.annotation.PostConstruct; import javax.security.auth.x500.X500Principal; import java.security.PublicKey; import java.security.cert.CertPath; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.List; import static org.thingsboard.server.transport.lwm2m.server.uplink.LwM2mTypeServer.CLIENT; @Slf4j @Component @TbLwM2mTransportComponent @RequiredArgsConstructor public class TbLwM2MDtlsCertificateVerifier implements NewAdvancedCertificateVerifier { private final TbLwM2MDtlsSessionStore sessionStorage; private final LwM2MTransportServerConfig config; private final LwM2mCredentialsSecurityInfoValidator securityInfoValidator; private final TbEditableSecurityStore securityStore; @SuppressWarnings("deprecation") private StaticCertificateVerifier staticCertificateVerifier; @Value("${transport.lwm2m.server.security.skip_validity_check_for_client_cert:false}") private boolean skipValidityCheckForClientCert; @Override public List<CertificateType> getSupportedCertificateType() { return Arrays.asList(CertificateType.X_509, CertificateType.RAW_PUBLIC_KEY); } @PostConstruct public void init() { try { /* by default trust all */ X509Certificate[] trustedCertificates = new X509Certificate[0]; if (config.getKeyStoreValue() != null) { X509Certificate rootCAX509Cert = (X509Certificate) config.getKeyStoreValue().getCertificate(config.getRootCertificateAlias()); if (rootCAX509Cert != null) { trustedCertificates = new X509Certificate[1]; trustedCertificates[0] = rootCAX509Cert; } } staticCertificateVerifier = new StaticCertificateVerifier(trustedCertificates); } catch (Exception e) { log.info("Failed to initialize the "); } } @Override public CertificateVerificationResult verifyCertificate(ConnectionId cid, ServerNames serverName, Boolean clientUsage, boolean truncateCertificatePath, CertificateMessage message, DTLSSession session) { CertPath certChain = message.getCertificateChain(); if (certChain == null) { //We trust all RPK on this layer, and use TbLwM2MAuthorizer PublicKey publicKey = message.getPublicKey(); return new CertificateVerificationResult(cid, publicKey, null); } else { try { boolean x509CredentialsFound = false; CertPath certpath = message.getCertificateChain(); X509Certificate[] chain = certpath.getCertificates().toArray(new X509Certificate[0]); for (X509Certificate cert : chain) { try { if (!skipValidityCheckForClientCert) { cert.checkValidity(); } String strCert = SslUtil.getCertificateString(cert); String sha3Hash = EncryptionUtil.getSha3Hash(strCert); TbLwM2MSecurityInfo securityInfo = securityInfoValidator.getEndpointSecurityInfoByCredentialsId(sha3Hash, CLIENT); ValidateDeviceCredentialsResponse msg = securityInfo != null ? securityInfo.getMsg() : null; if (msg != null && org.thingsboard.server.common.data.StringUtils.isNotEmpty(msg.getCredentials())) { LwM2MCredentials credentials = JacksonUtil.fromString(msg.getCredentials(), LwM2MCredentials.class); if (!credentials.getClient().getSecurityConfigClientMode().equals(LwM2MSecurityMode.X509)) { continue; } X509ClientCredentials config = (X509ClientCredentials) credentials.getClient(); String certBody = config.getCert(); String endpoint = config.getEndpoint(); if (strCert.equals(certBody)) { x509CredentialsFound = true; DeviceProfile deviceProfile = msg.getDeviceProfile(); if (msg.hasDeviceInfo() && deviceProfile != null) { sessionStorage.put(endpoint, new TbX509DtlsSessionInfo(cert.getSubjectX500Principal().getName(), msg)); try { securityStore.put(securityInfo); } catch (NonUniqueSecurityInfoException e) { log.trace("Failed to add security info: {}", securityInfo, e); } break; } } else { log.trace("[{}][{}] Certificate mismatch. Expected: {}, Actual: {}", endpoint, sha3Hash, strCert, certBody); } } } catch (CertificateEncodingException | CertificateExpiredException | CertificateNotYetValidException e) { log.error(e.getMessage(), e); } } if (!x509CredentialsFound) { if (staticCertificateVerifier != null) { staticCertificateVerifier.verifyCertificate(message, session); } else { AlertMessage alert = new AlertMessage(AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.INTERNAL_ERROR, session.getPeer()); throw new HandshakeException("x509 verification not enabled!", alert); } } return new CertificateVerificationResult(cid, certpath, null); } catch (HandshakeException e) { log.trace("Certificate validation failed!", e); return new CertificateVerificationResult(cid, e, null); } } } @Override public List<X500Principal> getAcceptedIssuers() { return CertPathUtil.toSubjects(null); } @Override public void setResultHandler(HandshakeResultHandler resultHandler) { } }
package com.icss.snacks.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.icss.snacks.entity.User; import com.icss.snacks.service.UserService; /** * Servlet implementation class UserLoginServlet */ @WebServlet("/UserLoginServlet") public class UserLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public UserLoginServlet() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // doGet(request, response); String username = request.getParameter("username"); String pwd = request.getParameter("password"); UserService userService = new UserService(); User user; try { user = userService.login(username, pwd); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); request.getRequestDispatcher("error.jsp").forward(request, response); return; } if(user == null) { request.setAttribute("msg", "用户名或密码错误"); request.getRequestDispatcher("login.jsp").forward(request, response); } else if (user.getUsername().equals("admin")) { request.getSession().setAttribute("user", user); // 一次会话多次请求多次响应 request.getRequestDispatcher("back/index.jsp").forward(request, response); } else { request.getSession().setAttribute("user", user); // 一次会话多次请求多次响应 request.getRequestDispatcher("LatestCommdityServlet").forward(request, response); } } }
// This file is part of CPAchecker, // a tool for configurable software verification: // https://cpachecker.sosy-lab.org // // SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> // // SPDX-License-Identifier: Apache-2.0 package org.sosy_lab.cpachecker.cfa.parser.eclipse.c; import static com.google.common.base.Strings.isNullOrEmpty; import static org.sosy_lab.cpachecker.cfa.types.c.CTypes.withoutConst; import static org.sosy_lab.cpachecker.cfa.types.c.CTypes.withoutVolatile; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.LongSummaryStatistics; import java.util.logging.Level; import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.cdt.core.dom.ast.IASTArrayDeclarator; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; import org.eclipse.cdt.core.dom.ast.IASTArraySubscriptExpression; import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression; import org.eclipse.cdt.core.dom.ast.IASTCastExpression; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTConditionalExpression; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTDeclarator; import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier; import org.eclipse.cdt.core.dom.ast.IASTEqualsInitializer; import org.eclipse.cdt.core.dom.ast.IASTExpression; import org.eclipse.cdt.core.dom.ast.IASTExpressionList; import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement; import org.eclipse.cdt.core.dom.ast.IASTFieldDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFieldReference; import org.eclipse.cdt.core.dom.ast.IASTForStatement; import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression; import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTIdExpression; import org.eclipse.cdt.core.dom.ast.IASTInitializer; import org.eclipse.cdt.core.dom.ast.IASTInitializerClause; import org.eclipse.cdt.core.dom.ast.IASTInitializerList; import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration; import org.eclipse.cdt.core.dom.ast.IASTPointerOperator; import org.eclipse.cdt.core.dom.ast.IASTProblemDeclaration; import org.eclipse.cdt.core.dom.ast.IASTProblemStatement; import org.eclipse.cdt.core.dom.ast.IASTReturnStatement; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator; import org.eclipse.cdt.core.dom.ast.IASTStatement; import org.eclipse.cdt.core.dom.ast.IASTTypeId; import org.eclipse.cdt.core.dom.ast.IASTTypeIdExpression; import org.eclipse.cdt.core.dom.ast.IASTTypeIdInitializerExpression; import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression; import org.eclipse.cdt.core.dom.ast.IBasicType; import org.eclipse.cdt.core.dom.ast.IBasicType.Kind; import org.eclipse.cdt.core.dom.ast.IPointerType; import org.eclipse.cdt.core.dom.ast.IProblemType; import org.eclipse.cdt.core.dom.ast.c.ICASTArrayDesignator; import org.eclipse.cdt.core.dom.ast.c.ICASTArrayModifier; import org.eclipse.cdt.core.dom.ast.c.ICASTDesignatedInitializer; import org.eclipse.cdt.core.dom.ast.c.ICASTDesignator; import org.eclipse.cdt.core.dom.ast.c.ICASTFieldDesignator; import org.eclipse.cdt.core.dom.ast.gnu.IGNUASTCompoundStatementExpression; import org.eclipse.cdt.core.dom.ast.gnu.c.IGCCASTArrayRangeDesignator; import org.eclipse.cdt.internal.core.dom.parser.c.CASTArrayDesignator; import org.eclipse.cdt.internal.core.dom.parser.c.CASTArrayRangeDesignator; import org.eclipse.cdt.internal.core.dom.parser.c.CASTCompositeTypeSpecifier; import org.eclipse.cdt.internal.core.dom.parser.c.CASTDeclarator; import org.eclipse.cdt.internal.core.dom.parser.c.CASTFunctionCallExpression; import org.eclipse.cdt.internal.core.dom.parser.c.CASTLiteralExpression; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.common.log.LogManagerWithoutDuplicates; import org.sosy_lab.cpachecker.cfa.ast.FileLocation; import org.sosy_lab.cpachecker.cfa.ast.c.CAddressOfLabelExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CArrayDesignator; import org.sosy_lab.cpachecker.cfa.ast.c.CArrayRangeDesignator; import org.sosy_lab.cpachecker.cfa.ast.c.CArraySubscriptExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CAssignment; import org.sosy_lab.cpachecker.cfa.ast.c.CAstNode; import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression.BinaryOperator; import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpressionBuilder; import org.sosy_lab.cpachecker.cfa.ast.c.CCastExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CCharLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CComplexCastExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CComplexTypeDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CDesignatedInitializer; import org.sosy_lab.cpachecker.cfa.ast.c.CDesignator; import org.sosy_lab.cpachecker.cfa.ast.c.CExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CExpressionAssignmentStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CExpressionStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CFieldDesignator; import org.sosy_lab.cpachecker.cfa.ast.c.CFieldReference; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallAssignmentStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CIdExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CInitializer; import org.sosy_lab.cpachecker.cfa.ast.c.CInitializerExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CInitializerList; import org.sosy_lab.cpachecker.cfa.ast.c.CIntegerLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CLeftHandSide; import org.sosy_lab.cpachecker.cfa.ast.c.CLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CParameterDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CPointerExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CReturnStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CRightHandSide; import org.sosy_lab.cpachecker.cfa.ast.c.CSimpleDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CStringLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CTypeDefDeclaration; import org.sosy_lab.cpachecker.cfa.ast.c.CTypeIdExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CTypeIdExpression.TypeIdOperator; import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression.UnaryOperator; import org.sosy_lab.cpachecker.cfa.ast.c.CVariableDeclaration; import org.sosy_lab.cpachecker.cfa.parser.Parsers.EclipseCParserOptions; import org.sosy_lab.cpachecker.cfa.parser.Scope; import org.sosy_lab.cpachecker.cfa.simplification.ExpressionSimplificationVisitor; import org.sosy_lab.cpachecker.cfa.simplification.NonRecursiveExpressionSimplificationVisitor; import org.sosy_lab.cpachecker.cfa.types.MachineModel; import org.sosy_lab.cpachecker.cfa.types.c.CArrayType; import org.sosy_lab.cpachecker.cfa.types.c.CBasicType; import org.sosy_lab.cpachecker.cfa.types.c.CBitFieldType; import org.sosy_lab.cpachecker.cfa.types.c.CComplexType; import org.sosy_lab.cpachecker.cfa.types.c.CComplexType.ComplexTypeKind; import org.sosy_lab.cpachecker.cfa.types.c.CCompositeType; import org.sosy_lab.cpachecker.cfa.types.c.CCompositeType.CCompositeTypeMemberDeclaration; import org.sosy_lab.cpachecker.cfa.types.c.CDefaults; import org.sosy_lab.cpachecker.cfa.types.c.CElaboratedType; import org.sosy_lab.cpachecker.cfa.types.c.CEnumType; import org.sosy_lab.cpachecker.cfa.types.c.CEnumType.CEnumerator; import org.sosy_lab.cpachecker.cfa.types.c.CFunctionType; import org.sosy_lab.cpachecker.cfa.types.c.CFunctionTypeWithNames; import org.sosy_lab.cpachecker.cfa.types.c.CNumericTypes; import org.sosy_lab.cpachecker.cfa.types.c.CPointerType; import org.sosy_lab.cpachecker.cfa.types.c.CProblemType; import org.sosy_lab.cpachecker.cfa.types.c.CSimpleType; import org.sosy_lab.cpachecker.cfa.types.c.CStorageClass; import org.sosy_lab.cpachecker.cfa.types.c.CType; import org.sosy_lab.cpachecker.cfa.types.c.CTypedefType; import org.sosy_lab.cpachecker.cfa.types.c.CTypes; import org.sosy_lab.cpachecker.cfa.types.c.CVoidType; import org.sosy_lab.cpachecker.cfa.types.c.DefaultCTypeVisitor; import org.sosy_lab.cpachecker.exceptions.NoException; import org.sosy_lab.cpachecker.exceptions.UnrecognizedCodeException; import org.sosy_lab.cpachecker.util.Pair; import org.sosy_lab.cpachecker.util.Triple; class ASTConverter { // Calls to this functions are handled by this class and replaced with regular C code. private static final String FUNC_CONSTANT = "__builtin_constant_p"; private static final String FUNC_OFFSETOF = "__builtin_offsetof"; private static final String FUNC_EXPECT = "__builtin_expect"; private static final String FUNC_TYPES_COMPATIBLE = "__builtin_types_compatible_p"; private final ExpressionSimplificationVisitor expressionSimplificator; private final NonRecursiveExpressionSimplificationVisitor nonRecursiveExpressionSimplificator; private final CBinaryExpressionBuilder binExprBuilder; private final EclipseCParserOptions options; private final LogManager logger; private final ASTLiteralConverter literalConverter; private final ASTOperatorConverter operatorConverter; private final ASTTypeConverter typeConverter; private final MachineModel machinemodel; private final ParseContext parseContext; private final Scope scope; // this counter is static to make the replacing names for anonymous types, in // more than one file (which get parsed with different AstConverters, although // they are in the same run) unique private static int anonTypeCounter = 0; private final Sideassignments sideAssignmentStack; private final String staticVariablePrefix; private static final ContainsProblemTypeVisitor containsProblemTypeVisitor = new ContainsProblemTypeVisitor(); public ASTConverter( EclipseCParserOptions pOptions, Scope pScope, LogManagerWithoutDuplicates pLogger, ParseContext pParseContext, MachineModel pMachineModel, String pStaticVariablePrefix, Sideassignments pSideAssignmentStack) { this.options = pOptions; this.scope = pScope; this.logger = pLogger; this.typeConverter = new ASTTypeConverter(scope, this, pStaticVariablePrefix, pParseContext); this.literalConverter = new ASTLiteralConverter(pMachineModel, pParseContext); this.operatorConverter = new ASTOperatorConverter(pParseContext); this.parseContext = pParseContext; this.machinemodel = pMachineModel; this.staticVariablePrefix = pStaticVariablePrefix; this.sideAssignmentStack = pSideAssignmentStack; this.expressionSimplificator = new ExpressionSimplificationVisitor(pMachineModel, pLogger); this.nonRecursiveExpressionSimplificator = new NonRecursiveExpressionSimplificationVisitor(pMachineModel, pLogger); this.binExprBuilder = new CBinaryExpressionBuilder(pMachineModel, pLogger); } public CExpression convertExpressionWithoutSideEffects( IASTExpression e) { CAstNode node = convertExpressionWithSideEffects(e); if (node == null || node instanceof CExpression) { return (CExpression) node; } else if (node instanceof CFunctionCallExpression) { return addSideassignmentsForExpressionsWithoutSideEffects(node, e); } else if (e instanceof IASTUnaryExpression && (((IASTUnaryExpression)e).getOperator() == IASTUnaryExpression.op_postFixDecr || ((IASTUnaryExpression)e).getOperator() == IASTUnaryExpression.op_postFixIncr)) { return addSideAssignmentsForUnaryExpressions( ((CAssignment) node).getLeftHandSide(), node.getFileLocation(), ((CBinaryExpression) ((CAssignment) node).getRightHandSide()).getOperator()); } else if (node instanceof CAssignment) { sideAssignmentStack.addPreSideAssignment(node); return ((CAssignment) node).getLeftHandSide(); } else { throw new AssertionError("unknown expression " + node); } } /** * Simplify an expression as much as possible. * Use this when you always want to evaluate a specific expression if possible, * e.g. array lengths (which should be constant if possible). */ CExpression simplifyExpressionRecursively(CExpression exp) { return exp.accept(expressionSimplificator); } /** * Do a single step of expression simplification (not recursively). * Use this when you do not care about full evaluation, * or you know the operands are already evaluated if possible. */ CExpression simplifyExpressionOneStep(CExpression exp) { return exp.accept(nonRecursiveExpressionSimplificator); } private CExpression addSideassignmentsForExpressionsWithoutSideEffects(CAstNode node, IASTExpression e) { CIdExpression tmp; if (e.getExpressionType() instanceof IProblemType){ tmp = createInitializedTemporaryVariable(getLocation(e), ((CRightHandSide)node).getExpressionType(), (CInitializer)null); } else{ tmp = createTemporaryVariable(e); } sideAssignmentStack.addPreSideAssignment(new CFunctionCallAssignmentStatement(getLocation(e), tmp, (CFunctionCallExpression) node)); return tmp; } /** This method builds a preSideAssignment for x=x+1 or x=x-1 and * returns a tmp-variable, that has the value of x before the operation. * * @param exp the "x" of x=x+1 * @param fileLoc location of the expression * @param op binary operator, should be PLUS or MINUS */ private CIdExpression addSideAssignmentsForUnaryExpressions( final CLeftHandSide exp, final FileLocation fileLoc, final BinaryOperator op) { final CIdExpression tmp = createInitializedTemporaryVariable(fileLoc, exp.getExpressionType(), exp); final CBinaryExpression postExp = buildBinaryExpression(exp, CIntegerLiteralExpression.ONE, op); sideAssignmentStack.addPreSideAssignment(new CExpressionAssignmentStatement(fileLoc, exp, postExp)); return tmp; } private void addSideEffectDeclarationForType(CCompositeType type, FileLocation loc) { CComplexTypeDeclaration decl = new CComplexTypeDeclaration(loc, scope.isGlobalScope(), type); if (scope.registerTypeDeclaration(decl)) { sideAssignmentStack.addPreSideAssignment(decl); } } protected CAstNode convertExpressionWithSideEffects(IASTExpression e) { CAstNode converted = convertExpressionWithSideEffectsNotSimplified(e); if (converted == null || !options.simplifyConstExpressions() || !(converted instanceof CExpression)) { return converted; } return simplifyExpressionOneStep((CExpression)converted); } private CAstNode convertExpressionWithSideEffectsNotSimplified(IASTExpression e) { assert !(e instanceof CExpression); if (e == null) { return null; } else if (e instanceof IASTArraySubscriptExpression) { return convert((IASTArraySubscriptExpression)e); } else if (e instanceof IASTBinaryExpression) { return convert((IASTBinaryExpression)e); } else if (e instanceof IASTCastExpression) { return convert((IASTCastExpression)e); } else if (e instanceof IASTFieldReference) { return convert((IASTFieldReference)e); } else if (e instanceof IASTFunctionCallExpression) { return convert((IASTFunctionCallExpression)e); } else if (e instanceof IASTIdExpression) { CExpression exp = convert((IASTIdExpression)e); CType type = exp.getExpressionType(); // this id expression is the name of a function. When there is no // functionCallExpressionn or unaryexpression with pointertype and operator.Amper // around it, we create it. if (type instanceof CFunctionType && !(isFunctionCallNameExpression(e) || isAddressOfArgument(e))) { exp = new CUnaryExpression(exp.getFileLocation(), new CPointerType(type.isConst(), type.isVolatile(), type), exp, UnaryOperator.AMPER); } return exp; } else if (e instanceof IASTLiteralExpression) { final CType type = typeConverter.convert(e.getExpressionType()); return literalConverter.convert((IASTLiteralExpression)e, type, getLocation(e)); } else if (e instanceof IASTUnaryExpression) { return convert((IASTUnaryExpression)e); } else if (e instanceof IASTTypeIdExpression) { return convert((IASTTypeIdExpression)e); } else if (e instanceof IASTTypeIdInitializerExpression) { return convert((IASTTypeIdInitializerExpression)e); } else if (e instanceof IASTConditionalExpression) { return convert((IASTConditionalExpression)e); } else if (e instanceof IGNUASTCompoundStatementExpression) { return convert((IGNUASTCompoundStatementExpression)e); } else if (e instanceof IASTExpressionList) { return convertExpressionListAsExpression((IASTExpressionList)e); } else { throw parseContext.parseError("Unknown expression type " + e.getClass().getSimpleName(), e); } } private boolean isFunctionCallNameExpression(IASTExpression e) { return e.getParent() instanceof IASTFunctionCallExpression && e.getPropertyInParent() == IASTFunctionCallExpression.FUNCTION_NAME; } private boolean isAddressOfArgument(IASTExpression e) { return e.getParent() instanceof IASTUnaryExpression && ((IASTUnaryExpression) e.getParent()).getOperator() == IASTUnaryExpression.op_amper; } enum CONDITION { NORMAL, ALWAYS_FALSE, ALWAYS_TRUE } CONDITION getConditionKind(final CExpression condition) { if (condition instanceof CIntegerLiteralExpression || condition instanceof CCharLiteralExpression) { // constant int value if (isZero(condition)) { return CONDITION.ALWAYS_FALSE; } else { return CONDITION.ALWAYS_TRUE; } } return CONDITION.NORMAL; } private CAstNode convert(IASTConditionalExpression e) { // check condition kind so we can eventually skip creating an unnecessary branch CONDITION conditionKind = getConditionKind(e.getLogicalConditionExpression()); switch (conditionKind) { case ALWAYS_TRUE: return convertExpressionWithSideEffects(e.getPositiveResultExpression()); case ALWAYS_FALSE: return convertExpressionWithSideEffects(e.getNegativeResultExpression()); case NORMAL: // this means the return value (if there could be one) of the conditional // expression is not used if (convertType(e) instanceof CVoidType) { sideAssignmentStack.addConditionalExpression(e, null); // TODO we should not return a variable here, however null cannot be returned // perhaps we need a DummyExpression here return CIntegerLiteralExpression.ZERO; } CIdExpression tmp = createTemporaryVariable(e); assert !(tmp.getExpressionType() instanceof CVoidType); sideAssignmentStack.addConditionalExpression(e, tmp); return tmp; default: throw new AssertionError("Unhandled case statement: " + conditionKind); } } /** Computes the condition kind of an IASTExpression, logical ors and logical ands are resolved * the rest works as with the condition kind method for CExpressions */ private CONDITION getConditionKind(IASTExpression exp) { if (exp instanceof IASTBinaryExpression && (((IASTBinaryExpression) exp).getOperator() == IASTBinaryExpression.op_logicalAnd || ((IASTBinaryExpression) exp).getOperator() == IASTBinaryExpression.op_logicalOr)) { IASTBinaryExpression binExp = (IASTBinaryExpression) exp; switch (binExp.getOperator()) { case IASTBinaryExpression.op_logicalAnd: { CONDITION left = getConditionKind(binExp.getOperand1()); switch (left) { case ALWAYS_TRUE: return getConditionKind(binExp.getOperand2()); case ALWAYS_FALSE: return left; case NORMAL: if (getConditionKind(binExp.getOperand2()) == CONDITION.ALWAYS_FALSE) { return CONDITION.ALWAYS_FALSE; } else { return CONDITION.NORMAL; } default: throw new AssertionError("unhandled case statement"); } } case IASTBinaryExpression.op_logicalOr: { CONDITION left = getConditionKind(binExp.getOperand1()); switch (left) { case ALWAYS_TRUE: return CONDITION.ALWAYS_TRUE; case ALWAYS_FALSE: return getConditionKind(binExp.getOperand2()); case NORMAL: CONDITION right = getConditionKind(binExp.getOperand2()); if (right == CONDITION.ALWAYS_FALSE) { return CONDITION.NORMAL; } else { return right; } default: throw new AssertionError("unhandled case statement"); } } default: throw new AssertionError("unhandled case statement"); } } else { sideAssignmentStack.enterBlock(); // Here we call simplify manually, because for conditional expressions // we always want a full evaluation because we might be able to prevent // a branch in the CFA. // In global scope, this is even required because there cannot be any branches. CExpression simplifiedExp = simplifyExpressionRecursively(convertExpressionWithoutSideEffects(exp)); sideAssignmentStack.getAndResetConditionalExpressions(); sideAssignmentStack.getAndResetPostSideAssignments(); sideAssignmentStack.getAndResetPreSideAssignments(); sideAssignmentStack.leaveBlock(); return getConditionKind(simplifiedExp); } } private boolean isZero(CExpression exp) { if (exp instanceof CIntegerLiteralExpression) { BigInteger value = ((CIntegerLiteralExpression)exp).getValue(); return value.equals(BigInteger.ZERO); } if (exp instanceof CCharLiteralExpression) { char value = ((CCharLiteralExpression)exp).getCharacter(); return value == 0; } return false; } private CAstNode convert(IGNUASTCompoundStatementExpression e) { CIdExpression tmp = createTemporaryVariable(e); sideAssignmentStack.addConditionalExpression(e, tmp); return tmp; } private CAstNode convertExpressionListAsExpression(IASTExpressionList e) { CIdExpression tmp = createTemporaryVariable(e); sideAssignmentStack.addConditionalExpression(e, tmp); return tmp; } private CArraySubscriptExpression convert(IASTArraySubscriptExpression e) { CExpression arrayExpr = convertExpressionWithoutSideEffects(e.getArrayExpression()); CExpression subscriptExpr = convertExpressionWithoutSideEffects(toExpression(e.getArgument())); // Eclipse CDT has a bug in determining the result type if the array type is a typedef. CType resultType = arrayExpr.getExpressionType(); while (resultType instanceof CTypedefType) { resultType = ((CTypedefType)resultType).getRealType(); } if (resultType instanceof CArrayType) { resultType = ((CArrayType)resultType).getType(); } else if (resultType instanceof CPointerType) { resultType = ((CPointerType)resultType).getType(); } else { // TODO probably we should throw exception, // but for now we delegate to Eclipse CDT and see whether it knows better than we do resultType = typeConverter.convert(e.getExpressionType()); } return new CArraySubscriptExpression(getLocation(e), resultType, arrayExpr, subscriptExpr); } /** * creates temporary variables with increasing numbers. * * @return the idExpression of the variable for most cases, or <code>Null</code> if the * return-type is <code>Void</code>. */ private CIdExpression createTemporaryVariable(IASTExpression e) { CType type = convertType(e); if (type instanceof CVoidType) { return null; } return createInitializedTemporaryVariable( getLocation(e), type, (CInitializer)null); } /** * Convert Eclipse AST type to {@link CType}. */ private CType convertType(IASTExpression e) { CType type = typeConverter.convert(e.getExpressionType()); if (type.getCanonicalType() instanceof CVoidType) { if (e instanceof IASTFunctionCallExpression) { // Void method called and return value used. // Possibly this is an undeclared function. // Default return type in C for these cases is INT. return CNumericTypes.INT; } // workaround for strange CDT behaviour } else if (type instanceof CProblemType) { if (e instanceof IASTConditionalExpression) { return typeConverter.convert( ((IASTConditionalExpression) e).getNegativeResultExpression().getExpressionType()); } else if (e instanceof IGNUASTCompoundStatementExpression) { // manually ceck whether type of compundStatementExpression is void IGNUASTCompoundStatementExpression statementExpression = (IGNUASTCompoundStatementExpression) e; IASTStatement[] statements = statementExpression.getCompoundStatement().getStatements(); if (statements.length > 0) { IASTStatement lastStatement = statements[statements.length - 1]; if (lastStatement instanceof IASTExpressionStatement) { IASTExpression lastExpression = ((IASTExpressionStatement) lastStatement).getExpression(); return convertType(lastExpression); } else { return CVoidType.create(false, false); } } } } return type; } private CIdExpression createInitializedTemporaryVariable( final FileLocation loc, final CType pType, @Nullable CExpression initializer) { return createInitializedTemporaryVariable(loc, pType, initializer == null ? null : new CInitializerExpression(loc, initializer)); } /** * creates temporary variables with increasing numbers with a certain initializer. * If the initializer is 'null', no initializer will be created. */ private CIdExpression createInitializedTemporaryVariable( final FileLocation loc, final CType pType, @Nullable CInitializer initializer) { String name = "__CPAchecker_TMP_"; int i = 0; while (scope.variableNameInUse(name + i)) { i++; } name += i; // If there is no initializer, the variable cannot be const. // TODO: consider always adding a const modifier if there is an initializer CType type = (initializer == null) ? CTypes.withoutConst(pType) : pType; if (type instanceof CArrayType) { // Replace with pointer type. // This should actually be handled by Eclipse, because the C standard says in §5.4.2.1 (3) // that array types of operands are converted to pointer types except in a very few // specific cases (for which there will never be a temporary variable). type = new CPointerType(type.isConst(), type.isVolatile(), ((CArrayType) type).getType()); } CVariableDeclaration decl = new CVariableDeclaration(loc, scope.isGlobalScope(), CStorageClass.AUTO, type, name, name, scope.createScopedNameOf(name), initializer); scope.registerDeclaration(decl); sideAssignmentStack.addPreSideAssignment(decl); return new CIdExpression(loc, decl); } private CAstNode convert(IASTBinaryExpression e) { int eop = e.getOperator(); if (eop == IASTBinaryExpression.op_logicalOr || eop == IASTBinaryExpression.op_logicalAnd) { CONDITION o1 = getConditionKind(e.getOperand1()); CONDITION o2 = getConditionKind(e.getOperand2()); if (o1 == CONDITION.NORMAL || o2 == CONDITION.NORMAL) { CIdExpression tmp = createTemporaryVariable(e); sideAssignmentStack.addConditionalExpression(e, tmp); return tmp; } if ((eop == IASTBinaryExpression.op_logicalAnd && (o1 == CONDITION.ALWAYS_FALSE || o2 == CONDITION.ALWAYS_FALSE)) || (o1 == CONDITION.ALWAYS_FALSE && o2 == CONDITION.ALWAYS_FALSE)) { return CIntegerLiteralExpression.ZERO; } return CIntegerLiteralExpression.ONE; } Pair<BinaryOperator, Boolean> opPair = operatorConverter.convertBinaryOperator(e); BinaryOperator op = opPair.getFirst(); boolean isAssign = opPair.getSecond(); FileLocation fileLoc = getLocation(e); CExpression leftHandSide = convertExpressionWithoutSideEffects(e.getOperand1()); if (isAssign) { if (!(leftHandSide instanceof CLeftHandSide)) { throw parseContext.parseError( "Lefthandside of Assignment " + e.getRawSignature() + " is no CLeftHandside but should be.", leftHandSide); } CLeftHandSide lhs = (CLeftHandSide) leftHandSide; if (op == null) { // a = b CAstNode rightHandSide = convertExpressionWithSideEffects(e.getOperand2()); // right-hand side may have a function call if (rightHandSide instanceof CExpression) { // a = b return new CExpressionAssignmentStatement(fileLoc, lhs, (CExpression)rightHandSide); } else if (rightHandSide instanceof CFunctionCallExpression) { // a = f() return new CFunctionCallAssignmentStatement(fileLoc, lhs, (CFunctionCallExpression)rightHandSide); } else if (rightHandSide instanceof CAssignment) { sideAssignmentStack.addPreSideAssignment(rightHandSide); return new CExpressionAssignmentStatement(fileLoc, lhs, ((CAssignment) rightHandSide).getLeftHandSide()); } else { throw parseContext.parseError("Expression is not free of side-effects", e); } } else { // a += b etc. CExpression rightHandSide = convertExpressionWithoutSideEffects(e.getOperand2()); // first create expression "a + b" CBinaryExpression exp = buildBinaryExpression(leftHandSide, rightHandSide, op); // and now the assignment return new CExpressionAssignmentStatement(fileLoc, lhs, exp); } } else { CExpression rightHandSide = convertExpressionWithoutSideEffects(e.getOperand2()); return buildBinaryExpression(leftHandSide, rightHandSide, op); } } private CBinaryExpression buildBinaryExpression( CExpression operand1, CExpression operand2, BinaryOperator op) { try { return binExprBuilder.buildBinaryExpression(operand1, operand2, op); } catch (UnrecognizedCodeException e) { throw new CFAGenerationRuntimeException(e); } } private static boolean isPointerToVoid(final IASTExpression e) { return (e.getExpressionType() instanceof IPointerType) && ((IPointerType) e.getExpressionType()).getType() instanceof IBasicType && ((IBasicType)((IPointerType) e.getExpressionType()).getType()).getKind() == Kind.eVoid; } private static boolean isRightHandSide(final IASTExpression e) { return e.getParent() instanceof IASTBinaryExpression && ((IASTBinaryExpression) e.getParent()).getOperator() == IASTBinaryExpression.op_assign && ((IASTBinaryExpression) e.getParent()).getOperand2() == e; } private CAstNode convert(IASTCastExpression e) { final CExpression operand; final FileLocation loc = getLocation(e); /* using #typeConverter.convert(e.getExpressionType()); to recheck if our evaluated * castType is valid, is wrong in some cases, so we scip this check, and only * use our convert(IASTTypeID) method * a case where convert(e.getExpressionType()) fails is: * struct lock { * unsigned int slock; * } * * int tmp = (*(volatile typeof(lock->slock) *)&(lock->slock)); * * => the convert(IASTTypeId) method returns (unsigned int)* * => the convert(CType) method returns (volatile int)* * the second one is obviously wrong, because the unsigned is missing */ final CType castType = convert(e.getTypeId()); if (castType.equals(CVoidType.VOID)) { // ignore casts to void as in "(void) f();" return convertExpressionWithSideEffects(e.getOperand()); } // To recognize and simplify constructs e.g. struct s *ps = (struct s *) malloc(.../* e.g. sizeof(struct s)*/); if (e.getOperand() instanceof CASTFunctionCallExpression && castType.getCanonicalType() instanceof CPointerType && isRightHandSide(e) && isPointerToVoid(e.getOperand())) { return convertExpressionWithSideEffects(e.getOperand()); } else { operand = convertExpressionWithoutSideEffects(e.getOperand()); } if ("__imag__".equals(e.getTypeId().getRawSignature())) { return new CComplexCastExpression(loc, castType, operand, castType, false); } else if ("__real__".equals(e.getTypeId().getRawSignature())) { return new CComplexCastExpression(loc, castType, operand, castType, true); } if (e.getOperand() instanceof IASTFieldReference && ((IASTFieldReference)e.getOperand()).isPointerDereference()) { return createInitializedTemporaryVariable(loc, castType, new CCastExpression(loc, castType, operand)); } else { return new CCastExpression(loc, castType, operand); } } private static class ContainsProblemTypeVisitor extends DefaultCTypeVisitor<Boolean, NoException> { @Override public Boolean visitDefault(CType pT) { return Boolean.FALSE; } @Override public Boolean visit(final CArrayType t) { return t.getType().accept(this); } @Override public Boolean visit(final CElaboratedType t) { final CType realType = t.getRealType(); if (realType != null) { return realType.accept(this); } else { return false; } } @Override public Boolean visit(final CFunctionType t) { for (CType parameterType : t.getParameters()) { if (parameterType.accept(this)) { return true; } } return t.getReturnType().accept(this); } @Override public Boolean visit(final CPointerType t) { return t.getType().accept(this); } @Override public Boolean visit(final CProblemType t) { return true; } @Override public Boolean visit(CTypedefType t) { return t.getRealType().accept(this); } @Override public Boolean visit(CBitFieldType pCBitFieldType) { return pCBitFieldType.getType().accept(this); } } private static boolean containsProblemType(final CType type) { return type.accept(containsProblemTypeVisitor); } private CFieldReference convert(IASTFieldReference e) { CExpression owner = convertExpressionWithoutSideEffects(e.getFieldOwner()); String fieldName = convert(e.getFieldName()); final FileLocation loc = getLocation(e); CType ownerType = owner.getExpressionType().getCanonicalType(); if (e.isPointerDereference()) { if (ownerType instanceof CPointerType) { ownerType = ((CPointerType) ownerType).getType(); } else if (!(ownerType instanceof CProblemType)) { throw parseContext.parseError("Pointer dereference of non-pointer type " + ownerType, e); } } // In case of an anonymous struct, the type provided by Eclipse // does not match our type because we added a name. // So make sure to not use the Eclipse type. final CFieldReference fullFieldReference; List<Pair<String, CType>> wayToInnerField = ImmutableList.of(); if (ownerType instanceof CElaboratedType) { assert ((CElaboratedType) ownerType).getRealType() == null; // otherwise getCanonicalType is broken throw parseContext.parseError( "Cannot access the field " + fieldName + " in type " + ownerType + " which does not have a definition", e); } else if (ownerType instanceof CProblemType) { fullFieldReference = new CFieldReference(loc, typeConverter.convert(e.getExpressionType()), fieldName, owner, e.isPointerDereference()); } else if (ownerType instanceof CCompositeType) { wayToInnerField = getWayToInnerField((CCompositeType) ownerType, fieldName, loc, new ArrayList<>()); if (!wayToInnerField.isEmpty()) { CExpression current = owner; boolean isPointerDereference = e.isPointerDereference(); for (Pair<String, CType> field : wayToInnerField) { current = new CFieldReference( loc, field.getSecond(), field.getFirst(), current, isPointerDereference); isPointerDereference = false; } fullFieldReference = (CFieldReference) current; } else { throw parseContext.parseError( "Accessing unknown field " + fieldName + " in type " + ownerType, e); } } else { throw parseContext.parseError( "Cannot access field " + fieldName + " in type " + ownerType + " which is not a composite type", e); } // FOLLOWING IF CLAUSE WILL ONLY BE EVALUATED WHEN THE OPTION cfa.simplifyPointerExpressions IS SET TO TRUE // if the owner is a FieldReference itself there's the need for a temporary Variable // but only if we are not in global scope, otherwise there will be parsing errors if (options.simplifyPointerExpressions() && (wayToInnerField.size() > 1 || owner instanceof CFieldReference) && !scope.isGlobalScope()) { CExpression tmp = fullFieldReference; Deque<Pair<CType, String>> fields = new ArrayDeque<>(); while (tmp != owner) { fields.push(Pair.of(tmp.getExpressionType(), ((CFieldReference)tmp).getFieldName())); tmp = ((CFieldReference) tmp).getFieldOwner(); } boolean isFirstVisit = true; while (!fields.isEmpty()) { Pair<CType, String> actField = fields.pop(); // base case, when there is no field access left if (fields.isEmpty()) { // in case there is only one field access we have to check here on a pointer dereference if (isFirstVisit && e.isPointerDereference()) { CPointerExpression exp = new CPointerExpression(loc, owner.getExpressionType(), owner); CExpression tmpOwner = new CFieldReference(loc, actField.getFirst(), actField.getSecond(), exp, false); owner = createInitializedTemporaryVariable(loc, tmpOwner.getExpressionType(), tmpOwner); } else { owner = new CFieldReference(loc, actField.getFirst(), actField.getSecond(), owner, false); } } else { // here could be a pointer dereference, in this case we create a temporary variable // otherwise there is nothing special to be done if (isFirstVisit) { if (e.isPointerDereference()) { CPointerExpression exp = new CPointerExpression(loc, owner.getExpressionType(), owner); CExpression tmpOwner = new CFieldReference(loc, actField.getFirst(), actField.getSecond(), exp, false); owner = createInitializedTemporaryVariable(loc, tmpOwner.getExpressionType(), tmpOwner); } else { owner = new CFieldReference(loc, actField.getFirst(), actField.getSecond(), owner, false); } isFirstVisit = false; // only first field access may be an pointer dereference so we do not have to check anything // in this clause, just put a field reference to the next field on the actual owner } else { owner = new CFieldReference(loc, actField.getFirst(), actField.getSecond(), owner, false); } } } return (CFieldReference) owner; // FOLLOWING IF CLAUSE WILL ONLY BE EVALUATED WHEN THE OPTION cfa.simplifyPointerExpressions IS SET TO TRUE // if there is a "var->field" convert it to (*var).field } else if (options.simplifyPointerExpressions()) { return fullFieldReference.withExplicitPointerDereference(); } return fullFieldReference; } /** * This method creates a list of all necessary field access for finding the searched field. * Besides the case that the searched field is directly in the struct, there is the case * that the field is in an anonymous struct or union inside the "owner" struct. This anonymous * structs / unions are then the "way" to the searched field. * * @param allReferences an empty list * @return the fields (including the searched one) in the right order */ private static List<Pair<String, CType>> getWayToInnerField(CCompositeType owner, String fieldName, FileLocation loc, List<Pair<String, CType>> allReferences) { for (CCompositeTypeMemberDeclaration member : owner.getMembers()) { if (member.getName().equals(fieldName)) { allReferences.add(Pair.of(member.getName(), member.getType())); return ImmutableList.copyOf(allReferences); } } // no field found in current struct, so proceed to the structs/unions which are // fields inside the current struct for (CCompositeTypeMemberDeclaration member : owner.getMembers()) { CType memberType = member.getType().getCanonicalType(); if (memberType instanceof CCompositeType && member.getName().contains("__anon_type_member_")) { List<Pair<String, CType>> tmp = new ArrayList<>(allReferences); tmp.add(Pair.of(member.getName(), member.getType())); tmp = getWayToInnerField((CCompositeType)memberType, fieldName, loc, tmp); if (!tmp.isEmpty()) { return ImmutableList.copyOf(tmp); } } } return ImmutableList.of(); } private CRightHandSide convert(IASTFunctionCallExpression e) { CExpression functionName = convertExpressionWithoutSideEffects(e.getFunctionNameExpression()); CFunctionDeclaration declaration = null; final FileLocation loc = getLocation(e); if (functionName instanceof CIdExpression) { if (FUNC_TYPES_COMPATIBLE.equals(((CIdExpression) functionName).getName())) { sideAssignmentStack.enterBlock(); List<CExpression> params = new ArrayList<>(); for (IASTInitializerClause i : e.getArguments()) { params.add(convertExpressionWithoutSideEffects(toExpression(i))); } sideAssignmentStack.getAndResetConditionalExpressions(); sideAssignmentStack.getAndResetPostSideAssignments(); sideAssignmentStack.getAndResetPreSideAssignments(); sideAssignmentStack.leaveBlock(); if (params.size() == 2) { if (areCompatibleTypes(params.get(0).getExpressionType(), params.get(1).getExpressionType())) { return CIntegerLiteralExpression.ONE; } else { return CIntegerLiteralExpression.ZERO; } } } } List<CExpression> params = new ArrayList<>(); for (IASTInitializerClause i : e.getArguments()) { params.add(convertExpressionWithoutSideEffects(toExpression(i))); } if (functionName instanceof CIdExpression) { // this function is a gcc extension which checks if the given parameter is // a constant value. We can easily provide this functionality by checking // if the parameter is a literal expression. // We only do check it if the function is not declared. if (((CIdExpression) functionName).getName().equals(FUNC_CONSTANT) && params.size() == 1 && scope.lookupFunction(FUNC_CONSTANT) == null) { if (params.get(0) instanceof CLiteralExpression) { return CIntegerLiteralExpression.ONE; } else { return CIntegerLiteralExpression.ZERO; } } if (((CIdExpression) functionName).getName().equals(FUNC_OFFSETOF) && params.size() == 1 && params.get(0) instanceof CFieldReference) { CFieldReference exp = (CFieldReference) params.get(0); BigInteger offset = handleBuiltinOffsetOfFunction(exp, e); BigInteger byteInBit = new BigInteger("8"); if (offset.remainder(byteInBit).equals(BigInteger.ZERO)) { return new CIntegerLiteralExpression(loc, CNumericTypes.INT, offset.divide(byteInBit)); } else { throw parseContext.parseError("__builtin_offset is not applicable to bitfields ", exp); } } CSimpleDeclaration d = ((CIdExpression)functionName).getDeclaration(); if (d instanceof CFunctionDeclaration) { // it may also be a variable declaration, when a function pointer is called declaration = (CFunctionDeclaration)d; } if ((declaration == null) && FUNC_EXPECT.equals(((CIdExpression) functionName).getName()) && params.size() == 2) { // This is the GCC built-in function __builtin_expect(exp, c) // that behaves like (exp == c). // http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fexpect-3345 return buildBinaryExpression(params.get(0), params.get(1), BinaryOperator.EQUALS); } } // just unwrap typedefs, we do not want to put a canonical type into the CPointerExpression, // but the original type CType functionNameType = functionName.getExpressionType(); while (functionNameType instanceof CTypedefType) { functionNameType = ((CTypedefType) functionNameType).getRealType(); } if (functionNameType instanceof CPointerType && ((CPointerType) functionNameType).getType().getCanonicalType() instanceof CFunctionType) { // Function pointers can be called either via "*fp" or simply "fp". // We add the dereference operator, if it is missing. functionName = new CPointerExpression(functionName.getFileLocation(), ((CPointerType)functionNameType).getType(), functionName); } CType returnType = typeConverter.convert(e.getExpressionType()); if (containsProblemType(returnType)) { // workaround for Eclipse CDT problems if (declaration != null) { returnType = declaration.getType().getReturnType(); logger.log(Level.FINE, loc + ":", "Replacing return type", returnType, "of function call", e.getRawSignature(), "with", returnType); } else { final CType functionType = functionName.getExpressionType().getCanonicalType(); if (functionType instanceof CFunctionType) { returnType = ((CFunctionType) functionType).getReturnType(); logger.log(Level.FINE, loc + ":", "Replacing return type", returnType, "of function call", e.getRawSignature(), "with", returnType); } } } if (declaration == null && functionName instanceof CIdExpression && returnType instanceof CVoidType) { // Undeclared functions are a problem for analysis that need precise types. // We can at least set the return type to "int" as the standard says. logger.log(Level.FINE, loc + ":", "Setting return type of of undeclared function", functionName, "to int."); returnType = CNumericTypes.INT; } return new CFunctionCallExpression(loc, returnType, functionName, params, declaration); } private BigInteger handleBuiltinOffsetOfFunction(CFieldReference exp, IASTFunctionCallExpression e) { List<CFieldReference> fields = new ArrayList<>(); fields.add(exp); while (exp.getFieldOwner() instanceof CFieldReference) { CFieldReference tmp = (CFieldReference) exp.getFieldOwner(); exp = tmp; fields.add(exp); } if (!(exp.getFieldOwner() instanceof CIdExpression)) { throw parseContext.parseError( "unexpected type " + exp.getFieldOwner() + " in __builtin_offsetof argument: ", e); } final CType ownerType = exp.getFieldOwner().getExpressionType().getCanonicalType(); if (!(ownerType instanceof CCompositeType)) { throw parseContext.parseError( "unexpected type " + ownerType + " in __builtin_offsetof argument", e); } CCompositeType structType = (CCompositeType) ownerType; BigInteger sumOffset = BigInteger.ZERO; Collections.reverse(fields); for (CFieldReference field : fields) { BigInteger offset = machinemodel.getFieldOffsetInBits(structType, field.getFieldName()); sumOffset = sumOffset.add(offset); CFieldReference lastField = fields.get(fields.size() - 1); if (!field.equals(lastField)) { final CType fieldType = field.getExpressionType().getCanonicalType(); if (!(fieldType instanceof CCompositeType)) { throw parseContext.parseError( "unexpected type " + fieldType + " in __builtin_offsetof argument", e); } structType = (CCompositeType) fieldType; } } return sumOffset; } private boolean areCompatibleTypes(CType a, CType b) { // http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005ftypes_005fcompatible_005fp-3613 a = withoutConst(withoutVolatile(a.getCanonicalType())); b = withoutConst(withoutVolatile(b.getCanonicalType())); if (a.equals(b)) { return true; } if (a instanceof CArrayType && b instanceof CArrayType) { CArrayType arrayA = (CArrayType)a; CArrayType arrayB = (CArrayType)b; if (arrayA.getType().equals(arrayB.getType())) { if (arrayA.getLength() == null || arrayB.getLength() == null) { // The type int[] and int[5] are compatible return true; } } } return false; } private CIdExpression convert(IASTIdExpression e) { String name = convert(e.getName()); // Try to find declaration. // Variables per se actually do not bind stronger than function, // but local variables do. // Furthermore, a global variable and a function with the same name // cannot exist, so the following code works correctly. // We first try to lookup static variables. CSimpleDeclaration declaration = scope.lookupVariable(staticVariablePrefix + name); if (declaration == null) { declaration = scope.lookupVariable(name); } if (declaration == null) { declaration = scope.lookupFunction(staticVariablePrefix + name); } if (declaration == null) { declaration = scope.lookupFunction(name); } // declaration may still be null here, // for example when parsing AST patterns for the AutomatonCPA. if (declaration != null) { name = declaration.getName(); // may have been renamed } CType type; // Use declaration type when possible to fix issues with anonymous composites, problem types etc. if (declaration != null) { type = declaration.getType(); } else { type = typeConverter.convert(e.getExpressionType()); } if (declaration instanceof CEnumerator && type instanceof CElaboratedType && ((CElaboratedType)type).getKind() == ComplexTypeKind.ENUM && ((CElaboratedType)type).getRealType() == null) { // This is a reference to a value of an anonymous enum ("enum { e }"). // Such types cannot be looked up, and thus the CElaboratedType misses // the reference to the enum type. CEnumType enumType = ((CEnumerator)declaration).getEnum(); // enumType is null if an enum value is referenced inside the enum declaration, // e.g. like this: "enum { e1, e2 = e1 }" if (enumType != null) { type = new CElaboratedType(type.isConst(), type.isVolatile(), ComplexTypeKind.ENUM, enumType.getName(), enumType.getOrigName(), enumType); } } return new CIdExpression(getLocation(e), type, name, declaration); } private CAstNode convert(final IASTUnaryExpression e) { if (e.getOperator() == IASTUnaryExpression.op_bracketedPrimary) { // we can have side effects here return convertExpressionWithSideEffects(e.getOperand()); } final CExpression operand = convertExpressionWithoutSideEffects(e.getOperand()); if (operand == null) { return operand; } final FileLocation fileLoc = getLocation(e); final CType operandType = operand.getExpressionType(); switch (e.getOperator()) { case IASTUnaryExpression.op_bracketedPrimary: throw new AssertionError("handled above"); case IASTUnaryExpression.op_plus: return operand; case IASTUnaryExpression.op_star: { // In case of pointers inside field references that refer to inner fields // the CDT type is not as we want it, thus we resolve the type on our own. CType type; if (operandType instanceof CPointerType) { type = ((CPointerType) operandType).getType(); } else if (operandType instanceof CArrayType) { type = ((CArrayType) operandType).getType(); } else { if (!(operandType instanceof CProblemType)) { logger.logf(Level.WARNING, "%s: Dereferencing of non-pointer type %s in expression %s", fileLoc, operandType, e.getRawSignature()); } type = typeConverter.convert(e.getExpressionType()); } return simplifyUnaryPointerExpression(operand, fileLoc, type); } case IASTUnaryExpression.op_amper: { // FOLLOWING IF CLAUSE WILL ONLY BE EVALUATED WHEN THE OPTION cfa.simplifyPointerExpressions IS SET TO TRUE // in case of *& both can be left out if (options.simplifyPointerExpressions() && operand instanceof CPointerExpression) { return ((CPointerExpression)operand).getOperand(); } CType type = typeConverter.convert(e.getExpressionType()); if (containsProblemType(type)) { type = new CPointerType(true, false, operandType); } // if none of the special cases before fits the default unaryExpression is created return new CUnaryExpression(fileLoc, type, operand, UnaryOperator.AMPER); } case IASTUnaryExpression.op_labelReference: // L: void * addressOfLabel = && L; if (!(operand instanceof CIdExpression)) { throw parseContext.parseError("Invalid operand for address-of-label operator", e); } String labelName = ((CIdExpression)operand).getName(); // type given by CDT is problem type return new CAddressOfLabelExpression(fileLoc, CPointerType.POINTER_TO_VOID, labelName); case IASTUnaryExpression.op_prefixIncr: case IASTUnaryExpression.op_prefixDecr: // instead of ++x, create "x = x+1" BinaryOperator preOp; switch (e.getOperator()) { case IASTUnaryExpression.op_prefixIncr: preOp = BinaryOperator.PLUS; break; case IASTUnaryExpression.op_prefixDecr: preOp = BinaryOperator.MINUS; break; default: throw new AssertionError(); } CBinaryExpression preExp = buildBinaryExpression(operand, CIntegerLiteralExpression.ONE, preOp); CLeftHandSide lhsPre = (CLeftHandSide) operand; return new CExpressionAssignmentStatement(fileLoc, lhsPre, preExp); case IASTUnaryExpression.op_postFixIncr: case IASTUnaryExpression.op_postFixDecr: // instead of x++ create "x = x + 1" BinaryOperator postOp; switch (e.getOperator()) { case IASTUnaryExpression.op_postFixIncr: postOp = BinaryOperator.PLUS; break; case IASTUnaryExpression.op_postFixDecr: postOp = BinaryOperator.MINUS; break; default: throw new AssertionError(); } CBinaryExpression postExp = buildBinaryExpression(operand, CIntegerLiteralExpression.ONE, postOp); CLeftHandSide lhsPost = (CLeftHandSide) operand; CExpressionAssignmentStatement result = new CExpressionAssignmentStatement(fileLoc, lhsPost, postExp); if (e.getParent() instanceof IASTForStatement && e.getPropertyInParent() == IASTForStatement.ITERATION) { return result; } CExpression tmp = createInitializedTemporaryVariable(fileLoc, lhsPost.getExpressionType(), lhsPost); sideAssignmentStack.addPreSideAssignment(result); return tmp; case IASTUnaryExpression.op_not: try { return binExprBuilder.negateExpressionAndSimplify(operand); } catch (UnrecognizedCodeException ex) { throw new CFAGenerationRuntimeException(ex); } default: CType type; if (e.getOperator() == IASTUnaryExpression.op_alignOf) { type = CNumericTypes.INT; } else if (e.getOperator() == IASTUnaryExpression.op_minus && operand.getExpressionType() instanceof CSimpleType) { // CDT parser might get the type wrong in this case, e.g.: // literals that should be of type long would still be int instead of long, // because CDT only makes the operand long if there is a 'L' at the end // => we cannot use e.getExpressionType() here! CSimpleType innerType = (CSimpleType) operand.getExpressionType(); // now do not forget: operand should get promoted to int if its type is smaller than int: type = CTypes.isIntegerType(innerType) ? machinemodel.applyIntegerPromotion(innerType) : innerType; } else { type = typeConverter.convert(e.getExpressionType()); } return new CUnaryExpression(fileLoc, type, operand, operatorConverter.convertUnaryOperator(e)); } } /** returns a CPointerExpression, that may be simplified. */ private CExpression simplifyUnaryPointerExpression( final CExpression operand, final FileLocation fileLoc, final CType type) { // FOLLOWING IF CLAUSE WILL ONLY BE EVALUATED WHEN THE OPTION cfa.simplifyPointerExpressions IS SET TO TRUE if (options.simplifyPointerExpressions()) { final CType operandType = operand.getExpressionType(); // if there is a dereference on a field of a struct a temporary variable is needed if (operand instanceof CFieldReference) { CIdExpression tmpVar = createInitializedTemporaryVariable(fileLoc, operandType, operand); return new CPointerExpression(fileLoc, type, tmpVar); } // in case of *(a[index]) else if(operand instanceof CArraySubscriptExpression) { CIdExpression tmpVar = createInitializedTemporaryVariable(fileLoc, operandType, operand); return new CPointerExpression(fileLoc, type, tmpVar); } // in case of *& both can be left out else if(operand instanceof CUnaryExpression && ((CUnaryExpression)operand).getOperator() == UnaryOperator.AMPER) { return ((CUnaryExpression)operand).getOperand(); } // in case of ** a temporary variable is needed else if(operand instanceof CPointerExpression) { CIdExpression tmpVar = createInitializedTemporaryVariable(fileLoc, operandType, operand); return new CPointerExpression(fileLoc, type, tmpVar); } // in case of p.e. *(a+b) or *(a-b) or *(a ANY_OTHER_OPERATOR b) a temporary variable is needed else if(operand instanceof CBinaryExpression) { CIdExpression tmpVar = createInitializedTemporaryVariable(fileLoc, operandType, operand); return new CPointerExpression(fileLoc, type, tmpVar); } } // if none of the special cases before fits the default unaryExpression is created return new CPointerExpression(fileLoc, type, operand); } private CTypeIdExpression convert(IASTTypeIdExpression e) { TypeIdOperator typeIdOperator = operatorConverter.convertTypeIdOperator(e); CType expressionType; CType typeId = convert(e.getTypeId()); if (typeIdOperator == TypeIdOperator.ALIGNOF || typeIdOperator == TypeIdOperator.SIZEOF) { // sizeof and _Alignof always return int, CDT sometimes provides wrong type expressionType = CNumericTypes.INT; if (typeId.isIncomplete()) { // Cannot compute alignment throw parseContext.parseError( "Invalid application of " + typeIdOperator.getOperator() + " to incomplete type " + typeId, e); } } else { expressionType = typeConverter.convert(e.getExpressionType()); } return new CTypeIdExpression(getLocation(e), expressionType, typeIdOperator, typeId); } private CExpression convert(IASTTypeIdInitializerExpression e) { // This is a "compound literal" (C11 § 6.5.2.5). // It is similar to Java array instantiations with "new String[]{...}". FileLocation fileLoc = getLocation(e); CType type = convert(e.getTypeId()); CInitializer initializer = convert(e.getInitializer(), type, null); return createInitializedTemporaryVariable(fileLoc, type, initializer); } public CAstNode convert(final IASTStatement s) { if (s instanceof IASTExpressionStatement) { return convert((IASTExpressionStatement) s); } else if (s instanceof IASTReturnStatement) { return convert((IASTReturnStatement) s); } else if (s instanceof IASTProblemStatement) { throw parseContext.parseError((IASTProblemStatement) s); } else { throw parseContext.parseError("unknown statement: " + s.getClass(), s); } } public CStatement convert(final IASTExpressionStatement s) { return convertExpressionToStatement(s.getExpression()); } public CStatement convertExpressionToStatement(final IASTExpression e) { CAstNode node = convertExpressionWithSideEffects(e); if (node instanceof CExpressionAssignmentStatement) { return (CExpressionAssignmentStatement)node; } else if (node instanceof CFunctionCallAssignmentStatement) { return (CFunctionCallAssignmentStatement)node; } else if (node instanceof CFunctionCallExpression) { return new CFunctionCallStatement(getLocation(e), (CFunctionCallExpression)node); } else if (node instanceof CExpression) { return new CExpressionStatement(getLocation(e), (CExpression)node); } else if (node == null) { return null; } else { throw new AssertionError(); } } public CReturnStatement convert(final IASTReturnStatement s) { final FileLocation loc = getLocation(s); final Optional<CExpression> returnExp = Optional.fromNullable(convertExpressionWithoutSideEffects(s.getReturnValue())); final Optional<CVariableDeclaration> returnVariableDeclaration = ((FunctionScope)scope).getReturnVariable(); final Optional<CAssignment> returnAssignment; if (returnVariableDeclaration.isPresent()) { CIdExpression lhs = new CIdExpression(loc, returnVariableDeclaration.get()); CExpression rhs = null; if (returnExp.isPresent()) { rhs = returnExp.get(); } else { logger.log(Level.WARNING, loc + ":", "Return statement without expression in non-void function."); CInitializer defaultValue = CDefaults.forType(returnVariableDeclaration.get().getType(), loc); if (defaultValue instanceof CInitializerExpression) { rhs = ((CInitializerExpression)defaultValue).getExpression(); } } if (rhs != null) { returnAssignment = Optional.of(new CExpressionAssignmentStatement(loc, lhs, rhs)); } else { returnAssignment = Optional.absent(); } } else { if (returnExp.isPresent()) { logger.log(Level.WARNING, loc + ":", "Return statement with expression", returnExp.get(), "in void function."); } returnAssignment = Optional.absent(); } return new CReturnStatement(loc, returnExp, returnAssignment); } public CFunctionDeclaration convert(final IASTFunctionDefinition f) { Pair<CStorageClass, ? extends CType> specifier = convert(f.getDeclSpecifier()); CStorageClass cStorageClass = specifier.getFirst(); if (!(cStorageClass == CStorageClass.AUTO || cStorageClass == CStorageClass.STATIC || cStorageClass == CStorageClass.EXTERN)) { // storage class static is the same as auto, just with reduced visibility to a single compilation unit, // and as we only handle single compilation units, we can ignore it. A storage class extern associated // with a function definition, while superfluous, unless it's an inline function, is allowed, too. throw parseContext.parseError("Unsupported storage class for function definition", f); } Triple<CType, IASTInitializer, String> declarator = convert(f.getDeclarator(), specifier.getSecond(), cStorageClass == CStorageClass.STATIC); if (!(declarator.getFirst() instanceof CFunctionTypeWithNames)) { throw parseContext.parseError("Unsupported nested declarator for function definition", f); } if (declarator.getSecond() != null) { throw parseContext.parseError("Unsupported initializer for function definition", f); } if (declarator.getThird() == null) { throw parseContext.parseError("Missing name for function definition", f); } CFunctionTypeWithNames declSpec = (CFunctionTypeWithNames)declarator.getFirst(); return new CFunctionDeclaration( getLocation(f), declSpec, declSpec.getName(), declarator.getThird(), declSpec.getParameterDeclarations()); } public List<CDeclaration> convert(final IASTSimpleDeclaration d) { FileLocation fileLoc = getLocation(d); Pair<CStorageClass, ? extends CType> specifier = convert(d.getDeclSpecifier()); CStorageClass cStorageClass = specifier.getFirst(); CType type = specifier.getSecond(); IASTDeclarator[] declarators = d.getDeclarators(); List<CDeclaration> result = new ArrayList<>(); if (type instanceof CCompositeType || type instanceof CEnumType) { // struct, union, or enum declaration // split type definition from eventual variable declaration CComplexType complexType = (CComplexType)type; // in case of struct declarations with variable declarations we // need to add the struct declaration as sideeffect, so that // we can be sure the variable gets the correct (perhaps renamed) type if (declarators.length > 0 && type instanceof CCompositeType) { addSideEffectDeclarationForType((CCompositeType) complexType, fileLoc); complexType = scope.lookupType(complexType.getQualifiedName()); } else { result.add(new CComplexTypeDeclaration(fileLoc, scope.isGlobalScope(), complexType)); } // now replace type with an elaborated type referencing the new type type = new CElaboratedType(type.isConst(), type.isVolatile(), complexType.getKind(), complexType.getName(), complexType.getOrigName(), complexType); } else if (type instanceof CElaboratedType) { boolean typeAlreadyKnown = scope.lookupType(((CElaboratedType) type).getQualifiedName()) != null; boolean variableDeclaration = declarators != null && declarators.length > 0; if (!typeAlreadyKnown || !variableDeclaration) { CComplexTypeDeclaration newD = new CComplexTypeDeclaration(fileLoc, scope.isGlobalScope(), (CElaboratedType)type); result.add(newD); } } if (declarators != null) { for (IASTDeclarator c : declarators) { FileLocation declaratorLocation = getLocation(c); if (FileLocation.DUMMY.equals(declaratorLocation)) { declaratorLocation = fileLoc; } else if (c == declarators[0]) { declaratorLocation = new FileLocation( fileLoc.getFileName(), fileLoc.getNiceFileName(), fileLoc.getNodeOffset(), declaratorLocation.getNodeOffset() - fileLoc.getNodeOffset() + declaratorLocation.getNodeLength(), fileLoc.getStartingLineNumber(), declaratorLocation.getEndingLineNumber(), fileLoc.getStartingLineInOrigin(), fileLoc.getEndingLineInOrigin(), fileLoc.isOffsetRelatedToOrigin()); } result.add(createDeclaration(declaratorLocation, cStorageClass, type, c)); } } return result; } private CDeclaration createDeclaration(FileLocation fileLoc, CStorageClass cStorageClass, CType type, IASTDeclarator d) { boolean isGlobal = scope.isGlobalScope(); if (d != null) { Triple<CType, IASTInitializer, String> declarator = convert(d, type); type = declarator.getFirst(); IASTInitializer initializer = declarator.getSecond(); String name = declarator.getThird(); if (name == null) { throw parseContext.parseError("Declaration without name", d); } // first handle all special cases if (cStorageClass == CStorageClass.TYPEDEF) { if (initializer != null) { throw parseContext.parseError("Typedef with initializer", d); } name = scope.getFileSpecificTypeName(name); return new CTypeDefDeclaration(fileLoc, isGlobal, type, name, scope.createScopedNameOf(name)); } // We need to resolve typedefs, but we cannot call getCanonicalType() // because we need to leave the parameter types unchanged. CType innerType = type; while (innerType instanceof CTypedefType) { innerType = ((CTypedefType)innerType).getRealType(); } if (innerType instanceof CFunctionType) { if (initializer != null) { throw parseContext.parseError("Function definition with initializer", d); } // Note that this silently ignores const and volatile qualifiers // for typedefs of function types, but this is ok because const or volatile functions // are undefined behavior anyway (C11 §6.7.3 (9)). List<CParameterDeclaration> params; CFunctionType functionType = (CFunctionType)innerType; if (functionType instanceof CFunctionTypeWithNames) { params = ((CFunctionTypeWithNames)functionType).getParameterDeclarations(); } else { params = new ArrayList<>(functionType.getParameters().size()); int i = 0; for (CType paramType : functionType.getParameters()) { params.add(new CParameterDeclaration(fileLoc, paramType, "__param" + i++)); } } return new CFunctionDeclaration(fileLoc, functionType, name, params); } // now it should be a regular variable declaration if (cStorageClass == CStorageClass.EXTERN && initializer != null) { throw parseContext.parseError("Extern declarations cannot have initializers", d); } if (cStorageClass != CStorageClass.EXTERN && innerType instanceof CVoidType) { throw parseContext.parseError("Variable cannot have type void", d); } String origName = name; if (cStorageClass == CStorageClass.STATIC) { if (!isGlobal) { isGlobal = true; name = "static__" + ((FunctionScope)scope).getCurrentFunctionName() + "__" + name; } else { name = staticVariablePrefix + name; } cStorageClass = CStorageClass.AUTO; } if (!isGlobal && cStorageClass == CStorageClass.EXTERN) { // TODO: implement this, it "imports" the externally declared variable // into the scope of this block. throw parseContext.parseError("Local variable declared extern is unsupported", d); } if (!isGlobal && scope.variableNameInUse(name)) { String sep = "__"; int index = 1; while (scope.variableNameInUse(name + sep + index)) { ++index; } name = name + sep + index; } CVariableDeclaration declaration = new CVariableDeclaration(fileLoc, isGlobal, cStorageClass, type, name, origName, scope.createScopedNameOf(name), null); scope.registerDeclaration(declaration); // Now that we registered the declaration, we can parse the initializer. // We cannot do this before, because in the following code, the right "x" // actually binds to the left "x"! // int x = x; declaration.addInitializer(convert(initializer, declaration.getType(), declaration)); return declaration; } else { throw new CFAGenerationRuntimeException( "Declaration without declarator, but type is unknown: " + type.toASTString("")); } } private List<CCompositeTypeMemberDeclaration> convertDeclarationInCompositeType(final IASTDeclaration d, int nofMember) { if (d.getParent() instanceof CASTCompositeTypeSpecifier) { // FIXME: remove conditional after debugging } if (d instanceof IASTProblemDeclaration) { throw parseContext.parseError((IASTProblemDeclaration) d); } if (!(d instanceof IASTSimpleDeclaration)) { throw parseContext.parseError("unknown declaration type " + d.getClass().getSimpleName(), d); } IASTSimpleDeclaration sd = (IASTSimpleDeclaration)d; Pair<CStorageClass, ? extends CType> specifier = convert(sd.getDeclSpecifier()); //TODO: add knowledge about sd.DeclSpecifier.alignmentSpecifiers if (specifier.getFirst() != CStorageClass.AUTO) { throw parseContext.parseError("Unsupported storage class inside composite type", d); } CType type = specifier.getSecond(); if (type instanceof CCompositeType) { // Nested struct declaration CCompositeType compositeType = (CCompositeType)type; addSideEffectDeclarationForType(compositeType, getLocation(d)); type = new CElaboratedType(compositeType.isConst(), compositeType.isVolatile(), compositeType.getKind(), compositeType.getName(), compositeType.getOrigName(), compositeType); } List<CCompositeTypeMemberDeclaration> result; IASTDeclarator[] declarators = sd.getDeclarators(); if (declarators == null || declarators.length == 0) { // declaration without declarator, anonymous struct field? CCompositeTypeMemberDeclaration newD = createDeclarationForCompositeType(type, null, nofMember); result = Collections.singletonList(newD); } else if (declarators.length == 1) { CCompositeTypeMemberDeclaration newD = createDeclarationForCompositeType(type, declarators[0], nofMember); result = Collections.singletonList(newD); } else { result = new ArrayList<>(declarators.length); for (IASTDeclarator c : declarators) { result.add(createDeclarationForCompositeType(type, c, nofMember)); } } return result; } private CCompositeTypeMemberDeclaration createDeclarationForCompositeType(CType type, IASTDeclarator d, int nofMember) { String name = null; if (d != null) { Triple<CType, IASTInitializer, String> declarator = convert(d, type); if (declarator.getSecond() != null) { throw parseContext.parseError("Unsupported initializer inside composite type", d); } type = declarator.getFirst(); name = declarator.getThird(); } if (isNullOrEmpty(name)) { name = "__anon_type_member_" + nofMember; } return new CCompositeTypeMemberDeclaration(type, name); } private Triple<CType, IASTInitializer, String> convert(IASTDeclarator d, CType specifier) { while (d != null && d.getClass() == CASTDeclarator.class && d.getPointerOperators().length == 0 && d.getAttributes().length == 0 && d.getAttributeSpecifiers().length == 0 && d.getInitializer() == null && d.getNestedDeclarator() != null) { // This is an "empty" declarator with nothing else but the nested declarator. // It comes from code like "void ((*(f))(void));" // (the outer unnecessary parentheses are represented by this). // We just ignore this declarator like we ignore parentheses in expressions. d = d.getNestedDeclarator(); } if (d instanceof IASTFunctionDeclarator) { // TODO is it always right to assume that here is no static storage class return convert((IASTFunctionDeclarator)d, specifier, false); } else { // Parsing type declarations in C is complex. // For example, array modifiers and pointer operators are declared in the // "wrong" way: // "int (*drives[4])[6]" is "array 4 of pointer to array 6 of int" // (The inner most modifiers are the highest-level ones.) // So we don't do this recursively, but instead collect all modifiers // and apply them after we have reached the inner-most declarator. // Collection of all modifiers (outermost modifier is first). List<IASTNode> modifiers = new ArrayList<>(1); IASTInitializer initializer = null; String name = null; Integer bitFieldSize = null; // Descend into the nested chain of declarators. // Find out the name and the initializer, and collect all modifiers. IASTDeclarator currentDecl = d; while (currentDecl != null) { // TODO handle bitfields by checking for instanceof IASTFieldDeclarator if (currentDecl instanceof IASTFieldDeclarator) { if (bitFieldSize != null) { throw parseContext.parseError("Unsupported declaration with two bitfield descriptions", d); } IASTExpression bitField = ((IASTFieldDeclarator) currentDecl).getBitFieldSize(); if (bitField instanceof CASTLiteralExpression) { CExpression cExpression = convertExpressionWithoutSideEffects(bitField); if (cExpression instanceof CIntegerLiteralExpression) { bitFieldSize = ((CIntegerLiteralExpression) cExpression).getValue().intValue(); } else { throw parseContext.parseError("Unsupported bitfield specifier", d); } } } if (currentDecl instanceof IASTFunctionDeclarator) { throw parseContext.parseError("Unsupported declaration nested function declarations", d); } modifiers.addAll(Arrays.asList(currentDecl.getPointerOperators())); if (currentDecl instanceof IASTArrayDeclarator) { modifiers.addAll(Arrays.asList(((IASTArrayDeclarator) currentDecl).getArrayModifiers())); } if (currentDecl.getInitializer() != null) { if (initializer != null) { throw parseContext.parseError("Unsupported declaration with two initializers", d); } //xxx initializer = currentDecl.getInitializer(); } if (!currentDecl.getName().toString().isEmpty()) { if (name != null) { throw parseContext.parseError("Unsupported declaration with two names", d); } name = convert(currentDecl.getName()); } currentDecl = currentDecl.getNestedDeclarator(); } name = Strings.nullToEmpty(name); // there may be no name at all, for example in parameter declarations // Add the modifiers to the type. CType type = specifier; // array modifiers have to be added backwards, otherwise the arraysize is wrong // with multidimensional arrays List<IASTArrayModifier> tmpArrMod = new ArrayList<>(); for (IASTNode modifier : modifiers) { if (modifier instanceof IASTArrayModifier) { tmpArrMod.add((IASTArrayModifier) modifier); } else if (modifier instanceof IASTPointerOperator) { //add accumulated array modifiers before adding next pointer operator for (int i = tmpArrMod.size() -1; i >= 0; i--) { type = convert(tmpArrMod.get(i), type); } // clear added modifiers tmpArrMod.clear(); type = typeConverter.convert((IASTPointerOperator)modifier, type); } else { throw new AssertionError(); } } // add last array modifiers if necessary for (int i = tmpArrMod.size() -1; i >= 0; i--) { type = convert(tmpArrMod.get(i), type); } // Arrays with unknown length but an initializer // have their length calculated from the initializer. // Example: int a[] = { 1, 2 }; // will be converted as int a[2] = { 1, 2 }; if (type instanceof CArrayType) { CArrayType arrayType = (CArrayType)type; if (arrayType.getLength() == null && initializer instanceof IASTEqualsInitializer) { IASTInitializerClause initClause = ((IASTEqualsInitializer)initializer).getInitializerClause(); if (initClause instanceof IASTInitializerList) { int length = 0; int position = 0; for (IASTInitializerClause x : ((IASTInitializerList)initClause).getClauses()) { if (length == -1) { break; } if (x instanceof ICASTDesignatedInitializer) { for (ICASTDesignator designator : ((ICASTDesignatedInitializer) x).getDesignators()) { if (designator instanceof CASTArrayRangeDesignator) { CAstNode ceil = convertExpressionWithSideEffects(((CASTArrayRangeDesignator)designator).getRangeCeiling()); if (ceil instanceof CIntegerLiteralExpression) { int c = ((CIntegerLiteralExpression)ceil).getValue().intValue(); length = Math.max(length, c + 1); position = c + 1; // we need distinct numbers for the range bounds, if they // are not there we cannot calculate the length of the array // correctly } else { length = -1; break; } } else if (designator instanceof CASTArrayDesignator) { CAstNode subscript = convertExpressionWithSideEffects(((CASTArrayDesignator)designator).getSubscriptExpression()); int s = ((CIntegerLiteralExpression)subscript).getValue().intValue(); length = Math.max(length, s+1); position = s + 1; // we only know the length of the CASTArrayDesignator and the CASTArrayRangeDesignator, all other designators // have to be ignore, if one occurs, we cannot calculate the length of the array correctly } else { length = -1; break; } } } else { position++; length = Math.max(position, length); } } // only adjust the length of the array if we definitely know it if (length != -1) { CExpression lengthExp = new CIntegerLiteralExpression( getLocation(initializer), CNumericTypes.INT, BigInteger.valueOf(length)); type = new CArrayType(arrayType.isConst(), arrayType.isVolatile(), arrayType.getType(), lengthExp); } } else { // Arrays with unknown length but an string initializer // have their length calculated from the initializer. // Example: char a[] = "abc"; // will be converted as char a[4] = "abc"; if (initClause instanceof CASTLiteralExpression && (arrayType.getType().equals(CNumericTypes.CHAR) || arrayType.getType().equals(CNumericTypes.SIGNED_CHAR) || arrayType.getType().equals(CNumericTypes.UNSIGNED_CHAR))) { CASTLiteralExpression literalExpression = (CASTLiteralExpression) initClause; int length = literalExpression.getLength() - 1; CExpression lengthExp = new CIntegerLiteralExpression( getLocation(initializer), CNumericTypes.INT, BigInteger.valueOf(length)); type = new CArrayType(arrayType.isConst(), arrayType.isVolatile(), arrayType.getType(), lengthExp); } } } } if (bitFieldSize != null) { type = typeConverter.convertBitFieldType(bitFieldSize, type); } return Triple.of(type, initializer, name); } } private CType convert(IASTArrayModifier am, CType type) { if (am instanceof ICASTArrayModifier) { ICASTArrayModifier a = (ICASTArrayModifier)am; CExpression lengthExp = convertExpressionWithoutSideEffects(a.getConstantExpression()); if (lengthExp != null) { lengthExp = simplifyExpressionRecursively(lengthExp); } return new CArrayType(a.isConst(), a.isVolatile(), type, lengthExp); } else { throw parseContext.parseError("Unknown array modifier", am); } } private Triple<CType, IASTInitializer, String> convert(IASTFunctionDeclarator d, CType returnType, boolean isStaticFunction) { if (!(d instanceof IASTStandardFunctionDeclarator)) { throw parseContext.parseError("Unknown non-standard function definition", d); } IASTStandardFunctionDeclarator sd = (IASTStandardFunctionDeclarator)d; // handle return type returnType = typeConverter.convertPointerOperators(d.getPointerOperators(), returnType); if (returnType instanceof CSimpleType) { CSimpleType t = (CSimpleType)returnType; if (t.getType() == CBasicType.UNSPECIFIED) { // type of functions is implicitly int it not specified returnType = new CSimpleType(t.isConst(), t.isVolatile(), CBasicType.INT, t.isLong(), t.isShort(), t.isSigned(), t.isUnsigned(), t.isComplex(), t.isImaginary(), t.isLongLong()); } } // handle parameters List<CParameterDeclaration> paramsList = convert(sd.getParameters()); CFunctionTypeWithNames fType = new CFunctionTypeWithNames(returnType, paramsList, sd.takesVarArgs()); CType type = fType; String origname; if (d.getNestedDeclarator() != null) { Triple<? extends CType, IASTInitializer, String> nestedDeclarator = convert(d.getNestedDeclarator(), type); assert d.getName().getRawSignature().isEmpty() : d; assert nestedDeclarator.getSecond() == null; type = nestedDeclarator.getFirst(); origname = nestedDeclarator.getThird(); } else { origname = convert(d.getName()); } String qualifiedName = origname; if (isStaticFunction) { qualifiedName = staticVariablePrefix + origname; } fType.setName(qualifiedName); for (CParameterDeclaration param : paramsList) { param.setQualifiedName(FunctionScope.createQualifiedName(qualifiedName, param.getName())); } return Triple.of(type, d.getInitializer(), origname); } private Pair<CStorageClass, ? extends CType> convert(IASTDeclSpecifier d) { CStorageClass sc = typeConverter.convertCStorageClass(d); if (d instanceof IASTCompositeTypeSpecifier) { return Pair.of(sc, convert((IASTCompositeTypeSpecifier)d)); } else if (d instanceof IASTElaboratedTypeSpecifier) { return Pair.of(sc, typeConverter.convert((IASTElaboratedTypeSpecifier)d)); } else if (d instanceof IASTEnumerationSpecifier) { return Pair.of(sc, convert((IASTEnumerationSpecifier)d)); } else if (d instanceof IASTNamedTypeSpecifier) { return Pair.of(sc, typeConverter.convert((IASTNamedTypeSpecifier)d)); } else if (d instanceof IASTSimpleDeclSpecifier) { return Pair.of(sc, typeConverter.convert((IASTSimpleDeclSpecifier)d)); } else { throw parseContext.parseError("unknown declSpecifier", d); } } private CCompositeType convert(IASTCompositeTypeSpecifier d) { List<CCompositeTypeMemberDeclaration> list = new ArrayList<>(d.getMembers().length); int nofMember = 0; for (IASTDeclaration c : d.getMembers()) { List<CCompositeTypeMemberDeclaration> newCs = convertDeclarationInCompositeType(c, nofMember); nofMember++; assert !newCs.isEmpty(); list.addAll(newCs); } ComplexTypeKind kind; switch (d.getKey()) { case IASTCompositeTypeSpecifier.k_struct: kind = ComplexTypeKind.STRUCT; break; case IASTCompositeTypeSpecifier.k_union: kind = ComplexTypeKind.UNION; break; default: throw parseContext.parseError("Unknown key " + d.getKey() + " for composite type", d); } String name = convert(d.getName()); String origName = name; if (name.isEmpty()) { name = "__anon_type_"; if (d.getStorageClass() == IASTDeclSpecifier.sc_typedef) { name += ((IASTSimpleDeclaration)d.getParent()).getDeclarators()[0].getName().getRawSignature(); } else { name += anonTypeCounter++; } } for (Iterator<CCompositeTypeMemberDeclaration> it = list.iterator(); it.hasNext(); ) { CCompositeTypeMemberDeclaration member = it.next(); if (member.getType().isIncomplete()) { if (kind != ComplexTypeKind.STRUCT) { parseContext.parseError("Member " + member + " has incomplete type in union " + name, d); } if (it.hasNext()) { parseContext.parseError( "Member " + member + " in non-last position of struct " + name + " has incomplete type", d); } if (!(member.getType().getCanonicalType() instanceof CArrayType)) { parseContext.parseError( "Member " + member + " of struct " + name + " has incomplete non-array type", d); } } } CCompositeType compositeType = new CCompositeType(d.isConst(), d.isVolatile(), kind, list, name, origName); // in cases like struct s { (struct s)* f } // we need to fill in the binding from the inner "struct s" type to the outer compositeType.accept(new FillInBindingVisitor(kind, scope.getFileSpecificTypeName(name), compositeType)); return compositeType; } private CEnumType convert(IASTEnumerationSpecifier d) { List<CEnumerator> list = new ArrayList<>(d.getEnumerators().length); Long lastValue = -1L; // initialize with -1, so the first one gets value 0 for (IASTEnumerationSpecifier.IASTEnumerator c : d.getEnumerators()) { CEnumerator newC = convert(c, lastValue); list.add(newC); if (newC.hasValue()) { lastValue = newC.getValue(); } else { lastValue = null; } } String name = convert(d.getName()); String origName = name; // when the enum has no name we create one // (this may be the case when the enum declaration is surrounded by a typedef) if (name.isEmpty()) { name = "__anon_type_" + anonTypeCounter++; } CEnumType enumType = new CEnumType(d.isConst(), d.isVolatile(), list, name, origName); CSimpleType integerType = getEnumerationType(enumType); for (CEnumerator enumValue : enumType.getEnumerators()) { enumValue.setEnum(enumType); enumValue.setType(integerType); } return enumType; } private static final ImmutableList<CSimpleType> ENUM_REPRESENTATION_CANDIDATE_TYPES = ImmutableList.of( // list of types with incrementing size CNumericTypes.SIGNED_INT, CNumericTypes.UNSIGNED_INT, CNumericTypes.SIGNED_LONG_LONG_INT); /** * Compute a matching integer type for an enumeration. We use SIGNED_INT and switch to larger type * if needed. * * <p>§6.7.2.2 (4) Each enumerated type shall be compatible with char, a signed integer type, or * an unsigned integer type. The choice of type is implementation-defined, but shall be capable of * representing the values of all the members of the enumeration. */ private CSimpleType getEnumerationType(final CEnumType enumType) { LongSummaryStatistics enumStatistics = enumType.getEnumerators().stream() .filter(CEnumerator::hasValue) // some values might not have been simplified .mapToLong(CEnumerator::getValue) .summaryStatistics(); Preconditions.checkState( enumStatistics.getCount() > 0, "enumeration does not provide any values: %s", enumType); final BigInteger minValue = BigInteger.valueOf(enumStatistics.getMin()); final BigInteger maxValue = BigInteger.valueOf(enumStatistics.getMax()); for (CSimpleType integerType : ENUM_REPRESENTATION_CANDIDATE_TYPES) { if (minValue.compareTo(machinemodel.getMinimalIntegerValue(integerType)) >= 0 && maxValue.compareTo(machinemodel.getMaximalIntegerValue(integerType)) <= 0) { // if all enumeration values are matching into the range, we use it return integerType; } } // if nothing works, use the largest type we have: ULL return CNumericTypes.UNSIGNED_LONG_LONG_INT; } private CEnumerator convert(IASTEnumerationSpecifier.IASTEnumerator e, Long lastValue) { Long value = null; if (e.getValue() == null && lastValue != null) { value = lastValue + 1; } else { CExpression v = convertExpressionWithoutSideEffects(e.getValue()); // for enums we always expect constants and simplify them, // even if 'cfa.simplifyConstExpressions is disabled. // Lets assume that there is never a signed integer overflow or another property violation. v = simplifyExpressionRecursively(v); boolean negate = false; boolean complement = false; if (v instanceof CUnaryExpression && ((CUnaryExpression) v).getOperator() == UnaryOperator.MINUS) { CUnaryExpression u = (CUnaryExpression)v; negate = true; v = u.getOperand(); } else if (v instanceof CUnaryExpression && ((CUnaryExpression) v).getOperator() == UnaryOperator.TILDE) { CUnaryExpression u = (CUnaryExpression)v; complement = true; v = u.getOperand(); } assert !(v instanceof CUnaryExpression) : v; if (v instanceof CIntegerLiteralExpression) { value = ((CIntegerLiteralExpression)v).asLong(); } else if (v instanceof CCharLiteralExpression) { value = (long) ((CCharLiteralExpression) v).getCharacter(); } else { // ignore unsupported enum value and set it to NULL. // TODO bug? constant enums are ignored, if 'cfa.simplifyConstExpressions' is disabled. logger.logf( Level.WARNING, "enum constant '%s = %s' was not simplified and will be ignored in the following.", e.getName(), v.toQualifiedASTString()); } if (value != null) { if (negate) { value = -value; } else if (complement) { value = ~value; } } } String name = convert(e.getName()); CEnumerator result = new CEnumerator( getLocation(e), name, scope.createScopedNameOf(name), /* dummy integer type, the correct one will be set directly afterwards */ CNumericTypes.SIGNED_INT, value); scope.registerDeclaration(result); return result; } private IASTExpression toExpression(IASTInitializerClause i) { if (i instanceof IASTExpression) { return (IASTExpression)i; } throw parseContext.parseError("Initializer clause in unexpected location", i); } private CInitializer convert( IASTInitializerClause i, CType type, @Nullable CVariableDeclaration declaration) { if (i instanceof IASTExpression) { CExpression exp = convertExpressionWithoutSideEffects((IASTExpression)i); return new CInitializerExpression(exp.getFileLocation(), exp); } else if (i instanceof IASTInitializerList) { return convert((IASTInitializerList) i, type, declaration); } else if (i instanceof ICASTDesignatedInitializer) { return convert((ICASTDesignatedInitializer) i, type, declaration); } else { throw parseContext.parseError( "unknown initializer claus: " + i.getClass().getSimpleName(), i); } } private CInitializer convert( IASTInitializer i, CType type, @Nullable CVariableDeclaration declaration) { if (i == null) { return null; } else if (i instanceof IASTInitializerList) { return convert((IASTInitializerList) i, type, declaration); } else if (i instanceof IASTEqualsInitializer) { return convert((IASTEqualsInitializer) i, type, declaration); } else if (i instanceof ICASTDesignatedInitializer) { return convert((ICASTDesignatedInitializer) i, type, declaration); } else { throw parseContext.parseError("unknown initializer: " + i.getClass().getSimpleName(), i); } } private CInitializer convert( ICASTDesignatedInitializer init, CType type, @Nullable CVariableDeclaration declaration) { ICASTDesignator[] desInit = init.getDesignators(); CInitializer cInit = convert(init.getOperand(), type, declaration); FileLocation fileLoc = cInit.getFileLocation(); List<CDesignator> designators = new ArrayList<>(desInit.length); // convert all designators for (ICASTDesignator designator : desInit) { CDesignator r; if (designator instanceof ICASTFieldDesignator) { r = new CFieldDesignator(fileLoc, convert(((ICASTFieldDesignator) designator).getName())); } else if (designator instanceof ICASTArrayDesignator) { r = new CArrayDesignator(fileLoc, convertExpressionWithoutSideEffects(((ICASTArrayDesignator) designator).getSubscriptExpression())); } else if (designator instanceof IGCCASTArrayRangeDesignator) { r = new CArrayRangeDesignator(fileLoc, convertExpressionWithoutSideEffects(((IGCCASTArrayRangeDesignator) designator).getRangeFloor()), convertExpressionWithoutSideEffects(((IGCCASTArrayRangeDesignator) designator).getRangeCeiling())); } else { throw parseContext.parseError("Unsupported Designator", designator); } designators.add(r); } return new CDesignatedInitializer(fileLoc, designators, cInit); } private CInitializer convert( IASTInitializerList iList, CType type, @Nullable CVariableDeclaration declaration) { List<CInitializer> initializerList = new ArrayList<>(); if (declaration != null && iList.getSize() == 1) { if (type instanceof CSimpleType || type instanceof CPointerType) { IASTInitializerClause result = unpackBracedInitializer(iList); if (result != null) { return convert(result, type, declaration); } } } // TODO: we might need do to something similar for more types if (type instanceof CArrayType) { type = ((CArrayType) type).getType(); } for (IASTInitializerClause i : iList.getClauses()) { CInitializer newI = convert(i, type, declaration); if (newI != null) { initializerList.add(newI); } } return new CInitializerList(getLocation(iList), initializerList); } private @Nullable IASTInitializerClause unpackBracedInitializer(IASTInitializerList pIList) { if (pIList.getSize() == 1) { IASTInitializerClause clause = pIList.getClauses()[0]; if (clause instanceof IASTInitializerList) { return unpackBracedInitializer((IASTInitializerList) clause); } return clause; } return null; } private CInitializer convert( IASTEqualsInitializer i, CType type, @Nullable CVariableDeclaration declaration) { IASTInitializerClause ic = i.getInitializerClause(); if (ic instanceof IASTExpression) { IASTExpression e = (IASTExpression)ic; CAstNode initializer = convertExpressionWithSideEffects(e); if (initializer == null) { return null; } final CInitializerExpression result; if (initializer instanceof CAssignment) { sideAssignmentStack.addPreSideAssignment(initializer); result = new CInitializerExpression( getLocation(e), ((CAssignment) initializer).getLeftHandSide()); } else if (initializer instanceof CFunctionCallExpression) { FileLocation loc = getLocation(i); if (declaration != null && !declaration.getType().getCanonicalType().isConst()) { // This is a variable declaration like "int i = f();" // We can replace this with "int i; i = f();" CIdExpression var = new CIdExpression(loc, declaration); sideAssignmentStack.addPostSideAssignment(new CFunctionCallAssignmentStatement(loc, var, (CFunctionCallExpression) initializer)); return null; // empty initializer } else { // This is something more complicated, like a function call inside an array initializer. // We need a temporary variable. CIdExpression var = createTemporaryVariable(e); sideAssignmentStack.addPreSideAssignment(new CFunctionCallAssignmentStatement(loc, var, (CFunctionCallExpression) initializer)); result = new CInitializerExpression(loc, var); } } else if (initializer instanceof CExpression) { result = new CInitializerExpression(getLocation(ic), (CExpression) initializer); } else { throw parseContext.parseError( "Initializer is not free of side-effects, it is a " + initializer.getClass().getSimpleName(), e); } if (!areInitializerAssignable(type, result.getExpression())) { if (type.getCanonicalType() instanceof CPointerType && CTypes.isIntegerType(result.getExpression().getExpressionType())) { if (declaration != null) { logger.logf( Level.WARNING, "%s: Initialization of pointer variable %s with integer expression %s.", result.getFileLocation(), type.toASTString(declaration.getName()), result); } } else { throw parseContext.parseError( "Type " + type + " of declaration and type " + ((CExpression) initializer).getExpressionType() + " of initializer are not assignment compatible", e); } } return result; } else if (ic instanceof IASTInitializerList) { return convert((IASTInitializerList) ic, type, declaration); } else { throw parseContext.parseError("unknown initializer: " + i.getClass().getSimpleName(), i); } } /** Check for legal initializer according to C11 § 6.7.9 (11), (13) */ private boolean areInitializerAssignable( CType pDeclarationType, CExpression pInitializerExpression) { return pDeclarationType.canBeAssignedFrom(pInitializerExpression.getExpressionType()) || isStringInitialization(pDeclarationType, pInitializerExpression) || ((pInitializerExpression instanceof CIntegerLiteralExpression) // the literal '0' is by default treated as a Null-Pointer in context // of pointers (C-Standard 11 §6.3.2.3 (3)) && (((CIntegerLiteralExpression) pInitializerExpression).getValue().intValue() == 0) && pDeclarationType.canBeAssignedFrom(CPointerType.POINTER_TO_VOID)); } /** * This method determines whether the initialization is valid in accordance to C11 Standard, * §6.7.9, (32). * * @param pDeclarationType the type of the lhs of the initialization * @param pInitializerExpression the rhs expression of the initialization * @return if the initialization assigns a {@link CStringLiteralExpression} to an array or pointer * of/to <b><code>char</code></b> */ private boolean isStringInitialization( CType pDeclarationType, CExpression pInitializerExpression) { // TODO: Can we somehow handle wide-char-arrays and corresponding Strings? // E.g., 'wchar_t a[] = L"abc";' is valid, whereas 'char a[] = L"abc";' is not. if (pInitializerExpression instanceof CStringLiteralExpression) { // Not null default that results in false without an exception if the declaration type is // neither array nor pointer and allows to drop a redundant second check for CArrayType or // CPointerType CType canonicalType = CPointerType.POINTER_TO_VOID; if (pDeclarationType instanceof CArrayType) { canonicalType = ((CArrayType) pDeclarationType).getType().getCanonicalType(); } if (pDeclarationType instanceof CPointerType) { canonicalType = ((CPointerType) pDeclarationType).getType().getCanonicalType(); } return CTypes.copyDequalified(canonicalType).equals(CNumericTypes.CHAR); } return false; } private List<CParameterDeclaration> convert(IASTParameterDeclaration[] ps) { List<CParameterDeclaration> paramsList = new ArrayList<>(ps.length); for (IASTParameterDeclaration c : ps) { if (!c.getRawSignature().equals("void")) { paramsList.add(convert(c)); } else { // there may be a function declaration f(void), which is equal to f() // we don't want this dummy parameter "void" assert ps.length == 1; } } return paramsList; } private CParameterDeclaration convert(IASTParameterDeclaration p) { Pair<CStorageClass, ? extends CType> specifier = convert(p.getDeclSpecifier()); if (specifier.getFirst() != CStorageClass.AUTO) { throw parseContext.parseError("Unsupported storage class for parameters", p); } Triple<CType, IASTInitializer, String> declarator = convert(p.getDeclarator(), specifier.getSecond()); if (declarator.getSecond() != null) { throw parseContext.parseError("Unsupported initializer for parameters", p); } CType type = declarator.getFirst(); if (type instanceof CFunctionTypeWithNames) { CFunctionTypeWithNames functionType = (CFunctionTypeWithNames) type; type = new CPointerType(false, false, functionType); } return new CParameterDeclaration(getLocation(p), type, declarator.getThird()); } /** This function returns the converted file-location of an IASTNode. */ FileLocation getLocation(final IASTNode n) { return parseContext.getLocation(n); } static String convert(IASTName n) { return n.toString(); // TODO verify toString() is the correct method } CType convert(IASTTypeId t) { Pair<CStorageClass, ? extends CType> specifier = convert(t.getDeclSpecifier()); if (specifier.getFirst() != CStorageClass.AUTO) { throw parseContext.parseError("Unsupported storage class for type ids", t); } Triple<CType, IASTInitializer, String> declarator = convert(t.getAbstractDeclarator(), specifier.getSecond()); if (declarator.getSecond() != null) { throw parseContext.parseError("Unsupported initializer for type ids", t); } if (declarator.getThird() != null && !declarator.getThird().trim().isEmpty()) { throw parseContext.parseError("Unsupported name for type ids", t); } return declarator.getFirst(); } }
/* LCM type definition class file * This file was automatically generated by lcm-gen * DO NOT MODIFY BY HAND!!!! */ package armlab.lcm.msgs; import java.io.*; import java.util.*; import lcm.lcm.*; public final class cartesian_value_quantity implements lcm.lcm.LCMEncodable { public double x; public double y; public double z; public double a; public double b; public double c; public cartesian_value_quantity() { } public static final long LCM_FINGERPRINT; public static final long LCM_FINGERPRINT_BASE = 0xf31b4152afd20adaL; static { LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>()); } public static long _hashRecursive(ArrayList<Class<?>> classes) { if (classes.contains(armlab.lcm.msgs.cartesian_value_quantity.class)) return 0L; classes.add(armlab.lcm.msgs.cartesian_value_quantity.class); long hash = LCM_FINGERPRINT_BASE ; classes.remove(classes.size() - 1); return (hash<<1) + ((hash>>63)&1); } public void encode(DataOutput outs) throws IOException { outs.writeLong(LCM_FINGERPRINT); _encodeRecursive(outs); } public void _encodeRecursive(DataOutput outs) throws IOException { outs.writeDouble(this.x); outs.writeDouble(this.y); outs.writeDouble(this.z); outs.writeDouble(this.a); outs.writeDouble(this.b); outs.writeDouble(this.c); } public cartesian_value_quantity(byte[] data) throws IOException { this(new LCMDataInputStream(data)); } public cartesian_value_quantity(DataInput ins) throws IOException { if (ins.readLong() != LCM_FINGERPRINT) throw new IOException("LCM Decode error: bad fingerprint"); _decodeRecursive(ins); } public static armlab.lcm.msgs.cartesian_value_quantity _decodeRecursiveFactory(DataInput ins) throws IOException { armlab.lcm.msgs.cartesian_value_quantity o = new armlab.lcm.msgs.cartesian_value_quantity(); o._decodeRecursive(ins); return o; } public void _decodeRecursive(DataInput ins) throws IOException { this.x = ins.readDouble(); this.y = ins.readDouble(); this.z = ins.readDouble(); this.a = ins.readDouble(); this.b = ins.readDouble(); this.c = ins.readDouble(); } public armlab.lcm.msgs.cartesian_value_quantity copy() { armlab.lcm.msgs.cartesian_value_quantity outobj = new armlab.lcm.msgs.cartesian_value_quantity(); outobj.x = this.x; outobj.y = this.y; outobj.z = this.z; outobj.a = this.a; outobj.b = this.b; outobj.c = this.c; return outobj; } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * 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 com.hazelcast.config; import com.hazelcast.core.HazelcastException; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.QuickTest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.io.File; import java.io.PrintWriter; import java.net.URL; import java.net.URLDecoder; import static com.hazelcast.config.XMLConfigBuilderTest.HAZELCAST_END_TAG; import static com.hazelcast.config.XMLConfigBuilderTest.HAZELCAST_START_TAG; import static java.io.File.createTempFile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * These tests manipulate system properties, therefore they must be run in serial mode. */ @RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class XMLConfigWithSystemPropertyTest { @Before @After public void beforeAndAfter() { System.clearProperty("hazelcast.config"); } @Test public void testConfigurationWithFile() throws Exception { URL url = getClass().getClassLoader().getResource("hazelcast-default.xml"); assertNotNull(url); String decodedURL = URLDecoder.decode(url.getFile(), "UTF-8"); System.setProperty("hazelcast.config", decodedURL); Config config = new XmlConfigBuilder().build(); URL file = new URL("file:"); URL encodedURL = new URL(file, decodedURL); assertEquals(encodedURL, config.getConfigurationUrl()); } @Test(expected = HazelcastException.class) @SuppressWarnings("ResultOfMethodCallIgnored") public void loadingThroughSystemProperty_nonExistingFile() throws Exception { File file = createTempFile("foo", "bar"); file.delete(); System.setProperty("hazelcast.config", file.getAbsolutePath()); new XmlConfigBuilder(); } @Test public void loadingThroughSystemProperty_existingFile() throws Exception { String xml = HAZELCAST_START_TAG + " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>" + HAZELCAST_END_TAG; File file = createTempFile("foo", "bar"); file.deleteOnExit(); PrintWriter writer = new PrintWriter(file, "UTF-8"); writer.println(xml); writer.close(); System.setProperty("hazelcast.config", file.getAbsolutePath()); XmlConfigBuilder configBuilder = new XmlConfigBuilder(); Config config = configBuilder.build(); assertEquals("foobar", config.getGroupConfig().getName()); } @Test(expected = HazelcastException.class) public void loadingThroughSystemProperty_nonExistingClasspathResource() { System.setProperty("hazelcast.config", "classpath:idontexist"); new XmlConfigBuilder(); } @Test public void loadingThroughSystemProperty_existingClasspathResource() { System.setProperty("hazelcast.config", "classpath:test-hazelcast.xml"); XmlConfigBuilder configBuilder = new XmlConfigBuilder(); Config config = configBuilder.build(); assertEquals("foobar", config.getGroupConfig().getName()); } }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.remotefetch.core.dao.impl; import org.wso2.carbon.database.utils.jdbc.JdbcTemplate; import org.wso2.carbon.database.utils.jdbc.exceptions.TransactionException; import org.wso2.carbon.identity.remotefetch.common.DeploymentRevision; import org.wso2.carbon.identity.remotefetch.common.exceptions.RemoteFetchCoreException; import org.wso2.carbon.identity.remotefetch.core.constants.SQLConstants; import org.wso2.carbon.identity.remotefetch.core.dao.DeploymentRevisionDAO; import org.wso2.carbon.identity.remotefetch.core.util.JdbcUtils; import java.io.File; import java.sql.Timestamp; import java.util.Date; import java.util.List; /** * DAO of deployment revision. */ public class DeploymentRevisionDAOImpl implements DeploymentRevisionDAO { /** * @param deploymentRevision * @return * @throws RemoteFetchCoreException */ @Override public void createDeploymentRevision(DeploymentRevision deploymentRevision) throws RemoteFetchCoreException { JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(); try { jdbcTemplate.withTransaction(template -> template.executeInsert(SQLConstants.CREATE_REVISION, preparedStatement -> { preparedStatement.setString(1, deploymentRevision.getDeploymentRevisionId()); preparedStatement.setString(2, deploymentRevision.getConfigId()); preparedStatement.setString(3, deploymentRevision.getFile().getPath()); preparedStatement.setString(4, deploymentRevision.getFileHash()); preparedStatement.setString(5, deploymentRevision.getItemName()); preparedStatement.setString(6, deploymentRevision.getErrorMessage()); if (deploymentRevision.getDeployedDate() != null) { preparedStatement.setTimestamp(7, new Timestamp(deploymentRevision.getDeployedDate().getTime())); } else { preparedStatement.setTimestamp(7, null); } if (deploymentRevision.getDeploymentStatus() != null) { preparedStatement.setString(8, deploymentRevision.getDeploymentStatus().name()); } else { preparedStatement.setString(8, null); } if (deploymentRevision.getLastSynchronizedDate() != null) { preparedStatement.setTimestamp(9, new Timestamp(deploymentRevision.getLastSynchronizedDate().getTime())); } else { preparedStatement.setTimestamp(9, null); } }, deploymentRevision, false) ); } catch (TransactionException e) { throw new RemoteFetchCoreException("Error creating new DeploymentRevision " + deploymentRevision.getItemName(), e); } } /** * @param remoteFetchConfigurationId * @param itemName * @return * @throws RemoteFetchCoreException */ @Override public DeploymentRevision getDeploymentRevision(String remoteFetchConfigurationId, String itemName) throws RemoteFetchCoreException { JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(); DeploymentRevision deploymentRevision; try { deploymentRevision = jdbcTemplate.withTransaction(template -> { return jdbcTemplate.fetchSingleRecord(SQLConstants.GET_REVISION_BY_UNIQUE, (resultSet, rowNumber) -> { DeploymentRevision revisionObj = new DeploymentRevision( resultSet.getString(2), new File(resultSet.getString(3)) ); revisionObj.setDeploymentRevisionId(resultSet.getString(1)); revisionObj.setFileHash(resultSet.getString(4)); revisionObj.setDeployedDate(new Date(resultSet.getTimestamp(5).getTime())); revisionObj.setDeploymentStatus(DeploymentRevision. DeploymentStatus.valueOf(resultSet.getString(6))); revisionObj.setItemName(resultSet.getString(7)); revisionObj.setErrorMessage(resultSet.getString(8)); if (resultSet.getTimestamp(9) != null) { revisionObj.setLastSynchronizedDate(new Date(resultSet.getTimestamp(9).getTime())); } else { revisionObj.setLastSynchronizedDate(null); } return revisionObj; }, preparedStatement -> { preparedStatement.setString(1, remoteFetchConfigurationId); preparedStatement.setString(2, itemName); }); }); } catch (TransactionException e) { throw new RemoteFetchCoreException("Error reading DeploymentRevision id " + remoteFetchConfigurationId + " from database", e); } return deploymentRevision; } /** * @param deploymentRevision * @throws RemoteFetchCoreException */ @Override public void updateDeploymentRevision(DeploymentRevision deploymentRevision) throws RemoteFetchCoreException { JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(); try { jdbcTemplate.withTransaction(template -> { template.executeUpdate(SQLConstants.UPDATE_REVISION, preparedStatement -> { preparedStatement.setString(1, deploymentRevision.getConfigId()); preparedStatement.setString(2, deploymentRevision.getFile().getPath()); preparedStatement.setString(3, deploymentRevision.getFileHash()); if (deploymentRevision.getDeployedDate() != null) { preparedStatement.setTimestamp(4, new Timestamp(deploymentRevision.getDeployedDate().getTime())); } else { preparedStatement.setTimestamp(4, null); } preparedStatement.setString(5, deploymentRevision.getDeploymentStatus().name()); preparedStatement.setString(6, deploymentRevision.getItemName()); preparedStatement.setString(7, deploymentRevision.getErrorMessage()); if (deploymentRevision.getLastSynchronizedDate() != null) { preparedStatement.setTimestamp(8, new Timestamp(deploymentRevision.getLastSynchronizedDate().getTime())); } else { preparedStatement.setTimestamp(8, null); } preparedStatement.setString(9, deploymentRevision.getDeploymentRevisionId()); }); return null; }); } catch (TransactionException e) { throw new RemoteFetchCoreException("Error updating DeploymentRevision of id " + deploymentRevision.getDeploymentRevisionId(), e); } } /** * @param deploymentRevisionId * @throws RemoteFetchCoreException */ @Override public void deleteDeploymentRevision(String deploymentRevisionId) throws RemoteFetchCoreException { JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(); try { jdbcTemplate.withTransaction(template -> { template.executeUpdate(SQLConstants.DELETE_REVISION, preparedStatement -> { preparedStatement.setString(1, deploymentRevisionId); }); return null; }); } catch (TransactionException e) { throw new RemoteFetchCoreException("Error Deleting DeploymentRevision by id " + deploymentRevisionId, e); } } /** * @param remoteFetchConfigurationId * @return * @throws RemoteFetchCoreException */ @Override public List<DeploymentRevision> getDeploymentRevisionsByConfigurationId( String remoteFetchConfigurationId) throws RemoteFetchCoreException { JdbcTemplate jdbcTemplate = JdbcUtils.getNewTemplate(); try { return jdbcTemplate.withTransaction(template -> template.executeQuery(SQLConstants.GET_REVISIONS_BY_CONFIG, ((resultSet, rowNumber) -> { DeploymentRevision deploymentRevision = new DeploymentRevision( resultSet.getString(2), new File(resultSet.getString(3)) ); deploymentRevision.setDeploymentRevisionId(resultSet.getString(1)); deploymentRevision.setFileHash(resultSet.getString(4)); deploymentRevision.setDeployedDate(new Date(resultSet.getTimestamp(5).getTime())); deploymentRevision.setDeploymentStatus(DeploymentRevision. DeploymentStatus.valueOf(resultSet.getString(6))); deploymentRevision.setItemName(resultSet.getString(7)); deploymentRevision.setErrorMessage(resultSet.getString(8)); if (resultSet.getTimestamp(9) != null) { deploymentRevision.setLastSynchronizedDate(new Date(resultSet.getTimestamp(9).getTime())); } else { deploymentRevision.setLastSynchronizedDate(null); } return deploymentRevision; }), preparedStatement -> { preparedStatement.setString(1, remoteFetchConfigurationId); }) ); } catch (TransactionException e) { throw new RemoteFetchCoreException("Error reading DeploymentRevisions from database for configuration id " + remoteFetchConfigurationId, e); } } }
package pl.edu.agh.geotime.service.query; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.jpa.domain.Specifications; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import io.github.jhipster.service.QueryService; import pl.edu.agh.geotime.domain.*; // for static metamodels import pl.edu.agh.geotime.repository.AcademicUnitRepository; import pl.edu.agh.geotime.service.criteria.AcademicUnitCriteria; import pl.edu.agh.geotime.service.dto.AcademicUnitInfoDTO; @Service @Transactional(readOnly = true) public class AcademicUnitQueryService extends QueryService<AcademicUnit> { private final Logger log = LoggerFactory.getLogger(AcademicUnitQueryService.class); private final AcademicUnitRepository academicUnitRepository; public AcademicUnitQueryService(AcademicUnitRepository academicUnitRepository) { this.academicUnitRepository = academicUnitRepository; } @Transactional(readOnly = true) public List<AcademicUnitInfoDTO> findByCriteria(AcademicUnitCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specifications<AcademicUnit> specification = createSpecification(criteria); return academicUnitRepository.findAll(specification).stream() .map(AcademicUnitInfoDTO::new) .collect(Collectors.toList()); } private Specifications<AcademicUnit> createSpecification(AcademicUnitCriteria criteria) { Specifications<AcademicUnit> specification = Specifications.where(null); if (criteria != null) { if (criteria.getId() != null) { specification = specification.and(buildSpecification(criteria.getId(), AcademicUnit_.id)); } if (criteria.getName() != null) { specification = specification.and(buildStringSpecification(criteria.getName(), AcademicUnit_.name)); } if (criteria.getYear() != null) { specification = specification.and(buildSpecification(criteria.getYear(), AcademicUnit_.year)); } if (criteria.getDegree() != null) { specification = specification.and(buildSpecification(criteria.getDegree(), AcademicUnit_.degree)); } if (criteria.getDescription() != null) { specification = specification.and(buildStringSpecification(criteria.getDescription(), AcademicUnit_.description)); } if (criteria.getStudyFieldId() != null) { specification = specification.and(buildReferringEntitySpecification(criteria.getStudyFieldId(), AcademicUnit_.studyField, StudyField_.id)); } if (criteria.getClassUnitId() != null) { specification = specification.and(buildReferringEntitySpecification(criteria.getClassUnitId(), AcademicUnit_.classUnits, ClassUnit_.id)); } } return specification; } }
package com.thesis.inesc.CloudStorage; import com.google.common.base.Charsets; import com.google.common.io.ByteSource; import com.google.common.io.Files; import com.thesis.inesc.Exceptions.NoSuchFileFoundException; import com.thesis.inesc.Utilities.FilesUtilities; import com.thesis.inesc.Utilities.HashFunction; import org.jclouds.ContextBuilder; import org.jclouds.aws.s3.blobstore.AWSS3BlobStoreContext; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.domain.Blob; import org.jclouds.googlecloud.GoogleCredentialsFromJson; import org.jclouds.s3.S3Client; import java.io.File; import java.io.FileNotFoundException; import java.util.Properties; import java.io.IOException; import java.io.InputStream; import static java.lang.StrictMath.toIntExact; import static java.nio.charset.StandardCharsets.UTF_8; /** * Class that handles the cloud connectivity and associated operations * * @author Marcelo Regra da Silva * @created 07/05/2020 */ public class CloudConnectivity { private String credentialsAWSS3; private String identityAWSS3; private String jsonFileGCP; private final String AWSS3_PROVIDER = "aws-s3"; private final String GCP_PROVIDER = "google-cloud-storage"; private final String CONTAINER_NAME = "marcelosilva-jclouds-container1"; private final String CONFIG_FILE_PATH = "./Resources/config.properties"; public CloudConnectivity(){ super(); } /** * @param ownerID The ownerID * @param filePath The file path to add to the cloud */ public void addDataToAWSS3Cloud(String ownerID, String filePath) throws NoSuchFileFoundException { getCredentialsAWSS3(); CloudBlobContext creaetCloudBlobContext = createCloudBlobContextAWSS3(true); String fileData = getFileData(filePath); ByteSource payload = ByteSource.wrap(fileData.getBytes(Charsets.UTF_8)); try { String fileHash = HashFunction.fromByteToBase58(FilesUtilities.getFileHash(fileData.getBytes())); String blobName = ownerID + "/" + fileHash; addBlob(creaetCloudBlobContext.getBlobStore(), blobName, payload); } catch (IOException e) { e.printStackTrace(); } creaetCloudBlobContext.getContext().close(); } /** * @param ownerID The ownerID * @param filePath The file path to add to the cloud */ public void addDataToGoogleCloud(String ownerID, String filePath) throws NoSuchFileFoundException { getCredentialsGCP(); CloudBlobContext cloudBlobContext = createCloudBlobContextGCP(getCredentialFromJsonKeyFile(this.jsonFileGCP), true); try { // Create Container String fileData = getFileData(filePath); byte[] res = fileData.getBytes(Charsets.UTF_8); System.out.println(res.length); ByteSource payload = ByteSource.wrap(res); /*Uncomment for debugging purposes try { System.out.println((payload.size())); } catch (IOException e1) { e1.printStackTrace(); }*/ String fileHash = HashFunction.fromByteToBase58(FilesUtilities.getFileHash(fileData.getBytes())); String blobName = ownerID+ "/" + fileHash; addBlob(cloudBlobContext.getBlobStore(), blobName, payload); } catch (IOException e) { e.printStackTrace(); } cloudBlobContext.getContext().close(); } /** * @param fileHash The file hash which is the file name * @param ownerID The file owner ID * @return String File contents */ public String getDataFromAWSS3Cloud(String fileHash, String ownerID) throws NoSuchFileFoundException { getCredentialsAWSS3(); CloudBlobContext cloudBlobContext = createCloudBlobContextAWSS3(false); Blob blob = getBlobFromCloud(cloudBlobContext, ownerID, fileHash); S3Client api = cloudBlobContext.getContext().unwrapApi(S3Client.class); int size = 0; try { size = toIntExact(api.headObject(CONTAINER_NAME, ownerID+"/"+fileHash).getContentMetadata().getContentLength()); } catch(NullPointerException e1){ System.out.print("Data not in AWS S3."); System.out.flush(); return null; } return getFileFromCloudOperation(blob, size, cloudBlobContext); } /** * @param fileHash The file hash which is the file name * @param ownerID The file owner ID * @return String File contents */ public String getDataFromGoogleCloud(String ownerID, String fileHash) throws NoSuchFileFoundException { getCredentialsGCP(); CloudBlobContext cloudBlobContext = createCloudBlobContextGCP(getCredentialFromJsonKeyFile(this.jsonFileGCP), false); Blob blob = getBlobFromCloud(cloudBlobContext, ownerID, fileHash); int size = 0; try { size = toIntExact(blob.getMetadata().getSize()); } catch(NullPointerException e1){ System.out.println("Data not in GCP."); return null; } return getFileFromCloudOperation(blob, size, cloudBlobContext); } /** * @param blob The cloud blob * @param size A integer that idicates the size of the metada of the blob * @param cloudBlobContext Cloud blob context * @return String File contents */ private String getFileFromCloudOperation(Blob blob, int size, CloudBlobContext cloudBlobContext){ InputStream is = null; try { is = blob.getPayload().openStream(); } catch (IOException e) { e.printStackTrace(); } byte[] bytes = new byte[size]; try { is.read(bytes); System.out.println(new String(bytes)); is.close(); cloudBlobContext.getContext().close(); System.out.print("bss-termianl $ "); return new String(bytes); } catch (IOException e) { e.printStackTrace(); } cloudBlobContext.getContext().close(); return null; } /** * @param cloudBlobContext Cloud blob context * @param container The ownerID * @param fileName The fileName = fileHash * @return Blob */ private Blob getBlobFromCloud(CloudBlobContext cloudBlobContext, String container, String fileName){ Blob blob = null; try { blob = cloudBlobContext.getBlobStore().getBlob(CONTAINER_NAME, container + "/" + fileName); } catch(org.jclouds.rest.AuthorizationException e){ System.out.println("No authorization"); return null; } return blob; } /** * @param fileOwner The file owner ID * @param fileHash The file hash which is the file name */ public void deleteFromGoogleCloud(String fileOwner, String fileHash) throws NoSuchFileFoundException { getCredentialsGCP(); CloudBlobContext cloudBlobContext = createCloudBlobContextGCP(getCredentialFromJsonKeyFile(this.jsonFileGCP), false); deleteFileFromCloudOperation(cloudBlobContext, fileHash, fileOwner); } /** * @param fileHash The file hash which is the file name * @param fileOwner The file owner ID */ public void deleteDataFromAWSS3Cloud(String fileHash, String fileOwner) throws NoSuchFileFoundException { getCredentialsAWSS3(); //System.out.println("Connecting to AWS S3..."); CloudBlobContext cloudBlobContext = createCloudBlobContextAWSS3(false); deleteFileFromCloudOperation(cloudBlobContext, fileHash, fileOwner); } /** * @param cloudBlobContext Cloud blob context * @param fileHash The file hash which is the file name * @param fileOwner The file owner ID */ private void deleteFileFromCloudOperation(CloudBlobContext cloudBlobContext, String fileHash, String fileOwner){ cloudBlobContext.getBlobStore().removeBlob(CONTAINER_NAME, fileOwner+"/"+fileHash); cloudBlobContext.getContext().close(); } /** * @param ownerID The file owner ID * @param fileHash The file hash which is the file name * @param newFilePath The new file path to add to the cloud */ public void updateDataOnAWSS3Cloud(String ownerID, String fileHash, String newFilePath) throws NoSuchFileFoundException { getCredentialsAWSS3(); CloudBlobContext cloudBlobContext = createCloudBlobContextAWSS3(false); updateFileFromCloudOperation(cloudBlobContext, ownerID, fileHash, newFilePath); } /** * @param ownerID The file owner ID * @param fileHash The file hash which is the file name * @param newFilePath The new file path to add to the cloud */ public void updateDataOnGoogleCloud(String ownerID, String fileHash, String newFilePath) throws NoSuchFileFoundException { getCredentialsGCP(); CloudBlobContext cloudBlobContext = createCloudBlobContextGCP(getCredentialFromJsonKeyFile(this.jsonFileGCP), false); updateFileFromCloudOperation(cloudBlobContext, ownerID, fileHash, newFilePath); } /** * @param cloudBlobContext Cloud blob context * @param ownerID The file owner ID * @param fileHash The file hash which is the file name * @param newFilePath The new file path to add to the cloud */ private void updateFileFromCloudOperation(CloudBlobContext cloudBlobContext, String ownerID, String fileHash, String newFilePath){ cloudBlobContext.getBlobStore().removeBlob(CONTAINER_NAME, ownerID+"/"+fileHash); String fileData = getFileData(newFilePath); ByteSource payload = ByteSource.wrap(fileData.getBytes(Charsets.UTF_8)); try { String newFileHash = HashFunction.fromByteToBase58(FilesUtilities.getFileHash(fileData.getBytes())); String blobName = ownerID + "/" + newFileHash; addBlob(cloudBlobContext.getBlobStore(), blobName, payload); System.out.println("File added to the cloud: " + newFileHash); } catch (IOException e) { e.printStackTrace(); } cloudBlobContext.getContext().close(); } /** * @param pathToFile The path to the file we want to retrieve data from * @return String */ private String getFileData(String pathToFile){ InputStream in2 = FilesUtilities.getFileInputStream(pathToFile); byte[] fileData = FilesUtilities.getFileData(in2); //System.out.println(fileData.length); //Uncoment for debugging purposes return new String(fileData); } private void getCredentialsAWSS3() throws NoSuchFileFoundException { try (InputStream input = FilesUtilities.getFileInputStream(CONFIG_FILE_PATH)) { Properties prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find " + CONFIG_FILE_PATH); //TODO: throw new NoSuchFileFoundException(); } prop.load(input); this.credentialsAWSS3 = prop.getProperty("S3credentials"); this.identityAWSS3 = prop.getProperty("S3identity"); } catch (IOException ex) { //TODO: Handle exception properly } } private void getCredentialsGCP() throws NoSuchFileFoundException { try (InputStream input = FilesUtilities.getFileInputStream(CONFIG_FILE_PATH)) { Properties prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find " + CONFIG_FILE_PATH); //TODO: throw new NoSuchFileFoundException(); } prop.load(input); this.jsonFileGCP = prop.getProperty("GCPFileLocation"); } catch (IOException ex) { //TODO: Handle exception properly } } /** * @param pathToFile The path to the .json file that have the GCP credentials * @return String */ private static String getCredentialFromJsonKeyFile(String pathToFile) throws NoSuchFileFoundException { File file = new File(pathToFile); try { String fileContents = Files.toString(file, UTF_8); GoogleCredentialsFromJson credentialSupplier = new GoogleCredentialsFromJson(fileContents); String credential = credentialSupplier.get().credential; return credential; } catch (FileNotFoundException e1){ System.out.println("No credentials file."); throw new NoSuchFileFoundException(); } catch (IOException e) { System.err.println("Exception reading private key from '%s': " + pathToFile); //e.printStackTrace(); //System.exit(1); return null; } } /** * @param blobStore Blob to store * @param blobName Blob name * @param payload Blob payload */ private void addBlob(BlobStore blobStore, String blobName, ByteSource payload) throws IOException { Blob blob = blobStore.blobBuilder(blobName) .payload(payload) .contentLength(payload.size()) .build(); blobStore.putBlob(CONTAINER_NAME, blob); } /** * @param createContainer Boolean of whether it is or not to create a new container * @return CloudBlobContext Cloud blob context */ private CloudBlobContext createCloudBlobContextAWSS3(boolean createContainer){ CloudBlobContext cloudBlobContext = new CloudBlobContext(); BlobStoreContext context = ContextBuilder.newBuilder(AWSS3_PROVIDER).credentials(identityAWSS3, credentialsAWSS3).buildView(AWSS3BlobStoreContext.class); BlobStore blobStore = context.getBlobStore(); if(createContainer) { blobStore.createContainerInLocation(null, CONTAINER_NAME); } cloudBlobContext.setBlobStore(blobStore); cloudBlobContext.setContext(context); return cloudBlobContext; } /** * @param credentials GCP credentials * @param createContainer Boolean of whether it is or not to create a new container * @return CloudBlobContext Cloud blob context */ private CloudBlobContext createCloudBlobContextGCP(String credentials, boolean createContainer){ CloudBlobContext cloudBlobContext = new CloudBlobContext(); BlobStoreContext context = ContextBuilder.newBuilder(GCP_PROVIDER) .credentials("test-google-cloud@thesis-marcelo-jclouds.iam.gserviceaccount.com", credentials) .buildView(BlobStoreContext.class); BlobStore blobStore = context.getBlobStore(); if(createContainer) { blobStore.createContainerInLocation(null, CONTAINER_NAME); } cloudBlobContext.setContext(context); cloudBlobContext.setBlobStore(blobStore); return cloudBlobContext; } }
/******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * chris.gross@us.ibm.com - initial API and implementation * mario.winterer@scch.at - bugfix in 244333 * Marty Jones<martybjones@gmail.com> - custom header/footer font in bug 293743 *******************************************************************************/ package org.eclipse.nebula.widgets.grid; /* * Copyright Contributors to the GenevaERS Project. SPDX-License-Identifier: Apache-2.0 (c) Copyright IBM Corporation 2008. * * 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. */ import org.eclipse.nebula.widgets.grid.internal.DefaultColumnGroupHeaderRenderer; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.TypedListener; import java.util.Vector; /** * <p> * NOTE: THIS WIDGET AND ITS API ARE STILL UNDER DEVELOPMENT. THIS IS A PRE-RELEASE ALPHA * VERSION. USERS SHOULD EXPECT API CHANGES IN FUTURE VERSIONS. * </p> * Instances of this class represent a column group in a grid widget. A column group header is * displayed above grouped columns. The column group can optionally be configured to expand and * collapse. A column group in the expanded state shows {@code GridColumn}s whose detail property * is true. A column group in the collapsed state shows {@code GridColumn}s whose summary property * is true. * <p> * <dl> * <dt><b>Styles:</b></dt> * <dd>SWT.TOGGLE</dd> * <dt><b>Events:</b></dt> * <dd>Expand, Collapse</dd> * </dl> * * @author chris.gross@us.ibm.com */ public class GridColumnGroup extends Item { private Grid parent; private GridColumn[] columns = new GridColumn[] {}; private boolean expanded = true; private Font headerFont; /** * Header renderer. */ private GridHeaderRenderer headerRenderer = new DefaultColumnGroupHeaderRenderer(); /** * Constructs a new instance of this class given its parent (which must be a Table) and a style * value describing its behavior and appearance. * * @param parent the parent table * @param style the style of the group * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> */ public GridColumnGroup(Grid parent, int style) { super(parent, style); this.parent = parent; headerRenderer.setDisplay(getDisplay()); parent.newColumnGroup(this); } /** * Adds the listener to the collection of listeners who will * be notified when an item in the receiver is expanded or collapsed * by sending it one of the messages defined in the <code>TreeListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #removeTreeListener */ public void addTreeListener(TreeListener listener) { checkWidget (); if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Expand, typedListener); addListener (SWT.Collapse, typedListener); } /** * Removes the listener from the collection of listeners who will * be notified when items in the receiver are expanded or collapsed. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #addTreeListener */ public void removeTreeListener(TreeListener listener) { checkWidget (); if (listener == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); removeListener (SWT.Expand, listener); removeListener (SWT.Collapse, listener); } /** * Returns the parent grid. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Grid getParent() { checkWidget(); return parent; } int getNewColumnIndex() { if (columns.length == 0) { return -1; } GridColumn lastCol = columns[columns.length - 1]; return parent.indexOf(lastCol) + 1; } void newColumn(GridColumn column, int index) { GridColumn[] newAllColumns = new GridColumn[columns.length + 1]; System.arraycopy(columns, 0, newAllColumns, 0, columns.length); newAllColumns[newAllColumns.length - 1] = column; columns = newAllColumns; } void removeColumn(GridColumn col) { if (columns.length == 0) return; // widget is disposing GridColumn[] newAllColumns = new GridColumn[columns.length - 1]; int x = 0; for (int i = 0; i < columns.length; i++) { if (columns[i] != col) { newAllColumns[x] = columns[i]; x ++; } } columns = newAllColumns; } /** * Returns the columns within this group. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * @return the columns * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridColumn[] getColumns() { checkWidget(); GridColumn[] newArray = new GridColumn[columns.length]; System.arraycopy (columns, 0, newArray, 0, columns.length); return newArray; } /** * {@inheritDoc} */ public void dispose() { super.dispose(); if (parent.isDisposing()) return; GridColumn[] oldColumns = columns; columns = new GridColumn[0]; for (int i = 0; i < oldColumns.length; i++) { oldColumns[i].dispose(); } parent.removeColumnGroup(this); } /** * Gets the header renderer. * * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public GridHeaderRenderer getHeaderRenderer() { checkWidget(); return headerRenderer; } /** * Sets the header renderer. * * @param headerRenderer The headerRenderer to set. * @throws IllegalArgumentException * <ul> * <li>ERROR_NULL_ARGUMENT - if the renderer is null</li> * </ul> * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setHeaderRenderer(GridHeaderRenderer headerRenderer) { if (headerRenderer == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); this.headerRenderer = headerRenderer; headerRenderer.setDisplay(getDisplay()); } /** * Returns true if the receiver is expanded, false otherwise. * * @return the expanded attribute * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public boolean getExpanded() { checkWidget(); return expanded; } /** * Sets the expanded state of the receiver. * * @param expanded the expanded to set * @throws org.eclipse.swt.SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public void setExpanded(boolean expanded) { checkWidget(); this.expanded = expanded; if (!expanded && getParent().getCellSelectionEnabled()) { Vector collapsedCols = new Vector(); for (int j = 0; j < columns.length; j++) { if (!columns[j].isSummary()) { collapsedCols.add(new Integer(getParent().indexOf(columns[j]))); } } Point[] selection = getParent().getCellSelection(); for (int i = 0; i < selection.length; i++) { if (collapsedCols.contains(new Integer(selection[i].x))) { getParent().deselectCell(selection[i]); } } if (getParent().getFocusColumn() != null && getParent().getFocusColumn().getColumnGroup() == this) { getParent().updateColumnFocus(); } parent.updateColumnSelection(); } if (parent.getCellSelectionEnabled()) parent.refreshHoverState(); parent.setScrollValuesObsolete(); parent.redraw(); } /** * Returns the first visible column in this column group. * * @return first visible column */ GridColumn getFirstVisibleColumn() { GridColumn[] cols = parent.getColumnsInOrder(); for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this && cols[i].isVisible()) { return cols[i]; } } return null; } /** * Returns the last visible column in this column group. * * @return last visible column */ GridColumn getLastVisibleColumn() { GridColumn[] cols = parent.getColumnsInOrder(); GridColumn lastVisible = null; for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this && cols[i].isVisible()) { lastVisible = cols[i]; } } return lastVisible; } Rectangle getBounds() { Rectangle bounds = new Rectangle(0, 0, 0, 0); bounds.height = parent.getGroupHeaderHeight(); boolean foundFirstColumnInGroup = false; GridColumn[] cols = parent.getColumnsInOrder(); for (int i = 0; i < cols.length; i++) { if (cols[i].getColumnGroup() == this) { if (cols[i].isVisible()) { if (!foundFirstColumnInGroup) { bounds.x = parent.getOrigin(cols[i], null).x; foundFirstColumnInGroup = true; } bounds.width += cols[i].getWidth(); } } else { if (foundFirstColumnInGroup) { break; } } } return bounds; } /** * Sets whether or not text is word-wrapped in the header for this column group. If Grid.setAutoHeight(true) is set, the row height * is adjusted to accommodate word-wrapped text. * @param wordWrap Set to true to wrap the text, false otherwise * @see #getHeaderWordWrap() */ public void setHeaderWordWrap(boolean wordWrap) { checkWidget(); headerRenderer.setWordWrap(wordWrap); parent.redraw(); } /** * Returns whether or not text is word-wrapped in the header for this column group. * @return true if the header wraps its text. * @see GridColumn#setHeaderWordWrap(boolean) */ public boolean getHeaderWordWrap() { checkWidget(); return headerRenderer.isWordWrap(); } /** * Returns the font that the receiver will use to paint textual information * for the header. * * @return the receiver's font * @throws SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that * created the receiver</li> * </ul> */ public Font getHeaderFont() { checkWidget(); if (headerFont == null) { return parent.getFont(); } return headerFont; } /** * Sets the Font to be used when displaying the Header text. * @param font */ public void setHeaderFont(Font font) { checkWidget(); this.headerFont = font; } }
package com.hkm.slider.Transformers; import android.os.Build; import android.support.v4.view.ViewCompat; import android.view.View; import com.hkm.slider.Tricks.ViewPagerEx; public class FlipPageViewTransformer extends BaseTransformer { @Override protected void onTransform(View view, float position) { float percentage = 1 - Math.abs(position); if(Build.VERSION.SDK_INT >= 13){ view.setCameraDistance(12000); } setVisibility(view, position); setTranslation(view); setSize(view, position, percentage); setRotation(view, position, percentage); } private void setVisibility(View page, float position) { if (position < 0.5 && position > -0.5) { page.setVisibility(View.VISIBLE); } else { page.setVisibility(View.INVISIBLE); } } private void setTranslation(View view) { ViewPagerEx viewPager = (ViewPagerEx) view.getParent(); int scroll = viewPager.getScrollX() - view.getLeft(); ViewCompat.setTranslationX(view, scroll); } private void setSize(View view, float position, float percentage) { ViewCompat.setScaleX(view,(position != 0 && position != 1) ? percentage : 1); ViewCompat.setScaleY(view,(position != 0 && position != 1) ? percentage : 1); } private void setRotation(View view, float position, float percentage) { if (position > 0) { ViewCompat.setRotationY(view,-180 * (percentage + 1)); } else { ViewCompat.setRotationY(view,180 * (percentage + 1)); } } }
package main.testeeal.ee.src.controller; import Bean.Student; public class MyModelClas { public Student getStudent() { Student student = new Student(); student.setAge(15); student.setName("Nike"); //... return student; } }
/* * This file is part of jsFlow. * * Copyright (c) 2009 DE-CIX Management GmbH <http://www.de-cix.net> - All rights * reserved. * * Author: Thomas King <thomas.king@de-cix.net> * * This software is licensed under the Apache License, version 2.0. A copy of * the license agreement is included in this distribution. */ package net.decix.jsflow.header; import net.decix.util.HeaderBytesException; import net.decix.util.HeaderParseException; import net.decix.util.Utility; public class FlowRecordHeader { private long flowDataFormat; // 20 bit enterprise & 12 bit format; standard enterprise 0, format 1, 2, 3, 4, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012 private long flowDataLength; // in byte private RawPacketHeader rawPacket; public FlowRecordHeader() { } public long getFlowDataFormat() { return flowDataFormat; } public long getFlowDataLength() { return flowDataLength; } public void setFlowDataFormat(long flowDataFormat) { this.flowDataFormat = flowDataFormat; } public void setFlowDataLength(long flowDataLength) { this.flowDataLength = flowDataLength; } public void setRawPacketHeader(RawPacketHeader rawPacket) { this.rawPacket = rawPacket; } public RawPacketHeader getRawPacketHeader() { return rawPacket; } public static FlowRecordHeader parse(byte[] data) throws HeaderParseException { try { if (data.length < 8) throw new HeaderParseException("Data array too short."); FlowRecordHeader frd = new FlowRecordHeader(); // format byte[] format = new byte[4]; System.arraycopy(data, 0, format, 0, 4); frd.setFlowDataFormat(Utility.fourBytesToLong(format)); // length byte[] length = new byte[4]; System.arraycopy(data, 4, length, 0, 4); frd.setFlowDataLength(Utility.fourBytesToLong(length)); // raw packet header byte[] subData = new byte[(int) frd.getFlowDataLength()]; System.arraycopy(data, 8, subData, 0, (int) frd.getFlowDataLength()); RawPacketHeader rp = RawPacketHeader.parse(subData); frd.setRawPacketHeader(rp); return frd; } catch (Exception e) { throw new HeaderParseException("Parse error: " + e.getMessage()); } } public byte[] getBytes() throws HeaderBytesException { try { byte[] rawPacketBytes = rawPacket.getBytes(); byte[] data = new byte[8 + rawPacketBytes.length]; // format System.arraycopy(Utility.longToFourBytes(flowDataFormat), 0, data, 0, 4); // length System.arraycopy(Utility.longToFourBytes(flowDataLength), 0, data, 4, 4); // raw packet header System.arraycopy(rawPacketBytes, 0, data, 8, rawPacketBytes.length); return data; } catch (Exception e) { throw new HeaderBytesException("Error while generating the bytes: " + e.getMessage()); } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[FlowRecordHeader]:"); sb.append("Format: "); sb.append(getFlowDataFormat()); sb.append(", Length: "); sb.append(getFlowDataLength()); sb.append(", "); sb.append(getRawPacketHeader()); return sb.toString(); } }
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.systemtest.topic; import io.strimzi.api.kafka.model.KafkaTopic; import io.strimzi.operator.common.model.Labels; import io.strimzi.systemtest.BaseST; import io.strimzi.systemtest.Constants; import io.strimzi.systemtest.cli.KafkaCmdClient; import io.strimzi.systemtest.kafkaclients.AbstractKafkaClient; import io.strimzi.systemtest.kafkaclients.internalClients.InternalKafkaClient; import io.strimzi.systemtest.resources.KubernetesResource; import io.strimzi.systemtest.resources.ResourceManager; import io.strimzi.systemtest.resources.crd.KafkaClientsResource; import io.strimzi.systemtest.resources.crd.KafkaResource; import io.strimzi.systemtest.resources.crd.KafkaTopicResource; import io.strimzi.systemtest.utils.kafkaUtils.KafkaTopicUtils; import io.strimzi.systemtest.utils.kubeUtils.objects.PodUtils; import io.strimzi.test.TestUtils; import io.strimzi.test.k8s.exceptions.KubeClusterException; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.CreateTopicsResult; import org.apache.kafka.clients.admin.NewTopic; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static io.strimzi.systemtest.Constants.NODEPORT_SUPPORTED; import static io.strimzi.systemtest.Constants.REGRESSION; import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient; import static io.strimzi.test.k8s.KubeClusterResource.kubeClient; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @Tag(REGRESSION) public class TopicST extends BaseST { private static final Logger LOGGER = LogManager.getLogger(TopicST.class); private static final String NAMESPACE = "topic-cluster-test"; @Test void testMoreReplicasThanAvailableBrokers() { final String topicName = "topic-example"; int topicReplicationFactor = 5; int topicPartitions = 5; KafkaTopic kafkaTopic = KafkaTopicResource.topicWithoutWait(KafkaTopicResource.defaultTopic(CLUSTER_NAME, topicName, topicPartitions, topicReplicationFactor, 1).build()); assertThat("Topic exists in Kafka CR (Kubernetes)", hasTopicInCRK8s(kafkaTopic, topicName)); assertThat("Topic doesn't exists in Kafka itself", !hasTopicInKafka(topicName)); // Checking TO logs String tOPodName = cmdKubeClient().listResourcesByLabel("pod", Labels.STRIMZI_NAME_LABEL + "=my-cluster-entity-operator").get(0); String errorMessage = "Replication factor: 5 larger than available brokers: 3"; PodUtils.waitUntilMessageIsInLogs(tOPodName, "topic-operator", errorMessage); String tOlogs = kubeClient().logs(tOPodName, "topic-operator"); assertThat(tOlogs, containsString(errorMessage)); LOGGER.info("Delete topic {}", topicName); cmdKubeClient().deleteByName("kafkatopic", topicName); KafkaTopicUtils.waitForKafkaTopicDeletion(topicName); topicReplicationFactor = 3; final String newTopicName = "topic-example-new"; kafkaTopic = KafkaTopicResource.topic(CLUSTER_NAME, newTopicName, topicPartitions, topicReplicationFactor).done(); TestUtils.waitFor("Waiting for " + newTopicName + " to be created in Kafka", Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_TOPIC_CREATION, () -> KafkaCmdClient.listTopicsUsingPodCli(CLUSTER_NAME, 0).contains(newTopicName) ); assertThat("Topic exists in Kafka itself", hasTopicInKafka(newTopicName)); assertThat("Topic exists in Kafka CR (Kubernetes)", hasTopicInCRK8s(kafkaTopic, newTopicName)); } @Test void testCreateTopicViaKafka() { int topicPartitions = 3; LOGGER.debug("Creating topic {} with {} replicas and {} partitions", TOPIC_NAME, 3, topicPartitions); KafkaCmdClient.createTopicUsingPodCli(CLUSTER_NAME, 0, TOPIC_NAME, 3, topicPartitions); KafkaTopicUtils.waitForKafkaTopicCreation(TOPIC_NAME); KafkaTopic kafkaTopic = KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(TOPIC_NAME).get(); verifyTopicViaKafkaTopicCRK8s(kafkaTopic, TOPIC_NAME, topicPartitions); topicPartitions = 5; LOGGER.info("Editing topic via Kafka, settings to partitions {}", topicPartitions); KafkaCmdClient.updateTopicPartitionsCountUsingPodCli(CLUSTER_NAME, 0, TOPIC_NAME, topicPartitions); LOGGER.debug("Topic {} updated from {} to {} partitions", TOPIC_NAME, 3, topicPartitions); KafkaTopicUtils.waitForKafkaTopicPartitionChange(TOPIC_NAME, topicPartitions); verifyTopicViaKafka(TOPIC_NAME, topicPartitions); } @Tag(NODEPORT_SUPPORTED) @Test void testCreateTopicViaAdminClient() throws ExecutionException, InterruptedException, TimeoutException { String clusterName = CLUSTER_NAME + "-external-name"; KafkaResource.kafkaEphemeral(clusterName, 3, 3) .editSpec() .editKafka() .editListeners() .withNewKafkaListenerExternalNodePort() .withTls(false) .endKafkaListenerExternalNodePort() .endListeners() .endKafka() .endSpec() .done(); Properties properties = new Properties(); properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, AbstractKafkaClient.getExternalBootstrapConnect(NAMESPACE, clusterName)); try (AdminClient adminClient = AdminClient.create(properties)) { LOGGER.info("Creating async topic {} via Admin client", TOPIC_NAME); CreateTopicsResult crt = adminClient.createTopics(singletonList(new NewTopic(TOPIC_NAME, 1, (short) 1))); crt.all().get(); Set<String> topics = adminClient.listTopics().names().get(Constants.GLOBAL_CLIENTS_TIMEOUT, TimeUnit.MILLISECONDS); LOGGER.info("Verify that in Kafka cluster contains {} topics", 1); assertThat(topics.size(), is(1)); assertThat(topics.contains(TOPIC_NAME), is(true)); } LOGGER.info("Verify that corresponding {} KafkaTopic custom resources were created and topic is in Ready state", 1); KafkaTopicUtils.waitForKafkaTopicStatus(TOPIC_NAME, "Ready"); } @Test void testTopicModificationOfReplicationFactor() { String topicName = "topic-with-changed-replication"; KafkaTopicResource.topic(CLUSTER_NAME, topicName) .editSpec() .withReplicas(3) .endSpec() .done(); TestUtils.waitFor("Waiting to " + topicName + " to be ready", Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_TOPIC_CREATION, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(topicName).get().getStatus().getConditions().get(0).getType().equals("Ready") ); KafkaTopicResource.replaceTopicResource(topicName, t -> t.getSpec().setReplicas(1)); String exceptedMessage = "Changing 'spec.replicas' is not supported. This KafkaTopic's 'spec.replicas' should be reverted to 3 and then the replication should be changed directly in Kafka."; TestUtils.waitFor("Waiting for " + topicName + " to has to contains message" + exceptedMessage, Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_TOPIC_CREATION, () -> KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(topicName).get().getStatus().getConditions().get(0).getMessage().contains(exceptedMessage) ); String topicCRDMessage = KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(topicName).get().getStatus().getConditions().get(0).getMessage(); assertThat(topicCRDMessage, containsString(exceptedMessage)); cmdKubeClient().deleteByName("kafkatopic", topicName); KafkaTopicUtils.waitForKafkaTopicDeletion(topicName); } @Test void testSendingMessagesToNonExistingTopic() { int sent = 0; String topicName = TOPIC_NAME + "-" + rng.nextInt(Integer.MAX_VALUE); KafkaClientsResource.deployKafkaClients(false, CLUSTER_NAME + "-" + Constants.KAFKA_CLIENTS).done(); String defaultKafkaClientsPodName = ResourceManager.kubeClient().listPodsByPrefixInName(CLUSTER_NAME + "-" + Constants.KAFKA_CLIENTS).get(0).getMetadata().getName(); InternalKafkaClient internalKafkaClient = new InternalKafkaClient.Builder() .withUsingPodName(defaultKafkaClientsPodName) .withTopicName(topicName) .withNamespaceName(NAMESPACE) .withClusterName(CLUSTER_NAME) .withMessageCount(MESSAGE_COUNT) .withConsumerGroupName(CONSUMER_GROUP_NAME + rng.nextInt(Integer.MAX_VALUE)) .build(); LOGGER.info("Checking if {} is on topic list", topicName); boolean created = hasTopicInKafka(topicName); assertThat(created, is(false)); LOGGER.info("Topic with name {} is not created yet", topicName); LOGGER.info("Trying to send messages to non-existing topic {}", topicName); // Try produce multiple times in case first try will fail because topic is not exists yet for (int retry = 0; retry < 3; retry++) { sent = internalKafkaClient.sendMessagesPlain(); if (MESSAGE_COUNT == sent) { break; } } internalKafkaClient.assertSentAndReceivedMessages( sent, internalKafkaClient.receiveMessagesPlain() ); LOGGER.info("Checking if {} is on topic list", topicName); created = hasTopicInKafka(topicName); assertThat(created, is(true)); assertThat(KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(topicName).get().getStatus().getConditions().get(0).getType(), is("Ready")); LOGGER.info("Topic successfully created"); } @Test @Order(5) void testDeleteTopicEnableFalse() { String topicName = "my-deleted-topic"; String isolatedKafkaCluster = CLUSTER_NAME + "-isolated"; KafkaResource.kafkaEphemeral(isolatedKafkaCluster, 1, 1) .editSpec() .editKafka() .addToConfig("delete.topic.enable", false) .endKafka() .endSpec() .done(); KafkaClientsResource.deployKafkaClients(false, isolatedKafkaCluster + "-" + Constants.KAFKA_CLIENTS).done(); KafkaTopicResource.topic(isolatedKafkaCluster, topicName).done(); String kafkaClientsPodName = kubeClient().listPodsByPrefixInName(isolatedKafkaCluster + "-" + Constants.KAFKA_CLIENTS).get(0).getMetadata().getName(); InternalKafkaClient internalKafkaClient = new InternalKafkaClient.Builder() .withUsingPodName(kafkaClientsPodName) .withTopicName(topicName) .withNamespaceName(NAMESPACE) .withClusterName(isolatedKafkaCluster) .withMessageCount(MESSAGE_COUNT) .withConsumerGroupName(CONSUMER_GROUP_NAME + "-" + rng.nextInt(Integer.MAX_VALUE)) .build(); int sent = internalKafkaClient.sendMessagesPlain(); String topicUid = KafkaTopicUtils.topicSnapshot(topicName); LOGGER.info("Going to delete topic {}", topicName); KafkaTopicResource.kafkaTopicClient().inNamespace(NAMESPACE).withName(topicName).cascading(true).delete(); LOGGER.info("Topic {} deleted", topicName); KafkaTopicUtils.waitTopicHasRolled(topicName, topicUid); LOGGER.info("Wait topic {} recreation", topicName); KafkaTopicUtils.waitForKafkaTopicCreation(topicName); LOGGER.info("Topic {} recreated", topicName); int received = internalKafkaClient.receiveMessagesPlain(); assertThat(received, is(sent)); } boolean hasTopicInKafka(String topicName) { LOGGER.info("Checking topic {} in Kafka", topicName); return KafkaCmdClient.listTopicsUsingPodCli(CLUSTER_NAME, 0).contains(topicName); } boolean hasTopicInCRK8s(KafkaTopic kafkaTopic, String topicName) { LOGGER.info("Checking in KafkaTopic CR that topic {} exists", topicName); return kafkaTopic.getMetadata().getName().equals(topicName); } void verifyTopicViaKafka(String topicName, int topicPartitions) { TestUtils.waitFor("Describing topic " + topicName + " using pod CLI", Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.TIMEOUT_FOR_RESOURCE_READINESS, () -> { try { List<String> topicInfo = KafkaCmdClient.describeTopicUsingPodCli(CLUSTER_NAME, 0, topicName); LOGGER.info("Checking topic {} in Kafka {}", topicName, CLUSTER_NAME); LOGGER.debug("Topic {} info: {}", topicName, topicInfo); assertThat(topicInfo, hasItems("Topic:" + topicName, "PartitionCount:" + topicPartitions)); return true; } catch (KubeClusterException e) { LOGGER.info("Describing topic using pod cli occurred following error:{}", e.getMessage()); return false; } }); } void verifyTopicViaKafkaTopicCRK8s(KafkaTopic kafkaTopic, String topicName, int topicPartitions) { LOGGER.info("Checking in KafkaTopic CR that topic {} was created with expected settings", topicName); assertThat(kafkaTopic, is(notNullValue())); assertThat(KafkaCmdClient.listTopicsUsingPodCli(CLUSTER_NAME, 0), hasItem(topicName)); assertThat(kafkaTopic.getMetadata().getName(), is(topicName)); assertThat(kafkaTopic.getSpec().getPartitions(), is(topicPartitions)); } @BeforeAll void setup() { ResourceManager.setClassResources(); prepareEnvForOperator(NAMESPACE); applyRoleBindings(NAMESPACE); // 050-Deployment KubernetesResource.clusterOperator(NAMESPACE).done(); LOGGER.info("Deploying shared kafka across all test cases in {} namespace", NAMESPACE); KafkaResource.kafkaEphemeral(CLUSTER_NAME, 3, 1).done(); } }
/* * Copyright (C) 2018 Google Inc. * * 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 com.google.cloud.pso.pipeline; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test cases for the {@link SamplePipeline} class. */ @RunWith(JUnit4.class) public class SamplePipelineTest { /** * Tests the pipeline. */ @Test public void testSamplePipeline() { // Arrange // // Here perform the setup for the test. String[] args = new String[]{}; // Act // // Here perform the action which is being tested. SamplePipeline.main(args); // Assert // // Here perform the assertions for the test. assertThat(true, is(equalTo(true))); } }
package com.github.zhenwei.provider.jce.provider; import com.github.zhenwei.provider.jcajce.PKIXCertRevocationChecker; import com.github.zhenwei.provider.jcajce.PKIXCertRevocationCheckerParameters; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.PKIXCertPathChecker; class WrappedRevocationChecker implements PKIXCertRevocationChecker { private final PKIXCertPathChecker checker; public WrappedRevocationChecker(PKIXCertPathChecker checker) { this.checker = checker; } public void setParameter(String name, Object value) { // ignore. } public void initialize(PKIXCertRevocationCheckerParameters params) throws CertPathValidatorException { checker.init(false); } public void check(Certificate cert) throws CertPathValidatorException { checker.check(cert); } }
package org.smartregister.eusm.contract; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.json.JSONObject; import org.smartregister.domain.Event; import org.smartregister.eusm.domain.StructureDetail; import org.smartregister.view.contract.BaseRegisterContract; public interface TaskRegisterActivityContract { interface View extends BaseRegisterContract.View { int getLayoutId(); String getStructureIcon(); String getStructureName(); String getStructureType(); String getDistance(); String getCommune(); TaskRegisterActivityContract.Presenter presenter(); } interface Presenter extends BaseRegisterContract.Presenter { TaskRegisterActivityContract.View getView(); void saveForm(@NonNull String encounterType, @Nullable JSONObject form, @NonNull StructureDetail structureDetail); } interface Interactor { void saveForm(String encounterType, JSONObject form, StructureDetail structureDetail, InteractorCallBack interactorCallBack); void saveFixProblemForm(JSONObject form, InteractorCallBack interactorCallBack, StructureDetail structureDetail); void saveRecordGps(JSONObject form, InteractorCallBack interactorCallBack, StructureDetail structureDetail); void saveServicePointCheck(JSONObject form, InteractorCallBack interactorCallBack, StructureDetail structureDetail); void saveEventAndInitiateProcessing(String encounterType, JSONObject form, String bindType, InteractorCallBack interactorCallBack, String entityType); } interface InteractorCallBack { void onFormSaved(String encounterType, boolean isSuccessful, Event event); } }
/*============================================================================= * The MIT License (MIT) * * Copyright (c) 2022 Che-Hung Lin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *===========================================================================*/ package ch.dirtools.app.dao; import ch.platform.common.dao.BaseDao; import ch.dirtools.common.exception.ItemExistException; import ch.dirtools.common.exception.ItemNotFoundException; import ch.dirtools.domain.model.Item; import java.util.List; public interface ItemDao extends BaseDao<Item> { void addItem(Item item) throws ItemExistException; Item getItem(String itemName, String itemPath) throws ItemNotFoundException; List<Item> getAllItems(); int cleanup(); void saveItem(Item item); }
/** * Copyright (C) 2015 Red Hat, Inc. * * 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 io.fabric8.kubernetes.client.dsl.base; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.api.model.DeleteOptions; import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Status; import io.fabric8.kubernetes.api.model.StatusBuilder; import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale; import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.internal.VersionUsageUtils; import io.fabric8.kubernetes.client.utils.Serialization; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.kubernetes.client.utils.Utils; import io.fabric8.zjsonpatch.JsonDiff; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.concurrent.ExecutionException; import static io.fabric8.kubernetes.client.internal.PatchUtils.patchMapper; public class OperationSupport { public static final MediaType JSON = MediaType.parse("application/json"); public static final MediaType JSON_PATCH = MediaType.parse("application/json-patch+json"); public static final MediaType STRATEGIC_MERGE_JSON_PATCH = MediaType.parse("application/strategic-merge-patch+json"); public static final MediaType JSON_MERGE_PATCH = MediaType.parse("application/merge-patch+json"); protected static final ObjectMapper JSON_MAPPER = Serialization.jsonMapper(); protected static final ObjectMapper YAML_MAPPER = Serialization.yamlMapper(); private static final String CLIENT_STATUS_FLAG = "CLIENT_STATUS_FLAG"; protected OperationContext context; protected final OkHttpClient client; protected final Config config; protected final String resourceT; protected String namespace; protected String name; protected String apiGroupName; protected String apiGroupVersion; protected boolean dryRun; public OperationSupport() { this (new OperationContext()); } public OperationSupport(OkHttpClient client, Config config) { this(new OperationContext().withOkhttpClient(client).withConfig(config)); } public OperationSupport(OkHttpClient client, Config config, String namespace, DeletionPropagation propagationPolicy, long gracePeriodInSeconds) { this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(propagationPolicy).withGracePeriodSeconds(gracePeriodInSeconds)); } public OperationSupport(OperationContext ctx) { this.context = ctx; this.client = ctx.getClient(); this.config = ctx.getConfig(); this.resourceT = ctx.getPlural(); this.namespace = ctx.getNamespace(); this.name = ctx.getName() ; this.apiGroupName = ctx.getApiGroupName(); this.dryRun = ctx.getDryRun(); if (ctx.getApiGroupVersion() != null) { this.apiGroupVersion = ctx.getApiGroupVersion(); } else if (ctx.getConfig() != null) { this.apiGroupVersion = ctx.getConfig().getApiVersion(); } else { this.apiGroupVersion = "v1"; } } public String getAPIGroup() { return apiGroupName; } public String getAPIVersion() { return apiGroupVersion; } public String getResourceT() { return resourceT; } public String getNamespace() { return namespace; } public String getName() { return name; } public boolean isResourceNamespaced() { return true; } public URL getRootUrl() { try { if (!Utils.isNullOrEmpty(apiGroupName)) { return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion)); } return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion)); } catch (MalformedURLException e) { throw KubernetesClientException.launderThrowable(e); } } public URL getNamespacedUrl(String namespace) throws MalformedURLException { URL requestUrl = getRootUrl(); if (!isResourceNamespaced()) { //if resource is not namespaced don't even bother to check the namespace. } else if (Utils.isNotNullOrEmpty(namespace)) { requestUrl = new URL(URLUtils.join(requestUrl.toString(), "namespaces", namespace)); } requestUrl = new URL(URLUtils.join(requestUrl.toString(), resourceT)); return requestUrl; } public URL getNamespacedUrl() throws MalformedURLException { return getNamespacedUrl(getNamespace()); } public <T> URL getNamespacedUrl(T item) throws MalformedURLException { return getNamespacedUrl(checkNamespace(item)); } public URL getResourceUrl(String namespace, String name) throws MalformedURLException { return getResourceUrl(namespace, name, false); } public URL getResourceUrl(String namespace, String name, boolean status) throws MalformedURLException { if (name == null) { if (status) { throw new KubernetesClientException("Name not specified. But operation requires name."); } return getNamespacedUrl(namespace); } if (status) { return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name, "status")); } return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name)); } public URL getResourceUrl() throws MalformedURLException { if (name == null) { return getNamespacedUrl(); } return new URL(URLUtils.join(getNamespacedUrl().toString(), name)); } public URL getResourceURLForWriteOperation(URL resourceURL) throws MalformedURLException { if (dryRun) { return new URL(URLUtils.join(resourceURL.toString(), "?dryRun=All")); } return resourceURL; } public URL getResourceURLForPatchOperation(URL resourceUrl, PatchContext patchContext) throws MalformedURLException { if (patchContext != null) { String url = resourceUrl.toString(); if (patchContext.getForce() != null) { url = URLUtils.join(url, "?force=" + patchContext.getForce()); } if ((patchContext.getDryRun() != null && !patchContext.getDryRun().isEmpty()) || dryRun) { url = URLUtils.join(url, "?dryRun=All"); } if (patchContext.getFieldManager() != null) { url = URLUtils.join(url, "?fieldManager=" + patchContext.getFieldManager()); } return new URL(url); } return resourceUrl; } protected <T> String checkNamespace(T item) { String operationNs = getNamespace(); String itemNs = (item instanceof HasMetadata && ((HasMetadata)item).getMetadata() != null) ? ((HasMetadata) item).getMetadata().getNamespace() : null; if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) { if (!isResourceNamespaced()) { return null; } else { throw new KubernetesClientException("Namespace not specified. But operation requires namespace."); } } else if (Utils.isNullOrEmpty(itemNs)) { return operationNs; } else if (Utils.isNullOrEmpty(operationNs)) { return itemNs; } else if (itemNs.equals(operationNs)) { return itemNs; } throw new KubernetesClientException("Namespace mismatch. Item namespace:" + itemNs + ". Operation namespace:" + operationNs + "."); } protected <T> String checkName(T item) { String operationName = getName(); ObjectMeta metadata = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata() : null; String itemName = metadata != null ? metadata.getName() : null; if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) { return null; } else if (Utils.isNullOrEmpty(itemName)) { return operationName; } else if (Utils.isNullOrEmpty(operationName)) { return itemName; } else if (itemName.equals(operationName)) { return itemName; } throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + "."); } protected <T> T handleMetric(String resourceUrl, Class<T> type) throws InterruptedException, IOException, ExecutionException { Request.Builder requestBuilder = new Request.Builder() .get() .url(resourceUrl); return handleResponse(requestBuilder, type); } protected <T> void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException { handleDelete(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), checkName(resource))), gracePeriodSeconds, propagationPolicy, cascading); } protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException { RequestBody requestBody = null; DeleteOptions deleteOptions = new DeleteOptions(); if (gracePeriodSeconds >= 0) { deleteOptions.setGracePeriodSeconds(gracePeriodSeconds); } /* * Either the propagation policy or the orphan dependent (deprecated) property must be set, but not both. */ if (propagationPolicy != null) { deleteOptions.setPropagationPolicy(propagationPolicy.toString()); } else { deleteOptions.setOrphanDependents(!cascading); } if (dryRun) { deleteOptions.setDryRun(Collections.singletonList("All")); } requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions)); Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl); handleResponse(requestBuilder, null, Collections.<String, String>emptyMap()); } /** * Create a resource. * * @param resource resource provided * @param outputType resource type you want as output * @param <T> template argument for output type * @param <I> template argument for resource * * @return returns de-serialized version of apiserver response in form of type provided * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T, I> T handleCreate(I resource, Class<T> outputType) throws ExecutionException, InterruptedException, IOException { RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(resource)); Request.Builder requestBuilder = new Request.Builder().post(body).url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(resource), null))); return handleResponse(requestBuilder, outputType, Collections.<String, String>emptyMap()); } /** * Replace a resource. * * @param updated updated object * @param type type of the object provided * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, boolean status) throws ExecutionException, InterruptedException, IOException { return handleUpdate(updated, type, Collections.<String, String>emptyMap(), status); } /** * Update a resource, optionally performing placeholder substitution to the response. * * @param updated updated object * @param type type of object provided * @param parameters a HashMap containing parameters for processing object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleUpdate(T updated, Class<T> type, Map<String, String> parameters, boolean status) throws ExecutionException, InterruptedException, IOException { RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(updated)); Request.Builder requestBuilder = new Request.Builder().put(body).url(getResourceURLForWriteOperation(getResourceUrl(checkNamespace(updated), checkName(updated), status))); return handleResponse(requestBuilder, type, parameters); } /** * Send an http patch and handle the response. * * If current is not null and patchContext does not specify a patch type, then a JSON patch is assumed. Otherwise a STRATEGIC MERGE is assumed. * * @param patchContext patch options for patch request * @param current current object * @param updated updated object * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(PatchContext patchContext, T current, T updated, Class<T> type, boolean status) throws ExecutionException, InterruptedException, IOException { String patchForUpdate = null; if (current != null && (patchContext == null || patchContext.getPatchType() == PatchType.JSON)) { patchForUpdate = JSON_MAPPER.writeValueAsString(JsonDiff.asJson(patchMapper().valueToTree(current), patchMapper().valueToTree(updated))); if (patchContext == null) { patchContext = new PatchContext.Builder().withPatchType(PatchType.JSON).build(); } } else { patchForUpdate = Serialization.asJson(updated); current = updated; // use the updated to determine the path } return handlePatch(patchContext, current, patchForUpdate, type, status); } /** * Send an http patch and handle the response. * * @param current current object * @param patchForUpdate updated object spec as json string * @param type type of object * @param <T> template argument provided * * @return returns de-serialized version of api server response * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handlePatch(T current, Map<String, Object> patchForUpdate, Class<T> type) throws ExecutionException, InterruptedException, IOException { return handlePatch(new PatchContext.Builder().withPatchType(PatchType.STRATEGIC_MERGE).build(), current, JSON_MAPPER.writeValueAsString(patchForUpdate), type, false); } /** * Send an http patch and handle the response. * * @param patchContext patch options for patch request * @param current current object * @param patchForUpdate Patch string * @param type type of object * @param status if this is only the status subresource * @param <T> template argument provided * @return returns de-serialized version of api server response * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException in case of network errors */ protected <T> T handlePatch(PatchContext patchContext, T current, String patchForUpdate, Class<T> type, boolean status) throws ExecutionException, InterruptedException, IOException { MediaType bodyMediaType = getMediaTypeFromPatchContextOrDefault(patchContext); RequestBody body = RequestBody.create(bodyMediaType, patchForUpdate); Request.Builder requestBuilder = new Request.Builder().patch(body).url(getResourceURLForPatchOperation(getResourceUrl(checkNamespace(current), checkName(current), status), patchContext)); return handleResponse(requestBuilder, type, Collections.emptyMap()); } /** * Replace Scale of specified Kubernetes Resource * * @param resourceUrl Kubernetes resource URL * @param scale Scale object which we want to inject * @return updated Scale object * @throws ExecutionException in case of any execution exception * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Scale handleScale(String resourceUrl, Scale scale) throws ExecutionException, InterruptedException, IOException { Request.Builder requestBuilder; if (scale != null) { RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(scale)); requestBuilder = new Request.Builder().put(body).url(resourceUrl + "/scale"); } else { requestBuilder = new Request.Builder().get().url(resourceUrl + "/scale"); } return handleResponse(requestBuilder, Scale.class); } /** * Create rollback of a Deployment * * @param resourceUrl resource url * @param deploymentRollback DeploymentRollback resource * @return Status * @throws ExecutionException in case of any execution exception * @throws InterruptedException in case thread is interrupted * @throws IOException in some other I/O problem */ protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws ExecutionException, InterruptedException, IOException { RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback)); Request.Builder requestBuilder = new Request.Builder().post(body).url(resourceUrl + "/rollback"); return handleResponse(requestBuilder, Status.class); } /** * Send an http get. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param <T> template argument provided * * @return returns a deserialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type) throws ExecutionException, InterruptedException, IOException { return handleGet(resourceUrl, type, Collections.<String, String>emptyMap()); } /** * Send an http, optionally performing placeholder substitution to the response. * * @param resourceUrl resource URL to be processed * @param type type of resource * @param parameters A HashMap of strings containing parameters to be passed in request * @param <T> template argument provided * * @return Returns a deserialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException { Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl); return handleResponse(requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param requestBuilder Request Builder object * @param type type of resource * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(Request.Builder requestBuilder, Class<T> type) throws ExecutionException, InterruptedException, IOException { return handleResponse(requestBuilder, type, Collections.<String, String>emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param requestBuilder request builder * @param type type of object * @param parameters a hashmap containing parameters * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException { return handleResponse(client, requestBuilder, type, parameters); } /** * Send an http request and handle the response. * * @param client OkHttp client object * @param requestBuilder request builder * @param type type of object * @param <T> template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type) throws ExecutionException, InterruptedException, IOException { return handleResponse(client, requestBuilder, type, Collections.<String, String>emptyMap()); } /** * Send an http request and handle the response, optionally performing placeholder substitution to the response. * * @param client OkHttp client provided * @param requestBuilder Request builder * @param type Type of object provided * @param parameters A hashmap containing parameters * @param <T> Template argument provided * * @return Returns a de-serialized object as api server response of provided type. * @throws ExecutionException Execution Exception * @throws InterruptedException Interrupted Exception * @throws IOException IOException */ protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException { VersionUsageUtils.log(this.resourceT, this.apiGroupVersion); Request request = requestBuilder.build(); Response response = client.newCall(request).execute(); try (ResponseBody body = response.body()) { assertResponseCode(request, response); if (type != null) { try (InputStream bodyInputStream = body.byteStream()) { return Serialization.unmarshal(bodyInputStream, type, parameters); } } else { return null; } } catch (Exception e) { if (e instanceof KubernetesClientException) { throw e; } throw requestException(request, e); } finally { if(response != null && response.body() != null) { response.body().close(); } } } /** * Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not. * * @param request The {#link Request} object. * @param response The {@link Response} object. */ protected void assertResponseCode(Request request, Response response) { int statusCode = response.code(); String customMessage = config.getErrorMessages().get(statusCode); if (response.isSuccessful()) { return; } else if (customMessage != null) { throw requestFailure(request, createStatus(statusCode, combineMessages(customMessage, createStatus(response)))); } else { throw requestFailure(request, createStatus(response)); } } private String combineMessages(String customMessage, Status defaultStatus) { if (defaultStatus != null) { String message = defaultStatus.getMessage(); if (message != null && message.length() > 0) { return customMessage + " " + message; } } return customMessage; } public static Status createStatus(Response response) { String statusMessage = ""; ResponseBody body = response != null ? response.body() : null; int statusCode = response != null ? response.code() : 0; try { if (response == null) { statusMessage = "No response"; } else if (body != null) { statusMessage = body.string(); } else if (response.message() != null) { statusMessage = response.message(); } Status status = JSON_MAPPER.readValue(statusMessage, Status.class); if (status.getCode() == null) { status = new StatusBuilder(status).withCode(statusCode).build(); } return status; } catch (JsonParseException e) { return createStatus(statusCode, statusMessage); } catch (IOException e) { return createStatus(statusCode, statusMessage); } } public static Status createStatus(int statusCode, String message) { Status status = new StatusBuilder() .withCode(statusCode) .withMessage(message) .build(); status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true"); return status; } public static KubernetesClientException requestFailure(Request request, Status status) { StringBuilder sb = new StringBuilder(); sb.append("Failure executing: ").append(request.method()) .append(" at: ").append(request.url().toString()).append("."); if (status.getMessage() != null && !status.getMessage().isEmpty()) { sb.append(" Message: ").append(status.getMessage()).append("."); } if (status != null && !status.getAdditionalProperties().containsKey(CLIENT_STATUS_FLAG)) { sb.append(" Received status: ").append(status).append("."); } return new KubernetesClientException(sb.toString(), status.getCode(), status); } public static KubernetesClientException requestException(Request request, Exception e) { StringBuilder sb = new StringBuilder(); sb.append("Error executing: ").append(request.method()) .append(" at: ").append(request.url().toString()) .append(". Cause: ").append(e.getMessage()); return new KubernetesClientException(sb.toString(), e); } protected static <T> T unmarshal(InputStream is) { return Serialization.unmarshal(is); } protected static <T> T unmarshal(InputStream is, final Class<T> type) { return Serialization.unmarshal(is, type); } protected static <T> T unmarshal(InputStream is, TypeReference<T> type) { return Serialization.unmarshal(is, type); } protected static <T> Map getObjectValueAsMap(T object) { return JSON_MAPPER.convertValue(object, Map.class); } public Config getConfig() { return config; } private MediaType getMediaTypeFromPatchContextOrDefault(PatchContext patchContext) { if (patchContext != null && patchContext.getPatchType() != null) { return patchContext.getPatchType().getMediaType(); } return STRATEGIC_MERGE_JSON_PATCH; } }
// "Change type of 'p' to 'Point' and remove cast" "true" class Test { class Point {int x, y;} int test(boolean b) { Object p = new Point(); return b ? 0 : ((Po<caret>int)p).x; } }
package de.axxepta.oxygen.core; /** * @author Max on 01.09.2015. */ public interface SubjectInterface { //methods to register and unregister observers void register(ObserverInterface obj); //void unregister(ObserverInterface obj); //method to notify observers of change void notifyObservers(); //method to get updates from subject //public Object getUpdate(ObserverInterface obj); }
package com.stylefeng.guns.common.persistence.dao; import com.stylefeng.guns.common.persistence.model.Irrb.IrrBase; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * 灌区基本信息 Mapper 接口 * </p> * * @author hnsl * @since 2017-10-20 */ public interface IrrBaseMapper extends BaseMapper<IrrBase> { }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.phoenix.schema; public interface PDatum { /** * @return is this column nullable? */ boolean isNullable(); /** * @return data type of the column */ PDataType getDataType(); /** * @return the actual length of the column. For decimal, it would be its precision. For char or * varchar, it would be the maximum length as specified during schema definition. */ Integer getMaxLength(); /** * @return scale of a decimal number. */ Integer getScale(); /** * @return The SortOrder for this column, never null */ SortOrder getSortOrder(); }
/* * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.lang.model.util; import javax.lang.model.type.*; import javax.annotation.processing.SupportedSourceVersion; import static javax.lang.model.SourceVersion.*; import javax.lang.model.SourceVersion; /** * A visitor of types based on their {@linkplain TypeKind kind} with * default behavior appropriate for the {@link SourceVersion#RELEASE_7 * RELEASE_7} source version. For {@linkplain * TypeMirror types} <code><i>Xyz</i></code> that may have more than one * kind, the <code>visit<i>Xyz</i></code> methods in this class delegate * to the <code>visit<i>Xyz</i>As<i>Kind</i></code> method corresponding to the * first argument's kind. The <code>visit<i>Xyz</i>As<i>Kind</i></code> methods * call {@link #defaultAction defaultAction}, passing their arguments * to {@code defaultAction}'s corresponding parameters. * * <p> Methods in this class may be overridden subject to their * general contract. Note that annotating methods in concrete * subclasses with {@link java.lang.Override @Override} will help * ensure that methods are overridden as intended. * * <p> <b>WARNING:</b> The {@code TypeVisitor} interface implemented * by this class may have methods added to it in the future to * accommodate new, currently unknown, language structures added to * future versions of the Java&trade; programming language. * Therefore, methods whose names begin with {@code "visit"} may be * added to this class in the future; to avoid incompatibilities, * classes which extend this class should not declare any instance * methods with names beginning with {@code "visit"}. * * <p>When such a new visit method is added, the default * implementation in this class will be to call the {@link * #visitUnknown visitUnknown} method. A new type kind visitor class * will also be introduced to correspond to the new language level; * this visitor will have different default behavior for the visit * method in question. When the new visitor is introduced, all or * portions of this visitor may be deprecated. * * @param <R> the return type of this visitor's methods. Use {@link * Void} for visitors that do not need to return results. * @param <P> the type of the additional parameter to this visitor's * methods. Use {@code Void} for visitors that do not need an * additional parameter. * * @see TypeKindVisitor6 * @see TypeKindVisitor8 * @since 1.7 */ @SupportedSourceVersion(RELEASE_7) public class TypeKindVisitor7<R, P> extends TypeKindVisitor6<R, P> { /** * Constructor for concrete subclasses to call; uses {@code null} * for the default value. */ @SuppressWarnings("deprecation") // Superclass constructor deprecated protected TypeKindVisitor7() { super(null); } /** * Constructor for concrete subclasses to call; uses the argument * for the default value. * * @param defaultValue the value to assign to {@link #DEFAULT_VALUE} */ @SuppressWarnings("deprecation") // Superclass constructor deprecated protected TypeKindVisitor7(R defaultValue) { super(defaultValue); } /** * This implementation visits a {@code UnionType} by calling * {@code defaultAction}. * * @param t {@inheritDoc} * @param p {@inheritDoc} * @return the result of {@code defaultAction} */ @Override public R visitUnion(UnionType t, P p) { return defaultAction(t, p); } }
/* * Copyright 2015 Pawan Dubey pawandubey@outlook.com. * * 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 com.pawandubey.griffin.cli; import static com.pawandubey.griffin.Configurator.LINE_SEPARATOR; import com.pawandubey.griffin.Griffin; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.kohsuke.args4j.ParserProperties; import org.kohsuke.args4j.spi.BooleanOptionHandler; /** * * @author Pawan Dubey pawandubey@outlook.com */ public class PublishCommand implements GriffinCommand { @Option(name = "--help", aliases = {"-h"}, handler = BooleanOptionHandler.class, usage = "find help about this command") private boolean help = false; @Option(name = "--quick", aliases = {"-q"}, handler = BooleanOptionHandler.class, usage = "Publish only the files which have changed since the last modification." ) private Boolean fastParse = false; @Option(name = "--rebuild", aliases = {"-r"}, handler = BooleanOptionHandler.class, usage = "Rebuild the site from scratch. This may take time for more number of posts.") private Boolean rebuild = false; public PublishCommand() throws InterruptedException, IOException { } /** * Executes the command */ @Override public void execute() { if (help) { System.out.println("Publish the content in the current Griffin directory."); System.out.println("usage: griffin publish [option]"); System.out.println("Options: " + LINE_SEPARATOR); CmdLineParser parser = new CmdLineParser(this, ParserProperties.defaults().withUsageWidth(120)); parser.printUsage(System.out); return; } try { Griffin griffin = new Griffin(); griffin.printAsciiGriffin(); griffin.publish(fastParse, rebuild); System.out.println("All done for now! I will be bach!"); } catch (IOException | InterruptedException ex) { Logger.getLogger(PublishCommand.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.alipay.api.request; import com.alipay.api.domain.AlipayEbppCommunityIsvCreateModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayEbppCommunityIsvCreateResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.ebpp.community.isv.create request * * @author auto create * @since 1.0, 2021-11-09 14:30:01 */ public class AlipayEbppCommunityIsvCreateRequest implements AlipayRequest<AlipayEbppCommunityIsvCreateResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * ISV创建 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.ebpp.community.isv.create"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayEbppCommunityIsvCreateResponse> getResponseClass() { return AlipayEbppCommunityIsvCreateResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.generated; import com.microsoft.graph.models.extensions.WorkbookFunctionsPriceBody; import com.microsoft.graph.models.extensions.WorkbookFunctionResult; import com.microsoft.graph.requests.extensions.IWorkbookFunctionsPriceRequest; import com.microsoft.graph.requests.extensions.WorkbookFunctionsPriceRequest; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.options.Option; import com.microsoft.graph.options.QueryOption; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Base Workbook Functions Price Request. */ public class BaseWorkbookFunctionsPriceRequest extends BaseRequest implements IBaseWorkbookFunctionsPriceRequest { protected final WorkbookFunctionsPriceBody body; /** * The request for this WorkbookFunctionsPrice * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public BaseWorkbookFunctionsPriceRequest(final String requestUrl, final IBaseClient client, final java.util.List<? extends Option> requestOptions) { super(requestUrl, client, requestOptions, WorkbookFunctionResult.class); body = new WorkbookFunctionsPriceBody(); } public void post(final ICallback<WorkbookFunctionResult> callback) { send(HttpMethod.POST, callback, body); } public WorkbookFunctionResult post() throws ClientException { return send(HttpMethod.POST, body); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ public IWorkbookFunctionsPriceRequest select(final String value) { getQueryOptions().add(new QueryOption("$select", value)); return (WorkbookFunctionsPriceRequest)this; } /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ public IWorkbookFunctionsPriceRequest top(final int value) { getQueryOptions().add(new QueryOption("$top", value+"")); return (WorkbookFunctionsPriceRequest)this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ public IWorkbookFunctionsPriceRequest expand(final String value) { getQueryOptions().add(new QueryOption("$expand", value)); return (WorkbookFunctionsPriceRequest)this; } }
/* * Copyright 2021 TiDB Project Authors. * * 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 io.tidb.bigdata.flink.connector.source.enumerator; import io.tidb.bigdata.flink.connector.source.split.TiDBSourceSplit; import java.util.HashSet; import java.util.Set; public class TiDBSourceSplitEnumState { private final Set<TiDBSourceSplit> assignedSplits; public TiDBSourceSplitEnumState(Set<TiDBSourceSplit> splits) { this.assignedSplits = new HashSet<>(splits); } public Set<TiDBSourceSplit> assignedSplits() { return assignedSplits; } }
/** * Copyright 2005-2014 Red Hat, Inc. * * Red Hat licenses this file to you 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 io.fabric8.process.manager.commands; import io.fabric8.process.manager.Installation; import io.fabric8.process.manager.ProcessManager; import io.fabric8.process.manager.commands.support.ProcessControlCommandSupport; import org.apache.felix.gogo.commands.Command; /** */ @Command(name = "start", scope = "process", description = "Starts a managed process") public class StartAction extends ProcessControlCommandSupport { protected StartAction(ProcessManager processManager) { super(processManager); } @Override protected void doControlCommand(Installation installation) throws Exception { installation.getController().start(); } }
package com.iotake.suller.sullerj.binder.value; import java.lang.reflect.Field; public class NumberValueConverterFactory extends AbstractValueConverterFactory { public static class NumberValueConverter extends AbstractSingleSlotValueConverter { public NumberValueConverter(Class<?> targetType, Class<?> documentClass, Field field, String path) { super(Number.class, targetType, documentClass, field, path); } public Class<?> getSlotType() { return Double.class; } public Object toDocumentValue(Object beanValue) { if (beanValue == null) { return null; } checkBeanValueType(beanValue); return ((Number) beanValue).doubleValue(); } public Object toBeanValue(Object documentValue) { if (documentValue == null) { return null; } checkDocumentValueType(documentValue, getSlot()); return documentValue; } } public NumberValueConverterFactory() { super(Number.class); } protected ValueConverter doCreate(Class<?> targetType, Class<?> documentClass, Field field, String slotName, String slotNameSeparator) { return new NumberValueConverter(targetType, documentClass, field, slotName); } }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package microsoft.entityframeworkcore.metadata; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import microsoft.entityframeworkcore.metadata.IReadOnlyKey; import microsoft.entityframeworkcore.metadata.IReadOnlyKeyImplementation; /** * The base .NET class managing Microsoft.EntityFrameworkCore.Metadata.KeyComparer, Microsoft.EntityFrameworkCore, Version=6.0.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Metadata.KeyComparer" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Metadata.KeyComparer</a> */ public class KeyComparer extends NetObject { /** * Fully assembly qualified name: Microsoft.EntityFrameworkCore, Version=6.0.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 */ public static final String assemblyFullName = "Microsoft.EntityFrameworkCore, Version=6.0.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"; /** * Assembly name: Microsoft.EntityFrameworkCore */ public static final String assemblyShortName = "Microsoft.EntityFrameworkCore"; /** * Qualified class name: Microsoft.EntityFrameworkCore.Metadata.KeyComparer */ public static final String className = "Microsoft.EntityFrameworkCore.Metadata.KeyComparer"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public KeyComparer(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link KeyComparer}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link KeyComparer} instance * @throws java.lang.Throwable in case of error during cast operation */ public static KeyComparer cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new KeyComparer(from.getJCOInstance()); } // Constructors section public KeyComparer() throws Throwable { } // Methods section public boolean Equals(IReadOnlyKey x, IReadOnlyKey y) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("Equals", x == null ? null : x.getJCOInstance(), y == null ? null : y.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int Compare(IReadOnlyKey x, IReadOnlyKey y) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("Compare", x == null ? null : x.getJCOInstance(), y == null ? null : y.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int GetHashCode(IReadOnlyKey obj) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("GetHashCode", obj == null ? null : obj.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section // Instance Events section }
/* * #%L * SciJava Common shared library for SciJava software. * %% * Copyright (C) 2009 - 2020 SciJava developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package org.scijava.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Tests {@link DigestUtils}. * * @author Curtis Rueden */ public class DigestUtilsTest { private static final byte[] CAFEBABE_SHA1 = { 20, 101, -38, -47, 38, -45, 43, -9, -86, 93, 59, -107, -91, -57, -61, 49, -51, -1, 52, -33 }; private static final byte[] CAFEBABE_MD5 = { 45, 27, -67, -30, -84, -84, 10, -3, 7, 100, 109, -104, 21, 79, 64, 46 }; private static final byte[] HELLO_WORLD_SHA1 = { 123, 80, 44, 58, 31, 72, -56, 96, -102, -30, 18, -51, -5, 99, -99, -18, 57, 103, 63, 94 }; private static final String HELLO_WORLD_SHA1_HEX = "7b502c3a1f48c8609ae212cdfb639dee39673f5e"; private static final String CAFEBABE_SHA1_HEX = "1465dad126d32bf7aa5d3b95a5c7c331cdff34df"; private static final String HELLO_WORLD_SHA1_BASE64 = "e1AsOh9IyGCa4hLN+2Od7jlnP14="; private static final String CAFEBABE_SHA1_BASE64 = "FGXa0SbTK/eqXTuVpcfDMc3/NN8="; /** Tests {@link DigestUtils#bytes(String)}. */ @Test public void testBytesString() { final String s = "Hello world"; final byte[] bytes = DigestUtils.bytes(s); final byte[] expected = { 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 }; assertArrayEquals(expected, bytes); } /** Tests {@link DigestUtils#bytes(int)}. */ @Test public void testBytesInt() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); final byte[] expected = { -54, -2, -70, -66 }; assertArrayEquals(expected, bytes); } /** Tests {@link DigestUtils#hex(byte[])}. */ @Test public void testHex() { assertEquals("cafebabe", DigestUtils.hex(DigestUtils.bytes(0xcafebabe))); assertEquals("deadbeef", DigestUtils.hex(DigestUtils.bytes(0xdeadbeef))); assertEquals("00000000", DigestUtils.hex(DigestUtils.bytes(0x00000000))); assertEquals("ffffffff", DigestUtils.hex(DigestUtils.bytes(0xffffffff))); } /** Tests {@link DigestUtils#base64(byte[])}. */ @Test public void testBase64() { assertEquals("yv66vg==", DigestUtils.base64(DigestUtils.bytes(0xcafebabe))); assertEquals("3q2+7w==", DigestUtils.base64(DigestUtils.bytes(0xdeadbeef))); assertEquals("AAAAAA==", DigestUtils.base64(DigestUtils.bytes(0x00000000))); assertEquals("/////w==", DigestUtils.base64(DigestUtils.bytes(0xffffffff))); } /** Tests {@link DigestUtils#hash(String)}. */ @Test public void testHashString() { final byte[] hash = DigestUtils.hash("Hello world"); final byte[] expected = { -50, 89, -118, -92 }; assertArrayEquals(expected, hash); } /** Tests {@link DigestUtils#hash(byte[])}. */ @Test public void testHashBytes() { final byte[] bytes = DigestUtils.bytes("Hello world"); final byte[] hash = DigestUtils.hash(bytes); final byte[] expected = { -50, 89, -118, -92 }; assertArrayEquals(expected, hash); } /** Tests {@link DigestUtils#sha1(byte[])}. */ @Test public void testSHA1() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); final byte[] sha1 = DigestUtils.sha1(bytes); assertArrayEquals(CAFEBABE_SHA1, sha1); } /** Tests {@link DigestUtils#md5(byte[])}. */ @Test public void testMD5() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); final byte[] md5 = DigestUtils.md5(bytes); assertArrayEquals(CAFEBABE_MD5, md5); } /** Tests {@link DigestUtils#digest(String, byte[])}. */ @Test public void testDigest() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); final byte[] sha1 = DigestUtils.digest("SHA-1", bytes); final byte[] expectedSHA1 = DigestUtils.sha1(bytes); assertArrayEquals(expectedSHA1, sha1); final byte[] md5 = DigestUtils.digest("MD5", bytes); final byte[] expectedMD5 = DigestUtils.md5(bytes); assertArrayEquals(expectedMD5, md5); } /** Tests {@link DigestUtils#best(String)}. */ @Test public void testBestString() { final byte[] best = DigestUtils.best("Hello world"); assertArrayEquals(HELLO_WORLD_SHA1, best); } /** Tests {@link DigestUtils#best(byte[])}. */ @Test public void testBestBytes() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); final byte[] best = DigestUtils.best(bytes); assertArrayEquals(CAFEBABE_SHA1, best); } /** Tests {@link DigestUtils#bestHex(String)}. */ @Test public void testBestHexString() { assertEquals(HELLO_WORLD_SHA1_HEX, DigestUtils.bestHex("Hello world")); } /** Tests {@link DigestUtils#hex(byte[])}. */ @Test public void testBestHexBytes() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); assertEquals(CAFEBABE_SHA1_HEX, DigestUtils.bestHex(bytes)); } /** Tests {@link DigestUtils#bestBase64(String)}. */ @Test public void testBestBase64String() { assertEquals(HELLO_WORLD_SHA1_BASE64, DigestUtils.bestBase64("Hello world")); } /** Tests {@link DigestUtils#bestBase64(byte[])}. */ @Test public void testBestBase64Bytes() { final byte[] bytes = DigestUtils.bytes(0xcafebabe); assertEquals(CAFEBABE_SHA1_BASE64, DigestUtils.bestBase64(bytes)); } }
package io.cucumber.core.runner; import io.cucumber.core.backend.StepDefinition; import io.cucumber.core.eventbus.EventBus; import io.cucumber.core.feature.TestFeatureParser; import io.cucumber.core.gherkin.Feature; import io.cucumber.core.gherkin.Step; import io.cucumber.core.runtime.TimeServiceEventBus; import io.cucumber.core.stepexpression.Argument; import io.cucumber.core.stepexpression.StepExpression; import io.cucumber.core.stepexpression.StepExpressionFactory; import io.cucumber.core.stepexpression.StepTypeRegistry; import io.cucumber.datatable.DataTable; import io.cucumber.docstring.DocString; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; class CoreStepDefinitionTest { private final StepTypeRegistry stepTypeRegistry = new StepTypeRegistry(Locale.ENGLISH); private final EventBus bus = new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID); private final StepExpressionFactory stepExpressionFactory = new StepExpressionFactory(stepTypeRegistry, bus); private final UUID id = UUID.randomUUID(); @Test void should_apply_identity_transform_to_doc_string_when_target_type_is_object() { Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given I have some step\n" + " \"\"\"\n" + " content\n" + " \"\"\"\n"); StepDefinition stepDefinition = new StubStepDefinition("I have some step", Object.class); StepExpression expression = stepExpressionFactory.createExpression(stepDefinition); CoreStepDefinition coreStepDefinition = new CoreStepDefinition(id, stepDefinition, expression); Step step = feature.getPickles().get(0).getSteps().get(0); List<Argument> arguments = coreStepDefinition.matchedArguments(step); assertThat(arguments.get(0).getValue(), is(equalTo(DocString.create("content")))); } @Test void should_apply_identity_transform_to_data_table_when_target_type_is_object() { Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given I have some step\n" + " | content |\n"); StepDefinition stepDefinition = new StubStepDefinition("I have some step", Object.class); StepExpression expression = stepExpressionFactory.createExpression(stepDefinition); CoreStepDefinition coreStepDefinition = new CoreStepDefinition(id, stepDefinition, expression); List<Argument> arguments = coreStepDefinition.matchedArguments(feature.getPickles().get(0).getSteps().get(0)); assertThat(arguments.get(0).getValue(), is(equalTo(DataTable.create(singletonList(singletonList("content")))))); } @Test void should_convert_empty_pickle_table_cells_to_null_values() { Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given I have some step\n" + " | |\n"); StepDefinition stepDefinition = new StubStepDefinition("I have some step", Object.class); StepExpression expression = stepExpressionFactory.createExpression(stepDefinition); CoreStepDefinition coreStepDefinition = new CoreStepDefinition(id, stepDefinition, expression); List<Argument> arguments = coreStepDefinition.matchedArguments(feature.getPickles().get(0).getSteps().get(0)); assertEquals(DataTable.create(singletonList(singletonList(null))), arguments.get(0).getValue()); } @Test void transforms_to_map_of_double_to_double() throws Throwable { Method m = Steps.class.getMethod("mapOfDoubleToDouble", Map.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | 100.5 | 99.5 | \n" + " | 0.5 | -0.5 | \n" + " | 1000 | 999 | \n"); Map<Double, Double> stepDefs = runStepDef(m, false, feature); assertAll( () -> assertThat(stepDefs, hasEntry(1000.0, 999.0)), () -> assertThat(stepDefs, hasEntry(0.5, -0.5)), () -> assertThat(stepDefs, hasEntry(100.5, 99.5))); } @SuppressWarnings("unchecked") private <T> T runStepDef(Method method, boolean transposed, Feature feature) { StubStepDefinition stepDefinition = new StubStepDefinition("some text", transposed, method.getGenericParameterTypes()); StepExpression expression = stepExpressionFactory.createExpression(stepDefinition); CoreStepDefinition coreStepDefinition = new CoreStepDefinition(id, stepDefinition, expression); Step stepWithTable = feature.getPickles().get(0).getSteps().get(0); List<Argument> arguments = coreStepDefinition.matchedArguments(stepWithTable); List<Object> result = new ArrayList<>(); for (Argument argument : arguments) { result.add(argument.getValue()); } coreStepDefinition.getStepDefinition().execute(result.toArray(new Object[0])); return (T) stepDefinition.getArgs().get(0); } @Test void transforms_transposed_to_map_of_double_to_double() throws Throwable { Method m = Steps.class.getMethod("transposedMapOfDoubleToListOfDouble", Map.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | 100.5 | 99.5 | \n" + " | 0.5 | -0.5 | \n" + " | 1000 | 999 | \n"); Map<Double, List<Double>> stepDefs = runStepDef(m, true, feature); assertThat(stepDefs, hasEntry(100.5, asList(0.5, 1000.0))); } @Test void transforms_to_list_of_single_values() throws Throwable { Method m = Steps.class.getMethod("listOfListOfDoubles", List.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | 100.5 | 99.5 | \n" + " | 0.5 | -0.5 | \n" + " | 1000 | 999 | \n"); List<List<Double>> stepDefs = runStepDef(m, false, feature); assertThat(stepDefs.toString(), is(equalTo("[[100.5, 99.5], [0.5, -0.5], [1000.0, 999.0]]"))); } @Test void transforms_to_list_of_single_values_transposed() throws Throwable { Method m = Steps.class.getMethod("listOfListOfDoubles", List.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | 100.5 | 0.5 | 1000| \n" + " | 99.5 | -0.5 | 999 | \n"); List<List<Double>> stepDefs = runStepDef(m, true, feature); assertThat(stepDefs.toString(), is(equalTo("[[100.5, 99.5], [0.5, -0.5], [1000.0, 999.0]]"))); } @Test void passes_plain_data_table() throws Throwable { Method m = Steps.class.getMethod("plainDataTable", DataTable.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | Birth Date | \n" + " | 1957-05-10 | \n"); DataTable stepDefs = runStepDef(m, false, feature); assertAll( () -> assertThat(stepDefs.cell(0, 0), is(equalTo("Birth Date"))), () -> assertThat(stepDefs.cell(1, 0), is(equalTo("1957-05-10")))); } @Test void passes_transposed_data_table() throws Throwable { Method m = Steps.class.getMethod("plainDataTable", DataTable.class); Feature feature = TestFeatureParser.parse("" + "Feature: Test feature\n" + " Scenario: Test scenario\n" + " Given some text\n" + " | Birth Date | \n" + " | 1957-05-10 | \n"); DataTable stepDefs = runStepDef(m, true, feature); assertAll( () -> assertThat(stepDefs.cell(0, 0), is(equalTo("Birth Date"))), () -> assertThat(stepDefs.cell(0, 1), is(equalTo("1957-05-10")))); } @SuppressWarnings({ "WeakerAccess", "unused" }) public static class Steps { public void listOfListOfDoubles(List<List<Double>> listOfListOfDoubles) { } public void plainDataTable(DataTable dataTable) { } public void mapOfDoubleToDouble(Map<Double, Double> mapOfDoubleToDouble) { } public void transposedMapOfDoubleToListOfDouble(Map<Double, List<Double>> mapOfDoubleToListOfDouble) { } } }
package apimodels; import com.fasterxml.jackson.annotation.*; import io.ebean.Finder; import io.ebean.Model; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; public class ReceivedAccessPoint extends Model{ public String getMac() { return mac; } public Integer getPower() { return power; } @JsonProperty("mac") private String mac = null; @JsonProperty("power") private Integer power = null; }
package com.snowcattle.game.service.net.http.handler.async; import com.snowcattle.game.bootstrap.manager.LocalMananger; import com.snowcattle.game.common.config.GameServerConfig; import com.snowcattle.game.common.constant.ServiceName; import com.snowcattle.game.service.IService; import com.snowcattle.game.service.config.GameServerConfigService; import com.snowcattle.game.service.net.http.NetHttpServerConfig; import com.snowcattle.game.service.net.http.SdHttpServerConfig; import io.netty.util.concurrent.DefaultEventExecutorGroup; import org.springframework.stereotype.Service; /** * Created by jiangwenping on 2017/7/3. */ @Service public class AsyncNettyHttpHandlerService implements IService { /** * handler线程组 */ private DefaultEventExecutorGroup defaultEventExecutorGroup; @Override public String getId() { return ServiceName.AsyncNettyHttpHandlerService; } @Override public void startup() throws Exception { GameServerConfigService gameServerConfigService = LocalMananger.getInstance().getLocalSpringServiceManager().getGameServerConfigService(); NetHttpServerConfig netHttpServerConfig = gameServerConfigService.getNetHttpServerConfig(); if(netHttpServerConfig != null) { SdHttpServerConfig sdHttpServerConfig = netHttpServerConfig.getSdHttpServerConfig(); if (sdHttpServerConfig != null) { int threadSize = sdHttpServerConfig.getHandleThreadSize(); defaultEventExecutorGroup = new DefaultEventExecutorGroup(threadSize); } } } @Override public void shutdown() throws Exception { if(defaultEventExecutorGroup != null){ defaultEventExecutorGroup.shutdownGracefully(); } } public DefaultEventExecutorGroup getDefaultEventExecutorGroup() { return defaultEventExecutorGroup; } public void setDefaultEventExecutorGroup(DefaultEventExecutorGroup defaultEventExecutorGroup) { this.defaultEventExecutorGroup = defaultEventExecutorGroup; } }
package com.asuka.common.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * Redis配置 * @author wujiawei0926@yeah.net * @see * @since 2020/7/11 */ @EnableCaching @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); RedisSerializer<?> redisSerializer = new StringRedisSerializer(); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(lettuceConnectionFactory); template.setKeySerializer(redisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(redisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
package org.scec.vtk.commons.opensha.surfaces; import java.util.ArrayList; import org.scec.vtk.commons.opensha.faults.AbstractFaultSection; import vtk.vtkActor; /** * Inner class designed to allow pick behaviors to discern instances of FaultSection objects. * Wrapping a Shape3D in this way ensures future compatibility if pick behaviors * are added to other SCEC-VIDEO objects. * THIS IS JUST COPIED FROM FaultAccessor class in Fault3DPlugin. Ideally, it can be put in some * UTILS package. */ public class FaultSectionActorList extends ArrayList<vtkActor> { private AbstractFaultSection fault; public FaultSectionActorList(AbstractFaultSection fault) { this.fault = fault; } /** * Returns the display name of this <code>FaultShape3D</code>. * * @return the display name of this fault */ public String getInfo() { return fault.getInfo(); } public AbstractFaultSection getFault() { return fault; } }
import java.util.Comparator; import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("qr") @Implements("UserComparator2") public class UserComparator2 implements Comparator { @ObfuscatedName("v") @Export("reversed") final boolean reversed; public UserComparator2(boolean var1) { this.reversed = var1; } @ObfuscatedName("v") @ObfuscatedSignature(descriptor = "(Lnn;Lnn;I)I", garbageValue = "812232162") @Export("compare_bridged") int compare_bridged(User var1, User var2) { return this.reversed ? var1.getUsername().compareToTyped(var2.getUsername()) : var2.getUsername().compareToTyped(var1.getUsername()); } public int compare(Object var1, Object var2) { return this.compare_bridged(((User) (var1)), ((User) (var2))); } public boolean equals(Object var1) { return super.equals(var1); } }
package net.minecraft.util.datafix.fixes; import com.mojang.datafixers.DSL; import com.mojang.datafixers.DataFix; import com.mojang.datafixers.TypeRewriteRule; import com.mojang.datafixers.schemas.Schema; import com.mojang.datafixers.types.Type; import com.mojang.datafixers.util.Pair; import java.util.Map; import java.util.Objects; import net.minecraft.util.datafix.schemas.NamespacedSchema; public class RenameBiomesFix extends DataFix { private final String name; private final Map<String, String> biomes; public RenameBiomesFix(Schema p_16837_, boolean p_16838_, String p_16839_, Map<String, String> p_16840_) { super(p_16837_, p_16838_); this.biomes = p_16840_; this.name = p_16839_; } protected TypeRewriteRule makeRule() { Type<Pair<String, String>> type = DSL.named(References.BIOME.typeName(), NamespacedSchema.namespacedString()); if (!Objects.equals(type, this.getInputSchema().getType(References.BIOME))) { throw new IllegalStateException("Biome type is not what was expected."); } else { return this.fixTypeEverywhere(this.name, type, (p_16844_) -> { return (p_145634_) -> { return p_145634_.mapSecond((p_145636_) -> { return this.biomes.getOrDefault(p_145636_, p_145636_); }); }; }); } } }
package com.wook.realworld.exception; public class UsernameAlreadyExistsException extends RealWorldRuntimeException { private static final String MESSAGE = "이미 등록 된 이름이 있습니다."; public UsernameAlreadyExistsException() { super(MESSAGE); } public UsernameAlreadyExistsException(final Throwable cause) { super(MESSAGE, cause); } }
package com.ulisesbocchio.jasyptspringboot.environment; import com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorConfiguration; import com.ulisesbocchio.jasyptspringboot.encryptor.LazyStringEncryptor; import org.jasypt.encryption.StringEncryptor; import org.jasypt.properties.PropertyValueEncryptionUtils; import org.springframework.core.convert.support.ConfigurableConversionService; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MissingRequiredPropertiesException; import org.springframework.core.env.MutablePropertySources; import java.util.Map; /** * @author Ulises Bocchio */ public class EncryptableEnvironment implements ConfigurableEnvironment { private final ConfigurableEnvironment delegate; private StringEncryptor encryptor; public EncryptableEnvironment(ConfigurableEnvironment delegate) { this(delegate, discoverEncryptor(delegate)); } public EncryptableEnvironment(ConfigurableEnvironment delegate, StringEncryptor encryptor) { super(); this.delegate = delegate; this.encryptor = encryptor; } private static StringEncryptor discoverEncryptor(ConfigurableEnvironment delegate) { return new LazyStringEncryptor(StringEncryptorConfiguration.DEFAULT_LAZY_ENCRYPTOR_FACTORY, delegate); } @Override public void addActiveProfile(String profile) { delegate.addActiveProfile(profile); } @Override public MutablePropertySources getPropertySources() { return delegate.getPropertySources(); } @Override public Map<String, Object> getSystemEnvironment() { return delegate.getSystemEnvironment(); } @Override public Map<String, Object> getSystemProperties() { return delegate.getSystemProperties(); } @Override public void merge(ConfigurableEnvironment parent) { delegate.merge(parent); } @Override public ConfigurableConversionService getConversionService() { return delegate.getConversionService(); } @Override public void setConversionService(ConfigurableConversionService conversionService) { delegate.setConversionService(conversionService); } @Override public void setPlaceholderPrefix(String placeholderPrefix) { delegate.setPlaceholderPrefix(placeholderPrefix); } @Override public void setPlaceholderSuffix(String placeholderSuffix) { delegate.setPlaceholderSuffix(placeholderSuffix); } @Override public void setValueSeparator(String valueSeparator) { delegate.setValueSeparator(valueSeparator); } @Override public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) { delegate.setIgnoreUnresolvableNestedPlaceholders(ignoreUnresolvableNestedPlaceholders); } @Override public void setRequiredProperties(String... requiredProperties) { delegate.setRequiredProperties(requiredProperties); } @Override public void validateRequiredProperties() throws MissingRequiredPropertiesException { delegate.validateRequiredProperties(); } @Override public String[] getActiveProfiles() { return delegate.getActiveProfiles(); } @Override public void setActiveProfiles(String... profiles) { delegate.setActiveProfiles(profiles); } @Override public String[] getDefaultProfiles() { return delegate.getDefaultProfiles(); } @Override public void setDefaultProfiles(String... profiles) { delegate.setDefaultProfiles(profiles); } @Override public boolean acceptsProfiles(String... profiles) { return delegate.acceptsProfiles(profiles); } @Override public boolean containsProperty(String key) { return delegate.containsProperty(key); } @Override public String getProperty(String key) { return maybeDecrypt(delegate.getProperty(key)); } private String maybeDecrypt(String property) { if (PropertyValueEncryptionUtils.isEncryptedValue(property)) { return PropertyValueEncryptionUtils.decrypt(property, encryptor); } return property; } @Override public String getProperty(String key, String defaultValue) { return maybeDecrypt(delegate.getProperty(key, defaultValue)); } @Override public <T> T getProperty(String key, Class<T> targetType) { T property = delegate.getProperty(key, targetType); if (property != null && targetType == String.class) { property = (T) maybeDecrypt((String) property); } return property; } @Override public <T> T getProperty(String key, Class<T> targetType, T defaultValue) { T property = delegate.getProperty(key, targetType, defaultValue); if (property != null && targetType == String.class) { property = (T) maybeDecrypt((String) property); } return property; } @Override public <T> Class<T> getPropertyAsClass(String key, Class<T> targetType) { return delegate.getPropertyAsClass(key, targetType); } @Override public String getRequiredProperty(String key) throws IllegalStateException { return maybeDecrypt(delegate.getRequiredProperty(key)); } @Override public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException { T property = delegate.getRequiredProperty(key, targetType); if (property != null && targetType == String.class) { property = (T) maybeDecrypt((String) property); } return property; } @Override public String resolvePlaceholders(String text) { return delegate.resolvePlaceholders(text); } @Override public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException { return delegate.resolveRequiredPlaceholders(text); } }
package org.opencds.cqf.tooling.terminology.distributable; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.ContactDetail; import org.hl7.fhir.r4.model.ContactPoint; import org.hl7.fhir.r4.model.Extension; import org.hl7.fhir.r4.model.ValueSet; import org.hl7.fhir.r4.model.DateType; public class OrganizationalMetaData { private String canonicalUrlBase; private String copyright; private String jurisdiction; private String publisher; private String approvalDate; private String effectiveDate; private String lastReviewDate; private String authorName; private String authorTelecomSystem; private String authorTelecomValue; private String snomedVersion; private final String JURISDICTION_URL = "urn:iso:std:iso:3166"; private final String APPROVAL_DATE_URL = "http://hl7.org/fhir/StructureDefinition/resource-approvalDate"; private final String EFFECTIVE_DATE_URL = "http://hl7.org/fhir/StructureDefinition/valueset-effectiveDate"; private final String LAST_REVIEW_DATE_URL = "http://hl7.org/fhir/StructureDefinition/resource-lastReviewDate"; private final String AUTHOR_URL = "http://hl7.org/fhir/StructureDefinition/valueset-author"; public void populate(ValueSet valueSet) { if (!valueSet.hasId()) { throw new RuntimeException("Metadata template must include an id"); } valueSet.setUrl(canonicalUrlBase + "/ValueSet/" + valueSet.getId()); valueSet.setCopyright(copyright); valueSet.addJurisdiction( new CodeableConcept().addCoding(new Coding().setSystem(JURISDICTION_URL).setCode(jurisdiction)) ); valueSet.setPublisher(publisher); if (approvalDate != null) { valueSet.addExtension(new Extension().setUrl(APPROVAL_DATE_URL).setValue(new DateType(approvalDate))); } if (effectiveDate != null) { valueSet.addExtension(new Extension().setUrl(EFFECTIVE_DATE_URL).setValue(new DateType(effectiveDate))); } if (lastReviewDate != null) { valueSet.addExtension(new Extension().setUrl(LAST_REVIEW_DATE_URL).setValue(new DateType(lastReviewDate))); } if (authorName != null || authorTelecomSystem != null || authorTelecomValue != null) { ContactDetail authorDetail = new ContactDetail() .setName(authorName) .addTelecom( new ContactPoint() .setSystem(ContactPoint.ContactPointSystem.fromCode(authorTelecomSystem)) .setValue(authorTelecomValue) ); valueSet.addExtension(new Extension().setUrl(AUTHOR_URL).setValue(authorDetail)); } } public String getCanonicalUrlBase() { return canonicalUrlBase; } public void setCanonicalUrlBase(String canonicalUrlBase) { this.canonicalUrlBase = canonicalUrlBase; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } public String getJurisdiction() { return jurisdiction; } public void setJurisdiction(String jurisdiction) { this.jurisdiction = jurisdiction; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getAuthorTelecomSystem() { return authorTelecomSystem; } public void setAuthorTelecomSystem(String authorTelecomSystem) { this.authorTelecomSystem = authorTelecomSystem; } public String getAuthorTelecomValue() { return authorTelecomValue; } public void setAuthorTelecomValue(String authorTelecomValue) { this.authorTelecomValue = authorTelecomValue; } public String getApprovalDate() { return approvalDate; } public void setApprovalDate(String approvalDate) { this.approvalDate = approvalDate; } public String getEffectiveDate() { return effectiveDate; } public void setEffectiveDate(String effectiveDate) { this.effectiveDate = effectiveDate; } public String getLastReviewDate() { return lastReviewDate; } public void setLastReviewDate(String lastReviewDate) { this.lastReviewDate = lastReviewDate; } public String getSnomedVersion() { return snomedVersion; } public void setSnomedVersion(String snomedVersion) { this.snomedVersion = snomedVersion; } }
package dao; import models.Departments; import models.Users; import java.util.List; public interface UsersDao { //create void addUser(Users user); void addDeptToUser( Users user,Departments department); //read //update List<Users> getAll(); List<Departments> getAllDepartmentsUsers(int user_id); Users findById(int id); //delete void clearAllUsers(); }
/* * Copyright 2013-present Facebook, Inc. * * 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 com.facebook.buck.event; import com.google.common.collect.Lists; import com.google.common.eventbus.Subscribe; import java.util.List; public class FakeBuckEventListener { private final List<BuckEvent> events = Lists.newLinkedList(); @Subscribe @SuppressWarnings("unused") public void eventFired(BuckEvent event) { events.add(event); } public List<BuckEvent> getEvents() { return events; } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_06_01.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.microsoft.azure.management.network.v2019_06_01.ExpressRoutePort; import rx.Observable; import com.microsoft.azure.management.network.v2019_06_01.ExpressRoutePortsEncapsulation; import java.util.List; import com.microsoft.azure.SubResource; import java.util.ArrayList; import com.microsoft.azure.management.network.v2019_06_01.ExpressRouteLink; class ExpressRoutePortImpl extends GroupableResourceCoreImpl<ExpressRoutePort, ExpressRoutePortInner, ExpressRoutePortImpl, NetworkManager> implements ExpressRoutePort, ExpressRoutePort.Definition, ExpressRoutePort.Update { ExpressRoutePortImpl(String name, ExpressRoutePortInner inner, NetworkManager manager) { super(name, inner, manager); } @Override public Observable<ExpressRoutePort> createResourceAsync() { ExpressRoutePortsInner client = this.manager().inner().expressRoutePorts(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<ExpressRoutePort> updateResourceAsync() { ExpressRoutePortsInner client = this.manager().inner().expressRoutePorts(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<ExpressRoutePortInner> getInnerAsync() { ExpressRoutePortsInner client = this.manager().inner().expressRoutePorts(); return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public String allocationDate() { return this.inner().allocationDate(); } @Override public Integer bandwidthInGbps() { return this.inner().bandwidthInGbps(); } @Override public List<SubResource> circuits() { return this.inner().circuits(); } @Override public ExpressRoutePortsEncapsulation encapsulation() { return this.inner().encapsulation(); } @Override public String etag() { return this.inner().etag(); } @Override public String etherType() { return this.inner().etherType(); } @Override public List<ExpressRouteLink> links() { List<ExpressRouteLink> lst = new ArrayList<ExpressRouteLink>(); if (this.inner().links() != null) { for (ExpressRouteLinkInner inner : this.inner().links()) { lst.add( new ExpressRouteLinkImpl(inner, manager())); } } return lst; } @Override public String mtu() { return this.inner().mtu(); } @Override public String peeringLocation() { return this.inner().peeringLocation(); } @Override public Double provisionedBandwidthInGbps() { return this.inner().provisionedBandwidthInGbps(); } @Override public String provisioningState() { return this.inner().provisioningState(); } @Override public String resourceGuid() { return this.inner().resourceGuid(); } @Override public ExpressRoutePortImpl withBandwidthInGbps(Integer bandwidthInGbps) { this.inner().withBandwidthInGbps(bandwidthInGbps); return this; } @Override public ExpressRoutePortImpl withEncapsulation(ExpressRoutePortsEncapsulation encapsulation) { this.inner().withEncapsulation(encapsulation); return this; } @Override public ExpressRoutePortImpl withLinks(List<ExpressRouteLinkInner> links) { this.inner().withLinks(links); return this; } @Override public ExpressRoutePortImpl withPeeringLocation(String peeringLocation) { this.inner().withPeeringLocation(peeringLocation); return this; } @Override public ExpressRoutePortImpl withResourceGuid(String resourceGuid) { this.inner().withResourceGuid(resourceGuid); return this; } }
/* * @(#)ProcFormalParameter.java 2.1 2003/10/07 * * Copyright (C) 1999, 2003 D.A. Watt and D.F. Brown * Dept. of Computing Science, University of Glasgow, Glasgow G12 8QQ Scotland * and School of Computer and Math Sciences, The Robert Gordon University, * St. Andrew Street, Aberdeen AB25 1HG, Scotland. * All rights reserved. * * This software is provided free for educational use only. It may * not be used for commercial purposes without the prior written permission * of the authors. */ package Triangle.AbstractSyntaxTrees; import Triangle.SyntacticAnalyzer.SourcePosition; public class ProcFormalParameter extends FormalParameter { public ProcFormalParameter(Identifier iAST, FormalParameterSequence fpsAST, SourcePosition thePosition) { super(thePosition); I = iAST; FPS = fpsAST; } public Object visit(Visitor v, Object o) { return v.visitProcFormalParameter(this, o); } public Identifier I; public FormalParameterSequence FPS; public boolean equals(Object fpAST) { if (fpAST instanceof ProcFormalParameter) { ProcFormalParameter pfpAST = (ProcFormalParameter) fpAST; return FPS.equals(pfpAST.FPS); } else return false; } }
package org.jyg.gameserver.example.ygserver; import org.jyg.gameserver.db.BaseDBEntity; import org.jyg.gameserver.db.anno.DBTable; import org.jyg.gameserver.db.anno.DBTableFieldIgnore; @DBTable(tableName = "player") public class PlayerDB extends BaseDBEntity { private long id; private String name; private String password; @DBTableFieldIgnore private String content; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package pkg; sealed interface TestSealedInterfaces { } sealed class PermittedSubClassC implements TestSealedInterfaces { } non-sealed class PermittedSubClassD extends PermittedSubClassC { } non-sealed class PermittedSubClassE implements TestSealedInterfaces { } sealed interface PermittedSubInterfaceA extends TestSealedInterfaces { } non-sealed interface PermittedSubInterfaceB extends PermittedSubInterfaceA { }
/* * Copyright 2013-2022 Step Function I/O, LLC * * Licensed to Green Energy Corp (www.greenenergycorp.com) and Step Function I/O * LLC (https://stepfunc.io) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Green Energy Corp and Step Function I/O LLC license * this file to you 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 com.automatak.dnp3.impl; import com.automatak.dnp3.DNP3Manager; import com.automatak.dnp3.impl.mocks.NullLogHandler; import com.automatak.dnp3.impl.mocks.StackPair; import junit.framework.TestCase; import org.junit.Test; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class DNP3ManagerIntegrationTest extends TestCase { static final int NUM_STACKS = 10; static final int NUM_POINTS_PER_EVENT_TYPE = 50; static final int NUM_ITERATIONS = 10; static final int EVENTS_PER_ITERATION = 50; static final int START_PORT = 20010; static final int NUM_THREADS_IN_POOL = 4; static final Duration TIMEOUT = Duration.ofSeconds(10); static void withManager(int numThreads, Consumer<DNP3Manager> func) { final DNP3Manager manager = DNP3ManagerFactory.createManager(numThreads, new NullLogHandler()); try { func.accept(manager); } finally { manager.shutdown(); } } @Test public void testEventOrdering() { List<StackPair> stacks = new ArrayList<>(); withManager(NUM_THREADS_IN_POOL, manager -> { for(int i = 0; i < NUM_STACKS; ++i) { StackPair pair = new StackPair(manager, START_PORT+i, NUM_POINTS_PER_EVENT_TYPE, EVENTS_PER_ITERATION); stacks.add(pair); } final long start = System.currentTimeMillis(); stacks.forEach(pair -> pair.waitForChannelsOpen(TIMEOUT)); for(int i = 0; i < NUM_ITERATIONS; ++i) { stacks.forEach(pair -> pair.sendRandomValues()); stacks.forEach(pair -> pair.awaitSentValues(TIMEOUT)); } final long ELASPED_MS = System.currentTimeMillis() - start; final long TOTAL_EVENTS = NUM_STACKS*NUM_ITERATIONS*EVENTS_PER_ITERATION; final long RATE = (TOTAL_EVENTS * 1000)/ ELASPED_MS; System.out.println(String.format("%d events in %d ms == %d events/sec", TOTAL_EVENTS, ELASPED_MS, RATE)); }); } @Test public void testCommandOrdering() { List<StackPair> stacks = new ArrayList<>(); withManager(NUM_THREADS_IN_POOL, manager -> { for(int i = 0; i < NUM_STACKS; ++i) { StackPair pair = new StackPair(manager, START_PORT+i, NUM_POINTS_PER_EVENT_TYPE, EVENTS_PER_ITERATION); stacks.add(pair); } final long start = System.currentTimeMillis(); stacks.forEach(pair -> pair.waitForChannelsOpen(TIMEOUT)); for(int i = 0; i < NUM_ITERATIONS; ++i) { stacks.forEach(pair -> pair.sendRandomCommands()); stacks.forEach(pair -> pair.awaitSentCommands(TIMEOUT)); } final long ELASPED_MS = System.currentTimeMillis() - start; final long TOTAL_EVENTS = NUM_STACKS*NUM_ITERATIONS*EVENTS_PER_ITERATION; final long RATE = (TOTAL_EVENTS * 1000)/ ELASPED_MS; System.out.println(String.format("%d commands in %d ms == %d commands/sec", TOTAL_EVENTS, ELASPED_MS, RATE)); }); } }
package com.funi.muyq.demo.study.pattern.factory.abstractFactory; /** * @Author: [muyuanqiang] * @CreateDate: [2018/6/5 09:32] */ public class HisenseHouseholdAppliancesFactory implements HouseholdAppliancesFactory { public TV createTV() { return new HisenseTV(); } public Fridge createFridge() { return new HisenseFridge(); } }
package org.owasp.oag.hooks.session; import org.owasp.oag.session.Session; import org.owasp.oag.session.UserModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; @Component public class SessionHookChain { private final List<SessionHook> hooks; public SessionHookChain(@Autowired ApplicationContext context){ hooks = getSessionHooks(context); } public void createSession(String providerKey, UserModel model, ServerHttpResponse response) { var filterContext = new HashMap<String, Object>(); filterContext.put("providerKey", providerKey); filterContext.put("userModel", model); hooks.forEach(h -> h.createSession(filterContext, response)); } public void renewSession(Session oldSession, ServerHttpResponse response) { var filterContext = new HashMap<String, Object>(); filterContext.put("old-session", oldSession); hooks.forEach(h -> h.renewSession(filterContext, response)); } public void destroySession(ServerWebExchange exchange){ var filterContext = new HashMap<String, Object>(); hooks.forEach(h -> h.destroySession(filterContext, exchange)); } private List<SessionHook> getSessionHooks(ApplicationContext context) { var filters = context.getBeansOfType(SessionHook.class); List<SessionHook> sessionFilters = filters.values().stream() .sorted(Comparator.comparingInt(SessionHook::order)) .collect(Collectors.toList()); return sessionFilters; } }
package com.example.rohangupta.bottom_navigation_sample.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.rohangupta.bottom_navigation_sample.R; public class NewsFragment extends Fragment { public NewsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_news, container, false); } }
package org.osmdroid.samplefragments.events; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import org.osmdroid.R; import org.osmdroid.samplefragments.BaseSampleFragment; import org.osmdroid.util.BoundingBox; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.TileSystem; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Polygon; import java.util.ArrayList; import java.util.List; /** * Created by alex on 10/4/16. */ public class SampleZoomToBounding extends BaseSampleFragment implements View.OnClickListener { private static final int border = 10; private final TileSystem tileSystem = MapView.getTileSystem(); private Polygon polygon; /** * @since 6.1.0 * south, north */ private final double[] mSampleLatitudes = new double[] {0, 85, -85, 0}; /** * @since 6.1.0 */ private int mSampleLatitudeIndex; /** * @since 6.1.0 * west, east */ private final double[] mSampleLongitudes = new double[] {0, 10, 0, 10}; /** * @since 6.1.0 */ private int mSampleLongitudeIndex; @Override public String getSampleTitle() { return "Zoom to Bounding Box"; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.sample_cachemgr, container,false); mMapView = new MapView(getActivity()); ((LinearLayout) root.findViewById(R.id.mapview)).addView(mMapView); polygon = new Polygon(mMapView); final Button btnCache = root.findViewById(R.id.btnCache); btnCache.setOnClickListener(this); btnCache.setText("Zoom to bounds"); polygon.setStrokeColor(Color.parseColor("#990000FF")); polygon.setStrokeWidth(2); polygon.setFillColor(Color.parseColor("#330000FF")); mMapView.getOverlays().add(polygon); return root; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnCache: boolean ok = false; while (!ok) { final double south = getRandomLatitude(tileSystem.getMinLatitude()); final double north = getRandomLatitude(south); final double west = getRandomLongitude(); double east = getRandomLongitude(); final BoundingBox boundingBox = new BoundingBox(north, east, south, west); final double zoom = tileSystem.getBoundingBoxZoom(boundingBox, mMapView.getWidth() - 2 * border, mMapView.getHeight() - 2 * border); ok = zoom >= mMapView.getMinZoomLevel() && zoom <= mMapView.getMaxZoomLevel(); if (ok) { final String text = "with a border of " + border + " the computed zoom is " + zoom + " for box " + boundingBox; Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show(); final List<GeoPoint> points = new ArrayList<>(); if (west > east) { east += 360; } addPoints(points, north, west, north, east); addPoints(points, north, east, south, east); addPoints(points, south, east, south, west); addPoints(points, south, west, north, west); polygon.setPoints(points); mMapView.invalidate(); mMapView.zoomToBoundingBox(boundingBox, true, border); } } break; } } /** * Add a succession of GeoPoint's, separated by an increment, * taken from the segment between two GeoPoint's * @since 6.0.0 */ private void addPoints(final List<GeoPoint> pPoints, final double pBeginLat, final double pBeginLon, final double pEndLat, final double pEndLon) { final double increment = 10; // in degrees pPoints.add(new GeoPoint(pBeginLat, pBeginLon)); double lat = pBeginLat; double lon = pBeginLon; double incLat = pBeginLat == pEndLat ? 0 : pBeginLat < pEndLat ? increment : -increment; double incLon = pBeginLon == pEndLon ? 0 : pBeginLon < pEndLon ? increment : -increment; while (true) { if (incLat != 0) { lat += incLat; if (incLat < 0) { if (lat < pEndLat) { break; } } else { if (lat > pEndLat) { break; } } } if (incLon != 0) { lon += incLon; if (incLon < 0) { if (lon < pEndLon) { break; } } else { if (lon > pEndLon) { break; } } } pPoints.add(new GeoPoint(lat, lon)); } pPoints.add(new GeoPoint(pEndLat, pEndLon)); } private double getRandomLongitude() { if (mSampleLongitudeIndex < mSampleLongitudes.length) { return mSampleLongitudes[mSampleLongitudeIndex ++]; } return tileSystem.getRandomLongitude(Math.random()); } private double getRandomLatitude(final double pMinLatitude) { if (mSampleLatitudeIndex < mSampleLatitudes.length) { return mSampleLatitudes[mSampleLatitudeIndex ++]; } return tileSystem.getRandomLatitude(Math.random(), pMinLatitude); } }
package jsky.app.ot.gemini.nfiraos; import edu.gemini.shared.util.immutable.Option; import edu.gemini.shared.util.immutable.Some; import edu.gemini.shared.util.immutable.None; import edu.gemini.skycalc.Angle; import edu.gemini.skycalc.Offset; import edu.gemini.spModel.gemini.nfiraos.NfiraosOiwfs; import edu.gemini.spModel.guide.GuideProbe; import edu.gemini.spModel.obs.context.ObsContext; import edu.gemini.spModel.obscomp.SPInstObsComp; import edu.gemini.spModel.target.SPTarget; import edu.gemini.spModel.target.WatchablePos; import edu.gemini.spModel.target.env.GuideProbeTargets; import edu.gemini.spModel.target.env.TargetEnvironment; import edu.gemini.spModel.target.env.TargetEnvironmentDiff; import edu.gemini.spModel.target.offset.OffsetPosBase; import jsky.app.ot.gemini.inst.OiwfsPlotFeature$; import jsky.app.ot.tpe.*; import jsky.app.ot.tpe.feat.TpeGuidePosCreatableItem; import jsky.app.ot.util.BasicPropertyList; import jsky.app.ot.util.OtColor; import jsky.app.ot.util.PropertyWatcher; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.beans.PropertyChangeListener; import java.util.Collection; import java.util.Collections; /** * Draws the Nfiraos AO field of view and probe ranges. */ public final class NfiraosFeature extends TpeImageFeature implements PropertyWatcher, TpeModeSensitive, TpeDragSensitive { private AffineTransform trans; private boolean isEmpty; // Color for AO WFS limit. private static final Color AO_FOV_COLOR = Color.RED; private static final Color PROBE_RANGE_COLOR = OtColor.SALMON; // Composite used for drawing items that block the view private static final Composite BLOCKED = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F); // Property used to control drawing of the probe ranges. private static final BasicPropertyList props = new BasicPropertyList(NfiraosFeature.class.getName()); private static final String PROP_SHOW_RANGES = "Show Probe Ranges"; static { props.registerBooleanProperty(PROP_SHOW_RANGES, true); } // // XXX TODO FIXME: Is this needed? private enum RangeDisplayMode { probe1(true, false, false), probe2(false, true, false), probe3(false, false, true), all(true, true, true); private final boolean show1; private final boolean show2; private final boolean show3; RangeDisplayMode(boolean show1, boolean show2, boolean show3) { this.show1 = show1; this.show2 = show2; this.show3 = show3; } boolean show1() { return show1; } boolean show2() { return show2; } boolean show3() { return show3; } } private RangeDisplayMode rangeMode = RangeDisplayMode.all; /** * Construct the feature with its name and description. */ public NfiraosFeature() { super("Nfiraos", "Show the field of view of the Nfiraos WFS probes."); } /** * The position angle has changed. */ public void posAngleUpdate(TpeImageInfo tii) { reinit(); } /** * A property has changed. * * @see PropertyWatcher */ public void propertyChange(String propName) { _iw.repaint(); } /** * Override getProperties to return the properties supported by this * feature. */ @Override public BasicPropertyList getProperties() { return props; } /** * Turn on/off the drawing of probe ranges. */ public void setDrawProbeRanges(boolean draw) { props.setBoolean(PROP_SHOW_RANGES, draw); } /** * Gets the drawing of probe ranges. */ private boolean getDrawProbeRanges() { return props.getBoolean(PROP_SHOW_RANGES, true); } private PropertyChangeListener selListener = evt -> _redraw(); /** * Reinitialize (recalculate the positions and redraw). */ public void reinit(TpeImageWidget iw, TpeImageInfo tii) { _stopMonitorOffsetSelections(selListener); super.reinit(iw, tii); props.addWatcher(this); SPInstObsComp inst = _iw.getInstObsComp(); if (inst == null) return; // arrange to be notified if telescope positions are added, removed, or selected _monitorPosList(); // Monitor the selections of offset positions, since that affects the positions drawn _monitorOffsetSelections(selListener); double ppa = tii.getPixelsPerArcsec(); // Use selected offset position, rotated by position angle, if defined double posAngle = tii.getCorrectedPosAngleRadians(); double pixelsPerArcsec = tii.getPixelsPerArcsec(); Point2D.Double baseScreenPos = tii.getBaseScreenPos(); TpeContext ctx = _iw.getContext(); OffsetPosBase selectedOffsetPos = ctx.offsets().selectedPosOrNull(); double basePosX = baseScreenPos.x, basePosY = baseScreenPos.y; if (selectedOffsetPos != null) { // Get offset from base pos in pixels // Note that the offset positions rotate with the instrument. Point2D.Double p = new Point2D.Double( selectedOffsetPos.getXaxis() * pixelsPerArcsec, selectedOffsetPos.getYaxis() * pixelsPerArcsec); edu.gemini.spModel.util.Angle.rotatePoint(p, posAngle); double offsetX = p.x; double offsetY = p.y; basePosX -= offsetX; basePosY -= offsetY; } Point2D.Double offsetBaseScreenPos = new Point2D.Double(basePosX, basePosY); trans = new AffineTransform(); trans.translate(offsetBaseScreenPos.x, offsetBaseScreenPos.y); // The model already used the position angle, so just rotate by the difference between north and up in the image trans.rotate(-tii.getTheta()); trans.scale(ppa, ppa); } @Override public void unloaded() { props.deleteWatcher(this); super.unloaded(); } /** * Implements the TelescopePosWatcher interface. */ public void telescopePosLocationUpdate(WatchablePos tp) { _redraw(); } /** * Implements the TelescopePosWatcher interface. */ public void telescopePosGenericUpdate(WatchablePos tp) { _redraw(); } protected void handleTargetEnvironmentUpdate(TargetEnvironmentDiff diff) { _redraw(); } /** * Schedule a redraw of the image feature. */ private void _redraw() { if (_iw != null) _iw.repaint(); } // Slant of the lines drawn in the probe 1 and 2 ranges. Slant at a // 45 degree angle either falling (down) \ or rising (up) / private enum Orientation { vertical, horizontal, } // Creates a Paint that is used for filling the probe 1 and 2 ranges. private static Paint createProbeRangePaint(Graphics2D g2d, Orientation s, Color color) { return createProbeRangePaint(g2d, s, 16, 0.16, 0.4, color); } private static Paint createProbeRangeKeyPaint(Graphics2D g2d, Orientation s, Color color) { return createProbeRangePaint(g2d, s, 8, 0.32, 0.8, color); } private static Paint createProbeRangePaint(Graphics2D g2d, Orientation s, int skip, double alphaBg, double alphaLine, Color color) { final int size = skip * 2; final Rectangle2D.Double rec = new Rectangle2D.Double(0, 0, size, size); // Get a buffered image capable of being transparent. BufferedImage bim = g2d.getDeviceConfiguration().createCompatibleImage(size, size, Transparency.TRANSLUCENT); Graphics2D bimg = bim.createGraphics(); // Shade it with a light red color almost completely transparent. bimg.setColor(OtColor.makeTransparent(color, alphaBg)); bimg.setComposite(AlphaComposite.Src); bimg.fill(rec); // Now draw the slanting lines, which are also pretty transparent // though not quite as much as the background. bimg.setClip(0, 0, size, size); bimg.setColor(OtColor.makeTransparent(color, alphaLine)); if (s == Orientation.vertical) { for (int x = 0; x < size; x += skip) { bimg.drawLine(x, 0, x, size); } } else { for (int y = 0; y < size; y += skip) { bimg.drawLine(0, y, size, y); } } bimg.dispose(); return new TexturePaint(bim, rec); } // If _flipRA is -1, flip the RA axis of the area private Area flipArea(Area a) { if (_flipRA == -1) { a = a.createTransformedArea(AffineTransform.getScaleInstance(_flipRA, 1.0)); } return a; } // Rotate the selected offset position by the pos angle (Must be a better way to do this...). private Offset rotateByPosAngle(ObsContext ctx, OffsetPosBase selectedOffsetPos) { if (selectedOffsetPos == null) return new Offset(Angle.ANGLE_0DEGREES, Angle.ANGLE_0DEGREES); Offset offset = selectedOffsetPos.toSkycalcOffset(); double p = offset.p().toArcsecs().getMagnitude(); double q = offset.q().toArcsecs().getMagnitude(); double a = ctx.getPositionAngle().toRadians(); Point2D.Double pd = new Point2D.Double(p, q); edu.gemini.spModel.util.Angle.rotatePoint(pd, a); return new Offset(new Angle(pd.x, Angle.Unit.ARCSECS), new Angle(pd.y, Angle.Unit.ARCSECS)); } /** * Draw the feature. */ public void draw(Graphics g, TpeImageInfo tii) { TpeContext tpeCtx = _iw.getContext(); if (!isEnabled(tpeCtx)) return; if (trans == null) return; Graphics2D g2d = (Graphics2D) g; Color oldColor = g2d.getColor(); Option<ObsContext> ctxOpt = _iw.getObsContext(); if (ctxOpt.isEmpty()) return; ObsContext ctx = ctxOpt.getValue(); // Draw the AO window itself. A circle. Area a = new Area(NfiraosOiwfs.AO_BOUNDS); isEmpty = a.isEmpty(); if (isEmpty) return; // If aan offset pos is selected, use it Offset offset = rotateByPosAngle(ctx, tpeCtx.offsets().selectedPosOrNull()); Shape s = trans.createTransformedShape(flipArea(a)); g2d.setColor(AO_FOV_COLOR); g2d.draw(s); // Draw the probe ranges. if (getDrawProbeRanges()) { Area a1 = new Area(flipArea(NfiraosOiwfs.Wfs.oiwfs1.probeRange(ctx, Offset.ZERO_OFFSET))).createTransformedArea(trans); Area a2 = new Area(flipArea(NfiraosOiwfs.Wfs.oiwfs2.probeRange(ctx, Offset.ZERO_OFFSET))).createTransformedArea(trans); Area a3 = new Area(flipArea(NfiraosOiwfs.Wfs.oiwfs3.probeRange(ctx, Offset.ZERO_OFFSET))).createTransformedArea(trans); Stroke oldStroke = g2d.getStroke(); g2d.setStroke(OiwfsPlotFeature$.MODULE$.ThickDashedStroke()); g2d.setColor(OtColor.makeTransparent(AO_FOV_COLOR, 0.7)); g2d.draw(a1); g2d.setColor(OtColor.makeTransparent(AO_FOV_COLOR, 0.7)); g2d.draw(a2); g2d.setColor(OtColor.makeTransparent(AO_FOV_COLOR, 0.7)); g2d.draw(a3); // Paint p = g2d.getPaint(); // g2d.setPaint(createProbeRangePaint(g2d, Orientation.horizontal, PROBE_RANGE_COLOR)); // g2d.fill(a1); // // g2d.setPaint(createProbeRangePaint(g2d, Orientation.vertical, PROBE_RANGE_COLOR)); // g2d.fill(a2); // // g2d.setPaint(createProbeRangePaint(g2d, Orientation.vertical, PROBE_RANGE_COLOR)); // g2d.fill(a3); // g2d.setPaint(p); g2d.setStroke(oldStroke); } drawProbeArm(g2d, ctx, NfiraosOiwfs.Wfs.oiwfs1, offset); drawProbeArm(g2d, ctx, NfiraosOiwfs.Wfs.oiwfs2, offset); drawProbeArm(g2d, ctx, NfiraosOiwfs.Wfs.oiwfs3, offset); g2d.setColor(oldColor); } // draw the probe arm for the given wfs private void drawProbeArm(Graphics2D g2d, ObsContext ctx, NfiraosOiwfs.Wfs wfs, Offset offset) { wfs.probeArm(ctx, true, offset).foreach(a -> { if (a != null) { Shape s = trans.createTransformedShape(flipArea(a)); g2d.setColor(AO_FOV_COLOR); g2d.draw(s); Composite c = g2d.getComposite(); g2d.setComposite(BLOCKED); g2d.fill(s); g2d.setComposite(c); } }); } @Override public boolean isEnabled(TpeContext ctx) { return super.isEnabled(ctx) && ctx.nfiraos().isDefined(); } private void setRangeDisplayMode(RangeDisplayMode mode) { if (rangeMode == mode) return; rangeMode = mode; _redraw(); } public void handleModeChange(TpeMode mode, Option<Object> arg) { if ((mode != TpeMode.CREATE) || arg.isEmpty()) { setRangeDisplayMode(RangeDisplayMode.all); return; } Object value = arg.getValue(); if (!(value instanceof TpeGuidePosCreatableItem)) { setRangeDisplayMode(RangeDisplayMode.all); return; } TpeGuidePosCreatableItem item = (TpeGuidePosCreatableItem) value; GuideProbe guider = item.getGuideProbe(); if (guider == NfiraosOiwfs.Wfs.oiwfs1) { setRangeDisplayMode(RangeDisplayMode.probe1); } else if (guider == NfiraosOiwfs.Wfs.oiwfs2) { setRangeDisplayMode(RangeDisplayMode.probe2); } else { setRangeDisplayMode(RangeDisplayMode.all); } } private static boolean containsTarget(TargetEnvironment env, GuideProbe guider, SPTarget target) { final Option<GuideProbeTargets> gtOpt = env.getPrimaryGuideProbeTargets(guider); return gtOpt.exists(gt -> gt.containsTarget(target)); } public void handleDragStarted(Object dragObject, ObsContext context) { if (!(dragObject instanceof SPTarget)) return; SPTarget target = (SPTarget) dragObject; TargetEnvironment env = context.getTargets(); if (env == null) { setRangeDisplayMode(RangeDisplayMode.all); return; } if (containsTarget(env, NfiraosOiwfs.Wfs.oiwfs1, target)) { setRangeDisplayMode(RangeDisplayMode.probe1); } else if (containsTarget(env, NfiraosOiwfs.Wfs.oiwfs2, target)) { setRangeDisplayMode(RangeDisplayMode.probe2); } else { setRangeDisplayMode(RangeDisplayMode.all); } } public void handleDragStopped(ObsContext context) { setRangeDisplayMode(RangeDisplayMode.all); } private static class ProbeRangeIcon implements Icon { private final Orientation[] slants; ProbeRangeIcon(Orientation... slants) { this.slants = slants; } public int getIconWidth() { return 18; } public int getIconHeight() { return 18; } public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.black); g2d.fill(new Rectangle2D.Double(1, 1, 16, 16)); Paint origPaint = g2d.getPaint(); for (Orientation slant : slants) { Paint p = createProbeRangeKeyPaint(g2d, slant, PROBE_RANGE_COLOR); g2d.setPaint(p); g2d.fill(new Rectangle2D.Double(1, 1, 16, 16)); } g2d.setPaint(origPaint); } } @Override public Option<Component> getKey() { JPanel pan = new JPanel(new GridBagLayout()); pan.add(new JLabel("OIWFS1", new ProbeRangeIcon(Orientation.horizontal), JLabel.LEFT) {{ setForeground(Color.black); }}, new GridBagConstraints() {{ gridx = 0; gridy = 0; anchor = WEST; fill = HORIZONTAL; }} ); pan.add(new JLabel("OIWFS2", new ProbeRangeIcon(Orientation.vertical), JLabel.LEFT) {{ setForeground(Color.black); }}, new GridBagConstraints() {{ gridx = 1; gridy = 0; anchor = WEST; fill = HORIZONTAL; }} ); pan.add(new JLabel("Both", new ProbeRangeIcon(Orientation.horizontal, Orientation.vertical), JLabel.LEFT) {{ setForeground(Color.black); }}, new GridBagConstraints() {{ gridx = 2; gridy = 0; anchor = WEST; fill = HORIZONTAL; }} ); return new Some<>(pan); } public TpeImageFeatureCategory getCategory() { return TpeImageFeatureCategory.fieldOfView; } private static final TpeMessage WARNING = TpeMessage.warningMessage( "No valid region for OIWFS stars. Check offset positions."); public Option<Collection<TpeMessage>> getMessages() { if (!isEmpty) return None.instance(); return new Some<>(Collections.singletonList(WARNING)); } }
// Copyright 2017 The Closure Rules Authors. All Rights Reserved. // // 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 io.bazel.rules.closure.http; import dagger.BindsInstance; /** Component with lifecycle limited to individual HTTP request. */ public interface HttpRequestComponent<H extends HttpHandler> { /** Returns HTTP request handler. */ H handler(); /** Builder for {@link HttpRequestComponent}. */ public interface Builder< H extends HttpHandler, R extends HttpRequestComponent<H>, B extends Builder<H, R, B>> { /** Binds HTTP request to request object graph. */ @BindsInstance B request(HttpRequest request); /** Binds HTTP response to request object graph. */ @BindsInstance B response(HttpResponse response); /** Returns the request object graph. */ R build(); } }
package com.websystique.springsecurity.configuration; import com.websystique.springsecurity.service.RoleToUserProfileConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.websystique.springsecurity") public class AppConfig extends WebMvcConfigurerAdapter { @Autowired RoleToUserProfileConverter roleToUserProfileConverter; /** * Configure ViewResolvers to deliver preferred views. */ @Override public void configureViewResolvers(ViewResolverRegistry registry) { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); registry.viewResolver(viewResolver); } /** * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc... */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } /** * Configure Converter to be used. * In our example, we need a converter to convert string values[Roles] to UserProfiles in newUser.jsp */ @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(roleToUserProfileConverter); } /** * Configure MessageSource to lookup any validation/error message in internationalized property files */ @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } /** * Optional. It's only required when handling '.' in @PathVariables which otherwise ignore everything after last '.' in @PathVaidables argument. * It's a known bug in Spring [https://jira.spring.io/browse/SPR-6164], still present in Spring 4.1.7. * This is a workaround for this issue. */ @Override public void configurePathMatch(PathMatchConfigurer matcher) { matcher.setUseRegisteredSuffixPatternMatch(true); } }
package manager; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class HelperBase { WebDriver wd; public HelperBase(WebDriver wd) { this.wd = wd; } public boolean isElementPresent(By locator) { return wd.findElements(locator).size() > 0; } public void hideFooter(){ JavascriptExecutor js = (JavascriptExecutor) wd; js.executeScript("document.querySelector('footer').style.display='none';"); } public void pause(int millis) { try { Thread.sleep(millis); } catch (Exception e) { throw new RuntimeException(e); } } public void click(By locator) { wd.findElement(locator).click(); } public void type(By locator, String text) { if (text != null) { click(locator); wd.findElement(locator).clear(); wd.findElement(locator).sendKeys(text); } } public void scroll(int x,int y){ JavascriptExecutor js =(JavascriptExecutor) wd; js.executeScript("window.scrollBy(" + x + "," + y + ")"); } }
package org.ovirt.engine.ui.uicommonweb.models.profiles; import java.util.Collection; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.comparators.LexoNumericNameableComparator; import org.ovirt.engine.core.common.businessentities.network.VnicProfileView; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.QueryReturnValue; import org.ovirt.engine.core.common.queries.QueryType; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.help.HelpTag; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs; public class VnicProfileVmListModel extends SearchableListModel<VnicProfileView, VM> { public VnicProfileVmListModel() { setTitle(ConstantsManager.getInstance().getConstants().virtualMachinesTitle()); setHelpTag(HelpTag.virtual_machines); setHashName("virtual_machines"); //$NON-NLS-1$ setComparator(new LexoNumericNameableComparator<>()); updateActionAvailability(); } @Override protected void onEntityChanged() { super.onEntityChanged(); getSearchCommand().execute(); } @Override public void search() { if (getEntity() != null) { super.search(); } } @Override protected void syncSearch() { if (getEntity() == null) { return; } IdQueryParameters params = new IdQueryParameters(getEntity().getId()); params.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(QueryType.GetVmsByVnicProfileId, params, new AsyncQuery<QueryReturnValue>( returnValue -> setItems((Collection<VM>) returnValue.getReturnValue()))); } @Override protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); if (e.propertyName.equals("name")) { //$NON-NLS-1$ getSearchCommand().execute(); } } private void updateActionAvailability() { } @Override protected void onSelectedItemChanged() { super.onSelectedItemChanged(); updateActionAvailability(); } @Override protected void selectedItemsChanged() { super.selectedItemsChanged(); updateActionAvailability(); } @Override public void executeCommand(UICommand command) { super.executeCommand(command); } @Override protected String getListName() { return "VnicProfileVmListModel"; //$NON-NLS-1$ } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.search.aggregations.pipeline; import org.opensearch.common.io.stream.StreamInput; import org.opensearch.search.DocValueFormat; import org.opensearch.search.aggregations.InternalAggregation; import org.opensearch.search.aggregations.pipeline.BucketHelpers.GapPolicy; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class MaxBucketPipelineAggregator extends BucketMetricsPipelineAggregator { private List<String> maxBucketKeys; private double maxValue; MaxBucketPipelineAggregator(String name, String[] bucketsPaths, GapPolicy gapPolicy, DocValueFormat formatter, Map<String, Object> metadata) { super(name, bucketsPaths, gapPolicy, formatter, metadata); } /** * Read from a stream. */ public MaxBucketPipelineAggregator(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return MaxBucketPipelineAggregationBuilder.NAME; } @Override protected void preCollection() { maxBucketKeys = new ArrayList<>(); maxValue = Double.NEGATIVE_INFINITY; } @Override protected void collectBucketValue(String bucketKey, Double bucketValue) { if (bucketValue > maxValue) { maxBucketKeys.clear(); maxBucketKeys.add(bucketKey); maxValue = bucketValue; } else if (bucketValue.equals(maxValue)) { maxBucketKeys.add(bucketKey); } } @Override protected InternalAggregation buildAggregation(Map<String, Object> metadata) { String[] keys = maxBucketKeys.toArray(new String[maxBucketKeys.size()]); return new InternalBucketMetricValue(name(), keys, maxValue, format, metadata()); } }
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // Copyright (c) 2017 Citrix ShareFile. All rights reserved. // </auto-generated> // ------------------------------------------------------------------------------ package com.citrix.sharefile.api.models; import com.google.gson.annotations.SerializedName; public class SFEmailAddress extends SFODataObject { @SerializedName("Email") private String Email; @SerializedName("IsConfirmed") private Boolean IsConfirmed; @SerializedName("IsPrimary") private Boolean IsPrimary; public String getEmail() { return this.Email; } public void setEmail(String email) { this.Email = email; } public Boolean getIsConfirmed() { return this.IsConfirmed; } public void setIsConfirmed(Boolean isconfirmed) { this.IsConfirmed = isconfirmed; } public Boolean getIsPrimary() { return this.IsPrimary; } public void setIsPrimary(Boolean isprimary) { this.IsPrimary = isprimary; } }
package wechat.builder; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage; /** * @author Binary Wang(https://github.com/binarywang) */ public class TextBuilder extends AbstractBuilder { @Override public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WxMpService service) { WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content) .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) .build(); return m; } }
package ca.uhn.fhir.parser; /* * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2017 University Health Network * %% * 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. * #L% */ import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.text.WordUtils; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseBinary; import org.hl7.fhir.instance.model.api.IBaseBooleanDatatype; import org.hl7.fhir.instance.model.api.IBaseDecimalDatatype; import org.hl7.fhir.instance.model.api.IBaseExtension; import org.hl7.fhir.instance.model.api.IBaseHasExtensions; import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions; import org.hl7.fhir.instance.model.api.IBaseIntegerDatatype; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IDomainResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.INarrative; import org.hl7.fhir.instance.model.api.IPrimitiveType; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import ca.uhn.fhir.context.BaseRuntimeChildDefinition; import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition; import ca.uhn.fhir.context.BaseRuntimeElementDefinition; import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum; import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.context.RuntimeChildContainedResources; import ca.uhn.fhir.context.RuntimeChildDeclaredExtensionDefinition; import ca.uhn.fhir.context.RuntimeChildNarrativeDefinition; import ca.uhn.fhir.context.RuntimeChildUndeclaredExtensionDefinition; import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.model.api.BaseBundle; import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.BundleEntry; import ca.uhn.fhir.model.api.ExtensionDt; import ca.uhn.fhir.model.api.IPrimitiveDatatype; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions; import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; import ca.uhn.fhir.model.api.Tag; import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.base.composite.BaseCodingDt; import ca.uhn.fhir.model.base.composite.BaseContainedDt; import ca.uhn.fhir.model.primitive.DecimalDt; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.InstantDt; import ca.uhn.fhir.model.primitive.IntegerDt; import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.narrative.INarrativeGenerator; import ca.uhn.fhir.parser.json.GsonStructure; import ca.uhn.fhir.parser.json.JsonLikeArray; import ca.uhn.fhir.parser.json.JsonLikeObject; import ca.uhn.fhir.parser.json.JsonLikeStructure; import ca.uhn.fhir.parser.json.JsonLikeValue; import ca.uhn.fhir.parser.json.JsonLikeValue.ScalarType; import ca.uhn.fhir.parser.json.JsonLikeValue.ValueType; import ca.uhn.fhir.parser.json.JsonLikeWriter; import ca.uhn.fhir.rest.server.EncodingEnum; import ca.uhn.fhir.util.ElementUtil; /** * This class is the FHIR JSON parser/encoder. Users should not interact with this class directly, but should use * {@link FhirContext#newJsonParser()} to get an instance. */ public class JsonParser extends BaseParser implements IJsonLikeParser { private static final Set<String> BUNDLE_TEXTNODE_CHILDREN_DSTU1; private static final Set<String> BUNDLE_TEXTNODE_CHILDREN_DSTU2; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonParser.HeldExtension.class); static { HashSet<String> hashSetDstu1 = new HashSet<String>(); hashSetDstu1.add("title"); hashSetDstu1.add("id"); hashSetDstu1.add("updated"); hashSetDstu1.add("published"); hashSetDstu1.add("totalResults"); BUNDLE_TEXTNODE_CHILDREN_DSTU1 = Collections.unmodifiableSet(hashSetDstu1); HashSet<String> hashSetDstu2 = new HashSet<String>(); hashSetDstu2.add("type"); hashSetDstu2.add("base"); hashSetDstu2.add("total"); BUNDLE_TEXTNODE_CHILDREN_DSTU2 = Collections.unmodifiableSet(hashSetDstu2); } private FhirContext myContext; private boolean myPrettyPrint; /** * Do not use this constructor, the recommended way to obtain a new instance of the JSON parser is to invoke * {@link FhirContext#newJsonParser()}. * * @param theParserErrorHandler */ public JsonParser(FhirContext theContext, IParserErrorHandler theParserErrorHandler) { super(theContext, theParserErrorHandler); myContext = theContext; } private boolean addToHeldComments(int valueIdx, List<String> theCommentsToAdd, ArrayList<ArrayList<String>> theListToAddTo) { if (theCommentsToAdd.size() > 0) { theListToAddTo.ensureCapacity(valueIdx); while (theListToAddTo.size() <= valueIdx) { theListToAddTo.add(null); } if (theListToAddTo.get(valueIdx) == null) { theListToAddTo.set(valueIdx, new ArrayList<String>()); } theListToAddTo.get(valueIdx).addAll(theCommentsToAdd); return true; } return false; } private boolean addToHeldExtensions(int valueIdx, List<? extends IBaseExtension<?, ?>> ext, ArrayList<ArrayList<HeldExtension>> list, boolean theIsModifier, CompositeChildElement theChildElem) { if (ext.size() > 0) { list.ensureCapacity(valueIdx); while (list.size() <= valueIdx) { list.add(null); } if (list.get(valueIdx) == null) { list.set(valueIdx, new ArrayList<JsonParser.HeldExtension>()); } for (IBaseExtension<?, ?> next : ext) { list.get(valueIdx).add(new HeldExtension(next, theIsModifier, theChildElem)); } return true; } return false; } private void addToHeldIds(int theValueIdx, ArrayList<String> theListToAddTo, String theId) { theListToAddTo.ensureCapacity(theValueIdx); while (theListToAddTo.size() <= theValueIdx) { theListToAddTo.add(null); } if (theListToAddTo.get(theValueIdx) == null) { theListToAddTo.set(theValueIdx, theId); } } // private void assertObjectOfType(JsonLikeValue theResourceTypeObj, Object theValueType, String thePosition) { // if (theResourceTypeObj == null) { // throw new DataFormatException("Invalid JSON content detected, missing required element: '" + thePosition + "'"); // } // // if (theResourceTypeObj.getValueType() != theValueType) { // throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType); // } // } private void beginArray(JsonLikeWriter theEventWriter, String arrayName) throws IOException { theEventWriter.beginArray(arrayName); } private void beginObject(JsonLikeWriter theEventWriter, String arrayName) throws IOException { theEventWriter.beginObject(arrayName); } private JsonLikeWriter createJsonWriter(Writer theWriter) { JsonLikeStructure jsonStructure = new GsonStructure(); JsonLikeWriter retVal = jsonStructure.getJsonLikeWriter(theWriter); return retVal; } @Override public void doEncodeBundleToWriter(Bundle theBundle, Writer theWriter) throws IOException { JsonLikeWriter eventWriter = createJsonWriter(theWriter); doEncodeBundleToJsonLikeWriter(theBundle, eventWriter); } public void doEncodeBundleToJsonLikeWriter(Bundle theBundle, JsonLikeWriter theEventWriter) throws IOException { if (myPrettyPrint) { theEventWriter.setPrettyPrint(myPrettyPrint); } theEventWriter.init(); if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) { encodeBundleToWriterInDstu2Format(theBundle, theEventWriter); } else { encodeBundleToWriterInDstu1Format(theBundle, theEventWriter); } theEventWriter.flush(); } @Override protected void doEncodeResourceToWriter(IBaseResource theResource, Writer theWriter) throws IOException { JsonLikeWriter eventWriter = createJsonWriter(theWriter); doEncodeResourceToJsonLikeWriter(theResource, eventWriter); } public void doEncodeResourceToJsonLikeWriter(IBaseResource theResource, JsonLikeWriter theEventWriter) throws IOException { if (myPrettyPrint) { theEventWriter.setPrettyPrint(myPrettyPrint); } theEventWriter.init(); RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource); encodeResourceToJsonStreamWriter(resDef, theResource, theEventWriter, null, false, false); theEventWriter.flush(); } @Override public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) { JsonLikeStructure jsonStructure = new GsonStructure(); jsonStructure.load(theReader); T retVal = doParseResource(theResourceType, jsonStructure); return retVal; } public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, JsonLikeStructure theJsonStructure) { JsonLikeObject object = theJsonStructure.getRootObject(); JsonLikeValue resourceTypeObj = object.get("resourceType"); if (resourceTypeObj == null || !resourceTypeObj.isString() || isBlank(resourceTypeObj.getAsString())) { throw new DataFormatException("Invalid JSON content detected, missing required element: 'resourceType'"); } String resourceType = resourceTypeObj.getAsString(); ParserState<? extends IBaseResource> state = ParserState.getPreResourceInstance(this, theResourceType, myContext, true, getErrorHandler()); state.enteringNewElement(null, resourceType); parseChildren(object, state); state.endingElement(); state.endingElement(); @SuppressWarnings("unchecked") T retVal = (T) state.getObject(); return retVal; } @Override public void encodeBundleToJsonLikeWriter(Bundle theBundle, JsonLikeWriter theJsonLikeWriter) throws IOException, DataFormatException { Validate.notNull(theBundle, "theBundle must not be null"); Validate.notNull(theJsonLikeWriter, "theJsonLikeWriter must not be null"); doEncodeBundleToJsonLikeWriter(theBundle, theJsonLikeWriter); } private void encodeBundleToWriterInDstu1Format(Bundle theBundle, JsonLikeWriter theEventWriter) throws IOException { theEventWriter.beginObject(); write(theEventWriter, "resourceType", "Bundle"); writeTagWithTextNode(theEventWriter, "title", theBundle.getTitle()); writeTagWithTextNode(theEventWriter, "id", theBundle.getBundleId()); writeOptionalTagWithTextNode(theEventWriter, "updated", theBundle.getUpdated()); boolean linkStarted = false; linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "self", theBundle.getLinkSelf(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "first", theBundle.getLinkFirst(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "previous", theBundle.getLinkPrevious(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "next", theBundle.getLinkNext(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "last", theBundle.getLinkLast(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "fhir-base", theBundle.getLinkBase(), linkStarted); if (linkStarted) { theEventWriter.endArray(); } writeCategories(theEventWriter, theBundle.getCategories()); writeOptionalTagWithTextNode(theEventWriter, "totalResults", theBundle.getTotalResults()); writeAuthor(theBundle, theEventWriter); beginArray(theEventWriter, "entry"); for (BundleEntry nextEntry : theBundle.getEntries()) { theEventWriter.beginObject(); boolean deleted = nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false; if (deleted) { writeTagWithTextNode(theEventWriter, "deleted", nextEntry.getDeletedAt()); } writeTagWithTextNode(theEventWriter, "title", nextEntry.getTitle()); //TODO: Use of a deprecated method should be resolved. writeTagWithTextNode(theEventWriter, "id", nextEntry.getId()); linkStarted = false; linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "self", nextEntry.getLinkSelf(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "alternate", nextEntry.getLinkAlternate(), linkStarted); linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "search", nextEntry.getLinkSearch(), linkStarted); if (linkStarted) { theEventWriter.endArray(); } //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithTextNode(theEventWriter, "updated", nextEntry.getUpdated()); writeOptionalTagWithTextNode(theEventWriter, "published", nextEntry.getPublished()); writeCategories(theEventWriter, nextEntry.getCategories()); writeAuthor(nextEntry, theEventWriter); IResource resource = nextEntry.getResource(); if (resource != null && !resource.isEmpty() && !deleted) { RuntimeResourceDefinition resDef = myContext.getResourceDefinition(resource); encodeResourceToJsonStreamWriter(resDef, resource, theEventWriter, "content", false, true); } if (nextEntry.getSummary().isEmpty() == false) { write(theEventWriter, "summary", nextEntry.getSummary().getValueAsString()); } theEventWriter.endObject(); // entry object } theEventWriter.endArray(); // entry array theEventWriter.endObject(); // resource object } private void encodeBundleToWriterInDstu2Format(Bundle theBundle, JsonLikeWriter theEventWriter) throws IOException { theEventWriter.beginObject(); write(theEventWriter, "resourceType", "Bundle"); writeOptionalTagWithTextNode(theEventWriter, "id", theBundle.getId().getIdPart()); if (!ElementUtil.isEmpty(theBundle.getId().getVersionIdPart(), theBundle.getUpdated())) { beginObject(theEventWriter, "meta"); writeOptionalTagWithTextNode(theEventWriter, "versionId", theBundle.getId().getVersionIdPart()); writeOptionalTagWithTextNode(theEventWriter, "lastUpdated", theBundle.getUpdated()); theEventWriter.endObject(); } writeOptionalTagWithTextNode(theEventWriter, "type", theBundle.getType()); writeOptionalTagWithNumberNode(theEventWriter, "total", theBundle.getTotalResults()); boolean linkStarted = false; linkStarted = writeAtomLinkInDstu2Format(theEventWriter, "next", theBundle.getLinkNext(), linkStarted); linkStarted = writeAtomLinkInDstu2Format(theEventWriter, "self", theBundle.getLinkSelf(), linkStarted); linkStarted = writeAtomLinkInDstu2Format(theEventWriter, "first", theBundle.getLinkFirst(), linkStarted); linkStarted = writeAtomLinkInDstu2Format(theEventWriter, "previous", theBundle.getLinkPrevious(), linkStarted); linkStarted = writeAtomLinkInDstu2Format(theEventWriter, "last", theBundle.getLinkLast(), linkStarted); if (linkStarted) { theEventWriter.endArray(); } beginArray(theEventWriter, "entry"); for (BundleEntry nextEntry : theBundle.getEntries()) { theEventWriter.beginObject(); if (nextEntry.getResource() != null && isNotBlank(nextEntry.getResource().getIdElement().getValue()) && (nextEntry.getResource().getId().getBaseUrl() != null || nextEntry.getResource().getId().getValueAsString().startsWith("urn:"))) { writeOptionalTagWithTextNode(theEventWriter, "fullUrl", nextEntry.getResource().getId().getValue()); } boolean deleted = nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false; IResource resource = nextEntry.getResource(); if (resource != null && !resource.isEmpty() && !deleted) { RuntimeResourceDefinition resDef = myContext.getResourceDefinition(resource); encodeResourceToJsonStreamWriter(resDef, resource, theEventWriter, "resource", false, true); } if (nextEntry.getSearchMode().isEmpty() == false || nextEntry.getScore().isEmpty() == false) { beginObject(theEventWriter, "search"); writeOptionalTagWithTextNode(theEventWriter, "mode", nextEntry.getSearchMode().getValueAsString()); writeOptionalTagWithDecimalNode(theEventWriter, "score", nextEntry.getScore()); theEventWriter.endObject(); // IResource nextResource = nextEntry.getResource(); } if (nextEntry.getTransactionMethod().isEmpty() == false || nextEntry.getLinkSearch().isEmpty() == false) { beginObject(theEventWriter, "request"); writeOptionalTagWithTextNode(theEventWriter, "method", nextEntry.getTransactionMethod().getValue()); writeOptionalTagWithTextNode(theEventWriter, "url", nextEntry.getLinkSearch().getValue()); theEventWriter.endObject(); } if (deleted) { beginObject(theEventWriter, "deleted"); if (nextEntry.getResource() != null) { write(theEventWriter, "type", myContext.getResourceDefinition(nextEntry.getResource()).getName()); writeOptionalTagWithTextNode(theEventWriter, "resourceId", nextEntry.getResource().getId().getIdPart()); writeOptionalTagWithTextNode(theEventWriter, "versionId", nextEntry.getResource().getId().getVersionIdPart()); } writeTagWithTextNode(theEventWriter, "instant", nextEntry.getDeletedAt()); theEventWriter.endObject(); } // linkStarted = false; // linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "self", nextEntry.getLinkSelf(), linkStarted); // linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "alternate", nextEntry.getLinkAlternate(), // linkStarted); // linkStarted = writeAtomLinkInDstu1Format(theEventWriter, "search", nextEntry.getLinkSearch(), // linkStarted); // if (linkStarted) { // theEventWriter.writeEnd(); // } // // writeOptionalTagWithTextNode(theEventWriter, "updated", nextEntry.getUpdated()); // writeOptionalTagWithTextNode(theEventWriter, "published", nextEntry.getPublished()); // // writeCategories(theEventWriter, nextEntry.getCategories()); // // writeAuthor(nextEntry, theEventWriter); if (nextEntry.getSummary().isEmpty() == false) { write(theEventWriter, "summary", nextEntry.getSummary().getValueAsString()); } theEventWriter.endObject(); // entry object } theEventWriter.endArray(); // entry array theEventWriter.endObject(); // resource object } private void encodeChildElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, IBase theNextValue, BaseRuntimeElementDefinition<?> theChildDef, String theChildName, boolean theContainedResource, CompositeChildElement theChildElem, boolean theForceEmpty) throws IOException { switch (theChildDef.getChildType()) { case ID_DATATYPE: { IIdType value = (IIdType) theNextValue; String encodedValue = "id".equals(theChildName) ? value.getIdPart() : value.getValue(); if (isBlank(encodedValue)) { break; } if (theChildName != null) { write(theEventWriter, theChildName, encodedValue); } else { theEventWriter.write(encodedValue); } break; } case PRIMITIVE_DATATYPE: { final IPrimitiveType<?> value = (IPrimitiveType<?>) theNextValue; if (isBlank(value.getValueAsString())) { if (theForceEmpty) { theEventWriter.writeNull(); } break; } if (value instanceof IBaseIntegerDatatype) { if (theChildName != null) { write(theEventWriter, theChildName, ((IBaseIntegerDatatype) value).getValue()); } else { theEventWriter.write(((IBaseIntegerDatatype) value).getValue()); } } else if (value instanceof IBaseDecimalDatatype) { BigDecimal decimalValue = ((IBaseDecimalDatatype) value).getValue(); decimalValue = new BigDecimal(decimalValue.toString()) { private static final long serialVersionUID = 1L; @Override public String toString() { return value.getValueAsString(); } }; if (theChildName != null) { write(theEventWriter, theChildName, decimalValue); } else { theEventWriter.write(decimalValue); } } else if (value instanceof IBaseBooleanDatatype) { if (theChildName != null) { write(theEventWriter, theChildName, ((IBaseBooleanDatatype) value).getValue()); } else { Boolean booleanValue = ((IBaseBooleanDatatype) value).getValue(); if (booleanValue != null) { theEventWriter.write(booleanValue.booleanValue()); } } } else { String valueStr = value.getValueAsString(); if (theChildName != null) { write(theEventWriter, theChildName, valueStr); } else { theEventWriter.write(valueStr); } } break; } case RESOURCE_BLOCK: case COMPOSITE_DATATYPE: { if (theChildName != null) { theEventWriter.beginObject(theChildName); } else { theEventWriter.beginObject(); } encodeCompositeElementToStreamWriter(theResDef, theResource, theNextValue, theEventWriter, theContainedResource, theChildElem); theEventWriter.endObject(); break; } case CONTAINED_RESOURCE_LIST: case CONTAINED_RESOURCES: { /* * Disabled per #103 ContainedDt value = (ContainedDt) theNextValue; for (IResource next : * value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) { continue; } * encodeResourceToJsonStreamWriter(theResDef, next, theWriter, null, true, * fixContainedResourceId(next.getId().getValue())); } */ List<IBaseResource> containedResources = getContainedResources().getContainedResources(); if (containedResources.size() > 0) { beginArray(theEventWriter, theChildName); for (IBaseResource next : containedResources) { IIdType resourceId = getContainedResources().getResourceId(next); encodeResourceToJsonStreamWriter(theResDef, next, theEventWriter, null, true, fixContainedResourceId(resourceId.getValue())); } theEventWriter.endArray(); } break; } case PRIMITIVE_XHTML_HL7ORG: case PRIMITIVE_XHTML: { if (!isSuppressNarratives()) { IPrimitiveType<?> dt = (IPrimitiveType<?>) theNextValue; if (theChildName != null) { write(theEventWriter, theChildName, dt.getValueAsString()); } else { theEventWriter.write(dt.getValueAsString()); } } else { if (theChildName != null) { // do nothing } else { theEventWriter.writeNull(); } } break; } case RESOURCE: IBaseResource resource = (IBaseResource) theNextValue; RuntimeResourceDefinition def = myContext.getResourceDefinition(resource); encodeResourceToJsonStreamWriter(def, resource, theEventWriter, theChildName, false, true); break; case UNDECL_EXT: default: throw new IllegalStateException("Should not have this state here: " + theChildDef.getChildType().name()); } } private void encodeCompositeElementChildrenToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, JsonLikeWriter theEventWriter, boolean theContainedResource, CompositeChildElement theParent) throws IOException { { String elementId = getCompositeElementId(theElement); if (isNotBlank(elementId)) { write(theEventWriter, "id", elementId); } } boolean haveWrittenExtensions = false; for (CompositeChildElement nextChildElem : super.compositeChildIterator(theElement, theContainedResource, theParent)) { BaseRuntimeChildDefinition nextChild = nextChildElem.getDef(); if (nextChildElem.getDef().getElementName().equals("extension") || nextChildElem.getDef().getElementName().equals("modifierExtension") || nextChild instanceof RuntimeChildDeclaredExtensionDefinition) { if (!haveWrittenExtensions) { extractAndWriteExtensionsAsDirectChild(theElement, theEventWriter, myContext.getElementDefinition(theElement.getClass()), theResDef, theResource, nextChildElem); haveWrittenExtensions = true; } continue; } if (nextChild instanceof RuntimeChildNarrativeDefinition) { INarrativeGenerator gen = myContext.getNarrativeGenerator(); if (gen != null) { INarrative narr; if (theResource instanceof IResource) { narr = ((IResource) theResource).getText(); } else if (theResource instanceof IDomainResource) { narr = ((IDomainResource) theResource).getText(); } else { narr = null; } if (narr != null && narr.isEmpty()) { gen.generateNarrative(myContext, theResource, narr); if (!narr.isEmpty()) { RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild; String childName = nextChild.getChildNameByDatatype(child.getDatatype()); BaseRuntimeElementDefinition<?> type = child.getChildByName(childName); encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, narr, type, childName, theContainedResource, nextChildElem, false); continue; } } } } else if (nextChild instanceof RuntimeChildContainedResources) { String childName = nextChild.getValidChildNames().iterator().next(); BaseRuntimeElementDefinition<?> child = nextChild.getChildByName(childName); encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, null, child, childName, theContainedResource, nextChildElem, false); continue; } List<? extends IBase> values = nextChild.getAccessor().getValues(theElement); values = super.preProcessValues(nextChild, theResource, values, nextChildElem); if (values == null || values.isEmpty()) { continue; } String currentChildName = null; boolean inArray = false; ArrayList<ArrayList<HeldExtension>> extensions = new ArrayList<ArrayList<HeldExtension>>(0); ArrayList<ArrayList<HeldExtension>> modifierExtensions = new ArrayList<ArrayList<HeldExtension>>(0); ArrayList<ArrayList<String>> comments = new ArrayList<ArrayList<String>>(0); ArrayList<String> ids = new ArrayList<String>(0); int valueIdx = 0; for (IBase nextValue : values) { if (nextValue == null || nextValue.isEmpty()) { if (nextValue instanceof BaseContainedDt) { if (theContainedResource || getContainedResources().isEmpty()) { continue; } } else { continue; } } BaseParser.ChildNameAndDef childNameAndDef = super.getChildNameAndDef(nextChild, nextValue); if (childNameAndDef == null) { continue; } String childName = childNameAndDef.getChildName(); BaseRuntimeElementDefinition<?> childDef = childNameAndDef.getChildDef(); boolean primitive = childDef.getChildType() == ChildTypeEnum.PRIMITIVE_DATATYPE; if ((childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCES || childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) && theContainedResource) { continue; } boolean force = false; if (primitive) { if (nextValue instanceof ISupportsUndeclaredExtensions) { List<ExtensionDt> ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredExtensions(); force |= addToHeldExtensions(valueIdx, ext, extensions, false, nextChildElem); ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredModifierExtensions(); force |= addToHeldExtensions(valueIdx, ext, modifierExtensions, true, nextChildElem); } else { if (nextValue instanceof IBaseHasExtensions) { IBaseHasExtensions element = (IBaseHasExtensions) nextValue; List<? extends IBaseExtension<?, ?>> ext = element.getExtension(); force |= addToHeldExtensions(valueIdx, ext, extensions, false, nextChildElem); } if (nextValue instanceof IBaseHasModifierExtensions) { IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) nextValue; List<? extends IBaseExtension<?, ?>> ext = element.getModifierExtension(); force |= addToHeldExtensions(valueIdx, ext, extensions, true, nextChildElem); } } if (nextValue.hasFormatComment()) { force |= addToHeldComments(valueIdx, nextValue.getFormatCommentsPre(), comments); force |= addToHeldComments(valueIdx, nextValue.getFormatCommentsPost(), comments); } String elementId = getCompositeElementId(nextValue); if (isNotBlank(elementId)) { force = true; addToHeldIds(valueIdx, ids, elementId); } } if (currentChildName == null || !currentChildName.equals(childName)) { if (inArray) { theEventWriter.endArray(); } if (nextChild.getMax() > 1 || nextChild.getMax() == Child.MAX_UNLIMITED) { beginArray(theEventWriter, childName); inArray = true; encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, null, theContainedResource, nextChildElem, force); } else if (nextChild instanceof RuntimeChildNarrativeDefinition && theContainedResource) { // suppress narratives from contained resources } else { encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, childName, theContainedResource, nextChildElem, false); } currentChildName = childName; } else { encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, null, theContainedResource, nextChildElem, force); } valueIdx++; } if (inArray) { theEventWriter.endArray(); } if (!extensions.isEmpty() || !modifierExtensions.isEmpty() || !comments.isEmpty()) { if (inArray) { // If this is a repeatable field, the extensions go in an array too beginArray(theEventWriter, '_' + currentChildName); } else { beginObject(theEventWriter, '_' + currentChildName); } for (int i = 0; i < valueIdx; i++) { boolean haveContent = false; List<HeldExtension> heldExts = Collections.emptyList(); List<HeldExtension> heldModExts = Collections.emptyList(); if (extensions.size() > i && extensions.get(i) != null && extensions.get(i).isEmpty() == false) { haveContent = true; heldExts = extensions.get(i); } if (modifierExtensions.size() > i && modifierExtensions.get(i) != null && modifierExtensions.get(i).isEmpty() == false) { haveContent = true; heldModExts = modifierExtensions.get(i); } ArrayList<String> nextComments; if (comments.size() > i) { nextComments = comments.get(i); } else { nextComments = null; } if (nextComments != null && nextComments.isEmpty() == false) { haveContent = true; } String elementId = null; if (ids.size() > i) { elementId = ids.get(i); haveContent |= isNotBlank(elementId); } if (!haveContent) { theEventWriter.writeNull(); } else { if (inArray) { theEventWriter.beginObject(); } if (isNotBlank(elementId)) { write(theEventWriter, "id", elementId); } if (nextComments != null && !nextComments.isEmpty()) { beginArray(theEventWriter, "fhir_comments"); for (String next : nextComments) { theEventWriter.write(next); } theEventWriter.endArray(); } writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, heldExts, heldModExts); if (inArray) { theEventWriter.endObject(); } } } if (inArray) { theEventWriter.endArray(); } else { theEventWriter.endObject(); } } } } private void encodeCompositeElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theNextValue, JsonLikeWriter theEventWriter, boolean theContainedResource, CompositeChildElement theParent) throws IOException, DataFormatException { writeCommentsPreAndPost(theNextValue, theEventWriter); encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theNextValue, theEventWriter, theContainedResource, theParent); } @Override public void encodeResourceToJsonLikeWriter(IBaseResource theResource, JsonLikeWriter theJsonLikeWriter) throws IOException, DataFormatException { Validate.notNull(theResource, "theResource can not be null"); Validate.notNull(theJsonLikeWriter, "theJsonLikeWriter can not be null"); if (theResource.getStructureFhirVersionEnum() != myContext.getVersion().getVersion()) { throw new IllegalArgumentException("This parser is for FHIR version " + myContext.getVersion().getVersion() + " - Can not encode a structure for version " + theResource.getStructureFhirVersionEnum()); } doEncodeResourceToJsonLikeWriter(theResource, theJsonLikeWriter); } private void encodeResourceToJsonStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, String theObjectNameOrNull, boolean theContainedResource, boolean theSubResource) throws IOException { IIdType resourceId = null; // if (theResource instanceof IResource) { // IResource res = (IResource) theResource; // if (StringUtils.isNotBlank(res.getId().getIdPart())) { // if (theContainedResource) { // resourceId = res.getId().getIdPart(); // } else if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) { // resourceId = res.getId().getIdPart(); // } // } // } else if (theResource instanceof IAnyResource) { // IAnyResource res = (IAnyResource) theResource; // if (/* theContainedResource && */StringUtils.isNotBlank(res.getIdElement().getIdPart())) { // resourceId = res.getIdElement().getIdPart(); // } // } if (StringUtils.isNotBlank(theResource.getIdElement().getIdPart())) { resourceId = theResource.getIdElement(); if (theResource.getIdElement().getValue().startsWith("urn:")) { resourceId = null; } if (myContext.getVersion().getVersion().equals(FhirVersionEnum.DSTU1)) { resourceId = null; } } if (!theContainedResource) { if (super.shouldEncodeResourceId(theResource) == false) { resourceId = null; } else if (!theSubResource && getEncodeForceResourceId() != null) { resourceId = getEncodeForceResourceId(); } } encodeResourceToJsonStreamWriter(theResDef, theResource, theEventWriter, theObjectNameOrNull, theContainedResource, resourceId); } private void encodeResourceToJsonStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, String theObjectNameOrNull, boolean theContainedResource, IIdType theResourceId) throws IOException { if (!theContainedResource) { super.containResourcesForEncoding(theResource); } RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource); if (theObjectNameOrNull == null) { theEventWriter.beginObject(); } else { beginObject(theEventWriter, theObjectNameOrNull); } write(theEventWriter, "resourceType", resDef.getName()); if (theResourceId != null && theResourceId.hasIdPart()) { write(theEventWriter, "id", theResourceId.getIdPart()); if (theResourceId.hasFormatComment()) { beginObject(theEventWriter, "_id"); writeCommentsPreAndPost(theResourceId, theEventWriter); theEventWriter.endObject(); } } if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1) && theResource instanceof IResource) { IResource resource = (IResource) theResource; // Object securityLabelRawObj = List<BaseCodingDt> securityLabels = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.SECURITY_LABELS); List<? extends IIdType> profiles = extractMetadataListNotNull(resource, ResourceMetadataKeyEnum.PROFILES); profiles = super.getProfileTagsForEncoding(resource, profiles); TagList tags = getMetaTagsForEncoding(resource); InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED); IdDt resourceId = resource.getId(); String versionIdPart = resourceId.getVersionIdPart(); if (isBlank(versionIdPart)) { versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource); } if (super.shouldEncodeResourceMeta(resource) && ElementUtil.isEmpty(versionIdPart, updated, securityLabels, tags, profiles) == false) { beginObject(theEventWriter, "meta"); writeOptionalTagWithTextNode(theEventWriter, "versionId", versionIdPart); writeOptionalTagWithTextNode(theEventWriter, "lastUpdated", updated); if (profiles != null && profiles.isEmpty() == false) { beginArray(theEventWriter, "profile"); for (IIdType profile : profiles) { if (profile != null && isNotBlank(profile.getValue())) { theEventWriter.write(profile.getValue()); } } theEventWriter.endArray(); } if (securityLabels.isEmpty() == false) { beginArray(theEventWriter, "security"); for (BaseCodingDt securityLabel : securityLabels) { theEventWriter.beginObject(); encodeCompositeElementChildrenToStreamWriter(resDef, resource, securityLabel, theEventWriter, theContainedResource, null); theEventWriter.endObject(); } theEventWriter.endArray(); } if (tags != null && tags.isEmpty() == false) { beginArray(theEventWriter, "tag"); for (Tag tag : tags) { if (tag.isEmpty()) { continue; } theEventWriter.beginObject(); writeOptionalTagWithTextNode(theEventWriter, "system", tag.getScheme()); writeOptionalTagWithTextNode(theEventWriter, "code", tag.getTerm()); writeOptionalTagWithTextNode(theEventWriter, "display", tag.getLabel()); theEventWriter.endObject(); } theEventWriter.endArray(); } theEventWriter.endObject(); // end meta } } if (theResource instanceof IBaseBinary) { IBaseBinary bin = (IBaseBinary) theResource; String contentType = bin.getContentType(); if (isNotBlank(contentType)) { write(theEventWriter, "contentType", contentType); } String contentAsBase64 = bin.getContentAsBase64(); if (isNotBlank(contentAsBase64)) { write(theEventWriter, "content", contentAsBase64); } } else { encodeCompositeElementToStreamWriter(theResDef, theResource, theResource, theEventWriter, theContainedResource, new CompositeChildElement(resDef)); } theEventWriter.endObject(); } @Override public void encodeTagListToWriter(TagList theTagList, Writer theWriter) throws IOException { JsonLikeWriter theEventWriter = createJsonWriter(theWriter); encodeTagListToJsonLikeWriter(theTagList, theEventWriter); } @Override public void encodeTagListToJsonLikeWriter(TagList theTagList, JsonLikeWriter theEventWriter) throws IOException { if (myPrettyPrint) { theEventWriter.setPrettyPrint(myPrettyPrint); } theEventWriter.init(); theEventWriter.beginObject(); write(theEventWriter, "resourceType", TagList.ELEMENT_NAME); beginArray(theEventWriter, TagList.ATTR_CATEGORY); for (Tag next : theTagList) { theEventWriter.beginObject(); if (isNotBlank(next.getTerm())) { write(theEventWriter, Tag.ATTR_TERM, next.getTerm()); } if (isNotBlank(next.getLabel())) { write(theEventWriter, Tag.ATTR_LABEL, next.getLabel()); } if (isNotBlank(next.getScheme())) { write(theEventWriter, Tag.ATTR_SCHEME, next.getScheme()); } theEventWriter.endObject(); } theEventWriter.endArray(); theEventWriter.endObject(); theEventWriter.flush(); } /** * This is useful only for the two cases where extensions are encoded as direct children (e.g. not in some object * called _name): resource extensions, and extension extensions * @param theChildElem */ private void extractAndWriteExtensionsAsDirectChild(IBase theElement, JsonLikeWriter theEventWriter, BaseRuntimeElementDefinition<?> theElementDef, RuntimeResourceDefinition theResDef, IBaseResource theResource, CompositeChildElement theChildElem) throws IOException { List<HeldExtension> extensions = new ArrayList<HeldExtension>(0); List<HeldExtension> modifierExtensions = new ArrayList<HeldExtension>(0); // Undeclared extensions extractUndeclaredExtensions(theElement, extensions, modifierExtensions, theChildElem); // Declared extensions if (theElementDef != null) { extractDeclaredExtensions(theElement, theElementDef, extensions, modifierExtensions, theChildElem); } // Write the extensions writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, extensions, modifierExtensions); } private void extractDeclaredExtensions(IBase theResource, BaseRuntimeElementDefinition<?> resDef, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions, CompositeChildElement theChildElem) { for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsNonModifier()) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { if (nextValue != null) { if (nextValue.isEmpty()) { continue; } extensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); } } } for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsModifier()) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { if (nextValue != null) { if (nextValue.isEmpty()) { continue; } modifierExtensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); } } } } private void extractUndeclaredExtensions(IBase theElement, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions, CompositeChildElement theChildElem) { if (theElement instanceof ISupportsUndeclaredExtensions) { ISupportsUndeclaredExtensions element = (ISupportsUndeclaredExtensions) theElement; List<ExtensionDt> ext = element.getUndeclaredExtensions(); for (ExtensionDt next : ext) { if (next == null || next.isEmpty()) { continue; } extensions.add(new HeldExtension(next, false, theChildElem)); } ext = element.getUndeclaredModifierExtensions(); for (ExtensionDt next : ext) { if (next == null || next.isEmpty()) { continue; } modifierExtensions.add(new HeldExtension(next, true, theChildElem)); } } else { if (theElement instanceof IBaseHasExtensions) { IBaseHasExtensions element = (IBaseHasExtensions) theElement; List<? extends IBaseExtension<?, ?>> ext = element.getExtension(); for (IBaseExtension<?, ?> next : ext) { if (next == null || (ElementUtil.isEmpty(next.getValue()) && next.getExtension().isEmpty())) { continue; } extensions.add(new HeldExtension(next, false, theChildElem)); } } if (theElement instanceof IBaseHasModifierExtensions) { IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) theElement; List<? extends IBaseExtension<?, ?>> ext = element.getModifierExtension(); for (IBaseExtension<?, ?> next : ext) { if (next == null || next.isEmpty()) { continue; } modifierExtensions.add(new HeldExtension(next, true, theChildElem)); } } } } @Override public EncodingEnum getEncoding() { return EncodingEnum.JSON; } private JsonLikeArray grabJsonArray(JsonLikeObject theObject, String nextName, String thePosition) { JsonLikeValue object = theObject.get(nextName); if (object == null || object.isNull()) { return null; } if (!object.isArray()) { throw new DataFormatException("Syntax error parsing JSON FHIR structure: Expected ARRAY at element '" + thePosition + "', found '" + object.getJsonType() + "'"); } return object.getAsArray(); } // private JsonObject parse(Reader theReader) { // // PushbackReader pbr = new PushbackReader(theReader); // JsonObject object; // try { // while(true) { // int nextInt; // nextInt = pbr.read(); // if (nextInt == -1) { // throw new DataFormatException("Did not find any content to parse"); // } // if (nextInt == '{') { // pbr.unread('{'); // break; // } // if (Character.isWhitespace(nextInt)) { // continue; // } // throw new DataFormatException("Content does not appear to be FHIR JSON, first non-whitespace character was: '" + (char)nextInt + "' (must be '{')"); // } // // Gson gson = newGson(); // // object = gson.fromJson(pbr, JsonObject.class); // } catch (Exception e) { // throw new DataFormatException("Failed to parse JSON content, error was: " + e.getMessage(), e); // } // // return object; // } private void parseAlternates(JsonLikeValue theAlternateVal, ParserState<?> theState, String theElementName, String theAlternateName) { if (theAlternateVal == null || theAlternateVal.isNull()) { return; } if (theAlternateVal.isArray()) { JsonLikeArray array = theAlternateVal.getAsArray(); if (array.size() > 1) { throw new DataFormatException("Unexpected array of length " + array.size() + " (expected 0 or 1) for element: " + theElementName); } if (array.size() == 0) { return; } parseAlternates(array.get(0), theState, theElementName, theAlternateName); return; } JsonLikeValue alternateVal = theAlternateVal; if (alternateVal.isObject() == false) { getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.OBJECT, null, alternateVal.getJsonType(), null); return; } JsonLikeObject alternate = alternateVal.getAsObject(); for (String nextKey : alternate.keySet()) { JsonLikeValue nextVal = alternate.get(nextKey); if ("extension".equals(nextKey)) { boolean isModifier = false; JsonLikeArray array = nextVal.getAsArray(); parseExtension(theState, array, isModifier); } else if ("modifierExtension".equals(nextKey)) { boolean isModifier = true; JsonLikeArray array = nextVal.getAsArray(); parseExtension(theState, array, isModifier); } else if ("id".equals(nextKey)) { if (nextVal.isString()) { theState.attributeValue("id", nextVal.getAsString()); } else { getErrorHandler().incorrectJsonType(null, "id", ValueType.SCALAR, ScalarType.STRING, nextVal.getJsonType(), nextVal.getDataType()); } } else if ("fhir_comments".equals(nextKey)) { parseFhirComments(nextVal, theState); } } } @Override public <T extends IBaseResource> Bundle parseBundle(Class<T> theResourceType, Reader theReader) { JsonLikeStructure jsonStructure = new GsonStructure(); jsonStructure.load(theReader); Bundle retVal = parseBundle(theResourceType, jsonStructure); return retVal; } @Override public Bundle parseBundle(JsonLikeStructure theJsonLikeStructure) throws DataFormatException { return parseBundle(null, theJsonLikeStructure); } @Override public <T extends IBaseResource> Bundle parseBundle(Class<T> theResourceType, JsonLikeStructure theJsonStructure) { JsonLikeObject object = theJsonStructure.getRootObject(); JsonLikeValue resourceTypeObj = object.get("resourceType"); if (resourceTypeObj == null || !resourceTypeObj.isString()) { throw new DataFormatException("Invalid JSON content detected, missing required element: 'resourceType'"); } String resourceType = resourceTypeObj.getAsString(); if (!"Bundle".equals(resourceType)) { throw new DataFormatException("Trying to parse bundle but found resourceType other than 'Bundle'. Found: '" + resourceType + "'"); } ParserState<Bundle> state = ParserState.getPreAtomInstance(this, myContext, theResourceType, true, getErrorHandler()); if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) { state.enteringNewElement(null, "Bundle"); } else { state.enteringNewElement(null, "feed"); } parseBundleChildren(object, state); state.endingElement(); state.endingElement(); Bundle retVal = state.getObject(); return retVal; } private void parseBundleChildren(JsonLikeObject theObject, ParserState<?> theState) { for (String nextName : theObject.keySet()) { if ("resourceType".equals(nextName)) { continue; } else if ("entry".equals(nextName)) { JsonLikeArray entries = grabJsonArray(theObject, nextName, "entry"); for (int i = 0; i < entries.size(); i++) { JsonLikeValue jsonValue = entries.get(i); theState.enteringNewElement(null, "entry"); parseBundleChildren(jsonValue.getAsObject(), theState); theState.endingElement(); } continue; } else if (myContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { if ("link".equals(nextName)) { JsonLikeArray entries = grabJsonArray(theObject, nextName, "link"); for (int i = 0; i < entries.size(); i++) { JsonLikeValue jsonValue = entries.get(i); theState.enteringNewElement(null, "link"); JsonLikeObject linkObj = jsonValue.getAsObject(); String rel = linkObj.getString("rel", null); String href = linkObj.getString("href", null); theState.attributeValue("rel", rel); theState.attributeValue("href", href); theState.endingElement(); } continue; } else if (BUNDLE_TEXTNODE_CHILDREN_DSTU1.contains(nextName)) { theState.enteringNewElement(null, nextName); JsonLikeValue jsonElement = theObject.get(nextName); if (jsonElement.isScalar()) { theState.string(jsonElement.getAsString()); } theState.endingElement(); continue; } } else { if ("link".equals(nextName)) { JsonLikeArray entries = grabJsonArray(theObject, nextName, "link"); for (int i = 0; i < entries.size(); i++) { JsonLikeValue jsonValue = entries.get(i); theState.enteringNewElement(null, "link"); JsonLikeObject linkObj = jsonValue.getAsObject(); String rel = linkObj.getString("relation", null); String href = linkObj.getString("url", null); theState.enteringNewElement(null, "relation"); theState.attributeValue("value", rel); theState.endingElement(); theState.enteringNewElement(null, "url"); theState.attributeValue("value", href); theState.endingElement(); theState.endingElement(); } continue; } else if (BUNDLE_TEXTNODE_CHILDREN_DSTU2.contains(nextName)) { theState.enteringNewElement(null, nextName); // String obj = theObject.getString(nextName, null); JsonLikeValue obj = theObject.get(nextName); if (obj == null || obj.isNull()) { theState.attributeValue("value", null); } else if (obj.isScalar()) { theState.attributeValue("value", obj.getAsString()); } else { throw new DataFormatException("Unexpected JSON object for entry '" + nextName + "'"); } theState.endingElement(); continue; } } JsonLikeValue nextVal = theObject.get(nextName); parseChildren(theState, nextName, nextVal, null, null, false); } } private void parseChildren(JsonLikeObject theObject, ParserState<?> theState) { Set<String> keySet = theObject.keySet(); int allUnderscoreNames = 0; int handledUnderscoreNames = 0; for (String nextName : keySet) { if ("resourceType".equals(nextName)) { continue; } else if ("extension".equals(nextName)) { JsonLikeArray array = grabJsonArray(theObject, nextName, "extension"); parseExtension(theState, array, false); continue; } else if ("modifierExtension".equals(nextName)) { JsonLikeArray array = grabJsonArray(theObject, nextName, "modifierExtension"); parseExtension(theState, array, true); continue; } else if (nextName.equals("fhir_comments")) { parseFhirComments(theObject.get(nextName), theState); continue; } else if (nextName.charAt(0) == '_') { allUnderscoreNames++; continue; } JsonLikeValue nextVal = theObject.get(nextName); String alternateName = '_' + nextName; JsonLikeValue alternateVal = theObject.get(alternateName); if (alternateVal != null) { handledUnderscoreNames++; } parseChildren(theState, nextName, nextVal, alternateVal, alternateName, false); } // if (elementId != null) { // IBase object = (IBase) theState.getObject(); // if (object instanceof IIdentifiableElement) { // ((IIdentifiableElement) object).setElementSpecificId(elementId); // } else if (object instanceof IBaseResource) { // ((IBaseResource) object).getIdElement().setValue(elementId); // } // } /* * This happens if an element has an extension but no actual value. I.e. * if a resource has a "_status" element but no corresponding "status" * element. This could be used to handle a null value with an extension * for example. */ if (allUnderscoreNames > handledUnderscoreNames) { for (String alternateName : keySet) { if (alternateName.startsWith("_") && alternateName.length() > 1) { JsonLikeValue nextValue = theObject.get(alternateName); if (nextValue != null) { if (nextValue.isObject()) { String nextName = alternateName.substring(1); if (theObject.get(nextName) == null) { theState.enteringNewElement(null, nextName); parseAlternates(nextValue, theState, alternateName, alternateName); theState.endingElement(); } } else { getErrorHandler().incorrectJsonType(null, alternateName, ValueType.OBJECT, null, nextValue.getJsonType(), null); } } } } } } private void parseChildren(ParserState<?> theState, String theName, JsonLikeValue theJsonVal, JsonLikeValue theAlternateVal, String theAlternateName, boolean theInArray) { if (theName.equals("id")) { if (!theJsonVal.isString()) { getErrorHandler().incorrectJsonType(null, "id", ValueType.SCALAR, ScalarType.STRING, theJsonVal.getJsonType(), theJsonVal.getDataType()); } } if (theJsonVal.isArray()) { JsonLikeArray nextArray = theJsonVal.getAsArray(); JsonLikeValue alternateVal = theAlternateVal; if (alternateVal != null && alternateVal.isArray() == false) { getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.ARRAY, null, alternateVal.getJsonType(), null); alternateVal = null; } JsonLikeArray nextAlternateArray = JsonLikeValue.asArray(alternateVal); // could be null for (int i = 0; i < nextArray.size(); i++) { JsonLikeValue nextObject = nextArray.get(i); JsonLikeValue nextAlternate = null; if (nextAlternateArray != null) { nextAlternate = nextAlternateArray.get(i); } parseChildren(theState, theName, nextObject, nextAlternate, theAlternateName, true); } } else if (theJsonVal.isObject()) { if (!theInArray && theState.elementIsRepeating(theName)) { getErrorHandler().incorrectJsonType(null, theName, ValueType.ARRAY, null, ValueType.OBJECT, null); } theState.enteringNewElement(null, theName); parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName); JsonLikeObject nextObject = theJsonVal.getAsObject(); boolean preResource = false; if (theState.isPreResource()) { JsonLikeValue resType = nextObject.get("resourceType"); if (resType == null || !resType.isString()) { throw new DataFormatException("Missing required element 'resourceType' from JSON resource object, unable to parse"); } theState.enteringNewElement(null, resType.getAsString()); preResource = true; } parseChildren(nextObject, theState); if (preResource) { theState.endingElement(); } theState.endingElement(); } else if (theJsonVal.isNull()) { theState.enteringNewElement(null, theName); parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName); theState.endingElement(); } else { // must be a SCALAR theState.enteringNewElement(null, theName); theState.attributeValue("value", theJsonVal.getAsString()); parseAlternates(theAlternateVal, theState, theAlternateName, theAlternateName); theState.endingElement(); } } private void parseExtension(ParserState<?> theState, JsonLikeArray theValues, boolean theIsModifier) { for (int i = 0; i < theValues.size(); i++) { JsonLikeObject nextExtObj = JsonLikeValue.asObject(theValues.get(i)); JsonLikeValue jsonElement = nextExtObj.get("url"); String url; if (null == jsonElement || !(jsonElement.isScalar())) { String parentElementName; if (theIsModifier) { parentElementName = "modifierExtension"; } else { parentElementName = "extension"; } getErrorHandler().missingRequiredElement(new ParseLocation(parentElementName), "url"); url = null; } else { url = jsonElement.getAsString(); } theState.enteringNewElementExtension(null, url, theIsModifier); for (String next : nextExtObj.keySet()) { if ("url".equals(next)) { continue; } else if ("extension".equals(next)) { JsonLikeArray jsonVal = JsonLikeValue.asArray(nextExtObj.get(next)); parseExtension(theState, jsonVal, false); } else if ("modifierExtension".equals(next)) { JsonLikeArray jsonVal = JsonLikeValue.asArray(nextExtObj.get(next)); parseExtension(theState, jsonVal, true); } else { JsonLikeValue jsonVal = nextExtObj.get(next); parseChildren(theState, next, jsonVal, null, null, false); } } theState.endingElement(); } } private void parseFhirComments(JsonLikeValue theObject, ParserState<?> theState) { if (theObject.isArray()) { JsonLikeArray comments = theObject.getAsArray(); for (int i = 0; i < comments.size(); i++) { JsonLikeValue nextComment = comments.get(i); if (nextComment.isString()) { String commentText = nextComment.getAsString(); if (commentText != null) { theState.commentPre(commentText); } } } } } @Override public <T extends IBaseResource> T parseResource(Class<T> theResourceType, JsonLikeStructure theJsonLikeStructure) throws DataFormatException { /***************************************************** * ************************************************* * * ** NOTE: this duplicates most of the code in ** * * ** BaseParser.parseResource(Class<T>, Reader). ** * * ** Unfortunately, there is no way to avoid ** * * ** this without doing some refactoring of the ** * * ** BaseParser class. ** * * ************************************************* * *****************************************************/ /* * We do this so that the context can verify that the structure is for * the correct FHIR version */ if (theResourceType != null) { myContext.getResourceDefinition(theResourceType); } // Actually do the parse T retVal = doParseResource(theResourceType, theJsonLikeStructure); RuntimeResourceDefinition def = myContext.getResourceDefinition(retVal); if ("Bundle".equals(def.getName())) { BaseRuntimeChildDefinition entryChild = def.getChildByName("entry"); BaseRuntimeElementCompositeDefinition<?> entryDef = (BaseRuntimeElementCompositeDefinition<?>) entryChild.getChildByName("entry"); List<IBase> entries = entryChild.getAccessor().getValues(retVal); if (entries != null) { for (IBase nextEntry : entries) { /** * If Bundle.entry.fullUrl is populated, set the resource ID to that */ // TODO: should emit a warning and maybe notify the error handler if the resource ID doesn't match the // fullUrl idPart BaseRuntimeChildDefinition fullUrlChild = entryDef.getChildByName("fullUrl"); if (fullUrlChild == null) { continue; // TODO: remove this once the data model in tinder plugin catches up to 1.2 } List<IBase> fullUrl = fullUrlChild.getAccessor().getValues(nextEntry); if (fullUrl != null && !fullUrl.isEmpty()) { IPrimitiveType<?> value = (IPrimitiveType<?>) fullUrl.get(0); if (value.isEmpty() == false) { List<IBase> entryResources = entryDef.getChildByName("resource").getAccessor().getValues(nextEntry); if (entryResources != null && entryResources.size() > 0) { IBaseResource res = (IBaseResource) entryResources.get(0); String versionId = res.getIdElement().getVersionIdPart(); res.setId(value.getValueAsString()); if (isNotBlank(versionId) && res.getIdElement().hasVersionIdPart() == false) { res.setId(res.getIdElement().withVersion(versionId)); } } } } } } } return retVal; } @Override public IBaseResource parseResource(JsonLikeStructure theJsonLikeStructure) throws DataFormatException { return parseResource(null, theJsonLikeStructure); } @Override public TagList parseTagList(Reader theReader) { JsonLikeStructure jsonStructure = new GsonStructure(); jsonStructure.load(theReader); TagList retVal = parseTagList(jsonStructure); return retVal; } @Override public TagList parseTagList(JsonLikeStructure theJsonStructure) { JsonLikeObject object = theJsonStructure.getRootObject(); JsonLikeValue resourceTypeObj = object.get("resourceType"); String resourceType = resourceTypeObj.getAsString(); ParserState<TagList> state = ParserState.getPreTagListInstance(this, myContext, true, getErrorHandler()); state.enteringNewElement(null, resourceType); parseChildren(object, state); state.endingElement(); state.endingElement(); return state.getObject(); } @Override public IParser setPrettyPrint(boolean thePrettyPrint) { myPrettyPrint = thePrettyPrint; return this; } private void write(JsonLikeWriter theEventWriter, String theChildName, Boolean theValue) throws IOException { if (theValue != null) { theEventWriter.write(theChildName, theValue.booleanValue()); } } // private void parseExtensionInDstu2Style(boolean theModifier, ParserState<?> theState, String // theParentExtensionUrl, String theExtensionUrl, JsonArray theValues) { // String extUrl = UrlUtil.constructAbsoluteUrl(theParentExtensionUrl, theExtensionUrl); // theState.enteringNewElementExtension(null, extUrl, theModifier); // // for (int extIdx = 0; extIdx < theValues.size(); extIdx++) { // JsonObject nextExt = theValues.getJsonObject(extIdx); // for (String nextKey : nextExt.keySet()) { // // if (nextKey.startsWith("value") && nextKey.length() > 5 && // // myContext.getRuntimeChildUndeclaredExtensionDefinition().getChildByName(nextKey) != null) { // JsonElement jsonVal = nextExt.get(nextKey); // if (jsonVal.getValueType() == ValueType.ARRAY) { // /* // * Extension children which are arrays are sub-extensions. Any other value type should be treated as a value. // */ // JsonArray arrayValue = (JsonArray) jsonVal; // parseExtensionInDstu2Style(theModifier, theState, extUrl, nextKey, arrayValue); // } else { // parseChildren(theState, nextKey, jsonVal, null, null); // } // } // } // // theState.endingElement(); // } private void write(JsonLikeWriter theEventWriter, String theChildName, BigDecimal theDecimalValue) throws IOException { theEventWriter.write(theChildName, theDecimalValue); } private void write(JsonLikeWriter theEventWriter, String theChildName, Integer theValue) throws IOException { theEventWriter.write(theChildName, theValue); } private boolean writeAtomLinkInDstu1Format(JsonLikeWriter theEventWriter, String theRel, StringDt theLink, boolean theStarted) throws IOException { boolean retVal = theStarted; if (isNotBlank(theLink.getValue())) { if (theStarted == false) { theEventWriter.beginArray("link"); retVal = true; } theEventWriter.beginObject(); write(theEventWriter, "rel", theRel); write(theEventWriter, "href", theLink.getValue()); theEventWriter.endObject(); } return retVal; } private boolean writeAtomLinkInDstu2Format(JsonLikeWriter theEventWriter, String theRel, StringDt theLink, boolean theStarted) throws IOException { boolean retVal = theStarted; if (isNotBlank(theLink.getValue())) { if (theStarted == false) { theEventWriter.beginArray("link"); retVal = true; } theEventWriter.beginObject(); write(theEventWriter, "relation", theRel); write(theEventWriter, "url", theLink.getValue()); theEventWriter.endObject(); } return retVal; } private void writeAuthor(BaseBundle theBundle, JsonLikeWriter theEventWriter) throws IOException { if (StringUtils.isNotBlank(theBundle.getAuthorName().getValue())) { beginArray(theEventWriter, "author"); theEventWriter.beginObject(); writeTagWithTextNode(theEventWriter, "name", theBundle.getAuthorName()); writeOptionalTagWithTextNode(theEventWriter, "uri", theBundle.getAuthorUri()); theEventWriter.endObject(); theEventWriter.endArray(); } } private void writeCategories(JsonLikeWriter theEventWriter, TagList categories) throws IOException { if (categories != null && categories.size() > 0) { theEventWriter.beginArray("category"); for (Tag next : categories) { theEventWriter.beginObject(); write(theEventWriter, "term", defaultString(next.getTerm())); write(theEventWriter, "label", defaultString(next.getLabel())); write(theEventWriter, "scheme", defaultString(next.getScheme())); theEventWriter.endObject(); } theEventWriter.endArray(); } } private void writeCommentsPreAndPost(IBase theNextValue, JsonLikeWriter theEventWriter) throws IOException { if (theNextValue.hasFormatComment()) { beginArray(theEventWriter, "fhir_comments"); List<String> pre = theNextValue.getFormatCommentsPre(); if (pre.isEmpty() == false) { for (String next : pre) { theEventWriter.write(next); } } List<String> post = theNextValue.getFormatCommentsPost(); if (post.isEmpty() == false) { for (String next : post) { theEventWriter.write(next); } } theEventWriter.endArray(); } } private void writeExtensionsAsDirectChild(IBaseResource theResource, JsonLikeWriter theEventWriter, RuntimeResourceDefinition resDef, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions) throws IOException { if (extensions.isEmpty() == false) { beginArray(theEventWriter, "extension"); for (HeldExtension next : extensions) { next.write(resDef, theResource, theEventWriter); } theEventWriter.endArray(); } if (modifierExtensions.isEmpty() == false) { beginArray(theEventWriter, "modifierExtension"); for (HeldExtension next : modifierExtensions) { next.write(resDef, theResource, theEventWriter); } theEventWriter.endArray(); } } private void writeOptionalTagWithDecimalNode(JsonLikeWriter theEventWriter, String theElementName, DecimalDt theValue) throws IOException { if (theValue != null && theValue.isEmpty() == false) { write(theEventWriter, theElementName, theValue.getValue()); } } private void writeOptionalTagWithNumberNode(JsonLikeWriter theEventWriter, String theElementName, IntegerDt theValue) throws IOException { if (theValue != null && theValue.isEmpty() == false) { write(theEventWriter, theElementName, theValue.getValue().intValue()); } } private void writeOptionalTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, IPrimitiveDatatype<?> thePrimitive) throws IOException { if (thePrimitive == null) { return; } String str = thePrimitive.getValueAsString(); writeOptionalTagWithTextNode(theEventWriter, theElementName, str); } private void writeOptionalTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, String theValue) throws IOException { if (StringUtils.isNotBlank(theValue)) { write(theEventWriter, theElementName, theValue); } } private void writeTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, IPrimitiveDatatype<?> theIdDt) throws IOException { if (theIdDt != null && !theIdDt.isEmpty()) { write(theEventWriter, theElementName, theIdDt.getValueAsString()); } else { theEventWriter.writeNull(theElementName); } } private void writeTagWithTextNode(JsonLikeWriter theEventWriter, String theElementName, StringDt theStringDt) throws IOException { if (StringUtils.isNotBlank(theStringDt.getValue())) { write(theEventWriter, theElementName, theStringDt.getValue()); } // else { // theEventWriter.writeNull(theElementName); // } } public static Gson newGson() { Gson gson = new GsonBuilder().disableHtmlEscaping().create(); return gson; } private static void write(JsonLikeWriter theWriter, String theName, String theValue) throws IOException { theWriter.write(theName, theValue); } private class HeldExtension implements Comparable<HeldExtension> { private CompositeChildElement myChildElem; private RuntimeChildDeclaredExtensionDefinition myDef; private boolean myModifier; private IBaseExtension<?, ?> myUndeclaredExtension; private IBase myValue; public HeldExtension(IBaseExtension<?, ?> theUndeclaredExtension, boolean theModifier, CompositeChildElement theChildElem) { assert theUndeclaredExtension != null; myUndeclaredExtension = theUndeclaredExtension; myModifier = theModifier; myChildElem = theChildElem; } public HeldExtension(RuntimeChildDeclaredExtensionDefinition theDef, IBase theValue, CompositeChildElement theChildElem) { assert theDef != null; assert theValue != null; myDef = theDef; myValue = theValue; myChildElem = theChildElem; } @Override public int compareTo(HeldExtension theArg0) { String url1 = myDef != null ? myDef.getExtensionUrl() : myUndeclaredExtension.getUrl(); String url2 = theArg0.myDef != null ? theArg0.myDef.getExtensionUrl() : theArg0.myUndeclaredExtension.getUrl(); url1 = defaultString(url1); url2 = defaultString(url2); return url1.compareTo(url2); } public void write(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter) throws IOException { if (myUndeclaredExtension != null) { writeUndeclaredExtension(theResDef, theResource, theEventWriter, myUndeclaredExtension); } else { theEventWriter.beginObject(); writeCommentsPreAndPost(myValue, theEventWriter); JsonParser.write(theEventWriter, "url", myDef.getExtensionUrl()); /* * This makes sure that even if the extension contains a reference to a contained * resource which has a HAPI-assigned ID we'll still encode that ID. * * See #327 */ List<? extends IBase> preProcessedValue = preProcessValues(myDef, theResource, Collections.singletonList(myValue), myChildElem); myValue = preProcessedValue.get(0); BaseRuntimeElementDefinition<?> def = myDef.getChildElementDefinitionByDatatype(myValue.getClass()); if (def.getChildType() == ChildTypeEnum.RESOURCE_BLOCK) { extractAndWriteExtensionsAsDirectChild(myValue, theEventWriter, def, theResDef, theResource, myChildElem); } else { String childName = myDef.getChildNameByDatatype(myValue.getClass()); encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, myValue, def, childName, false, null, false); } theEventWriter.endObject(); } } private void writeUndeclaredExtension(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonLikeWriter theEventWriter, IBaseExtension<?, ?> ext) throws IOException { IBase value = ext.getValue(); String extensionUrl = ext.getUrl(); theEventWriter.beginObject(); writeCommentsPreAndPost(myUndeclaredExtension, theEventWriter); String elementId = getCompositeElementId(ext); if (isNotBlank(elementId)) { JsonParser.write(theEventWriter, "id", getCompositeElementId(ext)); } JsonParser.write(theEventWriter, "url", extensionUrl); boolean noValue = value == null || value.isEmpty(); if (noValue && ext.getExtension().isEmpty()) { ourLog.debug("Extension with URL[{}] has no value", extensionUrl); } else if (noValue) { if (myModifier) { beginArray(theEventWriter, "modifierExtension"); } else { beginArray(theEventWriter, "extension"); } for (Object next : ext.getExtension()) { writeUndeclaredExtension(theResDef, theResource, theEventWriter, (IBaseExtension<?, ?>) next); } theEventWriter.endArray(); } else { /* * Pre-process value - This is called in case the value is a reference * since we might modify the text */ value = JsonParser.super.preProcessValues(myDef, theResource, Collections.singletonList(value), myChildElem).get(0); RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition(); String childName = extDef.getChildNameByDatatype(value.getClass()); if (childName == null) { childName = "value" + WordUtils.capitalize(myContext.getElementDefinition(value.getClass()).getName()); } BaseRuntimeElementDefinition<?> childDef = extDef.getChildElementDefinitionByDatatype(value.getClass()); if (childDef == null) { throw new ConfigurationException("Unable to encode extension, unregognized child element type: " + value.getClass().getCanonicalName()); } encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, value, childDef, childName, true, null, false); } // theEventWriter.name(myUndeclaredExtension.get); theEventWriter.endObject(); } } }
package org.xmlactions.pager.actions.mapping; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.xmlactions.action.ActionConst; import org.xmlactions.action.config.ExecContext; import org.xmlactions.action.config.IExecContext; import org.xmlactions.common.io.ResourceUtils; import org.xmlactions.web.RequestExecContext; public class TestJSONGetAction { private static Logger logger = LoggerFactory.getLogger(TestJSONGetAction.class); private static IExecContext execContext; private static final String[] configFiles = { ActionConst.SPRING_STARTUP_CONFIG, "/config/spring/test-spring-pager-web-startup.xml" }; private String json = "{\r\n" + " \"rates\": [{\n" + " \"type\": \"FIT\",\n" + " \"packageType\": \"FIT\",\n" + " \"price\": {\n" + " \"currency\": \"GBP\",\n" + " \"amount\": 42900\n" + " },\n" + " \"pkgPrice\": {\n" + " \"currency\": \"GBP\",\n" + " \"amount\": 85800\n" + " },\n" + " \"adultPrice\": {\n" + " \"currency\": \"GBP\",\n" + " \"amount\": 42900\n" + " },\n" + " \"childPrice\": {\n" + " \"currency\": \"GBP\",\n" + " \"amount\": 0\n" + " }\n" + " }]\n" + "}"; @Before public void setUp() { if (execContext == null) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(configFiles); execContext = (IExecContext) applicationContext.getBean(ActionConst.EXEC_CONTEXT_BEAN_REF); RequestExecContext.set(execContext); } } @Test public void testJSONFormat() { String jsonString = "{\"name\":\"Fred\"}"; JSONObject jsonObject = new JSONObject(jsonString); jsonString = "{ \"data\": [{\"name\":\"Fred\"}]}"; jsonObject = new JSONObject(jsonString); } @Test public void testFromFile() throws Exception { String jsonString = ResourceUtils.loadFile("/org/xmlactions/pager/actions/mapping/data.json"); JSONGetAction jsonGetAction = new JSONGetAction(); jsonGetAction.setJson_data(jsonString); jsonGetAction.setJson_path("root_att"); jsonGetAction.setIndex(0); String output = jsonGetAction.execute(execContext); assertEquals("The Root Attribute", output); jsonGetAction.setRow_map_name("fred"); output = jsonGetAction.execute(execContext); assertEquals("The Root Attribute", execContext.get("fred")); jsonGetAction.setRow_map_name(""); jsonGetAction.setJson_path("vessel_gear_types_category/image_url"); output = jsonGetAction.execute(execContext); assertEquals("images/gears/surrounding_nets.png", output); jsonGetAction.setRow_map_name("fred"); output = jsonGetAction.execute(execContext); assertEquals("images/gears/surrounding_nets.png", execContext.get("fred")); jsonGetAction.setRow_map_name(""); jsonGetAction.setIndex(1); output = jsonGetAction.execute(execContext); assertEquals("images/gears/seine_nets.jpg", output); jsonGetAction.setIndex(3); output = jsonGetAction.execute(execContext); assertEquals("images/gears/trawl_nets.jpg", output); jsonGetAction.setRow_map_name("fred"); jsonGetAction.setIndex(5); output = jsonGetAction.execute(execContext); assertEquals("images/gears/falling_gear.png", execContext.get("fred")); } @Test public void testFromHotelFileAsResponse() throws Exception { String jsonString = ResourceUtils.loadFile("/org/xmlactions/pager/actions/mapping/hotel.json"); JSONGetAction jsonGetAction = new JSONGetAction(); jsonGetAction.setJson_data(jsonString); jsonGetAction.setJson_path("location/coordinates"); jsonGetAction.setIndex(0); String output = jsonGetAction.execute(execContext); assertEquals("13.894", output); jsonGetAction.setIndex(1); output = jsonGetAction.execute(execContext); assertEquals("40.6972", output); jsonGetAction.setIndex(-1); output = jsonGetAction.execute(execContext); assertEquals("[13.894,40.6972]", output); } @Test public void testFromHotelFileAsKey() throws Exception { String jsonString = ResourceUtils.loadFile("/org/xmlactions/pager/actions/mapping/hotel.json"); JSONGetAction jsonGetAction = new JSONGetAction(); jsonGetAction.setJson_data(jsonString); jsonGetAction.setJson_path("location/coordinates"); jsonGetAction.setRow_map_name("fred"); jsonGetAction.setIndex(0); String output = jsonGetAction.execute(execContext); assertEquals("13.894", execContext.get("fred")); jsonGetAction.setIndex(1); jsonGetAction.setRow_map_name("fred"); output = jsonGetAction.execute(execContext); assertEquals("40.6972", execContext.get("fred")); jsonGetAction.setIndex(-1); jsonGetAction.setRow_map_name("fred"); output = jsonGetAction.execute(execContext); assertEquals("[13.894,40.6972]", execContext.get("fred")); } @Test public void testGetKey() throws Exception { String jsonString = ResourceUtils.loadFile("/org/xmlactions/pager/actions/mapping/hotel.json"); JSONGetAction jsonGetAction = new JSONGetAction(); jsonGetAction.setJson_data(jsonString); jsonGetAction.setJson_path("location/coordinates"); jsonGetAction.setIndex(0); String output = jsonGetAction.execute(execContext); assertEquals("13.894", output); jsonGetAction.setKey("ppp"); output = jsonGetAction.execute(execContext); assertEquals("", output); output = (String) execContext.get("ppp"); assertEquals("13.894", output); } @Test public void testJsonObject() throws Exception { Map<String, Object> map = new HashMap(); map.put("dara", json); execContext.addNamedMap("data", map); Object obj = execContext.get("data:dara/rates/type"); assertEquals("FIT", obj); JSONGetAction jsonGetAction = new JSONGetAction(); jsonGetAction.setJson_data("${data}"); jsonGetAction.setJson_path("dara/rates/pkgPrice/currency"); jsonGetAction.setIndex(0); String output = jsonGetAction.execute(execContext); assertEquals("GBP", output); jsonGetAction.setJson_path("dara/rates/pkgPrice/amount"); Object amount = jsonGetAction.execute(execContext); assertEquals("85800", amount); } }