repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
cybertheye/evolution-from-netty-to-springboot
mimic-tomcat/src/main/java/com/attackonarchitect/MimicTomcatServer.java
[ { "identifier": "ServletManagerFactory", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/servlet/ServletManagerFactory.java", "snippet": "public class ServletManagerFactory {\n private ServletManagerFactory(){}\n\n private static ServletManager servletManager;\n public static ServletManager getInstance(ComponentScanner provider, ServletContext servletContext){\n if(servletManager ==null){\n servletManager=ServletManagerImpl.getInstance(provider,servletContext);\n }\n return servletManager;\n }\n}" }, { "identifier": "ServletContext", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/context/ServletContext.java", "snippet": "public interface ServletContext {\n\n /**\n * 设置一个属性\n * @param name\n * @param obj\n */\n <T> void setAttribute(String name, T obj);\n\n /**\n * 取一个属性\n * @param name\n * @return\n */\n Object getAttribute(String name);\n// void register(EventListener listener);\n//\n// void registerAll(List<String> listeners);\n//\n\n Notifier getNotifiler();\n}" }, { "identifier": "ServletContextFactory", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/context/ServletContextFactory.java", "snippet": "public class ServletContextFactory {\n private ServletContextFactory() {\n }\n\n private static ServletContext cache;\n\n public static ServletContext getInstance(List<String> webListeners, Notifier notifier) {\n if (cache == null) {\n cache = ApplicationContext.getInstance(notifier);\n// ((ApplicationContext) cache).setNotifiler(notifier);\n// ServletContextEvent sce = new ServletContextEvent();\n// sce.setSource(cache);\n// sce.setName(\"ccccccccc\");\n// new Thread(new Runnable() {\n// @Override\n// public void run() {\n// notifyServletContextListener(webListeners, sce);\n// }\n// }).start();\n }\n\n return cache;\n }\n}" }, { "identifier": "DefaultMimicTomcatChannelHandler", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/handler/DefaultMimicTomcatChannelHandler.java", "snippet": "public class DefaultMimicTomcatChannelHandler extends ChannelInboundHandlerAdapter {\n\n private ComponentScanner scanner;\n private ServletContext servletContext;\n public DefaultMimicTomcatChannelHandler(ComponentScanner scanner, ServletContext servletContext) {\n this.scanner = scanner;\n this.servletContext = servletContext;\n }\n\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n MTRequest request = (MTRequest) msg;\n String uri = request.uri();\n\n RouteStrategy strategy = new RouteMaxMatchStrategy(ServletManagerFactory.getInstance(scanner,servletContext));\n Servlet servlet = strategy.route(uri);\n\n MTResponse response = new HttpMTResponse(ctx);\n\n Chain filterChain = FilterChainImplFactory.createFilterChain(servlet,uri,scanner);\n\n filterChain.start(request,response);\n }\n\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\n cause.printStackTrace();\n super.exceptionCaught(ctx, cause);\n }\n}" }, { "identifier": "MimicHttpInBoundHandler", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/handler/MimicHttpInBoundHandler.java", "snippet": "public class MimicHttpInBoundHandler extends ChannelInboundHandlerAdapter {\n private ServletContext servletContext;\n\n public MimicHttpInBoundHandler(ServletContext servletContext) {\n this.servletContext = servletContext;\n }\n\n\n @Override\n public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\n HttpRequest req = (HttpRequest) msg;\n\n HttpMTRequest request = HttpRequestProxyFactory.createProxy(req,servletContext).createRequest();\n Map<String,String> parameters = new HashMap<>();\n\n this.parseParameters(req,parameters);\n request.setParametersDepot(parameters);\n\n ServletRequestEvent servletRequestEvent = new ServletRequestEvent();\n //todo set属性\n\n this.notifyRequestListener(servletRequestEvent);\n\n super.channelRead(ctx, request);\n }\n\n private void parseParameters(HttpRequest req, Map<String, String> parameters) {\n String uri = req.uri();\n // 需要支持没有参数\n if(!uri.contains(\"?\")) return;\n\n\n String parametersPart = uri.split(\"\\\\?\")[1];\n // name=cy&password=123456\n\n String[] paramParts = parametersPart.split(\"&\");\n\n Arrays.stream(paramParts).forEach(pairParam->{\n String[] ps = pairParam.split(\"=\");\n parameters.put(ps[0],ps[1]);\n });\n }\n\n private void notifyRequestListener(ServletRequestEvent sre) {\n Notifier notifier = (Notifier) servletContext.getAttribute(\"notifier\");\n notifier.notifyListeners(ServletRequestListener.class,sre);\n }\n}" }, { "identifier": "Notifier", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/listener/Notifier.java", "snippet": "public interface Notifier {\n void notifyListeners(Class<?> listener ,Event event);\n}" }, { "identifier": "NotifierImpl", "path": "mimic-tomcat/src/main/java/com/attackonarchitect/listener/NotifierImpl.java", "snippet": "public class NotifierImpl implements Notifier{\n\n //web context\n private List<ServletContextListener> servletContextListenersList;\n private List<ServletContextAttributeListener> servletContextAttributeListenerList;\n\n //request\n private List<ServletRequestAttributeListener> servletRequestAttributeListenerList;\n\n //todo 添加其他的 listener\n\n\n public NotifierImpl(List<String> webListeners) {\n init(webListeners);\n }\n\n private void init(List<String> webListeners) {\n\n webListeners.forEach(listenerClazzName->{\n try {\n Class<?> clazz = Class.forName(listenerClazzName);\n //web context\n if (ServletContextListener.class.isAssignableFrom(clazz)) {\n getServletContextListenersList()\n .add((ServletContextListener) clazz.newInstance());\n }\n if(ServletContextAttributeListener.class.isAssignableFrom(clazz)){\n getServletContextAttributeListenerList()\n .add((ServletContextAttributeListener) clazz.newInstance());\n }\n\n // request\n if(ServletRequestAttributeListener.class.isAssignableFrom(clazz)){\n getServletRequestAttributeListenerList()\n .add((ServletRequestAttributeListener) clazz.newInstance());\n }\n\n // session\n // todo 增加其他类型的 Listener\n\n\n\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n } catch (InstantiationException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n\n\n });\n }\n\n @Override\n public void notifyListeners(Class<?> listener, Event event) {\n if(listener== ServletRequestAttributeListener.class){\n notifyServletRequestAttributeListeners(event);\n }\n if(listener == ServletContextAttributeListener.class){\n notifyServletContextAttributeListeners(event);\n }\n if(listener == ServletContextListener.class){\n notifyServletContextListeners(event);\n }\n\n //添加其他类型\n\n }\n\n private void notifyServletContextListeners(Event event) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n getServletContextListenersList()\n .forEach(listener -> {\n listener.contextInitialized((ServletContextEvent) event);\n });\n }\n }).start();\n\n }\n\n private void notifyServletContextAttributeListeners(Event event) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n getServletContextAttributeListenerList().forEach(listener->{\n listener.attributeAdded((ServletContextAttributeEvent) event);\n });\n }\n }).start();\n }\n\n private void notifyServletRequestAttributeListeners(Event event) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n getServletRequestAttributeListenerList().forEach(listener->{\n listener.requestAttributeAdded((ServletRequestAttributeEvent) event);\n });\n }\n }).start();\n }\n\n\n\n\n ////getter,setter\n\n\n public List<ServletContextAttributeListener> getServletContextAttributeListenerList() {\n if(servletContextAttributeListenerList == null){\n servletContextAttributeListenerList = new ArrayList<>();\n }\n return servletContextAttributeListenerList;\n }\n\n public List<ServletContextListener> getServletContextListenersList() {\n if(servletContextListenersList == null){\n servletContextListenersList = new ArrayList<>();\n }\n return servletContextListenersList;\n }\n\n public List<ServletRequestAttributeListener> getServletRequestAttributeListenerList() {\n if(servletRequestAttributeListenerList == null){\n servletRequestAttributeListenerList = new ArrayList<>();\n }\n return servletRequestAttributeListenerList;\n }\n\n}" } ]
import com.attackonarchitect.servlet.ServletManagerFactory; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import com.attackonarchitect.context.ServletContext; import com.attackonarchitect.context.ServletContextFactory; import com.attackonarchitect.handler.DefaultMimicTomcatChannelHandler; import com.attackonarchitect.handler.MimicHttpInBoundHandler; import com.attackonarchitect.listener.Notifier; import com.attackonarchitect.listener.NotifierImpl;
2,365
package com.attackonarchitect; /** * @description: */ public class MimicTomcatServer { private final int PORT; public MimicTomcatServer(int PORT) { this.PORT = PORT; } private ComponentScanner scanner; private ServletContext servletContext; public void start(Class<?> clazz){ scanner = new WebComponentScanner(clazz); Notifier notifier = new NotifierImpl(scanner.getWebListenerComponents()); servletContext = ServletContextFactory.getInstance(scanner.getWebListenerComponents(),notifier); servletContext.setAttribute("notifier",notifier); //初始化servlet一下,主要是preinit
package com.attackonarchitect; /** * @description: */ public class MimicTomcatServer { private final int PORT; public MimicTomcatServer(int PORT) { this.PORT = PORT; } private ComponentScanner scanner; private ServletContext servletContext; public void start(Class<?> clazz){ scanner = new WebComponentScanner(clazz); Notifier notifier = new NotifierImpl(scanner.getWebListenerComponents()); servletContext = ServletContextFactory.getInstance(scanner.getWebListenerComponents(),notifier); servletContext.setAttribute("notifier",notifier); //初始化servlet一下,主要是preinit
ServletManagerFactory.getInstance(scanner,servletContext);
0
2023-10-31 07:16:50+00:00
4k
373675032/verio-house
src/main/java/com/verio/service/RoomDetailService.java
[ { "identifier": "RoomDetailDao", "path": "src/main/java/com/verio/dao/RoomDetailDao.java", "snippet": "@Repository\npublic interface RoomDetailDao extends BaseMapper<RoomDetail> {\n\n}" }, { "identifier": "RoomDetail", "path": "src/main/java/com/verio/entity/RoomDetail.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@TableName(\"room_detail\")\npublic class RoomDetail implements Serializable {\n\n private static final long serialVersionUID = 707297687564965826L;\n\n /**\n * 主键ID\n */\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n /**\n * 房间ID\n */\n private Integer roomId;\n\n /**\n * 房间数量\n */\n private Integer bedroomCount;\n\n /**\n * 客厅数量\n */\n private Integer parlourCount;\n\n /**\n * 卫生间数量\n */\n private Integer restroomCount;\n\n /**\n * 浴室数量\n */\n private Integer bathroomCount;\n\n /**\n * 大小\n */\n private String capacity;\n\n /**\n * 车库数量\n */\n private Integer garage;\n\n /**\n * 小区\n */\n private String area;\n\n /**\n * 详细地址\n */\n private String address;\n\n /**\n * 类型\n */\n private String type;\n\n /**\n * 建造年限\n */\n private String buildYear;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 是否有电梯\n */\n private String elevator;\n\n /**\n * 是否有厨房\n */\n private String kitchen;\n\n /**\n * 免费Wi-Fi\n */\n private String freeWifi;\n\n /**\n * 窗户\n */\n private String window;\n\n /**\n * 是否有地铁\n */\n private String metro;\n\n /**\n * 租赁方式\n */\n private String rentType;\n\n /**\n * 创建时间\n */\n @JSONField(format = \"yyyy-MM-dd HH:mm:ss\")\n private Date createTime;\n\n /**\n * 修改时间\n */\n @JSONField(format = \"yyyy-MM-dd HH:mm:ss\")\n private Date updateTime;\n\n}" }, { "identifier": "Assert", "path": "src/main/java/com/verio/utils/Assert.java", "snippet": "public class Assert {\n\n public static boolean isEmpty(CharSequence s) {\n if (s == null || s.length() == 0) {\n return true;\n }\n for (int i = 0; i < s.length(); ++i) {\n if (' ' != s.charAt(i)) {\n return false;\n }\n }\n return true;\n }\n\n public static boolean isEmpty(Collection<?> obj) {\n return obj == null || obj.isEmpty();\n }\n\n public static boolean isEmpty(Map<?, ?> obj) {\n return obj == null || obj.isEmpty();\n }\n\n public static boolean isEmpty(Object[] obj) {\n return obj == null || obj.length == 0;\n }\n\n public static boolean isEmpty(Object obj) {\n return obj == null;\n }\n\n public static boolean isEmpty(List<?> obj) {\n return obj == null || obj.size() == 0;\n }\n\n public static boolean notEmpty(CharSequence s) {\n return !isEmpty(s);\n }\n\n public static boolean notEmpty(Collection<?> obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Map<?, ?> obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Object[] obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(Object obj) {\n return !isEmpty(obj);\n }\n\n public static boolean notEmpty(List<?> obj) {\n return !isEmpty(obj);\n }\n\n public static void assertNotEmpty(CharSequence s, String name) {\n if (isEmpty(s)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Collection<?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Map<?, ?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Object[] obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(Object obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n public static void assertNotEmpty(List<?> obj, String name) {\n if (isEmpty(obj)) {\n throwException(name);\n }\n }\n\n private static String throwException(String name) {\n throw new RuntimeException(\"REQUEST_PARAM_IS_NULL 请求参数<\" + name + \">为空\");\n }\n}" }, { "identifier": "BeanUtils", "path": "src/main/java/com/verio/utils/BeanUtils.java", "snippet": "public class BeanUtils {\r\n\r\n private static Map<String, BeanCopier> beanCopierMap = new HashMap();\r\n\r\n public static <T> T copy(Object src, Class<T> clazz) throws InstantiationException, IllegalAccessException {\r\n if ((null == src) || (null == clazz)) return null;\r\n Object des = clazz.newInstance();\r\n copy(src, des);\r\n return (T) des;\r\n }\r\n\r\n public static void copy(Object src, Object des) {\r\n if ((null == src) || (null == des)) return;\r\n String key = generateKey(src.getClass(), des.getClass());\r\n BeanCopier copier = (BeanCopier) beanCopierMap.get(key);\r\n if (null == copier) {\r\n copier = BeanCopier.create(src.getClass(), des.getClass(), false);\r\n beanCopierMap.put(key, copier);\r\n }\r\n copier.copy(src, des, null);\r\n }\r\n\r\n public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) throws InstantiationException, IllegalAccessException {\r\n if ((null == map) || (null == clazz)) return null;\r\n T bean = clazz.newInstance();\r\n map2Bean(map, bean);\r\n return bean;\r\n }\r\n\r\n public static <T> void map2Bean(Map<String, Object> map, T bean) {\r\n if ((null == map) || (null == bean)) return;\r\n BeanMap beanMap = BeanMap.create(bean);\r\n beanMap.putAll(map);\r\n }\r\n\r\n public static Map<String, Object> bean2Map(Object bean) {\r\n if (null == bean) return null;\r\n return copy(BeanMap.create(bean));\r\n }\r\n\r\n public static <T> List<Map<String, Object>> mapList(List<T> beanList) {\r\n if ((null == beanList) || (beanList.size() < 1)) return null;\r\n List<Map<String, Object>> mapList = new ArrayList();\r\n int i = 0;\r\n for (int size = beanList.size(); i < size; i++) {\r\n mapList.add(bean2Map(beanList.get(i)));\r\n }\r\n return mapList;\r\n }\r\n\r\n public static <K, V> Map<K, V> copy(Map<K, V> src) {\r\n if (null == src) return null;\r\n Map<K, V> des = new HashMap();\r\n des.putAll(src);\r\n return des;\r\n }\r\n\r\n public static void apply(Object des, Object... srcs) {\r\n if ((null == des) || (null == srcs) || (srcs.length < 1)) return;\r\n BeanMap desBeanMap = BeanMap.create(des);\r\n Set<?> keys = desBeanMap.keySet();\r\n BeanMap srcBeanMap = null;\r\n for (Object src : srcs) {\r\n if (null != src) {\r\n srcBeanMap = BeanMap.create(src);\r\n for (Object key : keys) {\r\n Object value = srcBeanMap.get(key);\r\n if ((null != value) && (null == desBeanMap.get(key))) {\r\n desBeanMap.put(des, key, value);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n public static void apply(Object des, List<Map<String, Object>> srcList) {\r\n Map<String, Object> src;\r\n if ((null == des) || (null == srcList) || (srcList.isEmpty())) return;\r\n BeanMap desBeanMap = BeanMap.create(des);\r\n Set<?> keys = desBeanMap.keySet();\r\n for (Iterator localIterator1 = srcList.iterator(); localIterator1.hasNext(); ) {\r\n src = (Map) localIterator1.next();\r\n if ((null != src) && (!src.isEmpty())) {\r\n for (Object key : keys) {\r\n Object value = src.get(key);\r\n if (null != value) {\r\n desBeanMap.put(des, key, value);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n private static String generateKey(Class<?> src, Class<?> des) {\r\n return src.getName() + des.getName();\r\n }\r\n\r\n public static <T> String beanToString(T value) {\r\n if (value == null) {\r\n return null;\r\n }\r\n Class<?> clazz = value.getClass();\r\n if (clazz == int.class || clazz == Integer.class) {\r\n return \"\" + value;\r\n } else if (clazz == String.class) {\r\n return (String) value;\r\n } else if (clazz == long.class || clazz == Long.class) {\r\n return \"\" + value;\r\n } else {\r\n return JSON.toJSONString(value);\r\n }\r\n }\r\n\r\n public static <T> T stringToBean(String str, Class<T> clazz) {\r\n if (str == null || str.length() <= 0 || clazz == null) {\r\n return null;\r\n }\r\n if (clazz == int.class || clazz == Integer.class) {\r\n return (T) Integer.valueOf(str);\r\n } else if (clazz == String.class) {\r\n return (T) str;\r\n } else if (clazz == long.class || clazz == Long.class) {\r\n return (T) Long.valueOf(str);\r\n } else {\r\n return JSON.toJavaObject(JSON.parseObject(str), clazz);\r\n }\r\n }\r\n}\r" }, { "identifier": "VariableNameUtils", "path": "src/main/java/com/verio/utils/VariableNameUtils.java", "snippet": "public class VariableNameUtils {\n\n private static Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n\n private static Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /**\n * 下划线转驼峰\n */\n public static String lineToHump(String str) {\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /**\n * 驼峰转下划线\n */\n public static String humpToLine(String str) {\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n}" } ]
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.verio.dao.RoomDetailDao; import com.verio.entity.RoomDetail; import com.verio.utils.Assert; import com.verio.utils.BeanUtils; import com.verio.utils.VariableNameUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.List; import java.util.Map;
2,965
package com.verio.service; /** * 房屋详情服务 * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Service public class RoomDetailService extends BaseService<RoomDetail> { @Autowired protected RoomDetailDao selfDao; @Override public List<RoomDetail> query(RoomDetail o) { QueryWrapper<RoomDetail> wrapper = new QueryWrapper<>(); if (Assert.notEmpty(o)) {
package com.verio.service; /** * 房屋详情服务 * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Service public class RoomDetailService extends BaseService<RoomDetail> { @Autowired protected RoomDetailDao selfDao; @Override public List<RoomDetail> query(RoomDetail o) { QueryWrapper<RoomDetail> wrapper = new QueryWrapper<>(); if (Assert.notEmpty(o)) {
Map<String, Object> bean2Map = BeanUtils.bean2Map(o);
3
2023-10-29 14:50:56+00:00
4k
Changbaiqi/yatori
yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/LoginAction.java
[ { "identifier": "ConverterLoginResponse", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/ConverterLoginResponse.java", "snippet": "public class ConverterLoginResponse {\n // Date-time helpers\n\n private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()\n .appendOptional(DateTimeFormatter.ISO_DATE_TIME)\n .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)\n .appendOptional(DateTimeFormatter.ISO_INSTANT)\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss.SX\"))\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ssX\"))\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\"))\n .toFormatter()\n .withZone(ZoneOffset.UTC);\n\n public static OffsetDateTime parseDateTimeString(String str) {\n return ZonedDateTime.from(ConverterLoginResponse.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();\n }\n\n private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()\n .appendOptional(DateTimeFormatter.ISO_TIME)\n .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)\n .parseDefaulting(ChronoField.YEAR, 2020)\n .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)\n .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)\n .toFormatter()\n .withZone(ZoneOffset.UTC);\n\n public static OffsetTime parseTimeString(String str) {\n return ZonedDateTime.from(ConverterLoginResponse.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();\n }\n // Serialize/deserialize helpers\n\n public static LoginResponseRequest fromJsonString(String json) throws IOException {\n return getObjectReader().readValue(json);\n }\n\n public static String toJsonString(LoginResponseRequest obj) throws JsonProcessingException {\n return getObjectWriter().writeValueAsString(obj);\n }\n\n private static ObjectReader reader;\n private static ObjectWriter writer;\n\n private static void instantiateMapper() {\n ObjectMapper mapper = new ObjectMapper();\n mapper.findAndRegisterModules();\n mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);\n SimpleModule module = new SimpleModule();\n module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {\n @Override\n public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {\n String value = jsonParser.getText();\n return ConverterLoginResponse.parseDateTimeString(value);\n }\n });\n mapper.registerModule(module);\n reader = mapper.readerFor(LoginResponseRequest.class);\n writer = mapper.writerFor(LoginResponseRequest.class);\n }\n\n private static ObjectReader getObjectReader() {\n if (reader == null) instantiateMapper();\n return reader;\n }\n\n private static ObjectWriter getObjectWriter() {\n if (writer == null) instantiateMapper();\n return writer;\n }\n}" }, { "identifier": "LoginResponseRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java", "snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n private LoginResponseData data;\n @JsonProperty(\"msg\")\n private String msg;\n @JsonProperty(\"sub_code\")\n private long subCode;\n @JsonProperty(\"sub_msg\")\n private Object subMsg;\n}" }, { "identifier": "ConverterToLogin", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/tologin/ConverterToLogin.java", "snippet": "public class ConverterToLogin {\n // Date-time helpers\n\n private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()\n .appendOptional(DateTimeFormatter.ISO_DATE_TIME)\n .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)\n .appendOptional(DateTimeFormatter.ISO_INSTANT)\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss.SX\"))\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ssX\"))\n .appendOptional(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\"))\n .toFormatter()\n .withZone(ZoneOffset.UTC);\n\n public static OffsetDateTime parseDateTimeString(String str) {\n return ZonedDateTime.from(ConverterToLogin.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();\n }\n\n private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()\n .appendOptional(DateTimeFormatter.ISO_TIME)\n .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)\n .parseDefaulting(ChronoField.YEAR, 2020)\n .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)\n .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)\n .toFormatter()\n .withZone(ZoneOffset.UTC);\n\n public static OffsetTime parseTimeString(String str) {\n return ZonedDateTime.from(ConverterToLogin.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();\n }\n // Serialize/deserialize helpers\n\n public static ToLoginRequest fromJsonString(String json) throws IOException {\n return getObjectReader().readValue(json);\n }\n\n public static String toJsonString(ToLoginRequest obj) throws JsonProcessingException {\n return getObjectWriter().writeValueAsString(obj);\n }\n\n private static ObjectReader reader;\n private static ObjectWriter writer;\n\n private static void instantiateMapper() {\n ObjectMapper mapper = new ObjectMapper();\n mapper.findAndRegisterModules();\n mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);\n SimpleModule module = new SimpleModule();\n module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {\n @Override\n public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {\n String value = jsonParser.getText();\n return ConverterToLogin.parseDateTimeString(value);\n }\n });\n mapper.registerModule(module);\n reader = mapper.readerFor(ToLoginRequest.class);\n writer = mapper.writerFor(ToLoginRequest.class);\n }\n\n private static ObjectReader getObjectReader() {\n if (reader == null) instantiateMapper();\n return reader;\n }\n\n private static ObjectWriter getObjectWriter() {\n if (writer == null) instantiateMapper();\n return writer;\n }\n}" }, { "identifier": "ToLoginRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/tologin/ToLoginRequest.java", "snippet": "@lombok.Data\npublic class ToLoginRequest {\n @JsonProperty(\"account\")\n private String account;\n @JsonProperty(\"code\")\n private String code;\n @JsonProperty(\"password\")\n private String password;\n}" }, { "identifier": "AccountCacheCangHui", "path": "yatori-core/src/main/java/com/cbq/yatori/core/entity/AccountCacheCangHui.java", "snippet": "@Data\npublic class AccountCacheCangHui implements AccountCache {\n private String session;\n private String code;\n private String token;\n private Integer status=0;\n\n private ExamJson examJson; //我的考试\n}" }, { "identifier": "User", "path": "yatori-core/src/main/java/com/cbq/yatori/core/entity/User.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User {\n private AccountType accountType; //对应账号平台类型\n private String url; //课程平台url\n private String account; //密码\n private String password; //账号\n private AccountCache cache; //账号缓存信息\n private CoursesCostom coursesCostom=new CoursesCostom(); //客制化课程\n}" }, { "identifier": "FileUtils", "path": "yatori-core/src/main/java/com/cbq/yatori/core/utils/FileUtils.java", "snippet": "public class FileUtils {\n private final static String PATH=\"cache\";\n\n static {\n File file = new File(PATH);\n if(!file.exists()){\n file.mkdir();\n }\n }\n public static File saveFile(byte bytes[], String fileName) {\n try {\n InputStream in = new ByteArrayInputStream(bytes);\n FileOutputStream file = new FileOutputStream(PATH+\"/\"+fileName);\n\n int j;\n while ((j = in.read()) != -1) {\n file.write(j);\n }\n file.flush();\n file.close();\n in.close();\n File file1 = new File(PATH+\"/\"+fileName);\n return file1;\n } catch (FileNotFoundException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 删除文件\n * @param file\n * @return\n */\n public static boolean deleteFile(File file){\n if(file.isFile() && file.exists()){\n file.delete();\n return true;\n }\n return false;\n }\n\n /**\n * 读取指定路径下的文本文件并返回文本字符串\n * @param file\n * @return\n */\n public static String readTxt(File file){\n if(!file.exists()){\n System.out.println(\"配置文件不存在!!!\");\n return null;\n }\n\n String text = \"\";\n try {\n InputStream inputStream = new FileInputStream(file);\n InputStreamReader inputStreamReader = new InputStreamReader(inputStream,getCharsetName(file));\n //FileReader fileReader = new FileReader(file);\n BufferedReader br = new BufferedReader(inputStreamReader);\n String res = null;\n while((res = br.readLine())!=null){\n text+=res;\n }\n } catch (FileNotFoundException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return text;\n }\n\n /**\n * 获取文件编码字符串\n *\n * @param file\n * @return\n */\n public static String getCharsetName(File file) throws IOException {\n InputStream is = Files.newInputStream(file.toPath());\n BufferedInputStream reader = new BufferedInputStream(is);\n byte[] buff = new byte[1024];\n int len = 0;\n// 检测文件编码\n UniversalDetector detector = new UniversalDetector(null);\n while ((len = reader.read(buff)) != -1 && !detector.isDone()) {\n detector.handleData(buff, 0, len);\n }\n detector.dataEnd();\n// 获取编码类型\n String encoding = detector.getDetectedCharset();\n detector.reset();\n reader.close();\n return encoding;\n }\n}" } ]
import com.cbq.yatori.core.action.canghui.entity.loginresponse.ConverterLoginResponse; import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest; import com.cbq.yatori.core.action.canghui.entity.tologin.ConverterToLogin; import com.cbq.yatori.core.action.canghui.entity.tologin.ToLoginRequest; import com.cbq.yatori.core.entity.AccountCacheCangHui; import com.cbq.yatori.core.entity.User; import com.cbq.yatori.core.utils.FileUtils; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import java.io.*; import java.net.SocketTimeoutException; import java.util.Map;
3,495
package com.cbq.yatori.core.action.canghui; /** * @description: 登录相关的Action * @author 长白崎 * @date 2023/10/23 15:19 * @version 1.0 */ @Slf4j public class LoginAction { /** * 获取SESSION * * @return */ public static String getSESSION(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); Request request = new Request.Builder() .url(user.getUrl() + "/api/v1/home/school_info") .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){ response.close(); return null; } if (response.header("set-cookie") != null) { //System.out.println(response.header("set-cookie").toString()); String[] split = response.header("set-cookie").split(";"); for (String s : split) { if (s.startsWith("SESSION")) { return s.split("=")[1]; } } } }catch (SocketTimeoutException e){ return null; }catch (JsonParseException jsonParseException){ //这种一般是访问过于频繁造成,这边延迟一一下 try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取验证码 */ public static File getCode(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); //RequestBody body = RequestBody.create(mediaType, ""); Request request = new Request.Builder() .url(user.getUrl() + "/api/v1/Kaptcha?v=%7Btime%28%29%7D") .addHeader("Cookie", "SESSION=" + ((AccountCacheCangHui)user.getCache()).getSession()) .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); byte[] bytes = response.body().bytes(); File file =FileUtils.saveFile(bytes,user.getAccountType().name()+"_"+user.getAccount()+"_"+(int)Math.random()*99999+".png"); return file; } catch (SocketTimeoutException e){ return null; }catch (JsonParseException jsonParseException){ //这种一般是访问过于频繁造成,这边延迟一一下 try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; }catch (IOException e) { log.error(""); e.printStackTrace(); } //CodeUtil.getData(bytes); return null; } /** * -1002代表验证码错误 * 登录 */ public static LoginResponseRequest toLogin(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("application/json"); //构建登录json ToLoginRequest loginRequest = new ToLoginRequest(); loginRequest.setCode(((AccountCacheCangHui)user.getCache()).getCode()); loginRequest.setAccount(user.getAccount()); loginRequest.setPassword(user.getPassword()); RequestBody body = null; try {
package com.cbq.yatori.core.action.canghui; /** * @description: 登录相关的Action * @author 长白崎 * @date 2023/10/23 15:19 * @version 1.0 */ @Slf4j public class LoginAction { /** * 获取SESSION * * @return */ public static String getSESSION(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); Request request = new Request.Builder() .url(user.getUrl() + "/api/v1/home/school_info") .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){ response.close(); return null; } if (response.header("set-cookie") != null) { //System.out.println(response.header("set-cookie").toString()); String[] split = response.header("set-cookie").split(";"); for (String s : split) { if (s.startsWith("SESSION")) { return s.split("=")[1]; } } } }catch (SocketTimeoutException e){ return null; }catch (JsonParseException jsonParseException){ //这种一般是访问过于频繁造成,这边延迟一一下 try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取验证码 */ public static File getCode(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); //RequestBody body = RequestBody.create(mediaType, ""); Request request = new Request.Builder() .url(user.getUrl() + "/api/v1/Kaptcha?v=%7Btime%28%29%7D") .addHeader("Cookie", "SESSION=" + ((AccountCacheCangHui)user.getCache()).getSession()) .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); byte[] bytes = response.body().bytes(); File file =FileUtils.saveFile(bytes,user.getAccountType().name()+"_"+user.getAccount()+"_"+(int)Math.random()*99999+".png"); return file; } catch (SocketTimeoutException e){ return null; }catch (JsonParseException jsonParseException){ //这种一般是访问过于频繁造成,这边延迟一一下 try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; }catch (IOException e) { log.error(""); e.printStackTrace(); } //CodeUtil.getData(bytes); return null; } /** * -1002代表验证码错误 * 登录 */ public static LoginResponseRequest toLogin(User user) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("application/json"); //构建登录json ToLoginRequest loginRequest = new ToLoginRequest(); loginRequest.setCode(((AccountCacheCangHui)user.getCache()).getCode()); loginRequest.setAccount(user.getAccount()); loginRequest.setPassword(user.getPassword()); RequestBody body = null; try {
body = RequestBody.create(mediaType, ConverterToLogin.toJsonString(loginRequest));
2
2023-10-30 04:15:41+00:00
4k
hezean/sustc
sustc-api/src/main/java/io/sustc/service/impl/DatabaseServiceImpl.java
[ { "identifier": "DanmuRecord", "path": "sustc-api/src/main/java/io/sustc/dto/DanmuRecord.java", "snippet": "@Data\npublic class DanmuRecord implements Serializable {\n\n /**\n * The danmu's video {@code bv}.\n */\n private String bv;\n\n /**\n * The danmu's sender {@code mid}.\n */\n private long mid;\n\n /**\n * The danmu's display time (in seconds) since the video starts.\n */\n private float time;\n\n /**\n * The danmu's content.\n */\n private String content;\n\n /**\n * The danmu's post time.\n */\n private Timestamp postTime;\n\n /**\n * The users' {@code mid} who liked this danmu.\n */\n private long[] likedBy;\n}" }, { "identifier": "UserRecord", "path": "sustc-api/src/main/java/io/sustc/dto/UserRecord.java", "snippet": "@Data\npublic class UserRecord implements Serializable {\n\n /**\n * The user's unique ID\n */\n private long mid;\n\n /**\n * The user's name\n */\n private String name;\n\n /**\n * The user's sex\n */\n private String sex;\n\n /**\n * The user's birthday, can be empty\n */\n private String birthday;\n\n /**\n * The user's level\n */\n private short level;\n\n /**\n * The user's current number of coins\n */\n private int coin;\n\n /**\n * The user's personal sign, can be null or empty\n */\n private String sign;\n\n /**\n * The user's identity\n */\n private Identity identity;\n\n /**\n * The user's password\n */\n private String password;\n\n /**\n * The user's unique qq, may be null or empty (not unique when null or empty)\n */\n private String qq;\n\n /**\n * The user's unique wechat, may be null or empty (not unique when null or empty)\n */\n private String wechat;\n\n /**\n * The users' {@code mid}s who are followed by this user\n */\n private long[] following;\n\n public enum Identity {\n USER,\n SUPERUSER,\n }\n}" }, { "identifier": "VideoRecord", "path": "sustc-api/src/main/java/io/sustc/dto/VideoRecord.java", "snippet": "@Data\npublic class VideoRecord implements Serializable {\n\n /**\n * The BV code of this video\n */\n private String bv;\n\n /**\n * The title of this video with length >= 1, the video titles of an owner cannot be the same\n */\n private String title;\n\n /**\n * The owner's {@code mid} of this video\n */\n private long ownerMid;\n\n /**\n * The owner's {@code name} of this video\n */\n private String ownerName;\n\n /**\n * The commit time of this video\n */\n private Timestamp commitTime;\n\n /**\n * The review time of this video, can be null\n */\n private Timestamp reviewTime;\n\n /**\n * The public time of this video, can be null\n */\n private Timestamp publicTime;\n\n /**\n * The length in seconds of this video\n */\n private float duration;\n\n /**\n * The description of this video\n */\n private String description;\n\n /**\n * The reviewer of this video, can be null\n */\n private Long reviewer;\n\n /**\n * The users' {@code mid}s who liked this video\n */\n private long[] like;\n\n /**\n * The users' {@code mid}s who gave coin to this video\n */\n private long[] coin;\n\n /**\n * The users' {@code mid}s who collected to this video\n */\n private long[] favorite;\n\n /**\n * The users' {@code mid}s who have watched this video\n */\n private long[] viewerMids;\n\n /**\n * The watch durations in seconds for the viewers {@code viewerMids}\n */\n private float[] viewTime;\n}" }, { "identifier": "DatabaseService", "path": "sustc-api/src/main/java/io/sustc/service/DatabaseService.java", "snippet": "public interface DatabaseService {\n\n /**\n * Acknowledges the authors of this project.\n *\n * @return a list of group members' student-id\n */\n List<Integer> getGroupMembers();\n\n /**\n * Imports data to an empty database.\n * Invalid data will not be provided.\n *\n * @param danmuRecords danmu records parsed from csv\n * @param userRecords user records parsed from csv\n * @param videoRecords video records parsed from csv\n */\n void importData(\n List<DanmuRecord> danmuRecords,\n List<UserRecord> userRecords,\n List<VideoRecord> videoRecords\n );\n\n /**\n * Truncates all tables in the database.\n * <p>\n * This would only be used in local benchmarking to help you\n * clean the database without dropping it, and won't affect your score.\n */\n void truncate();\n\n /**\n * Sums up two numbers via Postgres.\n * This method only demonstrates how to access database via JDBC.\n *\n * @param a the first number\n * @param b the second number\n * @return the sum of two numbers\n */\n Integer sum(int a, int b);\n}" } ]
import io.sustc.dto.DanmuRecord; import io.sustc.dto.UserRecord; import io.sustc.dto.VideoRecord; import io.sustc.service.DatabaseService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List;
1,734
package io.sustc.service.impl; /** * It's important to mark your implementation class with {@link Service} annotation. * As long as the class is annotated and implements the corresponding interface, you can place it under any package. */ @Service @Slf4j public class DatabaseServiceImpl implements DatabaseService { /** * Getting a {@link DataSource} instance from the framework, whose connections are managed by HikariCP. * <p> * Marking a field with {@link Autowired} annotation enables our framework to automatically * provide you a well-configured instance of {@link DataSource}. * Learn more: <a href="https://www.baeldung.com/spring-dependency-injection">Dependency Injection</a> */ @Autowired private DataSource dataSource; @Override public List<Integer> getGroupMembers() { //TODO: replace this with your own student IDs in your group return Arrays.asList(12210000, 12210001, 12210002); } @Override public void importData( List<DanmuRecord> danmuRecords, List<UserRecord> userRecords,
package io.sustc.service.impl; /** * It's important to mark your implementation class with {@link Service} annotation. * As long as the class is annotated and implements the corresponding interface, you can place it under any package. */ @Service @Slf4j public class DatabaseServiceImpl implements DatabaseService { /** * Getting a {@link DataSource} instance from the framework, whose connections are managed by HikariCP. * <p> * Marking a field with {@link Autowired} annotation enables our framework to automatically * provide you a well-configured instance of {@link DataSource}. * Learn more: <a href="https://www.baeldung.com/spring-dependency-injection">Dependency Injection</a> */ @Autowired private DataSource dataSource; @Override public List<Integer> getGroupMembers() { //TODO: replace this with your own student IDs in your group return Arrays.asList(12210000, 12210001, 12210002); } @Override public void importData( List<DanmuRecord> danmuRecords, List<UserRecord> userRecords,
List<VideoRecord> videoRecords
2
2023-10-27 03:27:20+00:00
4k
sgware/sabre
src/edu/uky/cs/nil/sabre/prog/RepeatedNodeHeuristic.java
[ { "identifier": "Settings", "path": "src/edu/uky/cs/nil/sabre/Settings.java", "snippet": "public class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final String AUTHORS = \"Stephen G. Ware\";\n\t\n\t/** The major version number comes before the decimal points */\n\tpublic static final int MAJOR_VERSION_NUMBER = 0;\n\t\n\t/** The minor version number comes after the decimal point */\n\tpublic static final int MINOR_VERSION_NUMBER = 7;\n\t\n\t/** The full version number (major + minor) as a string */\n\tpublic static final String VERSION_STRING = MAJOR_VERSION_NUMBER + \".\" + MINOR_VERSION_NUMBER;\n\t\n\t/**\n\t * A long encoding the version number which can be used as a serial version UID\n\t */\n\tpublic static final long VERSION_UID = java.nio.ByteBuffer.allocate(8).putInt(MAJOR_VERSION_NUMBER).putInt(MINOR_VERSION_NUMBER).getLong(0);\n\t\n\t/** A header including title, authors, and version number */\n\tpublic static final String CREDITS = TITLE + \" v\" + VERSION_STRING + \" by \" + AUTHORS;\n\t\n\t/** The name of the Boolean type which is pre-defined in all problems */\n\tpublic static final String BOOLEAN_TYPE_NAME = \"boolean\";\n\t\n\t/** The ID number and index of the Boolean type */\n\tpublic static final int BOOLEAN_TYPE_ID = 0;\n\t\n\t/** The comment associated with the Boolean type by default */\n\tpublic static final String BOOLEAN_TYPE_COMMENT = \"\";\n\t\n\t/** The name of the number type which is pre-defined in all problems */\n\tpublic static final String NUMBER_TYPE_NAME = \"number\";\n\t\n\t/** The ID number and index of the number type */\n\tpublic static final int NUMBER_TYPE_ID = 1;\n\t\n\t/** The comment associated with the number type by default */\n\tpublic static final String NUMBER_TYPE_COMMENT = \"\";\n\t\n\t/**\n\t * The name of the entity type which is the parent type of all other types\n\t * and is pre-defined in all problems\n\t */\n\tpublic static final String ENTITY_TYPE_NAME = \"entity\";\n\t\n\t/** The ID number and index of the entity type */\n\tpublic static final int ENTITY_TYPE_ID = 2;\n\t\n\t/** The comment associated with the entity type by default */\n\tpublic static final String ENTITY_TYPE_COMMENT = \"\";\n\t\n\t/**\n\t * The name of the character type which represents beings with beliefs and\n\t * intentions and is pre-defined in all problems\n\t */\n\tpublic static final String CHARACTER_TYPE_NAME = \"character\";\n\t\n\t/** The ID number and index of the character type */\n\tpublic static final int CHARACTER_TYPE_ID = 3;\n\t\n\t/** The comment associated with the character type by default */\n\tpublic static final String CHARACTER_TYPE_COMMENT = \"\";\n\t\n\t/** The comment associated with a newly defined type by default */\n\tpublic static final String DEFAULT_TYPE_COMMENT = \"\";\n\t\n\t/** The comment associated with a newly defined entity by default */\n\tpublic static final String DEFAULT_ENTITY_COMMENT = \"\";\t\n\t\n\t/** The comment associated with a newly defined problem by default */\n\tpublic static final String DEFAULT_PROBLEM_COMMENT = \"\";\n}" }, { "identifier": "CompiledProblem", "path": "src/edu/uky/cs/nil/sabre/comp/CompiledProblem.java", "snippet": "public class CompiledProblem extends Problem {\n\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** The compiled fluents tracked in every state of the problem */\n\tpublic final ImmutableSet<CompiledFluent> fluents;\n\t\n\t/** The set of all compiled events that can ever occur */\n\tpublic final ImmutableSet<CompiledEvent> events;\n\t\n\t/** All the compiled actions defined in this problem */\n\tpublic final EventSet<CompiledAction> actions;\n\t\n\t/** All the compiled triggers defined in this problem */\n\tpublic final EventSet<CompiledTrigger> triggers;\n\t\n\t/** A clause representing the initial state */\n\tpublic final Clause<Effect> initial;\n\t\n\t/** The initial state of the problem before planning begins */\n\tpublic final FiniteState start;\n\t\n\t/** The author's utility function */\n\tpublic final Conditional<Disjunction<Clause<Precondition>>> utility;\n\t\n\t/**\n\t * A compiled mapping which returns a utility function for each character\n\t */\n\tpublic final CompiledMapping<Conditional<Disjunction<Clause<Precondition>>>> utilities;\n\n\t/**\n\t * Constructs a new compiled problem.\n\t * \n\t * @param name the name\n\t * @param universe the universe\n\t * @param fluents the compiled fluents\n\t * @param actions the compiled actions\n\t * @param triggers the compiled triggers\n\t * @param initial the compiled initial clause\n\t * @param start the initial state\n\t * @param utility the author's utility expression\n\t * @param utilities each character's utility expressions\n\t * @param comment the comment\n\t */\n\tprotected CompiledProblem(\n\t\tString name,\n\t\tUniverse universe,\n\t\tImmutableSet<CompiledFluent> fluents,\n\t\tEventSet<CompiledAction> actions,\n\t\tEventSet<CompiledTrigger> triggers,\n\t\tClause<Effect> initial,\n\t\tFiniteState start,\n\t\tConditional<Disjunction<Clause<Precondition>>> utility,\n\t\tCompiledMapping<Conditional<Disjunction<Clause<Precondition>>>> utilities,\n\t\tString comment\n\t) {\n\t\tsuper(\n\t\t\tname,\n\t\t\tuniverse,\n\t\t\tfluents.cast(Fluent.class),\n\t\t\tactions.cast(Action.class),\n\t\t\ttriggers.cast(Trigger.class),\n\t\t\tinitial,\n\t\t\tutility,\n\t\t\tutilities.cast(Expression.class),\n\t\t\tcomment\n\t\t);\n\t\tthis.fluents = fluents;\n\t\tthis.events = super.events.cast(CompiledEvent.class);\n\t\tthis.actions = actions;\n\t\tthis.triggers = triggers;\n\t\tthis.initial = initial;\n\t\tthis.start = start;\n\t\tthis.utility = utility;\n\t\tthis.utilities = utilities;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[Compiled Problem \\\"\" + name + \"\\\": \" + fluents.size() + \" fluents; \" + actions.size() + \" actions; \" + triggers.size() + \" triggers; \" + (1 + universe.characters.size()) + \" utilities]\";\n\t}\n\t\n\t@Override\n\tpublic CompiledFluent getFluent(Signature signature) {\n\t\treturn (CompiledFluent) super.getFluent(signature);\n\t}\n\t\n\t@Override\n\tpublic CompiledEvent getEvent(Signature signature) {\n\t\treturn (CompiledEvent) super.getEvent(signature);\n\t}\n\t\n\t@Override\n\tpublic CompiledAction getAction(Signature signature) {\n\t\treturn (CompiledAction) super.getAction(signature);\n\t}\n\t\n\t@Override\n\tpublic CompiledTrigger getTrigger(Signature signature) {\n\t\treturn (CompiledTrigger) super.getTrigger(signature);\n\t}\n\t\n\t/**\n\t * Returns a compiled fluent defined in this problem based on a given\n\t * {@link Fluent fluent}, which does not need to be compiled and does not\n\t * need to be from this problem. The returned fluent will have the same\n\t * characters and signature as the given fluent, but all of its elements\n\t * will be elements defined in this problem.\n\t * \n\t * @param fluent a fluent whose characters and signature match the desired\n\t * fluent\n\t * @return a compiled fluent defined in this problem\n\t * @throws edu.uky.cs.nil.sabre.FormatException if no compiled fluent is\n\t * defined in this problem\n\t */\n\tpublic CompiledFluent getFluent(Fluent fluent) {\n\t\tfor(CompiledFluent compiled : fluents)\n\t\t\tif(compiled.characters.equals(fluent.characters) && compiled.signature.equals(fluent.signature))\n\t\t\t\treturn compiled;\n\t\tthrow Exceptions.notDefined(\"Fluent\", fluent.toString());\n\t}\n}" }, { "identifier": "Status", "path": "src/edu/uky/cs/nil/sabre/util/Worker.java", "snippet": "public static class Status {\n\t\t\n\tprivate String message = \"working...\";\n\tprivate Object[] arguments = NO_ARGUMENTS;\n\t\t\n\t/**\n\t * Constructs a new status with a given message and arguments.\n\t * \n\t * @param message the message, suitable to be passed to {@link\n\t * String#format(String, Object...)}\n\t * @param arguments the arguments to be passed to {@link\n\t * String#format(String, Object...)}\n\t */\n\tpublic Status(String message, Object...arguments) {\n\t\tthis.message = message;\n\t\tthis.arguments = arguments;\n\t}\n\t\t\n\t/**\n\t * Constructs a new status with a default message and no arguments.\n\t */\n\tpublic Status() {\n\t\tthis(\"working...\", NO_ARGUMENTS);\n\t}\n\t\t\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(message, arguments);\n\t}\n\t\t\n\t/**\n\t * Sets the format of the message this status object will display.\n\t * When {@link #toString()} is called to display the message, the\n\t * string and arguments will be passed to\n\t * {@link String#format(String, Object...)}, so the string and\n\t * arguments should be formatted accordingly.\n\t * \n\t * @param message the format of the message\n\t * @param arguments argument to be substituted into the message\n\t */\n\tpublic void setMessage(String message, Object...arguments) {\n\t\tthis.message = message;\n\t\tthis.arguments = arguments;\n\t}\n\t\t\n\t/**\n\t * Sets the message this status object will display. When the message\n\t * is set via this method, the status will have no arguments.\n\t * \n\t * @param message the message\n\t */\n\tpublic void setMessage(String message) {\n\t\tsetMessage(message, NO_ARGUMENTS);\n\t}\n\t\t\n\t/**\n\t * Updates one of the arguments previously passed to {@link\n\t * #setMessage(String, Object...)}. This method does not actually\n\t * generate the status message (only {@link #toString()} does that), so\n\t * it has a very low cost and can be called frequently.\n\t * \n\t * @param index the index of the argument to update\n\t * @param value the new value of the argument\n\t * @throws IndexOutOfBoundsException if there is no argument defined\n\t * at that index\n\t */\n\tpublic void update(int index, Object value) {\n\t\targuments[index] = value;\n\t}\n}" } ]
import java.util.HashMap; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.comp.CompiledProblem; import edu.uky.cs.nil.sabre.util.Worker.Status;
2,884
package edu.uky.cs.nil.sabre.prog; /** * The repeated node heuristic is a wrapper around a {@link ProgressionCost cost * function} that can improve the efficiency of a {@link ProgressionSearch * heuristic progression search} by preventing it from revisiting the same node * multiple times. Each time this cost function evaluates a node, it calculates * the sum of its {@link ProgressionNode#getTemporalOffset() temporal offset} * and {@link ProgressionNode#getTemporalDepth() temporal depth}. If the node * has never been evaluated before, or if that sum is less than the last time * the node was evaluated, that sum is recorded and this heuristic passes thru * to {@link #parent the heuristic it wraps around}. If the node has been * evaluated before, and if the sum is greater than or equal to the recorded * sum, this heuristic returns {@link Double#POSITIVE_INFINITY positive * infinity}. This prevents a node from being visited more than once at the * same temporal level. The sum of temporal offset and depth is checked because * a previous search of the same node might have failed due to search's * temporal limits, so repeating the search at a lower temporal level might * succeed. * * @author Stephen G. Ware */ public class RepeatedNodeHeuristic implements ProgressionCost { /** * A {@link ProgressionCostFactory factory} for producing {@link * RepeatedNodeHeuristic repeated node heuristics}. * * @author Stephen G. Ware */ public static class Factory implements ProgressionCostFactory { /** Serial version ID */
package edu.uky.cs.nil.sabre.prog; /** * The repeated node heuristic is a wrapper around a {@link ProgressionCost cost * function} that can improve the efficiency of a {@link ProgressionSearch * heuristic progression search} by preventing it from revisiting the same node * multiple times. Each time this cost function evaluates a node, it calculates * the sum of its {@link ProgressionNode#getTemporalOffset() temporal offset} * and {@link ProgressionNode#getTemporalDepth() temporal depth}. If the node * has never been evaluated before, or if that sum is less than the last time * the node was evaluated, that sum is recorded and this heuristic passes thru * to {@link #parent the heuristic it wraps around}. If the node has been * evaluated before, and if the sum is greater than or equal to the recorded * sum, this heuristic returns {@link Double#POSITIVE_INFINITY positive * infinity}. This prevents a node from being visited more than once at the * same temporal level. The sum of temporal offset and depth is checked because * a previous search of the same node might have failed due to search's * temporal limits, so repeating the search at a lower temporal level might * succeed. * * @author Stephen G. Ware */ public class RepeatedNodeHeuristic implements ProgressionCost { /** * A {@link ProgressionCostFactory factory} for producing {@link * RepeatedNodeHeuristic repeated node heuristics}. * * @author Stephen G. Ware */ public static class Factory implements ProgressionCostFactory { /** Serial version ID */
private static final long serialVersionUID = Settings.VERSION_UID;
0
2023-10-26 18:14:19+00:00
4k
sngular/pact-annotation-processor
src/test/resources/basic/NumericDataTypesBuilder.java
[ { "identifier": "CustomDslModifier", "path": "src/main/java/com/sngular/annotation/processor/mapping/CustomDslModifier.java", "snippet": "@FunctionalInterface\npublic interface CustomDslModifier {\n\n PactDslJsonBody apply(final PactDslJsonBody pactDslJsonBody);\n\n}" }, { "identifier": "NumericDataTypes", "path": "src/test/resources/basic/NumericDataTypes.java", "snippet": "@PactDslBodyBuilder\npublic class NumericDataTypes {\n\n @Example(\"10\")\n private Integer integer;\n\n @Example(\"20\")\n private int primitiveInt;\n\n @Example(\"30\")\n private Long longObject;\n\n @Example(\"40\")\n private long primitiveLong;\n\n @Example(\"50.1234\")\n private Float floatObject;\n\n @Example(\"60.2345\")\n private float primitiveFloat;\n\n @Example(\"70.3456\")\n private Double doubleObject;\n\n @Example(\"80.4567\")\n private double primitiveDouble;\n\n @Example(\"90\")\n private Short shortObject;\n\n @Example(\"100\")\n private short primitiveShort;\n\n @Example(\"110\")\n private Byte byteObject;\n\n @Example(\"120\")\n private byte primitiveByte;\n\n @Example(\"1303812548123548216\")\n private BigInteger bigIntegerObject;\n\n @Example(\"1402354872534672834.2345\")\n private BigDecimal bigDecimalObject;\n\n protected Integer getInteger() {\n return integer;\n }\n\n protected void setInteger(final Integer integer) {\n this.integer = integer;\n }\n\n protected int getPrimitiveInt() {\n return primitiveInt;\n }\n\n protected void setPrimitiveInt(final int primitiveInt) {\n this.primitiveInt = primitiveInt;\n }\n\n protected Long getLongObject() {\n return longObject;\n }\n\n protected void setLongObject(final Long longObject) {\n this.longObject = longObject;\n }\n\n protected long getPrimitiveLong() {\n return primitiveLong;\n }\n\n protected void setPrimitiveLong(final long primitiveLong) {\n this.primitiveLong = primitiveLong;\n }\n\n public Float getFloatObject() {\n return floatObject;\n }\n\n public void setFloatObject(Float floatObject) {\n this.floatObject = floatObject;\n }\n\n public float getPrimitiveFloat() {\n return primitiveFloat;\n }\n\n public void setPrimitiveFloat(float primitiveFloat) {\n this.primitiveFloat = primitiveFloat;\n }\n\n public Double getDoubleObject() {\n return doubleObject;\n }\n\n public void setDoubleObject(Double doubleObject) {\n this.doubleObject = doubleObject;\n }\n\n public double getPrimitiveDouble() {\n return primitiveDouble;\n }\n\n public void setPrimitiveDouble(double primitiveDouble) {\n this.primitiveDouble = primitiveDouble;\n }\n\n public Short getShortObject() {\n return shortObject;\n }\n\n public void setShortObject(Short shortObject) {\n this.shortObject = shortObject;\n }\n\n public short getPrimitiveShort() {\n return primitiveShort;\n }\n\n public void setPrimitiveShort(short primitiveShort) {\n this.primitiveShort = primitiveShort;\n }\n\n public Byte getByteObject() {\n return byteObject;\n }\n\n public void setByteObject(Byte byteObject) {\n this.byteObject = byteObject;\n }\n\n public byte getPrimitiveByte() {\n return primitiveByte;\n }\n\n public void setPrimitiveByte(byte primitiveByte) {\n this.primitiveByte = primitiveByte;\n }\n\n public BigInteger getBigIntegerObject() {\n return bigIntegerObject;\n }\n\n public void setBigIntegerObject(BigInteger bigIntegerObject) {\n this.bigIntegerObject = bigIntegerObject;\n }\n\n public BigDecimal getBigDecimalObject() {\n return bigDecimalObject;\n }\n\n public void setBigDecimalObject(BigDecimal bigDecimalObject) {\n this.bigDecimalObject = bigDecimalObject;\n }\n}" } ]
import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.List; import java.util.Objects; import au.com.dius.pact.consumer.dsl.DslPart; import au.com.dius.pact.consumer.dsl.PactDslJsonArray; import au.com.dius.pact.consumer.dsl.PactDslJsonBody; import au.com.dius.pact.consumer.dsl.PactDslJsonRootValue; import com.sngular.annotation.processor.mapping.CustomDslModifier; import com.sngular.resources.basic.NumericDataTypes;
2,194
package com.sngular.resources.basic; public class NumericDataTypesBuilder { int integer = 10; int primitiveInt = 20; long longObject = 30L; long primitiveLong = 40L; float floatObject = 50.1234F; float primitiveFloat = 60.2345F; double doubleObject = 70.3456D; double primitiveDouble = 80.4567D; short shortObject = 90; short primitiveShort = 100; byte byteObject = 110; byte primitiveByte = 120; BigInteger bigIntegerObject = new BigInteger("1303812548123548216"); BigDecimal bigDecimalObject = new BigDecimal("1402354872534672834.2345"); public NumericDataTypesBuilder setInteger(final int integer) { this.integer = integer; return this; } public NumericDataTypesBuilder setPrimitiveInt(final int primitiveInt) { this.primitiveInt = primitiveInt; return this; } public NumericDataTypesBuilder setLongObject(final long longObject) { this.longObject = longObject; return this; } public NumericDataTypesBuilder setPrimitiveLong(final long primitiveLong) { this.primitiveLong = primitiveLong; return this; } public NumericDataTypesBuilder setFloatObject(final float floatObject) { this.floatObject = floatObject; return this; } public NumericDataTypesBuilder setPrimitiveFloat(final float primitiveFloat) { this.primitiveFloat = primitiveFloat; return this; } public NumericDataTypesBuilder setDoubleObject(final double doubleObject) { this.doubleObject = doubleObject; return this; } public NumericDataTypesBuilder setPrimitiveDouble(final double primitiveDouble) { this.primitiveDouble = primitiveDouble; return this; } public NumericDataTypesBuilder setShortObject(final short shortObject) { this.shortObject = shortObject; return this; } public NumericDataTypesBuilder setPrimitiveShort(final short primitiveShort) { this.primitiveShort = primitiveShort; return this; } public NumericDataTypesBuilder setByteObject(final byte byteObject) { this.byteObject = byteObject; return this; } public NumericDataTypesBuilder setPrimitiveByte(final byte primitiveByte) { this.primitiveByte = primitiveByte; return this; } public NumericDataTypesBuilder setBigIntegerObject(final BigInteger bigIntegerObject) { this.bigIntegerObject = bigIntegerObject; return this; } public NumericDataTypesBuilder setBigDecimalObject(final BigDecimal bigDecimalObject) { this.bigDecimalObject = bigDecimalObject; return this; } public DslPart build() { PactDslJsonBody pactDslJsonBody = new PactDslJsonBody(); if (Objects.nonNull(integer)) { pactDslJsonBody.integerType("integer", integer); } if (Objects.nonNull(primitiveInt)) { pactDslJsonBody.integerType("primitiveInt", primitiveInt); } if (Objects.nonNull(longObject)) { pactDslJsonBody.integerType("longObject", longObject); } if (Objects.nonNull(primitiveLong)) { pactDslJsonBody.integerType("primitiveLong", primitiveLong); } if (Objects.nonNull(floatObject)) { pactDslJsonBody.decimalType("floatObject", (double) floatObject); } if (Objects.nonNull(primitiveFloat)) { pactDslJsonBody.decimalType("primitiveFloat", (double) primitiveFloat); } if (Objects.nonNull(doubleObject)) { pactDslJsonBody.decimalType("doubleObject", doubleObject); } if (Objects.nonNull(primitiveDouble)) { pactDslJsonBody.decimalType("primitiveDouble", primitiveDouble); } if (Objects.nonNull(shortObject)) { pactDslJsonBody.integerType("shortObject", (int) shortObject); } if (Objects.nonNull(primitiveShort)) { pactDslJsonBody.integerType("primitiveShort", (int) primitiveShort); } if (Objects.nonNull(byteObject)) { pactDslJsonBody.integerType("byteObject", (int) byteObject); } if (Objects.nonNull(primitiveByte)) { pactDslJsonBody.integerType("primitiveByte", (int) primitiveByte); } if (Objects.nonNull(bigIntegerObject)) { pactDslJsonBody.integerType("bigIntegerObject", bigIntegerObject.intValue()); } if (Objects.nonNull(bigDecimalObject)) { pactDslJsonBody.decimalType("bigDecimalObject", bigDecimalObject); } return pactDslJsonBody; }
package com.sngular.resources.basic; public class NumericDataTypesBuilder { int integer = 10; int primitiveInt = 20; long longObject = 30L; long primitiveLong = 40L; float floatObject = 50.1234F; float primitiveFloat = 60.2345F; double doubleObject = 70.3456D; double primitiveDouble = 80.4567D; short shortObject = 90; short primitiveShort = 100; byte byteObject = 110; byte primitiveByte = 120; BigInteger bigIntegerObject = new BigInteger("1303812548123548216"); BigDecimal bigDecimalObject = new BigDecimal("1402354872534672834.2345"); public NumericDataTypesBuilder setInteger(final int integer) { this.integer = integer; return this; } public NumericDataTypesBuilder setPrimitiveInt(final int primitiveInt) { this.primitiveInt = primitiveInt; return this; } public NumericDataTypesBuilder setLongObject(final long longObject) { this.longObject = longObject; return this; } public NumericDataTypesBuilder setPrimitiveLong(final long primitiveLong) { this.primitiveLong = primitiveLong; return this; } public NumericDataTypesBuilder setFloatObject(final float floatObject) { this.floatObject = floatObject; return this; } public NumericDataTypesBuilder setPrimitiveFloat(final float primitiveFloat) { this.primitiveFloat = primitiveFloat; return this; } public NumericDataTypesBuilder setDoubleObject(final double doubleObject) { this.doubleObject = doubleObject; return this; } public NumericDataTypesBuilder setPrimitiveDouble(final double primitiveDouble) { this.primitiveDouble = primitiveDouble; return this; } public NumericDataTypesBuilder setShortObject(final short shortObject) { this.shortObject = shortObject; return this; } public NumericDataTypesBuilder setPrimitiveShort(final short primitiveShort) { this.primitiveShort = primitiveShort; return this; } public NumericDataTypesBuilder setByteObject(final byte byteObject) { this.byteObject = byteObject; return this; } public NumericDataTypesBuilder setPrimitiveByte(final byte primitiveByte) { this.primitiveByte = primitiveByte; return this; } public NumericDataTypesBuilder setBigIntegerObject(final BigInteger bigIntegerObject) { this.bigIntegerObject = bigIntegerObject; return this; } public NumericDataTypesBuilder setBigDecimalObject(final BigDecimal bigDecimalObject) { this.bigDecimalObject = bigDecimalObject; return this; } public DslPart build() { PactDslJsonBody pactDslJsonBody = new PactDslJsonBody(); if (Objects.nonNull(integer)) { pactDslJsonBody.integerType("integer", integer); } if (Objects.nonNull(primitiveInt)) { pactDslJsonBody.integerType("primitiveInt", primitiveInt); } if (Objects.nonNull(longObject)) { pactDslJsonBody.integerType("longObject", longObject); } if (Objects.nonNull(primitiveLong)) { pactDslJsonBody.integerType("primitiveLong", primitiveLong); } if (Objects.nonNull(floatObject)) { pactDslJsonBody.decimalType("floatObject", (double) floatObject); } if (Objects.nonNull(primitiveFloat)) { pactDslJsonBody.decimalType("primitiveFloat", (double) primitiveFloat); } if (Objects.nonNull(doubleObject)) { pactDslJsonBody.decimalType("doubleObject", doubleObject); } if (Objects.nonNull(primitiveDouble)) { pactDslJsonBody.decimalType("primitiveDouble", primitiveDouble); } if (Objects.nonNull(shortObject)) { pactDslJsonBody.integerType("shortObject", (int) shortObject); } if (Objects.nonNull(primitiveShort)) { pactDslJsonBody.integerType("primitiveShort", (int) primitiveShort); } if (Objects.nonNull(byteObject)) { pactDslJsonBody.integerType("byteObject", (int) byteObject); } if (Objects.nonNull(primitiveByte)) { pactDslJsonBody.integerType("primitiveByte", (int) primitiveByte); } if (Objects.nonNull(bigIntegerObject)) { pactDslJsonBody.integerType("bigIntegerObject", bigIntegerObject.intValue()); } if (Objects.nonNull(bigDecimalObject)) { pactDslJsonBody.decimalType("bigDecimalObject", bigDecimalObject); } return pactDslJsonBody; }
public NumericDataTypes buildExpectedInstance() {
1
2023-10-25 14:36:38+00:00
4k
granny/Pl3xMap
fabric/src/main/java/net/pl3x/map/fabric/server/FabricNetwork.java
[ { "identifier": "Constants", "path": "core/src/main/java/net/pl3x/map/core/network/Constants.java", "snippet": "public class Constants {\n public static final String MODID = \"pl3xmap\";\n\n public static final int PROTOCOL = 3;\n\n public static final int SERVER_DATA = 0;\n public static final int MAP_DATA = 1;\n\n public static final int RESPONSE_SUCCESS = 200;\n\n public static final int ERROR_NO_SUCH_MAP = -1;\n public static final int ERROR_NO_SUCH_WORLD = -2;\n public static final int ERROR_NOT_VANILLA_MAP = -3;\n}" }, { "identifier": "Network", "path": "core/src/main/java/net/pl3x/map/core/network/Network.java", "snippet": "public abstract class Network {\n public static final String CHANNEL = Constants.MODID + \":\" + Constants.MODID;\n\n public abstract void register();\n\n public abstract void unregister();\n\n public <T> void sendServerData(T player) {\n ByteArrayDataOutput out = out();\n\n out.writeInt(Constants.PROTOCOL);\n out.writeInt(Constants.SERVER_DATA);\n out.writeInt(Constants.RESPONSE_SUCCESS);\n\n out.writeUTF(Config.WEB_ADDRESS);\n\n send(player, out);\n }\n\n protected abstract <T> void sendMapData(T player, int id);\n\n protected abstract <T> void send(T player, ByteArrayDataOutput out);\n\n @SuppressWarnings(\"UnstableApiUsage\")\n protected ByteArrayDataOutput out() {\n return ByteStreams.newDataOutput();\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n protected ByteArrayDataInput in(byte[] bytes) {\n return ByteStreams.newDataInput(bytes);\n }\n}" }, { "identifier": "NetworkManager", "path": "fabric/src/main/java/net/pl3x/map/fabric/client/manager/NetworkManager.java", "snippet": "public class NetworkManager {\n private final ResourceLocation channel = new ResourceLocation(Constants.MODID, Constants.MODID);\n private final Pl3xMapFabricClient mod;\n\n public NetworkManager(@NotNull Pl3xMapFabricClient mod) {\n this.mod = mod;\n }\n\n public void initialize() {\n ClientPlayNetworking.registerGlobalReceiver(this.channel, (client, handler, buf, sender) -> {\n ByteArrayDataInput packet = in(accessByteBufWithCorrectSize(buf));\n\n int protocol = packet.readInt();\n if (protocol != Constants.PROTOCOL) {\n this.mod.setEnabled(false);\n return;\n }\n\n int packetType = packet.readInt();\n switch (packetType) {\n case Constants.SERVER_DATA -> {\n int response = packet.readInt();\n if (response != Constants.RESPONSE_SUCCESS) {\n this.mod.setEnabled(false);\n return;\n }\n this.mod.getTileManager().initialize();\n this.mod.setServerUrl(packet.readUTF());\n }\n case Constants.MAP_DATA -> {\n int response = packet.readInt();\n switch (response) {\n case Constants.ERROR_NO_SUCH_MAP, Constants.ERROR_NO_SUCH_WORLD, Constants.ERROR_NOT_VANILLA_MAP -> {\n MapInstance texture = (MapInstance) Minecraft.getInstance().gameRenderer.getMapRenderer().maps.get(packet.readInt());\n if (texture != null) {\n texture.skip();\n }\n }\n case Constants.RESPONSE_SUCCESS -> {\n MapInstance texture = (MapInstance) Minecraft.getInstance().gameRenderer.getMapRenderer().maps.get(packet.readInt());\n if (texture != null) {\n texture.setData(packet.readByte(), packet.readInt(), packet.readInt(), packet.readUTF());\n }\n }\n }\n }\n }\n });\n }\n\n public void requestServerData() {\n ByteArrayDataOutput out = out();\n out.writeInt(Constants.PROTOCOL);\n out.writeInt(Constants.SERVER_DATA);\n sendPacket(out);\n }\n\n public void requestMapData(int id) {\n ByteArrayDataOutput out = out();\n out.writeInt(Constants.PROTOCOL);\n out.writeInt(Constants.MAP_DATA);\n out.writeInt(id);\n sendPacket(out);\n }\n\n private void sendPacket(@NotNull ByteArrayDataOutput packet) {\n if (Minecraft.getInstance().getConnection() == null) {\n // not in game yet; reschedule\n this.mod.getScheduler().addTask(0, () -> sendPacket(packet));\n return;\n }\n ClientPlayNetworking.send(this.channel, new FriendlyByteBuf(Unpooled.wrappedBuffer(packet.toByteArray())));\n }\n\n public static byte[] accessByteBufWithCorrectSize(FriendlyByteBuf buf) {\n int i = buf.writerIndex();\n byte[] bytes = new byte[i];\n buf.getBytes(0, bytes);\n return bytes;\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n private @NotNull ByteArrayDataOutput out() {\n return ByteStreams.newDataOutput();\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n private @NotNull ByteArrayDataInput in(byte[] bytes) {\n return ByteStreams.newDataInput(bytes);\n }\n}" } ]
import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.MapItem; import net.minecraft.world.level.Level; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import net.pl3x.map.core.network.Constants; import net.pl3x.map.core.network.Network; import net.pl3x.map.fabric.client.manager.NetworkManager; import org.jetbrains.annotations.NotNull; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
1,710
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.fabric.server; public class FabricNetwork extends Network { private final Pl3xMapFabricServer mod; private final ResourceLocation channel; public FabricNetwork(Pl3xMapFabricServer mod) { this.mod = mod; this.channel = new ResourceLocation(Network.CHANNEL); } @Override public void register() { ServerPlayNetworking.registerGlobalReceiver(this.channel, (server, player, listener, byteBuf, sender) -> { ByteArrayDataInput in = in(NetworkManager.accessByteBufWithCorrectSize(byteBuf)); int action = in.readInt(); switch (action) {
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.fabric.server; public class FabricNetwork extends Network { private final Pl3xMapFabricServer mod; private final ResourceLocation channel; public FabricNetwork(Pl3xMapFabricServer mod) { this.mod = mod; this.channel = new ResourceLocation(Network.CHANNEL); } @Override public void register() { ServerPlayNetworking.registerGlobalReceiver(this.channel, (server, player, listener, byteBuf, sender) -> { ByteArrayDataInput in = in(NetworkManager.accessByteBufWithCorrectSize(byteBuf)); int action = in.readInt(); switch (action) {
case Constants.SERVER_DATA -> sendServerData(player);
0
2023-10-26 01:14:31+00:00
4k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/config/SqlAnalysisConfig.java
[ { "identifier": "SqlAnalysisSqlTypeEnum", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysisSqlTypeEnum.java", "snippet": "public enum SqlAnalysisSqlTypeEnum {\n\n SELECT(\"SELECT\", \"查询\"),\n UPDATE(\"UPDATE\", \"更新\"),\n INSERT(\"INSERT\", \"插入\"),\n DELETE(\"DELETE\", \"删除\");\n\n\n SqlAnalysisSqlTypeEnum(String type, String description) {\n this.type = type;\n this.description = description;\n }\n\n /**\n * sql类型\n */\n private String type;\n\n /**\n * 描述\n */\n private String description;\n\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n}" }, { "identifier": "SqlScoreRule", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/rule/SqlScoreRule.java", "snippet": "public class SqlScoreRule {\n\n /**\n * 检查字段\n */\n private MatchColumn matchColumn;\n\n /**\n * 匹配值\n */\n private String matchValue;\n\n /**\n * 匹配规则\n */\n private MatchType matchType;\n\n /**\n * 减分值\n */\n private Integer scoreDeduction;\n\n /**\n * 原因\n */\n private String reason;\n\n /**\n * 建议\n */\n private String suggestion ;\n\n\n /**\n * 是否严格规则,是的-直接触发警告,否-依赖综合评分进行警告\n */\n private Boolean strict ;\n\n public MatchColumn getMatchColumn() {\n return matchColumn;\n }\n\n public void setMatchColumn(MatchColumn matchColumn) {\n this.matchColumn = matchColumn;\n }\n\n public String getMatchValue() {\n return matchValue;\n }\n\n public void setMatchValue(String matchValue) {\n this.matchValue = matchValue;\n }\n\n public MatchType getMatchType() {\n return matchType;\n }\n\n public void setMatchType(MatchType matchType) {\n this.matchType = matchType;\n }\n\n public Integer getScoreDeduction() {\n return scoreDeduction;\n }\n\n public void setScoreDeduction(Integer scoreDeduction) {\n this.scoreDeduction = scoreDeduction;\n }\n\n public String getReason() {\n return reason;\n }\n\n public void setReason(String reason) {\n this.reason = reason;\n }\n\n public String getSuggestion() {\n return suggestion;\n }\n\n public void setSuggestion(String suggestion) {\n this.suggestion = suggestion;\n }\n\n public Boolean getStrict() {\n return strict;\n }\n\n public void setStrict(Boolean strict) {\n this.strict = strict;\n }\n}" }, { "identifier": "DuccMonitorUtil", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/util/DuccMonitorUtil.java", "snippet": "public class DuccMonitorUtil {\n\n private static Logger log = LoggerFactory.getLogger(DuccMonitorUtil.class);\n private static String duccConfig = \"\";\n\n /**\n * 启动监控\n * @param appName jone或者jdos应用名称\n * @param uri uri格式详解参见:https://git.jd.com/laf/laf-config/wikis/客户端使用指南->UCC配置服务\n * @param moniterKey 存储sql替换配置的key\n */\n public static void start(String appName,String uri,String moniterKey){\n try{\n //todo 配置中心监听\n// //创建ConfiguratorManager 实例,有1个就可以\n// ConfiguratorManager configuratorManager = ConfiguratorManager.getInstance() ;\n// //设置appName,jone或者jdos部署可自动获取,无需配置\n// configuratorManager.setApplication(appName);\n//\n// //resourceName是资源名,命名自定义,多个时不要重复\n// String resourceName = \"sql_analysis_config\";\n//\n// //创建资源对象,此处直接使用ducc远程,Name属性很重要,下面会用到\n// Resource resource = new Resource(resourceName, uri);\n// //给配置管理器添加管理的资源\n// configuratorManager.addResource(resource);\n//\n// //启动之后才可以获取配置\n// configuratorManager.start();\n//\n// //获取配置 (获取指定配置源下指定配置)\n// Property property = configuratorManager.getProperty(resourceName, moniterKey);\n// log.info(\"sql analysis ducc moniterKey:\" + property.getString());\n// duccConfig = property.getString();\n//\n// //添加监听器,配置项维度的监听器\n// configuratorManager.addListener(new PropertyListener.CustomPropertyListener(moniterKey) {\n// @Override\n// public void onUpdate(Property property) {\n// duccConfig = property.getString();\n// log.info(JSON.toJSONString(property));\n// SqlReplaceConfig.initConfig();\n// }\n// });\n }catch (Exception e){\n log.error(\"sql analysis ducc 监听启动失败\");\n }\n\n }\n\n /**\n * 获取ducc配置\n * @return\n */\n public static String getDuccConfig(){\n return duccConfig;\n }\n\n}" } ]
import com.jd.sql.analysis.analysis.SqlAnalysisSqlTypeEnum; import com.jd.sql.analysis.rule.SqlScoreRule; import com.jd.sql.analysis.util.DuccMonitorUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Properties;
2,127
package com.jd.sql.analysis.config; /** * @Author huhaitao21 * @Description sql 分析组件配置类 * @Date 19:36 2022/11/3 **/ public class SqlAnalysisConfig { private static Logger logger = LoggerFactory.getLogger(SqlAnalysisConfig.class); /** * 分析开关,默认关闭 */ private static Boolean analysisSwitch = false; /** * 一个id 只检查一次,默认开启 */ private static Boolean onlyCheckOnce = true; /** * 两次检查间隔 默认 5分钟 */ private static Long checkInterval = 5 * 60 * 1000L; /** * 例外sql id,集合 */ private static List<String> exceptSqlIds = new ArrayList<>(); /** * 进行分析的sql类型 */ private static List<String> sqlType = new ArrayList<>(); /** * 评分规则加载类, 默认 com.jd.sql.analysis.rule.SqlScoreRuleLoaderDefault */ private static String scoreRuleLoadClass; /** * 分析结果输出类,默认日志模式 com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault */ private static String outputModel; /** * 分析结果输出类,默认日志模式 com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault */ private static String outputClass; /** * 应用名称 */ private static String appName; /** * sqlReplaceModelSwitch */ private static Boolean sqlReplaceModelSwitch; /** * 分析开关 配置key */ private static final String ANALYSIS_SWITCH_KEY = "analysisSwitch"; /** * 同一id是否只检查一次 配置key */ private static final String ONLY_CHECK_ONCE = "onlyCheckOnce"; /** * 检查间隔时间 配置key */ private static final String CHECK_INTERVAL = "checkInterval"; /** * 例外sql id 配置key,多个需要逗号分隔 */ private static final String EXCEPT_SQL_IDS_KEY = "exceptSqlIds"; /** * 分析开关 配置key ,多个需要逗号分隔 */ private static final String SQL_TYPE_KEY = "sqlType"; /** * 规则加载类 配置key */ private static final String SCORE_RULE_LOAD_KEY = "scoreRuleLoadClass"; /** * 评分输出类 配置key */ private static final String OUTPUT_CLASS_KEY = "outputClass"; /** * 输出模式 配置key */ private static final String OUTPUT_MODEL_KEY = "outputModel"; /** * 应用名称 */ private static final String APP_NAME = "appName"; /** * 评分规则列表 */
package com.jd.sql.analysis.config; /** * @Author huhaitao21 * @Description sql 分析组件配置类 * @Date 19:36 2022/11/3 **/ public class SqlAnalysisConfig { private static Logger logger = LoggerFactory.getLogger(SqlAnalysisConfig.class); /** * 分析开关,默认关闭 */ private static Boolean analysisSwitch = false; /** * 一个id 只检查一次,默认开启 */ private static Boolean onlyCheckOnce = true; /** * 两次检查间隔 默认 5分钟 */ private static Long checkInterval = 5 * 60 * 1000L; /** * 例外sql id,集合 */ private static List<String> exceptSqlIds = new ArrayList<>(); /** * 进行分析的sql类型 */ private static List<String> sqlType = new ArrayList<>(); /** * 评分规则加载类, 默认 com.jd.sql.analysis.rule.SqlScoreRuleLoaderDefault */ private static String scoreRuleLoadClass; /** * 分析结果输出类,默认日志模式 com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault */ private static String outputModel; /** * 分析结果输出类,默认日志模式 com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault */ private static String outputClass; /** * 应用名称 */ private static String appName; /** * sqlReplaceModelSwitch */ private static Boolean sqlReplaceModelSwitch; /** * 分析开关 配置key */ private static final String ANALYSIS_SWITCH_KEY = "analysisSwitch"; /** * 同一id是否只检查一次 配置key */ private static final String ONLY_CHECK_ONCE = "onlyCheckOnce"; /** * 检查间隔时间 配置key */ private static final String CHECK_INTERVAL = "checkInterval"; /** * 例外sql id 配置key,多个需要逗号分隔 */ private static final String EXCEPT_SQL_IDS_KEY = "exceptSqlIds"; /** * 分析开关 配置key ,多个需要逗号分隔 */ private static final String SQL_TYPE_KEY = "sqlType"; /** * 规则加载类 配置key */ private static final String SCORE_RULE_LOAD_KEY = "scoreRuleLoadClass"; /** * 评分输出类 配置key */ private static final String OUTPUT_CLASS_KEY = "outputClass"; /** * 输出模式 配置key */ private static final String OUTPUT_MODEL_KEY = "outputModel"; /** * 应用名称 */ private static final String APP_NAME = "appName"; /** * 评分规则列表 */
private static List<SqlScoreRule> ruleList = new ArrayList<>();
1
2023-10-25 08:59:26+00:00
4k
easy-do/dnf-admin
be/src/main/java/plus/easydo/dnf/service/impl/GamePostalServiceImpl.java
[ { "identifier": "SignInConfigDate", "path": "be/src/main/java/plus/easydo/dnf/dto/SignInConfigDate.java", "snippet": "@Data\npublic class SignInConfigDate {\n\n /**物品名称*/\n private String name;\n /**物品id*/\n private Long itemId;\n /**物品数量*/\n private Long quantity;\n /**物品类型*/\n private Integer itemType;\n\n}" }, { "identifier": "Letter", "path": "be/src/main/java/plus/easydo/dnf/entity/Letter.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(value = \"letter\", dataSource = \"taiwan_cain_2nd\" ,onSet = MySetListener.class, onInsert = MyInsertListener.class, onUpdate = MyUpdateListener.class)\npublic class Letter implements Serializable {\n\n @Id(keyType = KeyType.Auto)\n private Integer letterId;\n /**角色id*/\n private Integer characNo;\n /**发送的角色id*/\n private Integer sendCharacNo = 1;\n /**发的角色名称*/\n private String sendCharacName = \"admin\";\n\n private String letterText;\n\n private LocalDateTime regDate;\n\n private Integer stat;\n\n}" }, { "identifier": "Postal", "path": "be/src/main/java/plus/easydo/dnf/entity/Postal.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(value = \"postal\", dataSource = \"taiwan_cain_2nd\" ,onSet = MySetListener.class, onInsert = MyInsertListener.class, onUpdate = MyUpdateListener.class)\npublic class Postal implements Serializable {\n\n @Id(keyType = KeyType.Auto)\n private Long postalId;\n\n /**物品id*/\n private Long itemId;\n\n /**发送时间*/\n private LocalDateTime occTime;\n\n /**接收的角色*/\n private Integer receiveCharacNo;\n\n /**发送的角色编号*/\n private Integer sendCharacNo = 0;\n\n /**发送的角色名*/\n private String sendCharacName;\n\n /**装备时装代表耐久 道具材料代表数量 时装固定是773*/\n private Long addInfo = 1L;\n\n /**为装备时,表示为品级 数值与品级关系较为随机 时装是1*/\n private Integer endurance = 1;\n\n /**强化*/\n private Integer upgrade = 0;\n\n /**锻造*/\n private Integer seperateUpgrade = 0;\n\n /**增幅类型 空-0','异次元体力-1','异次元精神-2','异次元力量-3','异次元智力-4'*/\n private Integer amplifyOption = 0;\n\n /**增幅数值*/\n private Integer amplifyValue = 0;\n\n /**金币*/\n private Long gold;\n\n /**打开标识 默认是0,时装是1*/\n private Integer avataFlag = 0;\n\n /**上限?*/\n private Integer unlimitFlag = 1;\n\n /** 是否封装 */\n private Integer sealFlag = 0;\n\n /**生物标识 默认是0,宠物是1*/\n private Integer creatureFlag = 0;\n\n /**信件id*/\n private Integer letterId;\n\n private Integer deleteFlag = 0;\n}" }, { "identifier": "AmplifyEnum", "path": "be/src/main/java/plus/easydo/dnf/enums/AmplifyEnum.java", "snippet": "public enum AmplifyEnum {\n\n EMPTY(0, \"空\"),\n PHYSICAL(1, \"异次元体力\"),\n SPIRIT(2, \"异次元精神\"),\n POWER(3, \"异次元力量\"),\n INTELLIGENCE(4, \"异次元智力\");\n\n private final Integer code;\n private final String name;\n\n AmplifyEnum(Integer code, String name) {\n this.code = code;\n this.name = name;\n }\n\n public static String getNameByCode(Integer jobCode) {\n for (AmplifyEnum rarityEnum : values()) {\n if (Objects.equals(rarityEnum.code, jobCode)) {\n return rarityEnum.name;\n }\n }\n return \"\";\n }\n\n public static Integer getCodeByName(String name) {\n for (AmplifyEnum amplifyEnum : values()) {\n if (Objects.equals(amplifyEnum.name, name)) {\n return amplifyEnum.code;\n }\n }\n return null;\n }\n\n public Integer getCode() {\n return code;\n }\n\n public String getName() {\n return name;\n }\n}" }, { "identifier": "ItemTypeEnum", "path": "be/src/main/java/plus/easydo/dnf/enums/ItemTypeEnum.java", "snippet": "@Getter\npublic enum ItemTypeEnum {\n\n EQUIPMENT(1,\"装备\"),\n CONSUMABLES(2,\"消耗品\"),\n MATERIAL(3,\"材料\"),\n MISSION_MATERIALS(4,\"任务材料\"),\n PET(5,\"宠物\"),\n PET_EQUIPMENT(6,\"宠物装备\"),\n PET_CONSUMABLES(7,\"宠物消耗品\"),\n FASHION(8,\"时装\"),\n EXPERT_JOB(10,\"副职业\");\n\n\n private final Integer code;\n private final String name;\n\n ItemTypeEnum(Integer code, String name) {\n this.code = code;\n this.name = name;\n }\n\n public static String getNameByCode(Integer jobCode) {\n for (ItemTypeEnum rarityEnum : values()) {\n if (Objects.equals(rarityEnum.code, jobCode)) {\n return rarityEnum.name;\n }\n }\n return \"\";\n }\n\n public static Integer getCodeByName(String name) {\n for (ItemTypeEnum rarityEnum : values()) {\n if (Objects.equals(rarityEnum.name, name)) {\n return rarityEnum.code;\n }\n }\n return null;\n }\n\n}" }, { "identifier": "BaseException", "path": "be/src/main/java/plus/easydo/dnf/exception/BaseException.java", "snippet": "public class BaseException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n private static final String DEFAULT_ERR_CODE = \"BASE_ERROR\";\n\n private static final String DEFAULT_ERR_MESSAGE = \"基础异常\";\n\n /**\n * 错误码\n */\n private String errCode;\n\n\n public BaseException() {\n super(DEFAULT_ERR_MESSAGE);\n this.errCode = DEFAULT_ERR_CODE;\n }\n\n public BaseException(String message) {\n super(message);\n this.errCode = DEFAULT_ERR_CODE;\n }\n\n public BaseException(String errCode, String message) {\n super(message);\n this.errCode = errCode;\n }\n\n public BaseException(String errCode, String message, Throwable cause) {\n super(message, cause);\n this.errCode = errCode;\n }\n\n public BaseException(String errCode, Throwable cause) {\n super(cause);\n this.errCode = errCode;\n }\n\n public String getErrCode() {\n return errCode;\n }\n}" }, { "identifier": "LetterManager", "path": "be/src/main/java/plus/easydo/dnf/manager/LetterManager.java", "snippet": "@Component\npublic class LetterManager extends ServiceImpl<LetterMapper, Letter> {\n\n}" }, { "identifier": "PostalManager", "path": "be/src/main/java/plus/easydo/dnf/manager/PostalManager.java", "snippet": "@Component\npublic class PostalManager extends ServiceImpl<PostalMapper, Postal> {\n}" }, { "identifier": "GamePostalService", "path": "be/src/main/java/plus/easydo/dnf/service/GamePostalService.java", "snippet": "public interface GamePostalService {\n\n /**\n * 为角色发送签到邮件\n *\n * @param roleId roleId\n * @param configData configData\n * @return boolean\n * @author laoyu\n * @date 2023/10/15\n */\n boolean sendSignInRoleMail(Integer roleId, SignInConfigDate configData);\n}" }, { "identifier": "Latin1ConvertUtil", "path": "be/src/main/java/plus/easydo/dnf/util/Latin1ConvertUtil.java", "snippet": "public class Latin1ConvertUtil {\n\n private Latin1ConvertUtil() {\n }\n\n public static String convertUtf8(String content){\n return CharsetUtil.convert(content,\"latin1\",\"utf8\");\n }\n\n public static String convertLatin1(String content){\n return CharsetUtil.convert(content,\"utf8\",\"latin1\");\n }\n}" } ]
import cn.hutool.core.date.LocalDateTimeUtil; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import plus.easydo.dnf.dto.SignInConfigDate; import plus.easydo.dnf.entity.Letter; import plus.easydo.dnf.entity.Postal; import plus.easydo.dnf.enums.AmplifyEnum; import plus.easydo.dnf.enums.ItemTypeEnum; import plus.easydo.dnf.exception.BaseException; import plus.easydo.dnf.manager.LetterManager; import plus.easydo.dnf.manager.PostalManager; import plus.easydo.dnf.service.GamePostalService; import plus.easydo.dnf.util.Latin1ConvertUtil;
2,267
package plus.easydo.dnf.service.impl; /** * @author laoyu * @version 1.0 * @description 游戏邮箱服务实现 * @date 2023/10/15 */ @Service @RequiredArgsConstructor
package plus.easydo.dnf.service.impl; /** * @author laoyu * @version 1.0 * @description 游戏邮箱服务实现 * @date 2023/10/15 */ @Service @RequiredArgsConstructor
public class GamePostalServiceImpl implements GamePostalService {
8
2023-10-29 03:26:16+00:00
4k
d0ge/sessionless
src/main/java/one/d4d/sessionless/forms/RequestEditorView.java
[ { "identifier": "SignerConfig", "path": "src/main/java/burp/config/SignerConfig.java", "snippet": "public class SignerConfig {\n @Expose\n private boolean enableDangerous;\n @Expose\n private boolean enableExpress;\n @Expose\n private boolean enableOAuth;\n @Expose\n private boolean enableTornado;\n @Expose\n private boolean enableUnknown;\n\n public SignerConfig() {\n this.enableDangerous = true;\n this.enableExpress = true;\n this.enableOAuth = false;\n this.enableTornado = true;\n this.enableUnknown = false;\n }\n\n public boolean isEnableDangerous() {\n return enableDangerous;\n }\n\n public void setEnableDangerous(boolean enableDangerous) {\n this.enableDangerous = enableDangerous;\n }\n\n public boolean isEnableExpress() {\n return enableExpress;\n }\n\n public void setEnableExpress(boolean enableExpress) {\n this.enableExpress = enableExpress;\n }\n\n public boolean isEnableOAuth() {\n return enableOAuth;\n }\n\n public void setEnableOAuth(boolean enableOAuth) {\n this.enableOAuth = enableOAuth;\n }\n\n public boolean isEnableTornado() {\n return enableTornado;\n }\n\n public void setEnableTornado(boolean enableTornado) {\n this.enableTornado = enableTornado;\n }\n\n public boolean isEnableUnknown() {\n return enableUnknown;\n }\n\n public void setEnableUnknown(boolean enableUnknown) {\n this.enableUnknown = enableUnknown;\n }\n}" }, { "identifier": "HexCodeAreaFactory", "path": "src/main/java/one/d4d/sessionless/hexcodearea/HexCodeAreaFactory.java", "snippet": "public class HexCodeAreaFactory {\n private final Logging logging;\n private final FontProvider fontProvider;\n\n public HexCodeAreaFactory(Logging logging, UserInterface userInterface) {\n this.logging = logging;\n this.fontProvider = new FontProvider(userInterface);\n }\n\n public CodeArea build() {\n CodeArea codeArea = new FontMetricsClearingCodeArea(logging);\n\n codeArea.setCommandHandler(new HexCodeAreaCommandHandler(codeArea));\n codeArea.setShowHeader(false);\n codeArea.setShowLineNumbers(false);\n codeArea.setViewMode(CODE_MATRIX);\n codeArea.setData(new ByteArrayEditableData());\n codeArea.setFont(fontProvider.editorFont());\n\n return codeArea;\n }\n}" }, { "identifier": "PresenterStore", "path": "src/main/java/one/d4d/sessionless/presenter/PresenterStore.java", "snippet": "public class PresenterStore {\n\n private final Map<Class, Presenter> presenters = new HashMap<>();\n\n public Presenter get(Class cls) {\n return presenters.get(cls);\n }\n\n public void register(Presenter presenter) {\n presenters.put(presenter.getClass(), presenter);\n }\n}" }, { "identifier": "RstaFactory", "path": "src/main/java/one/d4d/sessionless/rsta/RstaFactory.java", "snippet": "public class RstaFactory {\n private final DarkModeDetector darkModeDetector;\n private final FontProvider fontProvider;\n private final Logging logging;\n\n public RstaFactory(UserInterface userInterface, Logging logging) {\n this.darkModeDetector = new DarkModeDetector(userInterface);\n this.fontProvider = new FontProvider(userInterface);\n this.logging = logging;\n\n AbstractTokenMakerFactory tokenMakerFactory = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance();\n tokenMakerFactory.putMapping(MAPPING, TOKEN_MAKER_FQCN);\n SignedTokenMaker.errorLogger = logging::logToError;\n }\n\n public RSyntaxTextArea buildDefaultTextArea() {\n return fixKeyEventCapture(\n () -> new CustomizedRSyntaxTextArea(darkModeDetector, fontProvider, logging::logToError)\n );\n }\n\n public RSyntaxTextArea buildSerializedJWTTextArea() {\n CustomTokenColors customTokenColors = customTokenColors()\n .withForeground(JWT_PART1, Color.decode(\"#FB015B\"))\n .withForeground(JWT_PART2, Color.decode(\"#D63AFF\"))\n .withForeground(JWT_PART3, Color.decode(\"#00B9F1\"))\n .withForeground(JWT_PART4, Color.decode(\"#EA7600\"))\n .withForeground(JWT_PART5, Color.decode(\"#EDB219\"))\n .withForeground(JWT_SEPARATOR1, Color.decode(\"#A6A282\"))\n .withForeground(JWT_SEPARATOR2, Color.decode(\"#A6A282\"))\n .withForeground(JWT_SEPARATOR3, Color.decode(\"#A6A282\"))\n .withForeground(JWT_SEPARATOR4, Color.decode(\"#A6A282\"))\n .build();\n\n RSyntaxTextArea textArea = fixKeyEventCapture(\n () -> new CustomizedRSyntaxTextArea(\n darkModeDetector,\n fontProvider,\n logging::logToError,\n customTokenColors\n )\n );\n\n textArea.setSyntaxEditingStyle(SignedTokenizerConstants.MAPPING);\n\n return textArea;\n }\n\n // Ensure Burp key events not captured - https://github.com/bobbylight/RSyntaxTextArea/issues/269#issuecomment-776329702\n private RSyntaxTextArea fixKeyEventCapture(Supplier<RSyntaxTextArea> rSyntaxTextAreaSupplier) {\n JTextComponent.removeKeymap(\"RTextAreaKeymap\");\n\n RSyntaxTextArea textArea = rSyntaxTextAreaSupplier.get();\n\n UIManager.put(\"RSyntaxTextAreaUI.actionMap\", null);\n UIManager.put(\"RSyntaxTextAreaUI.inputMap\", null);\n UIManager.put(\"RTextAreaUI.actionMap\", null);\n UIManager.put(\"RTextAreaUI.inputMap\", null);\n\n return textArea;\n }\n}" }, { "identifier": "ErrorLoggingActionListenerFactory", "path": "src/main/java/one/d4d/sessionless/utils/ErrorLoggingActionListenerFactory.java", "snippet": "public class ErrorLoggingActionListenerFactory {\n private final Logging logging;\n\n public ErrorLoggingActionListenerFactory(Logging logging) {\n this.logging = logging;\n }\n\n public ErrorLoggingActionListener from(ActionListener actionListener) {\n return new ErrorLoggingActionListener(logging, actionListener);\n }\n}" } ]
import burp.api.montoya.collaborator.CollaboratorPayloadGenerator; import burp.api.montoya.http.HttpService; import burp.api.montoya.http.message.HttpRequestResponse; import burp.api.montoya.http.message.requests.HttpRequest; import burp.api.montoya.logging.Logging; import burp.api.montoya.ui.UserInterface; import burp.api.montoya.ui.editor.extension.ExtensionProvidedHttpRequestEditor; import burp.config.SignerConfig; import one.d4d.sessionless.hexcodearea.HexCodeAreaFactory; import one.d4d.sessionless.presenter.PresenterStore; import one.d4d.sessionless.rsta.RstaFactory; import one.d4d.sessionless.utils.ErrorLoggingActionListenerFactory; import java.net.URL; import static burp.api.montoya.internal.ObjectFactoryLocator.FACTORY;
1,722
package one.d4d.sessionless.forms; public class RequestEditorView extends EditorTab implements ExtensionProvidedHttpRequestEditor { private volatile HttpService httpService; public RequestEditorView( PresenterStore presenters, RstaFactory rstaFactory, Logging logging, UserInterface userInterface, CollaboratorPayloadGenerator collaboratorPayloadGenerator, SignerConfig signerConfig, boolean editable, boolean isProVersion) { super( presenters, rstaFactory, new HexCodeAreaFactory(logging, userInterface), collaboratorPayloadGenerator,
package one.d4d.sessionless.forms; public class RequestEditorView extends EditorTab implements ExtensionProvidedHttpRequestEditor { private volatile HttpService httpService; public RequestEditorView( PresenterStore presenters, RstaFactory rstaFactory, Logging logging, UserInterface userInterface, CollaboratorPayloadGenerator collaboratorPayloadGenerator, SignerConfig signerConfig, boolean editable, boolean isProVersion) { super( presenters, rstaFactory, new HexCodeAreaFactory(logging, userInterface), collaboratorPayloadGenerator,
new ErrorLoggingActionListenerFactory(logging),
4
2023-10-30 09:12:06+00:00
4k
ballerina-platform/module-ballerinax-ibm.ibmmq
native/src/main/java/io/ballerina/lib/ibm.ibmmq/headers/MQRFH2Header.java
[ { "identifier": "HeaderFieldValuesCallback", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/HeaderFieldValuesCallback.java", "snippet": "public class HeaderFieldValuesCallback implements Callback {\n\n private final CountDownLatch latch;\n private BTable headerValueTable;\n\n public HeaderFieldValuesCallback(CountDownLatch latch) {\n this.latch = latch;\n }\n\n @Override\n public void notifySuccess(Object result) {\n if (result instanceof BTable bTable) {\n this.headerValueTable = bTable;\n } else if (result instanceof BError bError) {\n bError.printStackTrace();\n headerValueTable = ValueCreator.createTableValue(TypeCreator.createTableType(TypeCreator\n .createRecordType(MQRFH2FIELD_RECORD_NAME, getModule(), 0, false, 0), false));\n }\n latch.countDown();\n }\n\n @Override\n public void notifyFailure(BError bError) {\n bError.printStackTrace();\n latch.countDown();\n System.exit(1);\n }\n\n public BTable getHeaderValueTable() {\n return headerValueTable;\n }\n}" }, { "identifier": "createError", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/CommonUtils.java", "snippet": "public static BError createError(String errorType, String message, Throwable throwable) {\n BError cause = ErrorCreator.createError(throwable);\n BMap<BString, Object> errorDetails = ValueCreator.createRecordValue(getModule(), ERROR_DETAILS);\n if (throwable instanceof MQException exception) {\n errorDetails.put(ERROR_REASON_CODE, exception.getReason());\n errorDetails.put(ERROR_ERROR_CODE, StringUtils.fromString(exception.getErrorCode()));\n errorDetails.put(ERROR_COMPLETION_CODE, exception.getCompCode());\n }\n return ErrorCreator.createError(\n ModuleUtils.getModule(), errorType, StringUtils.fromString(message), cause, errorDetails);\n}" }, { "identifier": "getModule", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/ModuleUtils.java", "snippet": "public static Module getModule() {\n return module;\n}" } ]
import com.ibm.mq.MQMessage; import com.ibm.mq.headers.MQDataException; import com.ibm.mq.headers.MQRFH2; import io.ballerina.lib.ibm.ibmmq.HeaderFieldValuesCallback; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.Runtime; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BIterator; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BObject; import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BTable; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import static io.ballerina.lib.ibm.ibmmq.CommonUtils.createError; import static io.ballerina.lib.ibm.ibmmq.Constants.CODED_CHARSET_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.ENCODING_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FLAGS_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FORMAT_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.IBMMQ_ERROR; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH2FIELD_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH2_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.STRUC_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.STRUC_LENGTH_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.VERSION_FIELD; import static io.ballerina.lib.ibm.ibmmq.ModuleUtils.getModule;
2,613
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * WSO2 LLC. 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.ballerina.lib.ibm.ibmmq.headers; /** * Header class with util methods for handling MQRFH2 headers. */ public class MQRFH2Header { private static final BString FIELD_VALUES_FIELD = StringUtils.fromString("fieldValues"); private static final BString FOLDER_STRINGS_FIELD = StringUtils.fromString("folderStrings"); private static final BString NAME_VALUE_CCSID_FIELD = StringUtils.fromString("nameValueCCSID"); private static final BString NAME_VALUE_DATA_FIELD = StringUtils.fromString("nameValueData"); private static final BString FOLDER_FIELD = StringUtils.fromString("folder"); private static final BString FIELD_FIELD = StringUtils.fromString("field"); private static final BString VALUE_FIELD = StringUtils.fromString("value"); private static final BString NAME_VALUE_LENGTH_FIELD = StringUtils.fromString("nameValueLength"); private static final String NATIVE_UTILS_OBJECT_NAME = "NativeUtils"; private static final String ADD_FIELDS_TO_TABLE_FUNCTION_NAME = "addMQRFH2FieldsToTable"; private MQRFH2Header() {} public static void decodeHeader(Runtime runtime, MQMessage msg, ArrayList<BMap<BString, Object>> headers) throws IOException { MQRFH2 mqrfh2 = new MQRFH2(); int dataOffset = msg.getDataOffset(); try { mqrfh2.read(msg); headers.add(getBHeaderFromMQRFH2(runtime, mqrfh2)); MQRFH2Header.decodeHeader(runtime, msg, headers); } catch (MQDataException e) { msg.seek(dataOffset); MQRFHHeader.decodeHeader(runtime, msg, headers); } } public static MQRFH2 createMQRFH2HeaderFromBHeader(BMap<BString, Object> bHeader) { MQRFH2 header = new MQRFH2(); header.setFlags(bHeader.getIntValue(FLAGS_FIELD).intValue()); header.setEncoding(bHeader.getIntValue(ENCODING_FIELD).intValue()); header.setCodedCharSetId(bHeader.getIntValue(CODED_CHARSET_ID_FIELD).intValue()); BArray folderStringsArray = bHeader.getArrayValue(FOLDER_STRINGS_FIELD); try { header.setFolderStrings(folderStringsArray.getStringArray()); } catch (IOException e) { throw createError(IBMMQ_ERROR, String .format("Error occurred while setting folder string to MQRFH2 header: %s", e.getMessage()), e); } header.setNameValueCCSID(bHeader.getIntValue(NAME_VALUE_CCSID_FIELD).intValue()); header.setNameValueData(bHeader.getArrayValue(NAME_VALUE_DATA_FIELD).getBytes()); header.setFormat(bHeader.getStringValue(FORMAT_FIELD).getValue()); BTable fieldTable = (BTable) bHeader.get(FIELD_VALUES_FIELD); BIterator fieldTableIterator = fieldTable.getIterator(); while (fieldTableIterator.hasNext()) { setFieldValueToMQRFH2Header(fieldTableIterator, header); } return header; } private static void setFieldValueToMQRFH2Header(BIterator fieldTableIterator, MQRFH2 header) { BMap<BString, Object> bField = (BMap<BString, Object>) ((BArray) fieldTableIterator.next()).get(1); String folder = bField.getStringValue(FOLDER_FIELD).getValue(); String field = bField.getStringValue(FIELD_FIELD).getValue(); Object value = bField.get(VALUE_FIELD); try { if (value instanceof Long longValue) { header.setLongFieldValue(folder, field, longValue.intValue()); } else if (value instanceof Integer intValue) { header.setIntFieldValue(folder, field, intValue); } else if (value instanceof Boolean booleanValue) { header.setFieldValue(folder, field, booleanValue); } else if (value instanceof Byte byteValue) { header.setByteFieldValue(folder, field, byteValue); } else if (value instanceof byte[] bytesValue) { header.setFieldValue(folder, field, bytesValue); } else if (value instanceof Float floatValue) { header.setFloatFieldValue(folder, field, floatValue); } else if (value instanceof Double doubleValue) { header.setFloatFieldValue(folder, field, doubleValue.floatValue()); } else if (value instanceof BString stringValue) { header.setFieldValue(folder, field, stringValue.getValue()); } else { header.setFieldValue(folder, field, value); } } catch (IOException e) { throw createError(IBMMQ_ERROR, String .format("Error occurred while setting field values to MQRFH2 header: %s", e.getMessage()), e); } } private static BMap<BString, Object> getBHeaderFromMQRFH2(Runtime runtime, MQRFH2 mqrfh2) throws IOException { BMap<BString, Object> header = ValueCreator.createRecordValue(getModule(), MQRFH2_RECORD_NAME); header.put(FLAGS_FIELD, mqrfh2.getFlags()); header.put(ENCODING_FIELD, mqrfh2.getEncoding()); header.put(CODED_CHARSET_ID_FIELD, mqrfh2.getCodedCharSetId()); BArray folderStringArray = ValueCreator.createArrayValue(TypeCreator .createArrayType(PredefinedTypes.TYPE_STRING)); String[] folderStrings = mqrfh2.getFolderStrings(); for (String folderString : folderStrings) { folderStringArray.append(StringUtils.fromString(folderString)); } header.put(FOLDER_STRINGS_FIELD, folderStringArray); header.put(NAME_VALUE_CCSID_FIELD, mqrfh2.getNameValueCCSID()); header.put(NAME_VALUE_DATA_FIELD, ValueCreator.createArrayValue(mqrfh2.getNameValueData())); header.put(NAME_VALUE_LENGTH_FIELD, mqrfh2.getNameValueLength()); header.put(FORMAT_FIELD, StringUtils.fromString(mqrfh2.getFormat())); header.put(STRUC_ID_FIELD, StringUtils.fromString(mqrfh2.getStrucId())); header.put(STRUC_LENGTH_FIELD, mqrfh2.getStrucLength()); header.put(VERSION_FIELD, mqrfh2.getVersion()); BTable fieldValuesTable = getBHeaderFieldValuesFromMQMessage(runtime, mqrfh2); header.put(FIELD_VALUES_FIELD, fieldValuesTable); return header; } private static BTable getBHeaderFieldValuesFromMQMessage(Runtime runtime, MQRFH2 mqrfh2) throws IOException { BArray fieldArray = ValueCreator.createArrayValue(TypeCreator.createArrayType(TypeCreator .createRecordType(MQRFH2FIELD_RECORD_NAME, getModule(), 0, false, 0))); MQRFH2.Element[] folders = mqrfh2.getFolders(); int i = 0; for (MQRFH2.Element folder : folders) { MQRFH2.Element[] children = folder.getChildren(); for (MQRFH2.Element child : children) { BMap<BString, Object> field = ValueCreator.createRecordValue(getModule(), MQRFH2FIELD_RECORD_NAME); field.put(FOLDER_FIELD, StringUtils.fromString(folder.getName())); field.put(FIELD_FIELD, StringUtils.fromString(child.getName())); field.put(VALUE_FIELD, getBValueForMQObjectValue(child.getValue())); fieldArray.add(i++, field); } } BObject nativeUtilsObject = ValueCreator.createObjectValue(getModule(), NATIVE_UTILS_OBJECT_NAME); CountDownLatch latch = new CountDownLatch(1);
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * WSO2 LLC. 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.ballerina.lib.ibm.ibmmq.headers; /** * Header class with util methods for handling MQRFH2 headers. */ public class MQRFH2Header { private static final BString FIELD_VALUES_FIELD = StringUtils.fromString("fieldValues"); private static final BString FOLDER_STRINGS_FIELD = StringUtils.fromString("folderStrings"); private static final BString NAME_VALUE_CCSID_FIELD = StringUtils.fromString("nameValueCCSID"); private static final BString NAME_VALUE_DATA_FIELD = StringUtils.fromString("nameValueData"); private static final BString FOLDER_FIELD = StringUtils.fromString("folder"); private static final BString FIELD_FIELD = StringUtils.fromString("field"); private static final BString VALUE_FIELD = StringUtils.fromString("value"); private static final BString NAME_VALUE_LENGTH_FIELD = StringUtils.fromString("nameValueLength"); private static final String NATIVE_UTILS_OBJECT_NAME = "NativeUtils"; private static final String ADD_FIELDS_TO_TABLE_FUNCTION_NAME = "addMQRFH2FieldsToTable"; private MQRFH2Header() {} public static void decodeHeader(Runtime runtime, MQMessage msg, ArrayList<BMap<BString, Object>> headers) throws IOException { MQRFH2 mqrfh2 = new MQRFH2(); int dataOffset = msg.getDataOffset(); try { mqrfh2.read(msg); headers.add(getBHeaderFromMQRFH2(runtime, mqrfh2)); MQRFH2Header.decodeHeader(runtime, msg, headers); } catch (MQDataException e) { msg.seek(dataOffset); MQRFHHeader.decodeHeader(runtime, msg, headers); } } public static MQRFH2 createMQRFH2HeaderFromBHeader(BMap<BString, Object> bHeader) { MQRFH2 header = new MQRFH2(); header.setFlags(bHeader.getIntValue(FLAGS_FIELD).intValue()); header.setEncoding(bHeader.getIntValue(ENCODING_FIELD).intValue()); header.setCodedCharSetId(bHeader.getIntValue(CODED_CHARSET_ID_FIELD).intValue()); BArray folderStringsArray = bHeader.getArrayValue(FOLDER_STRINGS_FIELD); try { header.setFolderStrings(folderStringsArray.getStringArray()); } catch (IOException e) { throw createError(IBMMQ_ERROR, String .format("Error occurred while setting folder string to MQRFH2 header: %s", e.getMessage()), e); } header.setNameValueCCSID(bHeader.getIntValue(NAME_VALUE_CCSID_FIELD).intValue()); header.setNameValueData(bHeader.getArrayValue(NAME_VALUE_DATA_FIELD).getBytes()); header.setFormat(bHeader.getStringValue(FORMAT_FIELD).getValue()); BTable fieldTable = (BTable) bHeader.get(FIELD_VALUES_FIELD); BIterator fieldTableIterator = fieldTable.getIterator(); while (fieldTableIterator.hasNext()) { setFieldValueToMQRFH2Header(fieldTableIterator, header); } return header; } private static void setFieldValueToMQRFH2Header(BIterator fieldTableIterator, MQRFH2 header) { BMap<BString, Object> bField = (BMap<BString, Object>) ((BArray) fieldTableIterator.next()).get(1); String folder = bField.getStringValue(FOLDER_FIELD).getValue(); String field = bField.getStringValue(FIELD_FIELD).getValue(); Object value = bField.get(VALUE_FIELD); try { if (value instanceof Long longValue) { header.setLongFieldValue(folder, field, longValue.intValue()); } else if (value instanceof Integer intValue) { header.setIntFieldValue(folder, field, intValue); } else if (value instanceof Boolean booleanValue) { header.setFieldValue(folder, field, booleanValue); } else if (value instanceof Byte byteValue) { header.setByteFieldValue(folder, field, byteValue); } else if (value instanceof byte[] bytesValue) { header.setFieldValue(folder, field, bytesValue); } else if (value instanceof Float floatValue) { header.setFloatFieldValue(folder, field, floatValue); } else if (value instanceof Double doubleValue) { header.setFloatFieldValue(folder, field, doubleValue.floatValue()); } else if (value instanceof BString stringValue) { header.setFieldValue(folder, field, stringValue.getValue()); } else { header.setFieldValue(folder, field, value); } } catch (IOException e) { throw createError(IBMMQ_ERROR, String .format("Error occurred while setting field values to MQRFH2 header: %s", e.getMessage()), e); } } private static BMap<BString, Object> getBHeaderFromMQRFH2(Runtime runtime, MQRFH2 mqrfh2) throws IOException { BMap<BString, Object> header = ValueCreator.createRecordValue(getModule(), MQRFH2_RECORD_NAME); header.put(FLAGS_FIELD, mqrfh2.getFlags()); header.put(ENCODING_FIELD, mqrfh2.getEncoding()); header.put(CODED_CHARSET_ID_FIELD, mqrfh2.getCodedCharSetId()); BArray folderStringArray = ValueCreator.createArrayValue(TypeCreator .createArrayType(PredefinedTypes.TYPE_STRING)); String[] folderStrings = mqrfh2.getFolderStrings(); for (String folderString : folderStrings) { folderStringArray.append(StringUtils.fromString(folderString)); } header.put(FOLDER_STRINGS_FIELD, folderStringArray); header.put(NAME_VALUE_CCSID_FIELD, mqrfh2.getNameValueCCSID()); header.put(NAME_VALUE_DATA_FIELD, ValueCreator.createArrayValue(mqrfh2.getNameValueData())); header.put(NAME_VALUE_LENGTH_FIELD, mqrfh2.getNameValueLength()); header.put(FORMAT_FIELD, StringUtils.fromString(mqrfh2.getFormat())); header.put(STRUC_ID_FIELD, StringUtils.fromString(mqrfh2.getStrucId())); header.put(STRUC_LENGTH_FIELD, mqrfh2.getStrucLength()); header.put(VERSION_FIELD, mqrfh2.getVersion()); BTable fieldValuesTable = getBHeaderFieldValuesFromMQMessage(runtime, mqrfh2); header.put(FIELD_VALUES_FIELD, fieldValuesTable); return header; } private static BTable getBHeaderFieldValuesFromMQMessage(Runtime runtime, MQRFH2 mqrfh2) throws IOException { BArray fieldArray = ValueCreator.createArrayValue(TypeCreator.createArrayType(TypeCreator .createRecordType(MQRFH2FIELD_RECORD_NAME, getModule(), 0, false, 0))); MQRFH2.Element[] folders = mqrfh2.getFolders(); int i = 0; for (MQRFH2.Element folder : folders) { MQRFH2.Element[] children = folder.getChildren(); for (MQRFH2.Element child : children) { BMap<BString, Object> field = ValueCreator.createRecordValue(getModule(), MQRFH2FIELD_RECORD_NAME); field.put(FOLDER_FIELD, StringUtils.fromString(folder.getName())); field.put(FIELD_FIELD, StringUtils.fromString(child.getName())); field.put(VALUE_FIELD, getBValueForMQObjectValue(child.getValue())); fieldArray.add(i++, field); } } BObject nativeUtilsObject = ValueCreator.createObjectValue(getModule(), NATIVE_UTILS_OBJECT_NAME); CountDownLatch latch = new CountDownLatch(1);
HeaderFieldValuesCallback headerFieldValuesCallback = new HeaderFieldValuesCallback(latch);
0
2023-10-27 05:54:44+00:00
4k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/impl/cameraoffset/CameraOffsetSchemeImpl.java
[ { "identifier": "CameraOffsetMode", "path": "common/src/main/java/net/leawind/mc/thirdperson/api/cameraoffset/CameraOffsetMode.java", "snippet": "public interface CameraOffsetMode {\n\t/**\n\t * 眼睛平滑系数\n\t */\n\tvoid getEyeSmoothFactor (@NotNull Vector3d v);\n\n\t/**\n\t * 距离平滑系数\n\t */\n\tdouble getDistanceSmoothFactor ();\n\n\t/**\n\t * 相机偏移平滑系数\n\t */\n\tvoid getOffsetSmoothFactor (@NotNull Vector2d v);\n\n\t/**\n\t * 相机到玩家的最大距离\n\t */\n\tdouble getMaxDistance ();\n\n\t/**\n\t * 设置相机到玩家的最大距离\n\t */\n\tvoid setMaxDistance (double distance);\n\n\t/**\n\t * 当前是否居中\n\t */\n\tboolean isCentered ();\n\n\t/**\n\t * 设置是否居中\n\t */\n\tvoid setCentered (boolean isCentered);\n\n\tboolean isCameraLeftOfPlayer ();\n\n\t/**\n\t * 设置相机在玩家的左边还是右边\n\t */\n\tvoid setSide (boolean isCameraLeftOfPlayer);\n\n\t/**\n\t * 切换到另一边,如果当前居中,则退出居中\n\t */\n\tvoid toNextSide ();\n\n\t/**\n\t * 获取偏移量\n\t * <p>\n\t * 根据当前是居中还是在两侧自动计算偏移量\n\t */\n\tVector2d getOffsetRatio (@NotNull Vector2d v);\n\n\t/**\n\t * 设置当相机位于两侧,而非居中时的偏移量。\n\t */\n\tvoid setSideOffsetRatio (@NotNull Vector2d v);\n\n\t/**\n\t * 获取当相机居中时的,垂直偏移量\n\t */\n\tdouble getCenterOffsetRatio ();\n\n\t/**\n\t * 设置当相机居中时的,垂直偏移量\n\t */\n\tvoid setCenterOffsetRatio (double offset);\n\n\t/**\n\t * 获取当相机位于两侧,而非居中时的偏移量。\n\t *\n\t * @param v 将取得的数据存入该向量\n\t * @return 与传入参数是同一个对象\n\t */\n\tVector2d getSideOffsetRatio (@NotNull Vector2d v);\n}" }, { "identifier": "CameraOffsetScheme", "path": "common/src/main/java/net/leawind/mc/thirdperson/api/cameraoffset/CameraOffsetScheme.java", "snippet": "public interface CameraOffsetScheme {\n\tstatic CameraOffsetScheme create (Config config) {\n\t\treturn new CameraOffsetSchemeImpl(config);\n\t}\n\n\t/**\n\t * 获取当前模式\n\t */\n\t@NotNull CameraOffsetMode getMode ();\n\n\t/**\n\t * 获取当前未启用的模式\n\t */\n\t@NotNull CameraOffsetMode getAnotherMode ();\n\n\t/**\n\t * 设置相机相对于玩家的方向\n\t * <p>\n\t *\n\t * @param side 大于0表示相机在玩家左侧\n\t */\n\tvoid setSide (double side);\n\n\t/**\n\t * 设置相机相对于玩家的方向\n\t *\n\t * @param isCameraLeftOfPlayer 相机是否在玩家左侧\n\t */\n\tvoid setSide (boolean isCameraLeftOfPlayer);\n\n\t/**\n\t * 切换到另一边\n\t */\n\tvoid toNextSide ();\n\n\t/**\n\t * 当前是否居中\n\t */\n\tboolean isCentered ();\n\n\t/**\n\t * 设置当前是否居中\n\t */\n\tvoid setCentered (boolean isCentered);\n\n\t/**\n\t * 设置当前是否处于瞄准模式\n\t */\n\tboolean isAiming ();\n\n\t/**\n\t * 当前是否处于瞄准模式\n\t */\n\tvoid setAiming (boolean aiming);\n}" }, { "identifier": "Config", "path": "common/src/main/java/net/leawind/mc/thirdperson/impl/config/Config.java", "snippet": "public class Config extends AbstractConfig {\n\t// ============================================================ //\n\tpublic @NotNull MonoList distanceMonoList;\n\tpublic @NotNull Set<ItemPattern> aim_item_patterns;\n\tpublic @NotNull Set<ItemPattern> use_aim_item_patterns;\n\t// ============================================================ //\n\tpublic @NotNull CameraOffsetScheme cameraOffsetScheme = CameraOffsetScheme.create(this);\n\n\tpublic Config () {\n\t\tDefaultConfig.setToDefault(this);\n\t\tdistanceMonoList = StaticMonoList.of(available_distance_count, camera_distance_min, camera_distance_max, i -> i * i, Math::sqrt);\n\t\taim_item_patterns = new HashSet<>();\n\t\tuse_aim_item_patterns = new HashSet<>();\n\t}\n\n\t/**\n\t * 配置项发生变化时更新\n\t */\n\tpublic void update () {\n\t\tupdateDistancesMonoList();\n\t\tupdateItemSet();\n\t}\n\n\t/**\n\t * 更新相机到玩家的距离的可调挡位们\n\t */\n\tpublic void updateDistancesMonoList () {\n\t\tdistanceMonoList = StaticMonoList.of(available_distance_count, camera_distance_min, camera_distance_max, i -> i * i, Math::sqrt);\n\t}\n\n\t/**\n\t * 更新自动瞄准物品集合\n\t * <p>\n\t * aiming_items 是字符串数组,其中的元素是nbt标签表达式\n\t * <p>\n\t * aiming_item_tags 是解析好的nbt标签集合,用于匹配玩家手持物品\n\t */\n\tpublic void updateItemSet () {\n\t\taim_item_patterns = new HashSet<>();\n\t\tuse_aim_item_patterns = new HashSet<>();\n\t\tItemPattern.addToSet(aim_item_patterns, aim_item_rules);\n\t\tItemPattern.addToSet(use_aim_item_patterns, use_aim_item_rules);\n\t\t// 内置物品匹配规则\n\t\tif (enable_buildin_aim_item_rules) {\n\t\t\tItemPattern.addToSet(aim_item_patterns, ModConstants.BUILDIN_AIM_ITEM_RULES);\n\t\t\tItemPattern.addToSet(use_aim_item_patterns, ModConstants.BUILDIN_USE_AIM_ITEM_RULES);\n\t\t}\n\t}\n}" } ]
import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetScheme; import net.leawind.mc.thirdperson.impl.config.Config; import org.jetbrains.annotations.NotNull;
1,832
package net.leawind.mc.thirdperson.impl.cameraoffset; /** * 第三人称相机的偏移方案 * <p> * 第三人称下,相机会根据其当前所处的模式来确定相机的行为。例如如何跟随玩家、如何旋转、与玩家的相对位置如何确定等。 * <p> * 默认有两种模式,按F5在第一人称和两种模式间切换 */ public class CameraOffsetSchemeImpl implements CameraOffsetScheme { private final @NotNull CameraOffsetMode normalMode; private final @NotNull CameraOffsetMode aimingMode; private boolean isAiming = false;
package net.leawind.mc.thirdperson.impl.cameraoffset; /** * 第三人称相机的偏移方案 * <p> * 第三人称下,相机会根据其当前所处的模式来确定相机的行为。例如如何跟随玩家、如何旋转、与玩家的相对位置如何确定等。 * <p> * 默认有两种模式,按F5在第一人称和两种模式间切换 */ public class CameraOffsetSchemeImpl implements CameraOffsetScheme { private final @NotNull CameraOffsetMode normalMode; private final @NotNull CameraOffsetMode aimingMode; private boolean isAiming = false;
public CameraOffsetSchemeImpl (@NotNull Config config) {
2
2023-10-31 05:52:36+00:00
4k
kandybaby/S3mediaArchival
backend/src/main/java/com/example/mediaarchival/controllers/UserController.java
[ { "identifier": "UserModel", "path": "backend/src/main/java/com/example/mediaarchival/models/UserModel.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class UserModel {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true, nullable = false)\n private String username;\n\n @Column(nullable = false)\n private String password;\n\n @Column(nullable = true)\n private String refreshToken;\n\n @Column private Date refreshExpiry;\n\n /**\n * Default constructor for JPA.\n */\n public UserModel() {}\n\n /**\n * Constructs a new UserModel with the specified username and password.\n *\n * @param username the username for the new user.\n * @param password the password for the new user.\n */\n public UserModel(String username, String password) {\n this.username = username;\n this.password = password;\n }\n\n /**\n * Gets the unique identifier for the user.\n *\n * @return the user ID.\n */\n public Long getId() {\n return id;\n }\n\n /**\n * Sets the unique identifier for the user.\n *\n * @param id the ID to set for the user.\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n /**\n * Gets the username for the user.\n *\n * @return the username.\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * Sets the username for the user. The username is unique and cannot be null.\n *\n * @param username the username to set.\n */\n public void setUsername(String username) {\n this.username = username;\n }\n\n /**\n * Gets the password for the user.\n *\n * @return the password.\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Sets the password for the user. The password cannot be null.\n *\n * @param password the password to set.\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Gets the refresh token for the user. This token is used to refresh authentication\n * when the current token expires.\n *\n * @return the refresh token, or null if it hasn't been set.\n */\n public String getRefreshToken() {\n return refreshToken;\n }\n\n /**\n * Sets the refresh token for the user.\n *\n * @param refreshToken the token to set for refreshing authentication.\n */\n public void setRefreshToken(String refreshToken) {\n this.refreshToken = refreshToken;\n }\n\n /**\n * Gets the expiry date for the refresh token.\n *\n * @return the refresh token expiry date, or null if the token hasn't been set or expired.\n */\n public Date getRefreshExpiry() {\n return refreshExpiry;\n }\n\n /**\n * Sets the expiry date for the refresh token.\n *\n * @param refreshExpiry the expiry date to set for the refresh token.\n */\n public void setRefreshExpiry(Date refreshExpiry) {\n this.refreshExpiry = refreshExpiry;\n }\n\n}" }, { "identifier": "UserRepository", "path": "backend/src/main/java/com/example/mediaarchival/repositories/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<UserModel, Long> {\n\n /**\n * Retrieves a user by their username.\n *\n * @param username the username to search for\n * @return the user with the specified username, or null if no such user exists\n */\n UserModel findByUsername(String username);\n\n /**\n * Retrieves a user by their refresh token.\n *\n * @param refreshToken the refresh token to search for\n * @return the user with the specified refresh token, or null if no such user exists\n */\n UserModel findByRefreshToken(String refreshToken);\n}" }, { "identifier": "LoginResponse", "path": "backend/src/main/java/com/example/mediaarchival/responses/LoginResponse.java", "snippet": "public class LoginResponse {\n @JsonProperty(\"JWT\")\n private final String JWT;\n\n /**\n * Default constructor for creating an empty LoginResponse.\n * This is typically used by frameworks for deserialization purposes.\n */\n public LoginResponse() {\n this.JWT = null;\n }\n\n /**\n * Constructs a LoginResponse with a specified JWT token.\n *\n * @param JWT The JSON Web Token that represents a successful authentication.\n */\n public LoginResponse(String JWT) {\n this.JWT = JWT;\n }\n}" }, { "identifier": "TokenUtils", "path": "backend/src/main/java/com/example/mediaarchival/utils/TokenUtils.java", "snippet": "public class TokenUtils {\n private static final String SECRET_KEY =\n Base64.getEncoder().encodeToString(new SecureRandom().generateSeed(64));\n\n private static final long JWT_EXPIRATION_MS = 1800000;\n\n private static final int TOKEN_LENGTH_BYTES = 64;\n\n private static final Logger errorLogger = LoggerFactory.getLogger(\"ERROR_LOGGER\");\n\n /**\n * Generates a JWT token for the given user details.\n *\n * @param userDetails The user details for which the token is to be generated.\n * @return A signed JWT token as a String.\n */\n public static String generateJwtToken(UserModel userDetails) {\n Map<String, Object> claims = new HashMap<>();\n return Jwts.builder()\n .setClaims(claims)\n .setSubject(userDetails.getUsername())\n .setIssuedAt(new Date())\n .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION_MS))\n .signWith(SignatureAlgorithm.HS512, getSecretKey())\n .compact();\n }\n\n /**\n * Generates a secure random refresh token.\n *\n * @return A base64 encoded secure random refresh token.\n */\n public static String generateRefreshToken() {\n SecureRandom secureRandom = new SecureRandom();\n byte[] tokenBytes = new byte[TOKEN_LENGTH_BYTES];\n secureRandom.nextBytes(tokenBytes);\n return Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);\n }\n\n /**\n * Validates a JWT token's signature and expiration date.\n *\n * @param token The JWT token to validate.\n * @return true if the token is valid, false otherwise.\n */\n public static boolean validateJwtToken(String token) {\n try {\n Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token);\n return true;\n } catch (Exception e) {\n errorLogger.error(e.getMessage());\n return false;\n }\n }\n\n /**\n * Extracts authentication information from a JWT token.\n *\n * @param token The JWT token from which to extract authentication details.\n * @return An Authentication object containing the username from the token.\n */\n public static Authentication getAuthenticationFromJwt(String token) {\n try {\n String username =\n Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody().getSubject();\n return new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());\n } catch (Exception e) {\n errorLogger.error(e.getMessage());\n return null;\n }\n }\n\n /**\n * Retrieves the secret key used for signing JWT tokens.\n *\n * @return The secret key for signing JWT tokens.\n */\n public static Key getSecretKey() {\n byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);\n return Keys.hmacShaKeyFor(keyBytes);\n }\n\n\n /**\n * Returns the configured JWT expiration time in milliseconds.\n *\n * @return The JWT expiration time in milliseconds.\n */\n public static long getJwtExpirationMs() {\n return JWT_EXPIRATION_MS;\n }\n}" } ]
import com.example.mediaarchival.models.UserModel; import com.example.mediaarchival.repositories.UserRepository; import com.example.mediaarchival.responses.LoginResponse; import com.example.mediaarchival.utils.TokenUtils; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletResponse; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*;
2,472
package com.example.mediaarchival.controllers; /** * Controller for managing user-related operations in the application. * This includes operations such as updating user details, authenticating users, * refreshing JWT tokens, and handling user logout. */ @RestController @RequestMapping("/api/users") public class UserController { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; @Autowired public UserController(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } /** * Updates the user's username or password. * * @param userRequest The user details to update. * @return A response entity indicating the result of the operation. */ @PutMapping("/update") public ResponseEntity<String> updateUser(@RequestBody UserModel userRequest) { UserModel user = userRepository.findAll().stream().findFirst().orElse(null); if (user != null) { if (userRequest.getUsername() != null && !userRequest.getUsername().isEmpty()) { user.setUsername(userRequest.getUsername()); } if (userRequest.getPassword() != null && !userRequest.getPassword().isEmpty()) { String hashedPassword = passwordEncoder.encode(userRequest.getPassword()); user.setPassword(hashedPassword); } userRepository.save(user); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("User not found."); } return ResponseEntity.status(HttpStatus.OK).body("User updated successfully."); } /** * Authenticates a user and provides JWT and refresh tokens. * * @param userRequest The user's login credentials. * @param response The HTTP response object for setting cookies. * @return A response entity containing the login response. */ @PostMapping("/authenticate") public ResponseEntity<LoginResponse> authenticateUser( @RequestBody UserModel userRequest, HttpServletResponse response) { // Validate user input (username and password) if (userRequest.getUsername() == null || userRequest.getUsername().isEmpty() || userRequest.getPassword() == null || userRequest.getPassword().isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new LoginResponse()); } // Find the user by username UserModel user = userRepository.findByUsername(userRequest.getUsername()); // Check if the user exists and the provided password matches if (user != null && passwordEncoder.matches(userRequest.getPassword(), user.getPassword())) {
package com.example.mediaarchival.controllers; /** * Controller for managing user-related operations in the application. * This includes operations such as updating user details, authenticating users, * refreshing JWT tokens, and handling user logout. */ @RestController @RequestMapping("/api/users") public class UserController { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; @Autowired public UserController(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } /** * Updates the user's username or password. * * @param userRequest The user details to update. * @return A response entity indicating the result of the operation. */ @PutMapping("/update") public ResponseEntity<String> updateUser(@RequestBody UserModel userRequest) { UserModel user = userRepository.findAll().stream().findFirst().orElse(null); if (user != null) { if (userRequest.getUsername() != null && !userRequest.getUsername().isEmpty()) { user.setUsername(userRequest.getUsername()); } if (userRequest.getPassword() != null && !userRequest.getPassword().isEmpty()) { String hashedPassword = passwordEncoder.encode(userRequest.getPassword()); user.setPassword(hashedPassword); } userRepository.save(user); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("User not found."); } return ResponseEntity.status(HttpStatus.OK).body("User updated successfully."); } /** * Authenticates a user and provides JWT and refresh tokens. * * @param userRequest The user's login credentials. * @param response The HTTP response object for setting cookies. * @return A response entity containing the login response. */ @PostMapping("/authenticate") public ResponseEntity<LoginResponse> authenticateUser( @RequestBody UserModel userRequest, HttpServletResponse response) { // Validate user input (username and password) if (userRequest.getUsername() == null || userRequest.getUsername().isEmpty() || userRequest.getPassword() == null || userRequest.getPassword().isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new LoginResponse()); } // Find the user by username UserModel user = userRepository.findByUsername(userRequest.getUsername()); // Check if the user exists and the provided password matches if (user != null && passwordEncoder.matches(userRequest.getPassword(), user.getPassword())) {
String jwt = TokenUtils.generateJwtToken(user);
3
2023-10-27 01:54:57+00:00
4k
siam1026/siam-cloud
siam-promotion/promotion-provider/src/main/java/com/siam/package_promotion/controller/member/CouponsMemberRelationController.java
[ { "identifier": "BasicData", "path": "siam-common/src/main/java/com/siam/package_common/entity/BasicData.java", "snippet": "public class BasicData extends BasicResult{\n private Object data;\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n}" }, { "identifier": "BasicResult", "path": "siam-common/src/main/java/com/siam/package_common/entity/BasicResult.java", "snippet": "@Data\npublic class BasicResult<T> {\n\n public static final Integer CODE_DEFAULT_SUCCESS = 200;\n public static final Integer CODE_DEFAULT_ERROR = 500;\n\n public static final String MESSAGE_DEFAULT_SUCCESS = \"请求成功\";\n public static final String MESSAGE_DEFAULT_ERROR = \"网络异常\";\n\n private Boolean success;\n\n private Integer code;\n\n private String message;\n\n private T data;\n\n public BasicResult() {\n }\n\n public BasicResult(Boolean success, Integer code, String message, T data) {\n this.success = success;\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public static BasicResult success() {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, null);\n }\n\n public static <T> BasicResult success(T data) {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, data);\n }\n\n public static BasicResult error(String message) {\n return new BasicResult(false, CODE_DEFAULT_ERROR, message, null);\n }\n}" }, { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }, { "identifier": "CouponsMemberRelation", "path": "siam-promotion/promotion-api/src/main/java/com/siam/package_promotion/entity/CouponsMemberRelation.java", "snippet": "@Data\n@TableName(\"tb_coupons_member_relation\")\npublic class CouponsMemberRelation {\n\n //页码\n private Integer pageNo = 1;\n\n //页面大小\n private Integer pageSize = 20;\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private Integer couponsId;\n\n private String couponsName;\n\n private Integer memberId;\n\n private Date startTime;\n\n private Date endTime;\n\n private Boolean isUsed;\n\n private Boolean isExpired;\n\n private Boolean isValid;\n\n private Date createTime;\n\n private Date updateTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Integer getCouponsId() {\n return couponsId;\n }\n\n public void setCouponsId(Integer couponsId) {\n this.couponsId = couponsId;\n }\n\n public String getCouponsName() {\n return couponsName;\n }\n\n public void setCouponsName(String couponsName) {\n this.couponsName = couponsName == null ? null : couponsName.trim();\n }\n\n public Integer getMemberId() {\n return memberId;\n }\n\n public void setMemberId(Integer memberId) {\n this.memberId = memberId;\n }\n\n public Date getStartTime() {\n return startTime;\n }\n\n public void setStartTime(Date startTime) {\n this.startTime = startTime;\n }\n\n public Date getEndTime() {\n return endTime;\n }\n\n public void setEndTime(Date endTime) {\n this.endTime = endTime;\n }\n\n public Boolean getIsUsed() {\n return isUsed;\n }\n\n public void setIsUsed(Boolean isUsed) {\n this.isUsed = isUsed;\n }\n\n public Boolean getIsExpired() {\n return isExpired;\n }\n\n public void setIsExpired(Boolean isExpired) {\n this.isExpired = isExpired;\n }\n\n public Boolean getIsValid() {\n return isValid;\n }\n\n public void setIsValid(Boolean isValid) {\n this.isValid = isValid;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n}" }, { "identifier": "CouponsMemberRelationService", "path": "siam-promotion/promotion-provider/src/main/java/com/siam/package_promotion/service/CouponsMemberRelationService.java", "snippet": "public interface CouponsMemberRelationService {\n\n /**\n * 创建\n * @param couponsMemberRelation\n */\n void insertSelective(CouponsMemberRelation couponsMemberRelation);\n\n /**\n * 通过id查询\n * @param id\n * @return\n */\n CouponsMemberRelation selectCouponsMemberRelationByPrimaryKey(Integer id);\n\n /**\n * 使用优惠卷\n */\n void updateCouponsUsed(Integer id, Boolean isUsed);\n\n Page<Map<String, Object>> getListByPage(int pageNo, int pageSize, CouponsMemberRelation couponsMemberRelation);\n\n void updateOverdue();\n\n Integer getCountsByMemberId(Integer memberId);\n\n void overdueSMSReminder();\n\n /**\n * 通过用户id获取是否含有可用优惠卷\n * @param memberId\n * @return\n */\n Boolean hasCouponsByMemberId(Integer memberId);\n\n\n\n}" }, { "identifier": "MemberSessionManager", "path": "siam-user/user-api/src/main/java/com/siam/package_user/auth/cache/MemberSessionManager.java", "snippet": "public interface MemberSessionManager {\n\n //缓存前缀\n String SESSION_PREFIX = \"LOGIN_USER:\";\n\n /**\n * 创建会话\n */\n void createSession(String token, Member member);\n\n /**\n * 获取会话\n */\n Member getSession(String token);\n\n /**\n * 删除会话\n */\n void removeSession(String token);\n\n /**\n * 是否已经登录\n */\n boolean haveSession(String token);\n}" }, { "identifier": "Member", "path": "siam-user/user-api/src/main/java/com/siam/package_user/entity/Member.java", "snippet": "@Data\n@TableName(\"tb_member\")\npublic class Member {\n\n //注册方式 1=微信一键登录 2=手机验证码 3=邀请注册\n public static final int REGISTER_WAY_OF_WECHAT = 1;\n public static final int REGISTER_WAY_OF_MOBILECODE = 2;\n public static final int REGISTER_WAY_OF_INVITE = 3;\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private String username;\n\n private String mobile;\n\n private String password;\n\n private String passwordSalt;\n\n private String nickname;\n\n private BigDecimal balance;\n\n private Integer loginCount;\n\n private String inviteCode;\n\n private String headImg;\n\n private String roles;\n\n private Integer sex;\n\n private String email;\n\n private Boolean isDisabled;\n\n private Boolean isDeleted;\n\n private String openId;\n\n private Boolean isBindWx;\n\n private BigDecimal points;\n\n private Integer vipStatus;\n\n private Integer vipType;\n\n private Date vipStartTime;\n\n private Date vipEndTime;\n\n private Integer type;\n\n private String vipNo;\n\n private Boolean isNewPeople;\n\n private Boolean isRemindNewPeople;\n\n private Date lastUseTime;\n\n private String lastUseAddress;\n\n private Integer registerWay;\n\n private String wxPublicPlatformOpenId;\n\n private Boolean isRequestWxNotify;\n\n private Date lastRequestWxNotifyTime;\n\n private BigDecimal inviteRewardAmount;\n\n private String realName;\n\n private BigDecimal totalBalance;\n\n private BigDecimal totalConsumeBalance;\n\n private BigDecimal totalPoints;\n\n private BigDecimal totalConsumePoints;\n\n private BigDecimal totalWithdrawInviteRewardAmount;\n\n private String paymentPassword;\n\n private String paymentPasswordSalt;\n\n private String inviteSuncode;\n\n private BigDecimal unreceivedPoints;\n\n private BigDecimal unreceivedInviteRewardAmount;\n\n private Date createTime;\n\n private Date updateTime;\n\n private Date lastLoginTime;\n}" }, { "identifier": "TokenUtil", "path": "siam-user/user-api/src/main/java/com/siam/package_user/util/TokenUtil.java", "snippet": "public class TokenUtil {\n\n public static final String TOKEN_HEADER_NAME = \"Authorization\";\n\n /**\n * 生成用户token\n *\n * @author 暹罗\n */\n public static String generateToken(Member member) {\n //设置7天过期\n long defaultTokenExpireSec = 7 * 24 * 60 * 60L;\n DateTime expirationDate = DateUtil.offsetMillisecond(new Date(), Convert.toInt(defaultTokenExpireSec) * 1000);\n String token = \"\";\n token = JWT.create().withAudience(member.getId().toString())\n .withIssuedAt(new Date())\n .withExpiresAt(expirationDate)\n .sign(Algorithm.HMAC256(member.getPassword()));\n return token;\n }\n\n /**\n * 生成管理员token\n *\n * @author 暹罗\n */\n public static String generateToken(Admin admin) {\n String token = \"\";\n token = JWT.create().withAudience(admin.getId().toString())\n .sign(Algorithm.HMAC256(admin.getPassword()));\n return token;\n }\n\n /**\n * 获取token\n *\n * @author 暹罗\n */\n public static String getToken() {\n String authToken = null;\n HttpServletRequest request = HttpContext.getRequest();\n\n //1、从header中获取\n authToken = request.getHeader(TOKEN_HEADER_NAME);\n if (StringUtils.isEmpty(authToken)) {\n authToken = request.getHeader(\"token\");\n }\n //2、从cookie中获取\n if (StringUtils.isEmpty(authToken)) {\n Cookie[] cookies = request.getCookies();\n if (cookies != null) {\n for (Cookie cookie : cookies) {\n if (TOKEN_HEADER_NAME.equals(cookie.getName())) {\n authToken = cookie.getValue();\n }\n }\n }\n }\n //3、从URL参数中获取\n if (StringUtils.isEmpty(authToken)) {\n authToken = request.getParameter(\"token\");\n }\n// if (StringUtils.isNotEmpty(authToken) && !authToken.equals(\"null\")) {\n// addLoginCookie(authToken);\n// }\n return authToken;\n }\n\n /**\n * 创建登录cookie\n */\n public static void addLoginCookie(String token) {\n Cookie authorization = new Cookie(TOKEN_HEADER_NAME, token);\n authorization.setMaxAge(getJwtSecretExpireSec().intValue());\n authorization.setHttpOnly(false);\n authorization.setPath(\"/\");\n\n Cookie randomKey_ = new Cookie(\"randomKey\", ToolUtil.getRandomString(6));\n randomKey_.setMaxAge(getJwtSecretExpireSec().intValue());\n randomKey_.setHttpOnly(false);\n randomKey_.setPath(\"/\");\n\n HttpServletResponse response = HttpContext.getResponse();\n response.addCookie(authorization);\n response.addCookie(randomKey_);\n }\n\n /**\n * 删除登录cookie\n */\n public static void deleteLoginCookie() {\n Cookie[] cookies = HttpContext.getRequest().getCookies();\n if (cookies != null) {\n for (Cookie cookie : cookies) {\n if (TOKEN_HEADER_NAME.equalsIgnoreCase(cookie.getName())) {\n Cookie temp = new Cookie(cookie.getName(), \"\");\n temp.setMaxAge(0);\n temp.setPath(\"/\");\n HttpContext.getResponse().addCookie(temp);\n }\n }\n }\n }\n\n /**\n * 获取系统地密钥过期时间(单位:秒)\n */\n public static Long getJwtSecretExpireSec() {\n //设置7天过期\n Long defaultSecs = 7 * 24 * 60 * 60L;\n return defaultSecs;\n }\n}" } ]
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_promotion.entity.CouponsMemberRelation; import com.siam.package_promotion.service.CouponsMemberRelationService; import com.siam.package_user.auth.cache.MemberSessionManager; import com.siam.package_user.entity.Member; import com.siam.package_user.util.TokenUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Map;
3,292
package com.siam.package_promotion.controller.member; @RestController @RequestMapping(value = "/rest/member/couponsMemberRelation") @Transactional(rollbackFor = Exception.class) @Api(tags = "优惠卷用关系接口", description = "CouponsMemberRelationController") public class CouponsMemberRelationController { @Autowired private CouponsMemberRelationService couponsMemberRelationService; // @Autowired // private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @ApiOperation(value = "新增优惠卷用户关系") @PostMapping(value = "/insert")
package com.siam.package_promotion.controller.member; @RestController @RequestMapping(value = "/rest/member/couponsMemberRelation") @Transactional(rollbackFor = Exception.class) @Api(tags = "优惠卷用关系接口", description = "CouponsMemberRelationController") public class CouponsMemberRelationController { @Autowired private CouponsMemberRelationService couponsMemberRelationService; // @Autowired // private MemberService memberService; @Autowired private MemberSessionManager memberSessionManager; @ApiOperation(value = "新增优惠卷用户关系") @PostMapping(value = "/insert")
public BasicResult insert(@RequestBody @Validated(value = {}) CouponsMemberRelation couponsMemberRelation) {
1
2023-10-26 10:45:10+00:00
4k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/session/SessionExecutor.java
[ { "identifier": "KeyEventInterface", "path": "app/src/main/java/sh/eliza/japaneseinput/KeycodeConverter.java", "snippet": "public interface KeyEventInterface {\n int getKeyCode();\n\n Optional<android.view.KeyEvent> getNativeEvent();\n}" }, { "identifier": "MozcLog", "path": "app/src/main/java/sh/eliza/japaneseinput/MozcLog.java", "snippet": "public class MozcLog {\n private MozcLog() {}\n\n public static boolean isLoggable(int logLevel) {\n return Log.isLoggable(MozcUtil.LOGTAG, logLevel);\n }\n\n public static void v(String msg) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.VERBOSE)) {\n Log.v(MozcUtil.LOGTAG, msg);\n }\n }\n\n public static void d(String msg) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.DEBUG)) {\n Log.d(MozcUtil.LOGTAG, msg);\n }\n }\n\n public static void d(String msg, Throwable e) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.DEBUG)) {\n Log.d(MozcUtil.LOGTAG, msg, e);\n }\n }\n\n public static void i(String msg) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.INFO)) {\n Log.i(MozcUtil.LOGTAG, msg);\n }\n }\n\n public static void w(String msg) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.WARN)) {\n Log.w(MozcUtil.LOGTAG, msg);\n }\n }\n\n public static void w(String msg, Throwable e) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.WARN)) {\n Log.w(MozcUtil.LOGTAG, msg, e);\n }\n }\n\n public static void e(String msg) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.ERROR)) {\n Log.e(MozcUtil.LOGTAG, msg);\n }\n }\n\n public static void e(String msg, Throwable e) {\n if (Log.isLoggable(MozcUtil.LOGTAG, Log.ERROR)) {\n Log.e(MozcUtil.LOGTAG, msg, e);\n }\n }\n}" }, { "identifier": "LayoutAdjustment", "path": "app/src/main/java/sh/eliza/japaneseinput/ViewManagerInterface.java", "snippet": "enum LayoutAdjustment {\n FILL,\n RIGHT,\n LEFT,\n}" } ]
import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Capability; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Capability.TextDeletionCapabilityType; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Command; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.CompositionMode; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Context.InputFieldType; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input.CommandType; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input.TouchEvent; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.InputOrBuilder; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.KeyEvent.SpecialKey; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Output; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Request; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.SessionCommand; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.SessionCommand.UsageStatsEvent; import org.mozc.android.inputmethod.japanese.protobuf.ProtoConfig.Config; import org.mozc.android.inputmethod.japanese.protobuf.ProtoUserDictionaryStorage.UserDictionaryCommand; import org.mozc.android.inputmethod.japanese.protobuf.ProtoUserDictionaryStorage.UserDictionaryCommandStatus; import sh.eliza.japaneseinput.KeycodeConverter.KeyEventInterface; import sh.eliza.japaneseinput.MozcLog; import sh.eliza.japaneseinput.MozcUtil; import sh.eliza.japaneseinput.ViewManagerInterface.LayoutAdjustment; import sh.eliza.japaneseinput.preference.ClientSidePreference;
3,531
/** Sends {@code MOVE_CURSOR} command to the server asynchronously. */ public void moveCursor(int cursorPosition, EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(ProtoCommands.SessionCommand.CommandType.MOVE_CURSOR) .setCursorPosition(cursorPosition)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code CONVERT_NEXT_PAGE} command to the server asynchronously. */ public void pageDown(EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.CONVERT_NEXT_PAGE)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code CONVERT_PREV_PAGE} command to the server asynchronously. */ public void pageUp(EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.CONVERT_PREV_PAGE)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code SWITCH_INPUT_FIELD_TYPE} command to the server asynchronously. */ public void switchInputFieldType(InputFieldType inputFieldType) { Preconditions.checkNotNull(inputFieldType); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(ProtoCommands.SessionCommand.CommandType.SWITCH_INPUT_FIELD_TYPE)) .setContext(ProtoCommands.Context.newBuilder().setInputFieldType(inputFieldType)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.absent()); } /** Sends {@code UNDO_OR_REWIND} command to the server asynchronously. */ public void undoOrRewind(List<TouchEvent> touchEventList, EvaluationCallback callback) { Preconditions.checkNotNull(touchEventList); Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.UNDO_OR_REWIND)) .addAllTouchEvents(touchEventList); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } // TODO(exv): replace this function // /** // * Sends {@code INSERT_TO_STORAGE} with given {@code type}, {@code key} and {@code values} // * to the server asynchronously. // */ // public void insertToStorage(StorageType type, String key, List<ByteString> values) { // Preconditions.checkNotNull(type); // Preconditions.checkNotNull(key); // Preconditions.checkNotNull(values); // Input.Builder inputBuilder = Input.newBuilder() // .setType(CommandType.INSERT_TO_STORAGE) // .setStorageEntry(GenericStorageEntry.newBuilder() // .setType(type) // .setKey(key) // .addAllValue(values)); // evaluateAsynchronously( // inputBuilder, Optional.<KeyEventInterface>absent(), // Optional.<EvaluationCallback>absent()); // } // TODO(exv): replace this function // public void expandSuggestion(EvaluationCallback callback) { // Preconditions.checkNotNull(callback); // Input.Builder inputBuilder = Input.newBuilder() // .setType(CommandType.SEND_COMMAND) // .setCommand( // SessionCommand.newBuilder().setType(SessionCommand.CommandType.EXPAND_SUGGESTION)); // evaluateAsynchronously( // inputBuilder, Optional.<KeyEventInterface>absent(), Optional.of(callback)); // } public void preferenceUsageStatsEvent(SharedPreferences sharedPreferences, Resources resources) { Preconditions.checkNotNull(sharedPreferences); Preconditions.checkNotNull(resources); // TODO(exv): replace this // sendIntegerUsageStatsUsageStatsEvent( // UsageStatsEvent.SOFTWARE_KEYBOARD_HEIGHT_DIP_LANDSCAPE, // (int) Math.ceil(MozcUtil.getDimensionForOrientation( // resources, R.dimen.ime_window_height, Configuration.ORIENTATION_LANDSCAPE))); // sendIntegerUsageStatsUsageStatsEvent( // UsageStatsEvent.SOFTWARE_KEYBOARD_HEIGHT_DIP_PORTRAIT, // (int) Math.ceil(MozcUtil.getDimensionForOrientation( // resources, R.dimen.ime_window_height, Configuration.ORIENTATION_PORTRAIT))); ClientSidePreference landscapePreference = ClientSidePreference.createFromSharedPreferences( sharedPreferences, resources, Configuration.ORIENTATION_LANDSCAPE); ClientSidePreference portraitPreference = ClientSidePreference.createFromSharedPreferences( sharedPreferences, resources, Configuration.ORIENTATION_PORTRAIT); sendIntegerUsageStatsUsageStatsEvent( UsageStatsEvent.SOFTWARE_KEYBOARD_LAYOUT_LANDSCAPE, landscapePreference.keyboardLayout.id); sendIntegerUsageStatsUsageStatsEvent( UsageStatsEvent.SOFTWARE_KEYBOARD_LAYOUT_PORTRAIT, portraitPreference.keyboardLayout.id); boolean layoutAdjustmentEnabledInLandscape =
// Copyright 2010-2018, Google Inc. // 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 Google Inc. 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 // OWNER 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 sh.eliza.japaneseinput.session; /** * This class handles asynchronous and synchronous execution of command evaluation based on {@link * SessionHandler}. * * <p>All execution is done on the single worker thread (not the UI thread). For asynchronous * execution, an evaluation task is sent to the worker thread, and the method returns immediately. * For synchronous execution, a task is sent to the worker thread, too, but it waits the execution * of the task (and pending tasks which have been sent before the task), and then returns. */ public class SessionExecutor { // At the moment we call mozc server via JNI interface directly, // while other platforms, e.g. Win/Mac/Linux etc, use IPC. // In order to keep the call order correctly, we call it from the single worker thread. // Note that we use well-known double check lazy initialization, // so that we can inject instances via reflections for testing purposes. private static volatile Optional<SessionExecutor> instance = Optional.absent(); private static SessionExecutor getInstanceInternal(Context applicationContext) { Optional<SessionExecutor> result = instance; if (!result.isPresent()) { synchronized (SessionExecutor.class) { result = instance; if (!result.isPresent()) { result = instance = Optional.of(new SessionExecutor()); result.get().reset(applicationContext); } } } return result.get(); } /** * Returns an instance of {@link SessionExecutor}. This method may return an instance without * initialization, assuming it will be initialized by client in appropriate timing. */ public static SessionExecutor getInstance(Context applicationContext) { return getInstanceInternal(Preconditions.checkNotNull(applicationContext)); } /** * Returns an instance of {@link SessionExecutor}. At first invocation, the instance will be * initialized by using given {@code factory}. Otherwise, the {@code factory} is simply ignored. */ public static SessionExecutor getInstanceInitializedIfNecessary(Context applicationContext) { return getInstanceInternal(Preconditions.checkNotNull(applicationContext)); } private static volatile Optional<HandlerThread> sessionHandlerThread = Optional.absent(); private static HandlerThread getHandlerThread() { Optional<HandlerThread> result = sessionHandlerThread; if (!result.isPresent()) { synchronized (SessionExecutor.class) { result = sessionHandlerThread; if (!result.isPresent()) { result = Optional.of(new HandlerThread("Session worker thread")); result.get().setDaemon(true); result.get().start(); sessionHandlerThread = result; } } } return result.get(); } /** An interface to accept the result of asynchronous evaluation. */ public interface EvaluationCallback { void onCompleted(Optional<Command> command, Optional<KeyEventInterface> triggeringKeyEvent); } private static class AsynchronousEvaluationContext { // For asynchronous evaluation, we set the sessionId in the callback running on the worker // thread. So, this class has Input.Builer as an argument for an evaluation, while // SynchronousEvaluationContext has Input because it is not necessary to be set sessionId. final long timeStamp; final Input.Builder inputBuilder; volatile Optional<Command> outCommand = Optional.absent(); final Optional<KeyEventInterface> triggeringKeyEvent; final Optional<EvaluationCallback> callback; final Optional<Handler> callbackHandler; AsynchronousEvaluationContext( long timeStamp, Input.Builder inputBuilder, Optional<KeyEventInterface> triggeringKeyEvent, Optional<EvaluationCallback> callback, Optional<Handler> callbackHandler) { this.timeStamp = timeStamp; this.inputBuilder = Preconditions.checkNotNull(inputBuilder); this.triggeringKeyEvent = Preconditions.checkNotNull(triggeringKeyEvent); this.callback = Preconditions.checkNotNull(callback); this.callbackHandler = Preconditions.checkNotNull(callbackHandler); } } private static class SynchronousEvaluationContext { final Input input; volatile Optional<Command> outCommand = Optional.absent(); final CountDownLatch evaluationSynchronizer; SynchronousEvaluationContext(Input input, CountDownLatch evaluationSynchronizer) { this.input = Preconditions.checkNotNull(input); this.evaluationSynchronizer = Preconditions.checkNotNull(evaluationSynchronizer); } } /** Context class just lines handler queue. */ private static class KeyEventCallbackContext { final KeyEventInterface triggeringKeyEvent; final EvaluationCallback callback; final Handler callbackHandler; KeyEventCallbackContext( KeyEventInterface triggeringKeyEvent, EvaluationCallback callback, Handler callbackHandler) { this.triggeringKeyEvent = Preconditions.checkNotNull(triggeringKeyEvent); this.callback = Preconditions.checkNotNull(callback); this.callbackHandler = Preconditions.checkNotNull(callbackHandler); } } /** * A core implementation of evaluation executing process. * * <p>This class takes messages from the UI thread. By using {@link SessionHandler}, it evaluates * the {@link Input} in a message, and then returns the result with notifying the UI thread if * necessary. All evaluations should be done with this class in order to keep evaluation in the * incoming order. */ private static class ExecutorMainCallback implements Handler.Callback { /** * Initializes the currently connected sesion handler. We need to initialize the current session * handler in the executor thread due to performance reason. This message should be run before * any other messages. */ static final int INITIALIZE_SESSION_HANDLER = 0; /** Deletes the session. */ static final int DELETE_SESSION = 1; /** Evaluates the command asynchronously. */ static final int EVALUATE_ASYNCHRONOUSLY = 2; /** * Evaluates the command asynchronously as similar to {@code EVALUATE_ASYNCHRONOUSLY}. The * difference from it is this should be used for the actual "key" event, such as "hit 'A' key," * "hit 'BACKSPACE'", "hit 'SPACEKEY'" or something. * * <p>Note: this is used to figure out whether it is ok to skip some heavier instruction in the * server. */ static final int EVALUATE_KEYEVENT_ASYNCHRONOUSLY = 3; /** Evaluates the command synchronously. */ static final int EVALUATE_SYNCHRONOUSLY = 4; /** Updates the current request, and notify it to the server. */ static final int UPDATE_REQUEST = 5; /** Just pass a message to callback. */ static final int PASS_TO_CALLBACK = 6; private static final long INVALID_SESSION_ID = 0; // TODO(exv): ensure list is exhaustive /** A set of CommandType which don't need session id. */ private static final Set<CommandType> SESSION_INDEPENDENT_COMMAND_TYPE_SET = Collections.unmodifiableSet( EnumSet.of( CommandType.NO_OPERATION, CommandType.SET_CONFIG, CommandType.GET_CONFIG, CommandType.CLEAR_USER_HISTORY, CommandType.CLEAR_USER_PREDICTION, CommandType.CLEAR_UNUSED_USER_PREDICTION, CommandType.RELOAD, CommandType.SEND_USER_DICTIONARY_COMMAND)); private final SessionHandler sessionHandler; // Mozc session's ID. // Set on CREATE_SESSION and will not be updated. private long sessionId = INVALID_SESSION_ID; private Optional<Request.Builder> request = Optional.absent(); // The logging for debugging is disabled by default. boolean isLogging = false; private ExecutorMainCallback(SessionHandler sessionHandler) { this.sessionHandler = Preconditions.checkNotNull(sessionHandler); } @Override public boolean handleMessage(Message message) { Preconditions.checkNotNull(message); // Dispatch the message. switch (message.what) { case INITIALIZE_SESSION_HANDLER: sessionHandler.initialize((Context) message.obj); break; case DELETE_SESSION: deleteSession(); break; case EVALUATE_ASYNCHRONOUSLY: case EVALUATE_KEYEVENT_ASYNCHRONOUSLY: evaluateAsynchronously((AsynchronousEvaluationContext) message.obj, message.getTarget()); break; case EVALUATE_SYNCHRONOUSLY: evaluateSynchronously((SynchronousEvaluationContext) message.obj); break; case UPDATE_REQUEST: updateRequest((Input.Builder) message.obj); break; case PASS_TO_CALLBACK: passToCallBack((KeyEventCallbackContext) message.obj); break; default: // We don't process unknown messages. return false; } return true; } private Command evaluate(Input input) { Command inCommand = Command.newBuilder().setInput(input).setOutput(Output.getDefaultInstance()).build(); // Note that toString() of ProtocolBuffers' message is very heavy. if (isLogging) { MozcCommandDebugger.inLog(inCommand); } Command outCommand = sessionHandler.evalCommand(inCommand); if (isLogging) { MozcCommandDebugger.outLog(outCommand); } return outCommand; } private void ensureSession() { if (sessionId != INVALID_SESSION_ID) { return; } // Send CREATE_SESSION command and keep the returned sessionId. Input input = Input.newBuilder() .setType(CommandType.CREATE_SESSION) .setCapability( Capability.newBuilder() .setTextDeletion(TextDeletionCapabilityType.DELETE_PRECEDING_TEXT)) .build(); sessionId = evaluate(input).getOutput().getId(); // Just after session creation, we send the default "request" to the server, // with ignoring its result. // Set mobile dedicated fields, which will not be changed. // Other fields may be set when the input view is changed. Request.Builder builder = Request.newBuilder(); MozcUtil.setSoftwareKeyboardRequest(builder); request = Optional.of(builder); evaluate( Input.newBuilder() .setId(sessionId) .setType(CommandType.SET_REQUEST) .setRequest(request.get()) .build()); } void deleteSession() { if (sessionId == INVALID_SESSION_ID) { return; } Input input = Input.newBuilder().setType(CommandType.DELETE_SESSION).setId(sessionId).build(); evaluate(input); sessionId = INVALID_SESSION_ID; request = Optional.absent(); } /** * Returns {@code true} iff the given {@code output} is squashable by following output. * * <p>Here, a squashable output A may be dropped if the next output B is sent before the UI * thread processes A (for performance reason). * * <p>{@link Output} consists from both fields which can be overwritten by following outputs * (e.g. composing text, a candidate list), and/or ones which cannot be (e.g. conversion * result). Squashing will happen when an output consists from only overwritable fields and then * another output, which will overwrite the UI change caused by the older output, comes. */ private static boolean isSquashableOutput(Output output) { // - If the output contains a result, it is not squashable because it is necessary // to commit the string to the client application. // - If it has deletion_range, it is not squashable either because it is necessary // to notify the editing to the client application. // - If the key is not consumed, it is not squashable because it is necessary to pass through // the event to the client application. // - If the event doesn't have candidates, it is not squashable because we need to ensure // the keyboard is visible. // - Otherwise squashable. An example is toggling a character. It contains neither // result string nor deletion_range, has candidates (by suggestion) and the keyevent // is consumed. return (output.getResult().getValue().length() == 0) && !output.hasDeletionRange() && output.getConsumed() && (output.getAllCandidateWords().getCandidatesCount() > 0); } /** * @return {@code true} if the given {@code inputBuilder} needs to be set session id. Otherwise * {@code false}. */ private static boolean isSessionIdRequired(InputOrBuilder input) { return !SESSION_INDEPENDENT_COMMAND_TYPE_SET.contains(input.getType()); } private void evaluateAsynchronously( AsynchronousEvaluationContext context, Handler sessionExecutorHandler) { // Before the evaluation, we remove all pending squashable result callbacks for performance // reason of less powerful devices. Input.Builder inputBuilder = context.inputBuilder; Optional<Handler> callbackHandler = context.callbackHandler; // TODO(exv): removed check to not squash EXPAND_SUGGESTION here. is that okay? if (callbackHandler.isPresent()) { // Do not squash by EXPAND_SUGGESTION request, because the result of EXPAND_SUGGESTION // won't affect the inputConnection in MozcService, as the result should update // only candidates conceptually. callbackHandler.get().removeMessages(CallbackHandler.SQUASHABLE_OUTPUT); } if (inputBuilder.hasKey() && (!inputBuilder.getKey().hasSpecialKey() || inputBuilder.getKey().getSpecialKey() == SpecialKey.BACKSPACE) && sessionExecutorHandler.hasMessages(EVALUATE_KEYEVENT_ASYNCHRONOUSLY)) { // Do not request suggestion result, due to performance reason, when: // - the key is normal key or backspace, and // - there is (at least one) following event. inputBuilder.setRequestSuggestion(false); } // We set the session id to the input in asynchronous evaluation before the evaluation, // if necessary. if (isSessionIdRequired(inputBuilder)) { ensureSession(); inputBuilder.setId(sessionId); } context.outCommand = Optional.of(evaluate(inputBuilder.build())); // Invoke callback handler if necessary. if (callbackHandler.isPresent()) { // For performance reason of, especially, less powerful devices, we want to skip // rendering whose effect will be overwritten by following (pending) rendering. // We annotate if the output can be overwritten or not here, so that we can remove // only those messages in later evaluation. Output output = context.outCommand.get().getOutput(); Message message = callbackHandler .get() .obtainMessage( isSquashableOutput(output) ? CallbackHandler.SQUASHABLE_OUTPUT : CallbackHandler.UNSQUASHABLE_OUTPUT, context); callbackHandler.get().sendMessage(message); } } private void evaluateSynchronously(SynchronousEvaluationContext context) { Input input = context.input; Preconditions.checkArgument( !isSessionIdRequired(input), "We expect only non-session-id-related input for synchronous evaluation: " + input); context.outCommand = Optional.of(evaluate(input)); // The client thread is waiting for the evaluation by evaluationSynchronizer, // so notify the thread via the lock. context.evaluationSynchronizer.countDown(); } private void updateRequest(Input.Builder inputBuilder) { ensureSession(); Preconditions.checkState(request.isPresent()); request.get().mergeFrom(inputBuilder.getRequest()); Input input = inputBuilder .setId(sessionId) .setType(CommandType.SET_REQUEST) .setRequest(request.get()) .build(); // Do not render the result because the result does not have preedit. evaluate(input); } private void passToCallBack(KeyEventCallbackContext context) { Handler callbackHandler = context.callbackHandler; Message message = callbackHandler.obtainMessage(CallbackHandler.UNSQUASHABLE_OUTPUT, context); callbackHandler.sendMessage(message); } } /** A handler to process callback for asynchronous evaluation on the UI thread. */ private static class CallbackHandler extends Handler { /** The message with this {@code what} cannot be overwritten by following evaluation. */ static final int UNSQUASHABLE_OUTPUT = 0; /** * The message with this {@code what} may be cancelled by following evaluation because the * result of the message would be overwritten soon. */ static final int SQUASHABLE_OUTPUT = 1; long cancelTimeStamp = System.nanoTime(); CallbackHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message message) { if (Preconditions.checkNotNull(message).obj.getClass() == KeyEventCallbackContext.class) { KeyEventCallbackContext keyEventContext = (KeyEventCallbackContext) message.obj; keyEventContext.callback.onCompleted( Optional.absent(), Optional.of(keyEventContext.triggeringKeyEvent)); return; } AsynchronousEvaluationContext context = (AsynchronousEvaluationContext) message.obj; // Note that this method should be run on the UI thread, where removePendingEvaluations runs, // so we don't need to take a lock here. if (context.timeStamp - cancelTimeStamp > 0) { Preconditions.checkState(context.callback.isPresent()); context.callback.get().onCompleted(context.outCommand, context.triggeringKeyEvent); } } } private Optional<Handler> handler = Optional.absent(); private Optional<ExecutorMainCallback> mainCallback = Optional.absent(); private final CallbackHandler callbackHandler; private SessionExecutor() { callbackHandler = new CallbackHandler(Looper.getMainLooper()); } private static void waitForQueueForEmpty(Handler handler) { final CountDownLatch synchronizer = new CountDownLatch(1); handler.post( new Runnable() { @Override public void run() { synchronizer.countDown(); } }); try { synchronizer.await(); } catch (InterruptedException exception) { MozcLog.w("waitForQueueForEmpty is interrupted."); } } /** Resets the instance by setting {@code SessionHandler} created by the given {@code factory}. */ public void reset(Context applicationContext) { Preconditions.checkNotNull(applicationContext); HandlerThread thread = getHandlerThread(); mainCallback = Optional.of(new ExecutorMainCallback(new LocalSessionHandler())); handler = Optional.of(new Handler(thread.getLooper(), mainCallback.get())); handler .get() .sendMessage( handler .get() .obtainMessage( ExecutorMainCallback.INITIALIZE_SESSION_HANDLER, applicationContext)); } /** * @param isLogging Set {@code true} if logging of evaluations is needed. */ public void setLogging(boolean isLogging) { if (mainCallback.isPresent()) { mainCallback.get().isLogging = isLogging; } } /** Remove pending evaluations from the pending queue. */ public void removePendingEvaluations() { callbackHandler.cancelTimeStamp = System.nanoTime(); if (handler.isPresent()) { handler.get().removeMessages(ExecutorMainCallback.EVALUATE_ASYNCHRONOUSLY); handler.get().removeMessages(ExecutorMainCallback.EVALUATE_KEYEVENT_ASYNCHRONOUSLY); handler.get().removeMessages(ExecutorMainCallback.EVALUATE_SYNCHRONOUSLY); handler.get().removeMessages(ExecutorMainCallback.UPDATE_REQUEST); } callbackHandler.removeMessages(CallbackHandler.UNSQUASHABLE_OUTPUT); callbackHandler.removeMessages(CallbackHandler.SQUASHABLE_OUTPUT); } public void deleteSession() { Preconditions.checkState(handler.isPresent()); handler.get().sendMessage(handler.get().obtainMessage(ExecutorMainCallback.DELETE_SESSION)); } /** * Evaluates the input caused by triggeringKeyEvent on the JNI worker thread. When the evaluation * is done, callbackHandler will receive the message with the evaluation context. * * <p>This method returns immediately, i.e., even after this method's invocation, it shouldn't be * assumed that the evaluation is done. * * @param inputBuilder the input data * @param triggeringKeyEvent a key event which triggers this evaluation * @param callback a callback handler if needed */ private void evaluateAsynchronously( Input.Builder inputBuilder, Optional<KeyEventInterface> triggeringKeyEvent, Optional<EvaluationCallback> callback) { Preconditions.checkState(handler.isPresent()); AsynchronousEvaluationContext context = new AsynchronousEvaluationContext( System.nanoTime(), Preconditions.checkNotNull(inputBuilder), Preconditions.checkNotNull(triggeringKeyEvent), Preconditions.checkNotNull(callback), callback.isPresent() ? Optional.of(callbackHandler) : Optional.absent()); int type = (triggeringKeyEvent.isPresent()) ? ExecutorMainCallback.EVALUATE_KEYEVENT_ASYNCHRONOUSLY : ExecutorMainCallback.EVALUATE_ASYNCHRONOUSLY; handler.get().sendMessage(handler.get().obtainMessage(type, context)); } /** Sends {@code SEND_KEY} command to the server asynchronously. */ public void sendKey( ProtoCommands.KeyEvent mozcKeyEvent, KeyEventInterface triggeringKeyEvent, List<TouchEvent> touchEventList, EvaluationCallback callback) { Preconditions.checkNotNull(mozcKeyEvent); Preconditions.checkNotNull(triggeringKeyEvent); Preconditions.checkNotNull(touchEventList); Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_KEY) .setKey(mozcKeyEvent) .addAllTouchEvents(touchEventList); evaluateAsynchronously(inputBuilder, Optional.of(triggeringKeyEvent), Optional.of(callback)); } /** Sends {@code SUBMIT} command to the server asynchronously. */ public void submit(EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand(SessionCommand.newBuilder().setType(SessionCommand.CommandType.SUBMIT)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code SWITCH_INPUT_MODE} command to the server asynchronously. */ public void switchInputMode( Optional<KeyEventInterface> triggeringKeyEvent, CompositionMode mode, EvaluationCallback callback) { Preconditions.checkNotNull(triggeringKeyEvent); Preconditions.checkNotNull(mode); Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(SessionCommand.CommandType.SWITCH_INPUT_MODE) .setCompositionMode(mode)); evaluateAsynchronously(inputBuilder, triggeringKeyEvent, Optional.of(callback)); } /** Sends {@code SUBMIT_CANDIDATE} command to the server asynchronously. */ public void submitCandidate( int candidateId, Optional<Integer> rowIndex, EvaluationCallback callback) { Preconditions.checkNotNull(rowIndex); Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(SessionCommand.CommandType.SUBMIT_CANDIDATE) .setId(candidateId)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); if (rowIndex.isPresent()) { candidateSubmissionStatsEvent(rowIndex.get()); } } private void candidateSubmissionStatsEvent(int rowIndex) { Preconditions.checkArgument(rowIndex >= 0); UsageStatsEvent event; switch (rowIndex) { case 0: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_0; break; case 1: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_1; break; case 2: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_2; break; case 3: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_3; break; case 4: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_4; break; case 5: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_5; break; case 6: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_6; break; case 7: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_7; break; case 8: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_8; break; case 9: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_9; break; default: event = UsageStatsEvent.SUBMITTED_CANDIDATE_ROW_GE10; } sendUsageStatsEvent(event); } /** Sends {@code RESET_CONTEXT} command to the server asynchronously. */ public void resetContext() { Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.RESET_CONTEXT)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.absent()); } /** Sends {@code MOVE_CURSOR} command to the server asynchronously. */ public void moveCursor(int cursorPosition, EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(ProtoCommands.SessionCommand.CommandType.MOVE_CURSOR) .setCursorPosition(cursorPosition)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code CONVERT_NEXT_PAGE} command to the server asynchronously. */ public void pageDown(EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.CONVERT_NEXT_PAGE)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code CONVERT_PREV_PAGE} command to the server asynchronously. */ public void pageUp(EvaluationCallback callback) { Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.CONVERT_PREV_PAGE)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } /** Sends {@code SWITCH_INPUT_FIELD_TYPE} command to the server asynchronously. */ public void switchInputFieldType(InputFieldType inputFieldType) { Preconditions.checkNotNull(inputFieldType); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder() .setType(ProtoCommands.SessionCommand.CommandType.SWITCH_INPUT_FIELD_TYPE)) .setContext(ProtoCommands.Context.newBuilder().setInputFieldType(inputFieldType)); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.absent()); } /** Sends {@code UNDO_OR_REWIND} command to the server asynchronously. */ public void undoOrRewind(List<TouchEvent> touchEventList, EvaluationCallback callback) { Preconditions.checkNotNull(touchEventList); Preconditions.checkNotNull(callback); Input.Builder inputBuilder = Input.newBuilder() .setType(CommandType.SEND_COMMAND) .setCommand( SessionCommand.newBuilder().setType(SessionCommand.CommandType.UNDO_OR_REWIND)) .addAllTouchEvents(touchEventList); evaluateAsynchronously(inputBuilder, Optional.absent(), Optional.of(callback)); } // TODO(exv): replace this function // /** // * Sends {@code INSERT_TO_STORAGE} with given {@code type}, {@code key} and {@code values} // * to the server asynchronously. // */ // public void insertToStorage(StorageType type, String key, List<ByteString> values) { // Preconditions.checkNotNull(type); // Preconditions.checkNotNull(key); // Preconditions.checkNotNull(values); // Input.Builder inputBuilder = Input.newBuilder() // .setType(CommandType.INSERT_TO_STORAGE) // .setStorageEntry(GenericStorageEntry.newBuilder() // .setType(type) // .setKey(key) // .addAllValue(values)); // evaluateAsynchronously( // inputBuilder, Optional.<KeyEventInterface>absent(), // Optional.<EvaluationCallback>absent()); // } // TODO(exv): replace this function // public void expandSuggestion(EvaluationCallback callback) { // Preconditions.checkNotNull(callback); // Input.Builder inputBuilder = Input.newBuilder() // .setType(CommandType.SEND_COMMAND) // .setCommand( // SessionCommand.newBuilder().setType(SessionCommand.CommandType.EXPAND_SUGGESTION)); // evaluateAsynchronously( // inputBuilder, Optional.<KeyEventInterface>absent(), Optional.of(callback)); // } public void preferenceUsageStatsEvent(SharedPreferences sharedPreferences, Resources resources) { Preconditions.checkNotNull(sharedPreferences); Preconditions.checkNotNull(resources); // TODO(exv): replace this // sendIntegerUsageStatsUsageStatsEvent( // UsageStatsEvent.SOFTWARE_KEYBOARD_HEIGHT_DIP_LANDSCAPE, // (int) Math.ceil(MozcUtil.getDimensionForOrientation( // resources, R.dimen.ime_window_height, Configuration.ORIENTATION_LANDSCAPE))); // sendIntegerUsageStatsUsageStatsEvent( // UsageStatsEvent.SOFTWARE_KEYBOARD_HEIGHT_DIP_PORTRAIT, // (int) Math.ceil(MozcUtil.getDimensionForOrientation( // resources, R.dimen.ime_window_height, Configuration.ORIENTATION_PORTRAIT))); ClientSidePreference landscapePreference = ClientSidePreference.createFromSharedPreferences( sharedPreferences, resources, Configuration.ORIENTATION_LANDSCAPE); ClientSidePreference portraitPreference = ClientSidePreference.createFromSharedPreferences( sharedPreferences, resources, Configuration.ORIENTATION_PORTRAIT); sendIntegerUsageStatsUsageStatsEvent( UsageStatsEvent.SOFTWARE_KEYBOARD_LAYOUT_LANDSCAPE, landscapePreference.keyboardLayout.id); sendIntegerUsageStatsUsageStatsEvent( UsageStatsEvent.SOFTWARE_KEYBOARD_LAYOUT_PORTRAIT, portraitPreference.keyboardLayout.id); boolean layoutAdjustmentEnabledInLandscape =
landscapePreference.layoutAdjustment != LayoutAdjustment.FILL;
2
2023-10-25 07:33:25+00:00
4k
ewolff/microservice-dapr
microservice-dapr-demo/microservice-dapr-invoicing/src/main/java/com/ewolff/microservice/invoicing/poller/InvoicePoller.java
[ { "identifier": "Invoice", "path": "microservice-dapr-demo/microservice-dapr-invoicing/src/main/java/com/ewolff/microservice/invoicing/Invoice.java", "snippet": "@Entity\npublic class Invoice {\n\n\t@Id\n\tprivate long id;\n\n\t@Embedded\n\tprivate Customer customer;\n\n\tprivate Date updated;\n\n\t@Embedded\n\tprivate Address billingAddress = new Address();\n\n\t@OneToMany(cascade = CascadeType.ALL)\n\tprivate List<InvoiceLine> invoiceLine;\n\n\tpublic Invoice() {\n\t\tsuper();\n\t\tinvoiceLine = new ArrayList<InvoiceLine>();\n\t}\n\n\tpublic Invoice(long id, Customer customer, Date updated, Address billingAddress, List<InvoiceLine> invoiceLine) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.customer = customer;\n\t\tthis.updated = updated;\n\t\tthis.billingAddress = billingAddress;\n\t\tthis.invoiceLine = invoiceLine;\n\t}\n\n\tpublic Address getBillingAddress() {\n\t\treturn billingAddress;\n\t}\n\n\tpublic void setBillingAddress(Address billingAddress) {\n\t\tthis.billingAddress = billingAddress;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic Date getUpdated() {\n\t\treturn updated;\n\t}\n\n\tpublic void setUpdated(Date created) {\n\t\tthis.updated = created;\n\t}\n\n\tpublic Customer getCustomer() {\n\t\treturn customer;\n\t}\n\n\tpublic void setCustomer(Customer customer) {\n\t\tthis.customer = customer;\n\t}\n\n\tpublic List<InvoiceLine> getInvoiceLine() {\n\t\treturn invoiceLine;\n\t}\n\n\tpublic void setInvoiceLine(List<InvoiceLine> invoiceLine) {\n\t\tthis.invoiceLine = invoiceLine;\n\t}\n\n\t@Transient\n\tpublic void setOrderLine(List<InvoiceLine> orderLine) {\n\t\tthis.invoiceLine = orderLine;\n\t}\n\n\tpublic void addLine(int count, Item item) {\n\t\tthis.invoiceLine.add(new InvoiceLine(count, item));\n\t}\n\n\tpublic int getNumberOfLines() {\n\t\treturn invoiceLine.size();\n\t}\n\n\tpublic double totalAmount() {\n\t\treturn invoiceLine.stream().map((ol) -> ol.getCount() * ol.getItem().getPrice()).reduce(0.0,\n\t\t\t\t(d1, d2) -> d1 + d2);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((billingAddress == null) ? 0 : billingAddress.hashCode());\n\t\tresult = prime * result + ((customer == null) ? 0 : customer.hashCode());\n\t\tresult = prime * result + (int) (id ^ (id >>> 32));\n\t\tresult = prime * result + ((invoiceLine == null) ? 0 : invoiceLine.hashCode());\n\t\tresult = prime * result + ((updated == null) ? 0 : updated.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tInvoice other = (Invoice) obj;\n\t\tif (billingAddress == null) {\n\t\t\tif (other.billingAddress != null)\n\t\t\t\treturn false;\n\t\t} else if (!billingAddress.equals(other.billingAddress))\n\t\t\treturn false;\n\t\tif (customer == null) {\n\t\t\tif (other.customer != null)\n\t\t\t\treturn false;\n\t\t} else if (!customer.equals(other.customer))\n\t\t\treturn false;\n\t\tif (id != other.id)\n\t\t\treturn false;\n\t\tif (invoiceLine == null) {\n\t\t\tif (other.invoiceLine != null)\n\t\t\t\treturn false;\n\t\t} else if (!invoiceLine.equals(other.invoiceLine))\n\t\t\treturn false;\n\t\tif (updated == null) {\n\t\t\tif (other.updated != null)\n\t\t\t\treturn false;\n\t\t} else if (!updated.equals(other.updated))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Invoice [id=\" + id + \", customer=\" + customer + \", updated=\" + updated + \", billingAddress=\"\n\t\t\t\t+ billingAddress + \", invoiceLine=\" + invoiceLine + \"]\";\n\t}\n\n}" }, { "identifier": "InvoiceService", "path": "microservice-dapr-demo/microservice-dapr-invoicing/src/main/java/com/ewolff/microservice/invoicing/InvoiceService.java", "snippet": "public interface InvoiceService {\r\n\r\n\tvoid generateInvoice(Invoice invoice);\r\n\r\n}" } ]
import java.time.ZonedDateTime; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import com.ewolff.microservice.invoicing.Invoice; import com.ewolff.microservice.invoicing.InvoiceService;
1,607
package com.ewolff.microservice.invoicing.poller; @Component public class InvoicePoller { private final Logger log = LoggerFactory.getLogger(InvoicePoller.class); private String url = ""; private RestTemplate restTemplate = new RestTemplate(); private ZonedDateTime lastModified = null; private boolean pollingActivated; private InvoiceService invoiceService; public InvoicePoller(@Value("${order.url}") String url, @Value("${poller.actived:true}") boolean pollingActivated, InvoiceService invoiceService) { super(); this.pollingActivated = pollingActivated; this.url = url; this.invoiceService = invoiceService; } @Scheduled(fixedDelay = 30000) public void poll() { if (pollingActivated) { pollInternal(); } } public void pollInternal() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set(HttpHeaders.ACCEPT, "*/*"); if (lastModified != null) { requestHeaders.setZonedDateTime(HttpHeaders.IF_MODIFIED_SINCE, lastModified); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { log.trace("data has been modified"); OrderFeed feed = response.getBody(); for (OrderFeedEntry entry : feed.getOrders()) { if ((lastModified == null) || (entry.getUpdated().after(Date.from(lastModified.toInstant())))) {
package com.ewolff.microservice.invoicing.poller; @Component public class InvoicePoller { private final Logger log = LoggerFactory.getLogger(InvoicePoller.class); private String url = ""; private RestTemplate restTemplate = new RestTemplate(); private ZonedDateTime lastModified = null; private boolean pollingActivated; private InvoiceService invoiceService; public InvoicePoller(@Value("${order.url}") String url, @Value("${poller.actived:true}") boolean pollingActivated, InvoiceService invoiceService) { super(); this.pollingActivated = pollingActivated; this.url = url; this.invoiceService = invoiceService; } @Scheduled(fixedDelay = 30000) public void poll() { if (pollingActivated) { pollInternal(); } } public void pollInternal() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set(HttpHeaders.ACCEPT, "*/*"); if (lastModified != null) { requestHeaders.setZonedDateTime(HttpHeaders.IF_MODIFIED_SINCE, lastModified); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { log.trace("data has been modified"); OrderFeed feed = response.getBody(); for (OrderFeedEntry entry : feed.getOrders()) { if ((lastModified == null) || (entry.getUpdated().after(Date.from(lastModified.toInstant())))) {
Invoice invoice = restTemplate.getForEntity(entry.getLink(), Invoice.class).getBody();
0
2023-10-25 09:22:16+00:00
4k
gongxuanzhang/EasyByte
easyByte-core/src/test/java/org/gongxuanzhang/easybyte/core/converter/read/DummyReadConverter.java
[ { "identifier": "Dummy", "path": "easyByte-core/src/test/java/org/gongxuanzhang/easybyte/core/Dummy.java", "snippet": "public class Dummy implements ByteWrapper {\n\n private Integer age;\n\n private String name;\n\n public Dummy() {\n\n }\n\n public Dummy(int age, String name) {\n this.age = age;\n this.name = name;\n }\n\n public Dummy(int age) {\n this.age = age;\n }\n\n public Dummy(String name) {\n this.name = name;\n }\n\n @Override\n public byte[] toBytes() {\n DynamicByteBuffer byteBuffer = DynamicByteBuffer.allocate();\n byteBuffer.appendInt(this.age == null ? -1 : this.age);\n byteBuffer.appendString(this.name);\n return byteBuffer.toBytes();\n }\n\n\n public Integer getAge() {\n return age;\n }\n\n public Dummy setAge(Integer age) {\n this.age = age;\n return this;\n }\n\n public String getName() {\n return name;\n }\n\n public Dummy setName(String name) {\n this.name = name;\n return this;\n }\n\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Dummy dummy = (Dummy) o;\n return Objects.equals(age, dummy.age) && Objects.equals(name, dummy.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(age, name);\n }\n}" }, { "identifier": "DynamicByteBuffer", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/DynamicByteBuffer.java", "snippet": "public interface DynamicByteBuffer extends CollectionByteBuffer, MapByteBuffer, StringByteBuffer, ReferenceByteBuffer\n , EasyByteConfiguration, ByteWrapper {\n\n\n /**\n * get a dynamicByteBuffer instance,similar to {@link ByteBuffer#allocate(int)}\n *\n * @return new dynamicByteBuffer\n **/\n static DynamicByteBuffer allocate() {\n return new JoinDynamicByteBuffer();\n }\n\n\n /**\n * get a dynamicByteBuffer instance with config,similar to {@link ByteBuffer#allocate(int)}\n *\n * @param config session config\n * @return new dynamicByteBuffer\n **/\n static DynamicByteBuffer allocate(ObjectConfig config) {\n return new JoinDynamicByteBuffer(config);\n }\n\n /**\n * wrap a byte array into buffer,similar to {@link ByteBuffer#wrap(byte[])}\n *\n * @param bytes The array that will back this buffer\n * @return new dynamicByteBuffer contain bytes\n **/\n static DynamicByteBuffer wrap(byte[] bytes) {\n return new JoinDynamicByteBuffer(bytes);\n }\n\n /**\n * wrap a byte array into buffer with config,similar to {@link ByteBuffer#wrap(byte[])}\n *\n * @param bytes The array that will back this buffer\n * @param config config\n * @return new dynamicByteBuffer contain bytes\n **/\n static DynamicByteBuffer wrap(byte[] bytes, ObjectConfig config) {\n return new JoinDynamicByteBuffer(bytes, config);\n }\n\n\n /**\n * append a byte,similar to {@link ByteBuffer#put(byte)}.\n *\n * @param b a byte\n * @return this\n **/\n DynamicByteBuffer append(byte b);\n\n\n /**\n * append a byte array ,similar to {@link ByteBuffer#put(byte[])}\n *\n * @param bytes byte array\n * @return this\n **/\n DynamicByteBuffer append(byte[] bytes);\n\n /**\n * append a short,similar to {@link ByteBuffer#putShort(short)}\n *\n * @param s a short\n * @return this\n **/\n DynamicByteBuffer appendShort(short s);\n\n /**\n * append a int,similar to {@link ByteBuffer#putInt(int)}\n *\n * @param i a int\n * @return this\n **/\n DynamicByteBuffer appendInt(int i);\n\n\n /**\n * append a long ,similar to {@link ByteBuffer#putLong(long)}\n *\n * @param l a long\n * @return this\n **/\n DynamicByteBuffer appendLong(long l);\n\n /**\n * append a float,similar to {@link ByteBuffer#putFloat(float)}\n *\n * @param f a float\n * @return this\n **/\n DynamicByteBuffer appendFloat(float f);\n\n /**\n * append a double,similar to {@link ByteBuffer#putDouble(double)}\n *\n * @param d a double\n * @return this\n **/\n DynamicByteBuffer appendDouble(double d);\n\n /**\n * append a char,similar to {@link ByteBuffer#putChar(char)}\n *\n * @param c a char\n * @return this\n **/\n DynamicByteBuffer appendChar(char c);\n\n /**\n * append a boolean as byte\n *\n * @param bool a boolean\n * @return this\n **/\n DynamicByteBuffer appendBoolean(boolean bool);\n\n /**\n * Read a byte from the buffer and advance the position, similar to {@link ByteBuffer#get()}.\n *\n * @return The byte in the buffer.\n **/\n byte get();\n\n /**\n * read a byte array input to container, similar to {@link ByteBuffer#get(byte[])}\n *\n * @param container {@link ByteBuffer#get(byte[])} param\n * @throws BufferUnderflowException If there are fewer than {@code container} bytes\n * remaining in this buffer\n **/\n void get(byte[] container);\n\n /**\n * read a special length from buffer.\n * if buffer remain less than length,it will throw error\n *\n * @param length read length of byte\n * @return a byte array filled from buffer,length is param\n **/\n byte[] getLength(int length);\n\n /**\n * Read a short from the buffer and advance the position, similar to {@link ByteBuffer#getShort()}.\n *\n * @return The short in the buffer.\n **/\n short getShort();\n\n /**\n * Read an integer from the buffer and advance the position, similar to {@link ByteBuffer#getInt()}.\n *\n * @return The integer in the buffer.\n **/\n int getInt();\n\n /**\n * Read a long from the buffer and advance the position, similar to {@link ByteBuffer#getLong()}.\n *\n * @return The long in the buffer.\n **/\n long getLong();\n\n /**\n * Read a float from the buffer and advance the position, similar to {@link ByteBuffer#getFloat()}.\n *\n * @return The float in the buffer.\n **/\n float getFloat();\n\n /**\n * Read a double from the buffer and advance the position, similar to {@link ByteBuffer#getDouble()}.\n *\n * @return The double in the buffer.\n **/\n double getDouble();\n\n /**\n * Read a boolean from the buffer and advance the position.\n * boolean as byte to save that zero is false and non-zero is true.\n **/\n boolean getBoolean();\n\n /**\n * Read a double from the buffer and advance the position, similar to {@link ByteBuffer#getChar()} .\n *\n * @return the char in the buffer\n **/\n char getChar();\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param collection {@link CollectionByteBuffer#appendCollection(Collection)}\n * @return this\n **/\n @Override\n DynamicByteBuffer appendCollection(Collection<?> collection);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param collection {@link CollectionByteBuffer#appendCollection(Collection, WriteConverter)}\n * @param convert {@link CollectionByteBuffer#appendCollection(Collection, WriteConverter)}\n * @return this\n **/\n @Override\n <V> DynamicByteBuffer appendCollection(Collection<V> collection, WriteConverter<V> convert);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param map {@link MapByteBuffer#appendMap(Map)}\n * @return this\n **/\n @Override\n DynamicByteBuffer appendMap(Map<?, ?> map);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param map {@link MapByteBuffer#appendMap(Map, WriteConverter, WriteConverter)}\n * @param keyConverter {@link MapByteBuffer#appendMap(Map, WriteConverter, WriteConverter)}\n * @param valueConverter {@link MapByteBuffer#appendMap(Map, WriteConverter, WriteConverter)}\n * @return this\n **/\n @Override\n <K, V> MapByteBuffer appendMap(Map<K, V> map, WriteConverter<K> keyConverter, WriteConverter<V> valueConverter);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param map {@link MapByteBuffer#appendMap(Map, WriteConverter)}\n * @param valueConverter {@link MapByteBuffer#appendMap(Map, WriteConverter)}\n * @return this\n **/\n @Override\n <K, V> MapByteBuffer appendMap(Map<K, V> map, WriteConverter<V> valueConverter);\n\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param o {@link ReferenceByteBuffer#appendObject(Object)}\n * @return this\n **/\n @Override\n DynamicByteBuffer appendObject(Object o);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param object {@link ReferenceByteBuffer#appendObject(Object, WriteConverter)}\n * @param converter {@link ReferenceByteBuffer#appendObject(Object, WriteConverter)}\n * @return this\n **/\n @Override\n <K> DynamicByteBuffer appendObject(K object, WriteConverter<K> converter);\n\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param s {@link StringByteBuffer#appendString(String)}\n * @return this\n **/\n @Override\n DynamicByteBuffer appendString(String s);\n\n /**\n * limit return type is {@link DynamicByteBuffer}\n *\n * @param s {@link StringByteBuffer#appendString(String, WriteConverter)}\n * @param convert {@link StringByteBuffer#appendString(String, WriteConverter)}\n * @return this\n **/\n @Override\n DynamicByteBuffer appendString(String s, WriteConverter<String> convert);\n\n}" }, { "identifier": "ReadConverter", "path": "easyByte-core/src/main/java/org/gongxuanzhang/easybyte/core/ReadConverter.java", "snippet": "@FunctionalInterface\npublic interface ReadConverter<V> {\n\n /**\n * convert object from byte array\n *\n * @param bytes from buffer,if length less zero bytes is null.\n * @param length general length is bytes length but sometime the length have special meaning\n * @return maybe null\n **/\n V toObject(byte[] bytes, int length);\n\n\n}" } ]
import org.gongxuanzhang.easybyte.core.Dummy; import org.gongxuanzhang.easybyte.core.DynamicByteBuffer; import org.gongxuanzhang.easybyte.core.ReadConverter;
2,788
package org.gongxuanzhang.easybyte.core.converter.read; /** * @author [email protected] **/ public class DummyReadConverter implements ReadConverter<Dummy> { @Override public Dummy toObject(byte[] bytes,int length) { if(length<0){ return null; }
package org.gongxuanzhang.easybyte.core.converter.read; /** * @author [email protected] **/ public class DummyReadConverter implements ReadConverter<Dummy> { @Override public Dummy toObject(byte[] bytes,int length) { if(length<0){ return null; }
DynamicByteBuffer buffer = DynamicByteBuffer.wrap(bytes);
1
2023-10-31 10:11:54+00:00
4k
Lyn4ever29/halo-plugin-export-md
src/main/java/cn/lyn4ever/export2md/service/impl/PostServiceImpl.java
[ { "identifier": "Content", "path": "src/main/java/cn/lyn4ever/export2md/halo/Content.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Content {\n private String raw;\n private String content;\n private String rawType;\n\n}" }, { "identifier": "ContentWrapper", "path": "src/main/java/cn/lyn4ever/export2md/halo/ContentWrapper.java", "snippet": "@Data\n@Builder\npublic class ContentWrapper {\n private String snapshotName;\n private String raw;\n private String content;\n private String rawType;\n\n public static ContentWrapper patchSnapshot(Snapshot patchSnapshot, Snapshot baseSnapshot) {\n Assert.notNull(baseSnapshot, \"The baseSnapshot must not be null.\");\n String baseSnapshotName = baseSnapshot.getMetadata().getName();\n if (StringUtils.equals(patchSnapshot.getMetadata().getName(), baseSnapshotName)) {\n return ContentWrapper.builder()\n .snapshotName(patchSnapshot.getMetadata().getName())\n .raw(patchSnapshot.getSpec().getRawPatch())\n .content(patchSnapshot.getSpec().getContentPatch())\n .rawType(patchSnapshot.getSpec().getRawType())\n .build();\n }\n String patchedContent = PatchUtils.applyPatch(baseSnapshot.getSpec().getContentPatch(),\n patchSnapshot.getSpec().getContentPatch());\n String patchedRaw = PatchUtils.applyPatch(baseSnapshot.getSpec().getRawPatch(),\n patchSnapshot.getSpec().getRawPatch());\n return ContentWrapper.builder()\n .snapshotName(patchSnapshot.getMetadata().getName())\n .raw(patchedRaw)\n .content(patchedContent)\n .rawType(patchSnapshot.getSpec().getRawType())\n .build();\n }\n}" }, { "identifier": "PostRequest", "path": "src/main/java/cn/lyn4ever/export2md/halo/PostRequest.java", "snippet": "@Data\npublic class PostRequest {\n\n\n private Post post;\n private Content content;\n\n public PostRequest(Post post, Content content) {\n this.post = post;\n this.content = content;\n }\n\n public ContentRequest contentRequest() {\n Ref subjectRef = Ref.of(post);\n return new ContentRequest(subjectRef, post.getSpec().getHeadSnapshot(), content.getRaw(),\n content.getContent(), content.getRawType());\n }\n}" }, { "identifier": "AbstractContentService", "path": "src/main/java/cn/lyn4ever/export2md/halo/service/AbstractContentService.java", "snippet": "@Slf4j\n@AllArgsConstructor\npublic abstract class AbstractContentService {\n\n private final ReactiveExtensionClient client;\n\n public Mono<ContentWrapper> getContent(String snapshotName, String baseSnapshotName) {\n if (StringUtils.isBlank(snapshotName) || StringUtils.isBlank(baseSnapshotName)) {\n return Mono.empty();\n }\n // TODO: refactor this method to use client.get instead of fetch but please be careful\n return client.fetch(Snapshot.class, baseSnapshotName)\n .doOnNext(this::checkBaseSnapshot)\n .flatMap(baseSnapshot -> {\n if (StringUtils.equals(snapshotName, baseSnapshotName)) {\n var contentWrapper = ContentWrapper.patchSnapshot(baseSnapshot, baseSnapshot);\n return Mono.just(contentWrapper);\n }\n return client.fetch(Snapshot.class, snapshotName)\n .map(snapshot -> ContentWrapper.patchSnapshot(snapshot, baseSnapshot));\n })\n .switchIfEmpty(Mono.defer(() -> {\n log.error(\"The content snapshot [{}] or base snapshot [{}] not found.\",\n snapshotName, baseSnapshotName);\n return Mono.empty();\n }));\n }\n\n protected void checkBaseSnapshot(Snapshot snapshot) {\n Assert.notNull(snapshot, \"The snapshot must not be null.\");\n if (!isBaseSnapshot(snapshot)) {\n throw new IllegalArgumentException(\n String.format(\"The snapshot [%s] is not a base snapshot.\",\n snapshot.getMetadata().getName()));\n }\n }\n\n protected Mono<ContentWrapper> draftContent(@Nullable String baseSnapshotName,\n ContentRequest contentRequest,\n @Nullable String parentSnapshotName) {\n Snapshot snapshot = contentRequest.toSnapshot();\n snapshot.getMetadata().setName(UUID.randomUUID().toString());\n snapshot.getSpec().setParentSnapshotName(parentSnapshotName);\n\n final String baseSnapshotNameToUse =\n StringUtils.defaultIfBlank(baseSnapshotName, snapshot.getMetadata().getName());\n return client.fetch(Snapshot.class, baseSnapshotName)\n .doOnNext(this::checkBaseSnapshot)\n .defaultIfEmpty(snapshot)\n .map(baseSnapshot -> determineRawAndContentPatch(snapshot, baseSnapshot,\n contentRequest)\n )\n .flatMap(source -> getContextUsername()\n .map(username -> {\n Snapshot.addContributor(source, username);\n source.getSpec().setOwner(username);\n return source;\n })\n .defaultIfEmpty(source)\n )\n .flatMap(snapshotToCreate -> client.create(snapshotToCreate)\n .flatMap(head -> restoredContent(baseSnapshotNameToUse, head)));\n }\n\n protected Mono<ContentWrapper> draftContent(String baseSnapshotName, ContentRequest content) {\n return this.draftContent(baseSnapshotName, content, content.headSnapshotName());\n }\n\n protected Mono<ContentWrapper> updateContent(String baseSnapshotName,\n ContentRequest contentRequest) {\n Assert.notNull(contentRequest, \"The contentRequest must not be null\");\n Assert.notNull(baseSnapshotName, \"The baseSnapshotName must not be null\");\n Assert.notNull(contentRequest.headSnapshotName(), \"The headSnapshotName must not be null\");\n return client.fetch(Snapshot.class, contentRequest.headSnapshotName())\n .flatMap(headSnapshot -> client.fetch(Snapshot.class, baseSnapshotName)\n .map(baseSnapshot -> determineRawAndContentPatch(headSnapshot, baseSnapshot,\n contentRequest)\n )\n )\n .flatMap(headSnapshot -> getContextUsername()\n .map(username -> {\n Snapshot.addContributor(headSnapshot, username);\n return headSnapshot;\n })\n .defaultIfEmpty(headSnapshot)\n )\n .flatMap(client::update)\n .flatMap(head -> restoredContent(baseSnapshotName, head));\n }\n\n protected Mono<ContentWrapper> restoredContent(String baseSnapshotName, Snapshot headSnapshot) {\n return client.fetch(Snapshot.class, baseSnapshotName)\n .doOnNext(this::checkBaseSnapshot)\n .map(baseSnapshot -> ContentWrapper.patchSnapshot(headSnapshot, baseSnapshot));\n }\n\n protected Snapshot determineRawAndContentPatch(Snapshot snapshotToUse,\n Snapshot baseSnapshot,\n ContentRequest contentRequest) {\n Assert.notNull(baseSnapshot, \"The baseSnapshot must not be null.\");\n Assert.notNull(contentRequest, \"The contentRequest must not be null.\");\n Assert.notNull(snapshotToUse, \"The snapshotToUse not be null.\");\n String originalRaw = baseSnapshot.getSpec().getRawPatch();\n String originalContent = baseSnapshot.getSpec().getContentPatch();\n String baseSnapshotName = baseSnapshot.getMetadata().getName();\n\n snapshotToUse.getSpec().setLastModifyTime(Instant.now());\n // it is the v1 snapshot, set the content directly\n if (StringUtils.equals(baseSnapshotName,\n snapshotToUse.getMetadata().getName())) {\n snapshotToUse.getSpec().setRawPatch(contentRequest.raw());\n snapshotToUse.getSpec().setContentPatch(contentRequest.content());\n MetadataUtil.nullSafeAnnotations(snapshotToUse)\n .put(Snapshot.KEEP_RAW_ANNO, Boolean.TRUE.toString());\n } else {\n // otherwise diff a patch based on the v1 snapshot\n String revisedRaw = contentRequest.rawPatchFrom(originalRaw);\n String revisedContent = contentRequest.contentPatchFrom(originalContent);\n snapshotToUse.getSpec().setRawPatch(revisedRaw);\n snapshotToUse.getSpec().setContentPatch(revisedContent);\n }\n return snapshotToUse;\n }\n\n protected Mono<String> getContextUsername() {\n return ReactiveSecurityContextHolder.getContext()\n .map(SecurityContext::getAuthentication)\n .map(Principal::getName);\n }\n\n\n /**\n * 更新自halo\n * @param snapshot\n * @return\n */\n private static boolean isBaseSnapshot(@NonNull Snapshot snapshot) {\n var annotations = snapshot.getMetadata().getAnnotations();\n if (annotations == null) {\n return false;\n }\n return Boolean.parseBoolean(annotations.get(Snapshot.KEEP_RAW_ANNO));\n }\n}" }, { "identifier": "PostService", "path": "src/main/java/cn/lyn4ever/export2md/service/PostService.java", "snippet": "public interface PostService {\n Mono<Post> draftPost(PostRequest postRequest);\n\n Mono<Post> updatePost(PostRequest postRequest);\n\n Mono<Post> updateBy(@NonNull Post post);\n\n Mono<ContentWrapper> getHeadContent(String postName);\n\n Mono<ContentWrapper> getHeadContent(Post post);\n\n Mono<ContentWrapper> getReleaseContent(String postName);\n\n Mono<ContentWrapper> getReleaseContent(Post post);\n\n Mono<Post> publish(Post post);\n\n Mono<Post> unpublish(Post post);\n\n Mono<Post> getByUsername(String postName, String username);\n\n PostRequest formatPost(File file);\n}" } ]
import cn.hutool.core.lang.UUID; import cn.hutool.json.JSONUtil; import cn.lyn4ever.export2md.halo.Content; import cn.lyn4ever.export2md.halo.ContentRequest; import cn.lyn4ever.export2md.halo.ContentWrapper; import cn.lyn4ever.export2md.halo.PostRequest; import cn.lyn4ever.export2md.halo.service.AbstractContentService; import cn.lyn4ever.export2md.service.PostService; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.StringJoiner; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.markdown4j.Markdown4jProcessor; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import reactor.util.retry.Retry; import run.halo.app.core.extension.content.Post; import run.halo.app.extension.Metadata; import run.halo.app.extension.ReactiveExtensionClient; import run.halo.app.extension.Ref; import run.halo.app.infra.Condition; import run.halo.app.infra.ConditionStatus;
2,762
package cn.lyn4ever.export2md.service.impl; /** * A default implementation of {@link PostService}. * * @author guqing * @since 2.0.0 */ @Slf4j @Component public class PostServiceImpl extends AbstractContentService implements PostService { private final ReactiveExtensionClient client; public PostServiceImpl(ReactiveExtensionClient client) { super(client); this.client = client; } /** * 保存文章 * * @param postRequest * @return */ @Override public Mono<Post> draftPost(PostRequest postRequest) { System.out.println(JSONUtil.toJsonStr(postRequest)); return Mono.defer( () -> { Post post = postRequest.getPost(); return getContextUsername() .map(username -> { post.getSpec().setOwner(username); return post; }) .defaultIfEmpty(post); } ) //保存文章 .flatMap(client::create) .flatMap(post -> { System.out.println("保存文章" + post.toString()); if (postRequest.getContent() == null) { return Mono.just(post); } var contentRequest = new ContentRequest(Ref.of(post), post.getSpec().getHeadSnapshot(), postRequest.getContent().getRaw(), postRequest.getContent().getContent(), postRequest.getContent().getRawType()); //保存文章内容 return draftContent(post.getSpec().getBaseSnapshot(), contentRequest) .flatMap(contentWrapper -> waitForPostToDraftConcludingWork( post.getMetadata().getName(), contentWrapper) ); }) .retryWhen(Retry.backoff(5, Duration.ofMillis(100)) .filter(OptimisticLockingFailureException.class::isInstance)); } private Mono<Post> waitForPostToDraftConcludingWork(String postName,
package cn.lyn4ever.export2md.service.impl; /** * A default implementation of {@link PostService}. * * @author guqing * @since 2.0.0 */ @Slf4j @Component public class PostServiceImpl extends AbstractContentService implements PostService { private final ReactiveExtensionClient client; public PostServiceImpl(ReactiveExtensionClient client) { super(client); this.client = client; } /** * 保存文章 * * @param postRequest * @return */ @Override public Mono<Post> draftPost(PostRequest postRequest) { System.out.println(JSONUtil.toJsonStr(postRequest)); return Mono.defer( () -> { Post post = postRequest.getPost(); return getContextUsername() .map(username -> { post.getSpec().setOwner(username); return post; }) .defaultIfEmpty(post); } ) //保存文章 .flatMap(client::create) .flatMap(post -> { System.out.println("保存文章" + post.toString()); if (postRequest.getContent() == null) { return Mono.just(post); } var contentRequest = new ContentRequest(Ref.of(post), post.getSpec().getHeadSnapshot(), postRequest.getContent().getRaw(), postRequest.getContent().getContent(), postRequest.getContent().getRawType()); //保存文章内容 return draftContent(post.getSpec().getBaseSnapshot(), contentRequest) .flatMap(contentWrapper -> waitForPostToDraftConcludingWork( post.getMetadata().getName(), contentWrapper) ); }) .retryWhen(Retry.backoff(5, Duration.ofMillis(100)) .filter(OptimisticLockingFailureException.class::isInstance)); } private Mono<Post> waitForPostToDraftConcludingWork(String postName,
ContentWrapper contentWrapper) {
1
2023-10-29 16:01:45+00:00
4k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/impl/modules/render/ViewModel.java
[ { "identifier": "TempleClient", "path": "src/main/java/xyz/templecheats/templeclient/TempleClient.java", "snippet": "@Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION)\npublic class TempleClient {\n public static String name = \"Temple Client 1.8.2\";\n\n public static final String MODID = \"templeclient\";\n public static final String NAME = \"Temple Client\";\n public static final String VERSION = \"1.8.2\";\n\n public static AnnotatedEventManager eventBus;\n public static SettingsManager settingsManager;\n public static ModuleManager moduleManager;\n public static EventManager clientEventManager;\n public static CommandManager commandManager;\n public static ClickGuiManager clickGui;\n public static ConfigManager configManager;\n public static CapeManager capeManager;\n private static Logger logger;\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n Display.setTitle(\"Loading \" + name);\n logger = event.getModLog();\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n Display.setTitle(name);\n MinecraftForge.EVENT_BUS.register(new TempleClient());\n\n eventBus = new AnnotatedEventManager();\n clientEventManager = new EventManager();\n MinecraftForge.EVENT_BUS.register(clientEventManager);\n\n settingsManager = new SettingsManager();\n\n (TempleClient.moduleManager = new ModuleManager()).initMods();\n logger.info(\"Module Manager Loaded.\");\n\n (TempleClient.commandManager = new CommandManager()).commandInit();\n logger.info(\"Commands Loaded.\");\n\n capeManager = new CapeManager();\n\n MinecraftForge.EVENT_BUS.register(clientEventManager);\n MinecraftForge.EVENT_BUS.register(commandManager);\n\n MinecraftForge.EVENT_BUS.register(new key());\n MinecraftForge.EVENT_BUS.register(new watermark());\n MinecraftForge.EVENT_BUS.register(new GuiEventsListener());\n\n clickGui = new ClickGuiManager();\n\n FontUtils.bootstrap();\n\n configManager = new ConfigManager();\n\n logger.info(\"Initialized Config!\");\n\n configManager.loadModules();\n\n Runtime.getRuntime().addShutdownHook(new ShutdownHook());\n }\n\n @SubscribeEvent\n public void onChat(ClientChatEvent event) {\n\n if(event.getMessage().startsWith(\".\")) {\n if(TempleClient.commandManager.executeCommand(event.getMessage())) {\n event.setCanceled(true);\n }\n }\n }\n\n public static void setSession(Session s) {\n Class<? extends Minecraft> mc = Minecraft.getMinecraft().getClass();\n\n try {\n Field session = null;\n\n for(Field f : mc.getDeclaredFields()) {\n if(f.getType().isInstance(s)) {\n session = f;\n }\n }\n\n if(session == null) {\n throw new IllegalStateException(\"Session Null\");\n }\n\n session.setAccessible(true);\n session.set(Minecraft.getMinecraft(), s);\n session.setAccessible(false);\n\n name = \"TempleClient 1.12.2 | User: \" + Minecraft.getMinecraft().getSession().getUsername();\n Display.setTitle(name);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n public static ModuleManager getModuleManager() {\n return TempleClient.moduleManager;\n }\n}" }, { "identifier": "Module", "path": "src/main/java/xyz/templecheats/templeclient/impl/modules/Module.java", "snippet": "public class Module {\n public String name;\n public boolean toggled;\n public int KeyCode;\n public Category category;\n public static Minecraft mc = Minecraft.getMinecraft();\n private boolean queueEnable;\n\n public Module(String name, int keyCode, Category c) {\n this.name = name;\n this.KeyCode = keyCode;\n this.category = c;\n }\n\n public boolean isEnabled() {\n return toggled;\n }\n\n public int getKey() {\n return KeyCode;\n }\n\n //do not override\n public final void onUpdateInternal() {\n if(mc.player != null) {\n if(this.queueEnable) {\n this.queueEnable = false;\n this.onEnable();\n }\n\n if(this.isToggled()) {\n this.onUpdate();\n }\n }\n\n this.onUpdateConstant();\n }\n\n public void onUpdate() {}\n\n public void onUpdateConstant() {}\n\n public void onEnable() {}\n\n public void onDisable() {}\n\n public void enable() {\n this.toggled = true;\n MinecraftForge.EVENT_BUS.register(this);\n TempleClient.eventBus.addEventListener(this);\n\n if(mc.player != null) {\n this.onEnable();\n } else {\n this.queueEnable = true;\n }\n }\n\n public void disable() {\n this.toggled = false;\n MinecraftForge.EVENT_BUS.unregister(this);\n TempleClient.eventBus.removeEventListener(this);\n\n if(mc.player != null) {\n this.onDisable();\n }\n }\n\n public void toggle() {\n this.setToggled(!this.isToggled());\n }\n\n public void setToggled(boolean toggled) {\n //dont do anything if the toggled state is the same\n if(toggled == this.toggled) return;\n\n if(toggled) {\n this.enable();\n } else {\n this.disable();\n }\n }\n\n public boolean isToggled() {\n return toggled;\n }\n\n public void setKey(int key) {\n this.KeyCode = key;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public String getName() {\n return this.name;\n }\n\n public enum Category {\n CHAT,\n COMBAT,\n MISC,\n MOVEMENT,\n RENDER,\n WORLD,\n CLIENT;\n }\n}" }, { "identifier": "Setting", "path": "src/main/java/xyz/templecheats/templeclient/impl/gui/clickgui/setting/Setting.java", "snippet": "public class Setting {\n\n\tprivate String name;\n\tprivate Module parent;\n\tprivate String mode;\n\n\tprivate String sval;\n\tprivate ArrayList<String> options;\n\tprivate String title;\n\n\tprivate boolean bval;\n\n\tprivate double dval;\n\tprivate double min;\n\tprivate double max;\n\tprivate boolean onlyint = false;\n\n\tprivate String text;\n\n\tprivate int color;\n\n\tpublic Setting(String name, Module parent, ArrayList<String> options, String title) {\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.options = options;\n\t\tthis.title = title;\n\t\tthis.mode = \"Combo\";\n\t}\n\n\tpublic Setting(String name, Module parent, boolean bval) {\n this.name = name;\n\t\tthis.parent = parent;\n\t\tthis.bval = bval;\n\t\tthis.mode = \"Check\";\n\t}\n\n\tpublic Setting(String name, Module parent, double dval, double min, double max, boolean onlyint) {\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.dval = dval;\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t\tthis.onlyint = onlyint;\n\t\tthis.mode = \"Slider\";\n\t}\n\n\n\tpublic String getName(){\n\t\treturn name;\n\t}\n\n\tpublic Module getParentMod(){\n\t\treturn parent;\n\t}\n\n\tpublic String getValString(){\n\t\treturn this.sval;\n\t}\n\n\tpublic void setValString(String in) {\n\t\tthis.sval = in;\n\t}\n\n\tpublic ArrayList<String> getOptions(){\n\t\treturn this.options;\n\t}\n\n\tpublic String getTitle(){\n\t\treturn this.title;\n\t}\n\n\tpublic boolean getValBoolean(){\n\t\treturn this.bval;\n\t}\n\n\tpublic void setValBoolean(boolean in){\n\t\tthis.bval = in;\n\t}\n\n\tpublic double getValDouble() {\n\t\tif(this.onlyint) {\n\t\t\tthis.dval = (int)dval;\n\t\t}\n\t\treturn this.dval;\n\t}\n\n public int getValInt() {\n return (int)dval;\n }\n\n\tpublic void setValDouble(double in){\n\t\tthis.dval = in;\n\t}\n\n\tpublic double getMin(){\n\t\treturn this.min;\n\t}\n\n\tpublic double getMax(){\n\t\treturn this.max;\n\t}\n\n\tpublic int getColor(){\n\t\treturn this.color;\n\t}\n\n\tpublic String getString(){\n\t\treturn this.text;\n\t}\n\n\tpublic boolean isCombo(){\n\t\treturn this.mode.equalsIgnoreCase(\"Combo\") ? true : false;\n\t}\n\n\tpublic boolean isCheck(){\n\t\treturn this.mode.equalsIgnoreCase(\"Check\") ? true : false;\n\t}\n\n\tpublic boolean isSlider(){\n\t\treturn this.mode.equalsIgnoreCase(\"Slider\") ? true : false;\n\t}\n\n\tpublic boolean isMode(){\n\t\treturn this.mode.equalsIgnoreCase(\"ModeButton\") ? true : false;\n\t}\n\n\tpublic boolean onlyInt(){\n\t\treturn this.onlyint;\n\t}\n}" }, { "identifier": "SettingsManager", "path": "src/main/java/xyz/templecheats/templeclient/impl/gui/clickgui/setting/SettingsManager.java", "snippet": "public class SettingsManager {\n\n\tprivate ArrayList<Setting> settings;\n\n\tpublic SettingsManager(){\n\t\tthis.settings = new ArrayList<Setting>();\n\t}\n\n\tpublic void rSetting(Setting in){\n\t\tthis.settings.add(in);\n\t}\n\n\tpublic ArrayList<Setting> getSettings(){\n\t\treturn this.settings;\n\t}\n\n\tpublic ArrayList<Setting> getSettingsByMod(Module mod){\n\t\tArrayList<Setting> out = new ArrayList<Setting>();\n\t\tfor(Setting s : getSettings()){\n\t\t\tif(s.getParentMod().equals(mod)){\n\t\t\t\tout.add(s);\n\t\t\t}\n\t\t}\n\t\tif(out.isEmpty()){\n\t\t\treturn null;\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic Setting getSettingByName(String mod, String name){\n\t\tfor(Setting set : getSettings()){\n\t\t\tif(set.getName().equalsIgnoreCase(name) && Objects.equals(set.getParentMod().name, mod)){\n\t\t\t\treturn set;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n}" } ]
import net.minecraft.client.Minecraft; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumHandSide; import xyz.templecheats.templeclient.TempleClient; import xyz.templecheats.templeclient.impl.modules.Module; import net.minecraftforge.client.event.RenderSpecificHandEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.Setting; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.SettingsManager;
2,662
package xyz.templecheats.templeclient.impl.modules.render; public class ViewModel extends Module { private Setting xPosMain, yPosMain, zPosMain; private Setting xSizeMain, ySizeMain, zSizeMain; public ViewModel() { super("ViewModel", Keyboard.KEY_NONE, Category.RENDER);
package xyz.templecheats.templeclient.impl.modules.render; public class ViewModel extends Module { private Setting xPosMain, yPosMain, zPosMain; private Setting xSizeMain, ySizeMain, zSizeMain; public ViewModel() { super("ViewModel", Keyboard.KEY_NONE, Category.RENDER);
SettingsManager settingsManager = TempleClient.settingsManager;
3
2023-10-28 12:03:50+00:00
4k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/processor/simple/RandomSpriteProvider.java
[ { "identifier": "ProcessingDataProvider", "path": "src/main/java/me/pepperbell/continuity/api/client/ProcessingDataProvider.java", "snippet": "public interface ProcessingDataProvider {\n\t<T> T getData(ProcessingDataKey<T> key);\n}" }, { "identifier": "ProcessingDataKeys", "path": "src/main/java/me/pepperbell/continuity/client/processor/ProcessingDataKeys.java", "snippet": "public final class ProcessingDataKeys {\n\tpublic static final ProcessingDataKey<BlockPos.Mutable> MUTABLE_POS_KEY = create(\"mutable_pos\", BlockPos.Mutable::new);\n\tpublic static final ProcessingDataKey<MeshBuilder> MESH_BUILDER_KEY = create(\"mesh_builder\", () -> RendererAccess.INSTANCE.getRenderer().meshBuilder());\n\tpublic static final ProcessingDataKey<BaseProcessingPredicate.BiomeCache> BIOME_CACHE_KEY = create(\"biome_cache\", BaseProcessingPredicate.BiomeCache::new, BaseProcessingPredicate.BiomeCache::reset);\n\tpublic static final ProcessingDataKey<BaseProcessingPredicate.BlockEntityNameCache> BLOCK_ENTITY_NAME_CACHE_KEY = create(\"block_entity_name_cache\", BaseProcessingPredicate.BlockEntityNameCache::new, BaseProcessingPredicate.BlockEntityNameCache::reset);\n\tpublic static final ProcessingDataKey<CompactCTMQuadProcessor.VertexContainer> VERTEX_CONTAINER_KEY = create(\"vertex_container\", CompactCTMQuadProcessor.VertexContainer::new);\n\tpublic static final ProcessingDataKey<StandardOverlayQuadProcessor.BlockStateAndBoolean> BLOCK_STATE_AND_BOOLEAN_KEY = create(\"block_state_and_boolean\", StandardOverlayQuadProcessor.BlockStateAndBoolean::new);\n\tpublic static final ProcessingDataKey<StandardOverlayQuadProcessor.OverlayRendererPool> STANDARD_OVERLAY_RENDERER_POOL_KEY = create(\"standard_overlay_renderer_pool\", StandardOverlayQuadProcessor.OverlayRendererPool::new, StandardOverlayQuadProcessor.OverlayRendererPool::reset);\n\tpublic static final ProcessingDataKey<SimpleOverlayQuadProcessor.OverlayRendererPool> SIMPLE_OVERLAY_RENDERER_POOL_KEY = create(\"simple_overlay_renderer_pool\", SimpleOverlayQuadProcessor.OverlayRendererPool::new, SimpleOverlayQuadProcessor.OverlayRendererPool::reset);\n\n\tprivate static <T> ProcessingDataKey<T> create(String id, Supplier<T> valueSupplier) {\n\t\treturn ProcessingDataKeyRegistry.INSTANCE.registerKey(ContinuityClient.asId(id), valueSupplier);\n\t}\n\n\tprivate static <T> ProcessingDataKey<T> create(String id, Supplier<T> valueSupplier, Consumer<T> valueResetAction) {\n\t\treturn ProcessingDataKeyRegistry.INSTANCE.registerKey(ContinuityClient.asId(id), valueSupplier, valueResetAction);\n\t}\n\n\tpublic static void init() {\n\t}\n}" }, { "identifier": "Symmetry", "path": "src/main/java/me/pepperbell/continuity/client/processor/Symmetry.java", "snippet": "public enum Symmetry {\n\tNONE,\n\tOPPOSITE,\n\tALL;\n\n\tpublic Direction getActualFace(Direction face) {\n\t\tif (this == Symmetry.OPPOSITE) {\n\t\t\tif (face.getDirection() == Direction.AxisDirection.POSITIVE) {\n\t\t\t\tface = face.getOpposite();\n\t\t\t}\n\t\t} else if (this == Symmetry.ALL) {\n\t\t\tface = Direction.DOWN;\n\t\t}\n\t\treturn face;\n\t}\n}" }, { "identifier": "RandomCTMProperties", "path": "src/main/java/me/pepperbell/continuity/client/properties/RandomCTMProperties.java", "snippet": "public class RandomCTMProperties extends BaseCTMProperties {\n\tprotected RandomIndexProvider.Factory indexProviderFactory = RandomIndexProvider.UnweightedFactory.INSTANCE;\n\tprotected int randomLoops = 0;\n\tprotected Symmetry symmetry = Symmetry.NONE;\n\tprotected boolean linked = false;\n\n\tpublic RandomCTMProperties(Properties properties, Identifier id, String packName, int packPriority, String method) {\n\t\tsuper(properties, id, packName, packPriority, method);\n\t}\n\n\t@Override\n\tpublic void init() {\n\t\tsuper.init();\n\t\tparseWeights();\n\t\tparseRandomLoops();\n\t\tparseSymmetry();\n\t\tparseLinked();\n\t}\n\n\tprotected void parseWeights() {\n\t\tString weightsStr = properties.getProperty(\"weights\");\n\t\tif (weightsStr != null) {\n\t\t\tweightsStr = weightsStr.trim();\n\t\t\tString[] weightStrs = weightsStr.split(\"[ ,]\");\n\t\t\tif (weightStrs.length != 0) {\n\t\t\t\tIntList weights = new IntArrayList();\n\t\t\t\tfor (int i = 0; i < weightStrs.length; i++) {\n\t\t\t\t\tString weightStr = weightStrs[i];\n\t\t\t\t\tif (!weightStr.isEmpty()) {\n\t\t\t\t\t\tString[] parts = weightStr.split(\"-\");\n\t\t\t\t\t\tint length = parts.length;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (length == 2) {\n\t\t\t\t\t\t\t\tint min = Integer.parseInt(parts[0]);\n\t\t\t\t\t\t\t\tint max = Integer.parseInt(parts[1]);\n\t\t\t\t\t\t\t\tif (max >= min) {\n\t\t\t\t\t\t\t\t\tfor (int weight = min; weight <= max; weight++) {\n\t\t\t\t\t\t\t\t\t\tweights.add(weight);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (length == 1) {\n\t\t\t\t\t\t\t\tint weight = Integer.parseInt(parts[0]);\n\t\t\t\t\t\t\t\tif (weight > 0) {\n\t\t\t\t\t\t\t\t\tweights.add(weight);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t}\n\t\t\t\t\t\tContinuityClient.LOGGER.warn(\"Invalid 'weights' element '\" + weightStr + \"' at index '\" + i + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (weights.size() > 1) {\n\t\t\t\t\tindexProviderFactory = new RandomIndexProvider.WeightedFactory(weights.toIntArray());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected void parseRandomLoops() {\n\t\tString randomLoopsStr = properties.getProperty(\"randomLoops\");\n\t\tif (randomLoopsStr != null) {\n\t\t\trandomLoopsStr = randomLoopsStr.trim();\n\t\t\ttry {\n\t\t\t\tint randomLoops = Integer.parseInt(randomLoopsStr);\n\t\t\t\tif (randomLoops >= 0 && randomLoops <= 9) {\n\t\t\t\t\tthis.randomLoops = randomLoops;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t//\n\t\t\t}\n\t\t\tContinuityClient.LOGGER.warn(\"Invalid 'randomLoops' value '\" + randomLoopsStr + \"' in file '\" + id + \"' in pack '\" + packName + \"'\");\n\t\t}\n\t}\n\n\tprotected void parseSymmetry() {\n\t\tSymmetry symmetry = PropertiesParsingHelper.parseSymmetry(properties, \"symmetry\", id, packName);\n\t\tif (symmetry != null) {\n\t\t\tthis.symmetry = symmetry;\n\t\t}\n\t}\n\n\tprotected void parseLinked() {\n\t\tString linkedStr = properties.getProperty(\"linked\");\n\t\tif (linkedStr != null) {\n\t\t\tlinkedStr = linkedStr.trim();\n\t\t\tlinked = Boolean.parseBoolean(linkedStr);\n\t\t}\n\t}\n\n\tpublic RandomIndexProvider.Factory getIndexProviderFactory() {\n\t\treturn indexProviderFactory;\n\t}\n\n\tpublic int getRandomLoops() {\n\t\treturn randomLoops;\n\t}\n\n\tpublic Symmetry getSymmetry() {\n\t\treturn symmetry;\n\t}\n\n\tpublic boolean getLinked() {\n\t\treturn linked;\n\t}\n}" }, { "identifier": "RandomIndexProvider", "path": "src/main/java/me/pepperbell/continuity/client/util/RandomIndexProvider.java", "snippet": "public interface RandomIndexProvider {\n\tint getRandomIndex(int random);\n\n\tinterface Factory {\n\t\tRandomIndexProvider createIndexProvider(int size);\n\t}\n\n\tclass Unweighted implements RandomIndexProvider {\n\t\tprotected int size;\n\n\t\tpublic Unweighted(int size) {\n\t\t\tthis.size = size;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getRandomIndex(int random) {\n\t\t\treturn Math.abs(random) % size;\n\t\t}\n\t}\n\n\tclass UnweightedFactory implements Factory {\n\t\tpublic static final UnweightedFactory INSTANCE = new UnweightedFactory();\n\n\t\t@Override\n\t\tpublic RandomIndexProvider createIndexProvider(int size) {\n\t\t\treturn new Unweighted(size);\n\t\t}\n\t}\n\n\tclass Weighted implements RandomIndexProvider {\n\t\tprotected int[] weights;\n\t\tprotected int weightSum;\n\t\tprotected int maxIndex;\n\n\t\tpublic Weighted(int[] weights, int weightSum, int maxIndex) {\n\t\t\tthis.weights = weights;\n\t\t\tthis.weightSum = weightSum;\n\t\t\tthis.maxIndex = maxIndex;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getRandomIndex(int random) {\n\t\t\tint index;\n\t\t\tint tempWeight = Math.abs(random) % weightSum;\n\t\t\tfor (index = 0; index < maxIndex && tempWeight >= weights[index]; index++) {\n\t\t\t\ttempWeight -= weights[index];\n\t\t\t}\n\t\t\treturn index;\n\t\t}\n\t}\n\n\tclass WeightedFactory implements Factory {\n\t\tprotected int[] weights;\n\n\t\tpublic WeightedFactory(int[] weights) {\n\t\t\tthis.weights = weights;\n\t\t}\n\n\t\t@Override\n\t\tpublic RandomIndexProvider createIndexProvider(int size) {\n\t\t\tint[] newWeights = new int[size];\n\t\t\tint copiedLength = Math.min(weights.length, newWeights.length);\n\t\t\tSystem.arraycopy(weights, 0, newWeights, 0, copiedLength);\n\n\t\t\tint weightSum = 0;\n\t\t\tfor (int i = 0; i < copiedLength; i++) {\n\t\t\t\tweightSum += weights[i];\n\t\t\t}\n\n\t\t\tif (copiedLength < newWeights.length) {\n\t\t\t\tint averageWeight = weightSum / copiedLength;\n\t\t\t\tfor (int i = copiedLength; i < newWeights.length; i++) {\n\t\t\t\t\tnewWeights[i] = averageWeight;\n\t\t\t\t\tweightSum += averageWeight;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn new Weighted(newWeights, weightSum, size - 1);\n\t\t}\n\t}\n}" } ]
import java.util.Random; import java.util.function.Supplier; import it.unimi.dsi.fastutil.HashCommon; import me.pepperbell.continuity.api.client.ProcessingDataProvider; import me.pepperbell.continuity.client.processor.ProcessingDataKeys; import me.pepperbell.continuity.client.processor.Symmetry; import me.pepperbell.continuity.client.properties.RandomCTMProperties; import me.pepperbell.continuity.client.util.RandomIndexProvider; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.client.texture.Sprite; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BlockRenderView;
2,464
package me.pepperbell.continuity.client.processor.simple; public class RandomSpriteProvider implements SpriteProvider { protected Sprite[] sprites;
package me.pepperbell.continuity.client.processor.simple; public class RandomSpriteProvider implements SpriteProvider { protected Sprite[] sprites;
protected RandomIndexProvider indexProvider;
4
2023-10-29 00:08:50+00:00
4k
BBMQyyds/Bright-Light-Building-Dreams
children/src/main/java/com/blbd/children/controller/TaskController.java
[ { "identifier": "HttpResponseEntity", "path": "children/src/main/java/com/blbd/children/beans/HttpResponseEntity.java", "snippet": "@Repository\npublic class HttpResponseEntity {\n private String code;//状态码\n private Object data;//数据\n private String message;//消息\n\n public HttpResponseEntity() {\n }\n\n public HttpResponseEntity(String code, Object data, String message) {\n this.code = code;\n this.data = data;\n this.message = message;\n }\n\n @Override\n public String toString() {\n return \"HttpResponseEntity{\" +\n \"code='\" + code + '\\'' +\n \", data=\" + data +\n \", message='\" + message + '\\'' +\n '}';\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n}" }, { "identifier": "TaskDTO", "path": "children/src/main/java/com/blbd/children/dao/dto/TaskDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class TaskDTO {\n\n private Integer highestScore;\n private Task task;\n}" }, { "identifier": "Child", "path": "children/src/main/java/com/blbd/children/dao/entity/Child.java", "snippet": "@Data\r\n@EqualsAndHashCode(callSuper = false)\r\n@Accessors(chain = true)\r\n@TableName(\"child\")\r\n@AllArgsConstructor\r\n//@ApiModel(value=\"Child对象\", description=\"\")\r\npublic class Child {\r\n @TableId(value = \"id\", type = IdType.ASSIGN_UUID)\r\n private String id;\r\n @TableField(\"username\")\r\n private String username;\r\n @TableField(\"score\")\r\n private Integer score;\r\n @TableField(\"password\")\r\n private String password;\r\n @TableField(\"name\")\r\n private String name;\r\n @TableField(\"grade\")\r\n private String grade;\r\n @TableField(\"locate\")\r\n private String locate;\r\n @TableField(\"duty\")\r\n private Integer duty;\r\n @TableField(\"completed_tasks\")\r\n private Integer completedTasks;\r\n @TableField(\"volunteer_id\")\r\n private String volunteerId;\r\n public Child(String id, String username, Integer score) {\r\n this.id = id;\r\n this.username = username;\r\n this.score = score;\r\n }\r\n\r\n public Child() {\r\n\r\n }\r\n}\r" }, { "identifier": "Task", "path": "children/src/main/java/com/blbd/children/dao/entity/Task.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"task\")\n//@ApiModel(value=\"Task对象\", description=\"\")\npublic class Task implements Serializable {\n\n private static final long serialVersionUID=1L;\n\n /**\n * 主键ID\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_UUID)\n private String id;\n\n /**\n * 积分\n */\n @TableField(\"score\")\n private Integer score;\n\n /**\n * 任务开始时间\n */\n @TableField(\"start_time\")\n private Date startTime;\n\n /**\n * 任务截止时间\n */\n @TableField(\"finish_time\")\n private Date finishTime;\n\n /**\n * 任务讲解视频地址\n */\n @TableField(\"video\")\n private String video;\n\n /**\n * 科目\n */\n @TableField(\"subject\")\n private String subject;\n\n /**\n * 年级\n */\n @TableField(\"grade\")\n private String grade;\n\n /**\n * 任务状态\n */\n @TableField(\"status\")\n private String status;\n\n /**\n * 是否必做\n */\n @TableField(\"is_must_do\")\n private Boolean isMustDo;\n\n /**\n * 任务内容\n */\n @TableField(\"content\")\n private String content;\n\n /**\n * 任务名称\n */\n @TableField(\"name\")\n private String name;\n\n /**\n * 任务图片地址\n */\n @TableField(\"task_photo\")\n private String taskPhoto;\n\n /**\n * 已完成的人数\n */\n @TableField(\"complete_num\")\n private Integer completedNum;\n\n /**\n * 该任务的学生最高获得分数\n */\n @TableField(\"max_score\")\n private Integer maxScore;\n\n}" }, { "identifier": "TaskChild", "path": "children/src/main/java/com/blbd/children/dao/entity/TaskChild.java", "snippet": "@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"task_child\")\n@Data\npublic class TaskChild implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 孩子ID,复合主键,外键\n */\n// @TableId\n private String childId;\n\n /**\n * 任务ID,复合主键,外键\n */\n// @TableId\n private String taskId;\n\n /**\n * 任务对应的积分,由任务ID查出来\n */\n private Integer score;\n\n /**\n * 任务开始时间,由任务ID查出来\n */\n private Date taskStartTime;\n\n /**\n * 任务完成时间,提交任务(上传任务图片时自动创建)\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date taskFinishTime;\n\n /**\n * 任务截止时间,由任务ID查出来\n */\n private Date taskEndTime;\n\n /**\n * 是否已完成--任务已提交就算完成,插入时和更新时自动为1\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Boolean isCompleted;\n\n /**\n * 是否已批改,插入和更新时初始为0,未批改\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Integer isCorrected;\n\n /**\n * 指派阶段,插入和更新时初始为1\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private String assignmentStage;\n\n /**\n * 孩子提交的作业图片的地址\n */\n private String homeworkPhoto;\n\n /**\n * 志愿者对作业的评价,插入和更新时初始为null\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private String comments;\n\n /**\n * 作业审批通过时间,插入和更新时初始为null\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date taskApproveTime;\n}" }, { "identifier": "TaskVolunteer", "path": "children/src/main/java/com/blbd/children/dao/entity/TaskVolunteer.java", "snippet": "@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@Data\n@TableName(\"task_volunteer\")\npublic class TaskVolunteer {\n private String volunteerId;\n private String childId;\n private String taskId;\n private Date approvalStartTime;\n private Date approvalFinishTime;\n private Date approvalEndTime;\n private byte isCompletedApproval;\n private String approvalComments;\n private String homeworkPhoto;\n private String taskPhoto;\n private String childName;\n private String taskName;\n private String taskVideo;\n private Integer getScore;\n}" }, { "identifier": "TaskMapper", "path": "children/src/main/java/com/blbd/children/mapper/TaskMapper.java", "snippet": "@Repository\npublic interface TaskMapper extends BaseMapper<Task> {\n\n}" }, { "identifier": "TaskVolunteerMapper", "path": "children/src/main/java/com/blbd/children/mapper/TaskVolunteerMapper.java", "snippet": "@Repository\npublic interface TaskVolunteerMapper extends BaseMapper<TaskVolunteer> {\n\n\n}" }, { "identifier": "TaskService", "path": "children/src/main/java/com/blbd/children/service/TaskService.java", "snippet": "public interface TaskService extends IService<Task> {\n /**\n * 列表\n */\n public List<Task> getAllTaskList();\n\n /**\n * 增\n */\n public int addTask(Task entity);\n\n /**\n * 通过ID删除\n */\n public boolean deleteTaskById(String id);\n\n /**\n * 通过ID改\n */\n public int editTask(Task entity);\n\n /**\n * 通过ID查一个任务\n */\n public Task queryTaskById(String id);\n\n /**\n * 查询满足条件的任务列表\n */\n public List<Task> list(Wrapper queryWrapper);\n\n\n /**\n * 查询所有任务的最高得分\n */\n public List<Map<String, Object>> getMaxScoreForEachTask();\n\n}" }, { "identifier": "TaskVolunteerService", "path": "children/src/main/java/com/blbd/children/service/TaskVolunteerService.java", "snippet": "public interface TaskVolunteerService {\n}" } ]
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.blbd.children.beans.HttpResponseEntity; import com.blbd.children.dao.dto.TaskDTO; import com.blbd.children.dao.entity.Child; import com.blbd.children.dao.entity.Task; import com.blbd.children.dao.entity.TaskChild; import com.blbd.children.dao.entity.TaskVolunteer; import com.blbd.children.mapper.TaskMapper; import com.blbd.children.mapper.TaskVolunteerMapper; import com.blbd.children.service.TaskService; import com.blbd.children.service.TaskVolunteerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors;
2,502
package com.blbd.children.controller; /** * @author zxr * @since 2023-11-02 */ @RestController @RequestMapping("children/task") public class TaskController { @Resource TaskMapper taskMapper; @Autowired TaskVolunteerMapper taskVolunteerMapper; @Autowired
package com.blbd.children.controller; /** * @author zxr * @since 2023-11-02 */ @RestController @RequestMapping("children/task") public class TaskController { @Resource TaskMapper taskMapper; @Autowired TaskVolunteerMapper taskVolunteerMapper; @Autowired
TaskVolunteerService taskVolunteerService;
9
2023-10-30 12:49:28+00:00
4k
sancar/kafkaDDS
src/test/java/io/github/sancar/kafkadds/ReplicatedMapTest.java
[ { "identifier": "Linearizable", "path": "src/main/java/io/github/sancar/kafkadds/linearizable/Linearizable.java", "snippet": "public class Linearizable {\n\n public static ReplicatedMap newMap(Properties properties) {\n return new ReplicatedMap(new KafkaBroadcast(properties));\n }\n}" }, { "identifier": "ReplicatedMap", "path": "src/main/java/io/github/sancar/kafkadds/linearizable/ReplicatedMap.java", "snippet": "public class ReplicatedMap implements ConcurrentMap<String, String>, Closeable {\n\n public record VersionedValue(int version, String value) {\n }\n\n private final AtomicBoolean isRunning = new AtomicBoolean(true);\n\n // This lock is make sure that the data map and wait map is updated/read atomically\n private final Lock lock = new ReentrantLock();\n private final ValueBarrier lastUpdateBarrier = new ValueBarrier();\n private final TotalOrderBroadcast totalOrderBroadcast;\n private final HashMap<String, List<CompletableFuture<VersionedValue>>> waitMap = new HashMap<>();\n private final Map<String, VersionedValue> data = new ConcurrentHashMap<>();\n\n public ReplicatedMap(TotalOrderBroadcast totalOrderBroadcast) {\n this.totalOrderBroadcast = totalOrderBroadcast;\n new Thread(() -> {\n while (isRunning.get()) {\n Collection<Message> messages = totalOrderBroadcast.consume();\n\n messages.forEach(message -> {\n if (Records.HeaderValues.WRITE_ATTEMPT.equals(message.op())) {\n try {\n lock.lock();\n Records.WriteAttemptKey attempt = toObject(message.key(), Records.WriteAttemptKey.class);\n VersionedValue old = data.get(attempt.key());\n int existingVersion = 0;\n if (old != null) {\n existingVersion = old.version;\n }\n\n Records.WriteAttemptValue value = toObject(message.value(), Records.WriteAttemptValue.class);\n var newValue = new VersionedValue(value.version(), value.value());\n if (value.version() > existingVersion) {\n data.put(attempt.key(), newValue);\n }\n\n List<CompletableFuture<VersionedValue>> futures = waitMap.remove(attempt.key() + \":\" + value.version());\n if (futures != null) {\n futures.forEach(f -> f.complete(newValue));\n }\n } finally {\n lock.unlock();\n }\n\n }\n lastUpdateBarrier.setIfBigger(message.offset());\n });\n }\n }).start();\n }\n\n private void linearizableRead() {\n String jsonKey = toJson(new Records.WaitKey(\"read\"));\n\n long offset = totalOrderBroadcast.offer(jsonKey, \"true\", Records.HeaderValues.WAIT_KEY);\n // wait for the message we sent to get back\n try {\n lastUpdateBarrier.await(offset, 1, TimeUnit.DAYS);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public String get(Object key) {\n linearizableRead();\n\n VersionedValue existingVal = data.get(key);\n if (existingVal == null) {\n return null;\n }\n return existingVal.value;\n }\n\n @Override\n public String put(String key, String value) {\n linearizableRead();\n int nextVersion;\n VersionedValue existingVal = data.get(key);\n\n if (existingVal == null) {\n nextVersion = 1;\n } else {\n nextVersion = existingVal.version + 1;\n }\n\n totalOrderBroadcastOffer(key, value, nextVersion);\n\n if (existingVal == null) {\n return null;\n }\n return existingVal.value;\n }\n\n @Override\n public void putAll(@NotNull Map<? extends String, ? extends String> m) {\n throw new RuntimeException(\"Implement me\");\n }\n\n @Override\n public void clear() {\n throw new RuntimeException(\"Implement me\");\n }\n\n @NotNull\n @Override\n public Set<String> keySet() {\n linearizableRead();\n return data.keySet();\n }\n\n @NotNull\n @Override\n public Collection<String> values() {\n linearizableRead();\n return data.values().stream().map(versionedValue -> versionedValue.value).toList();\n }\n\n @NotNull\n @Override\n public Set<Entry<String, String>> entrySet() {\n linearizableRead();\n return data.entrySet().stream()\n .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue().value))\n .collect(Collectors.toSet());\n }\n\n public String putIfAbsent(@NotNull String key, @NotNull String value) {\n linearizableRead();\n int nextVersion;\n CompletableFuture<VersionedValue> f = new CompletableFuture<>();\n\n\n try {\n lock.lock();\n VersionedValue existingVal = data.get(key);\n if (existingVal != null && existingVal.value != null) {\n return existingVal.value;\n }\n if (existingVal == null) {\n nextVersion = 1;\n } else {\n nextVersion = existingVal.version + 1;\n }\n\n registerToWaitFirstMessage(f, key, nextVersion);\n } finally {\n lock.unlock();\n }\n\n totalOrderBroadcastOffer(key, value, nextVersion);\n\n VersionedValue firstMessageBack = f.join();\n // if the first message we get back is ours. Then putIfAbsent is successful.\n if (value.equals(firstMessageBack.value)) {\n return null;\n }\n // otherwise, there was another set/remove, putIfAbsent failed.\n return firstMessageBack.value;\n }\n\n private void registerToWaitFirstMessage(CompletableFuture<VersionedValue> f, String key, int version) {\n waitMap.compute(key + \":\" + version, (s, futures) -> {\n if (futures == null) {\n futures = new LinkedList<>();\n }\n futures.add(f);\n return futures;\n });\n }\n\n @Override\n public boolean remove(@NotNull Object key, Object value) {\n throw new RuntimeException(\"Implement me\");\n }\n\n @Override\n public boolean replace(@NotNull String key, @NotNull String oldValue, @NotNull String newValue) {\n linearizableRead();\n int nextVersion;\n CompletableFuture<VersionedValue> f = new CompletableFuture<>();\n\n try {\n lock.lock();\n VersionedValue existingVal = data.get(key);\n if (existingVal == null) {\n return false;\n }\n if (!oldValue.equals(existingVal.value)) {\n return false;\n }\n nextVersion = existingVal.version + 1;\n\n registerToWaitFirstMessage(f, key, nextVersion);\n } finally {\n lock.unlock();\n }\n\n totalOrderBroadcastOffer(key, newValue, nextVersion);\n\n VersionedValue firstMessageBack = f.join();\n // if the first message we get back is ours. Then `replace` is successful.\n // otherwise, there was another set/remove, replace failed.\n return newValue.equals(firstMessageBack.value);\n }\n\n private void totalOrderBroadcastOffer(@NotNull String key, String newValue, int nextVersion) {\n String jsonKey = toJson(new Records.WriteAttemptKey(key));\n String jsonValue = toJson(new Records.WriteAttemptValue(nextVersion, newValue));\n totalOrderBroadcast.offer(jsonKey, jsonValue, Records.HeaderValues.WRITE_ATTEMPT);\n }\n\n @Override\n public String replace(@NotNull String key, @NotNull String value) {\n linearizableRead();\n int nextVersion;\n VersionedValue existingVal;\n try {\n lock.lock();\n existingVal = data.get(key);\n if (existingVal == null || existingVal.value == null) {\n return null;\n }\n\n nextVersion = existingVal.version + 1;\n } finally {\n lock.unlock();\n }\n\n totalOrderBroadcastOffer(key, value, nextVersion);\n return existingVal.value;\n }\n\n @Override\n public String remove(Object key) {\n linearizableRead();\n int nextVersion;\n VersionedValue existingVal = data.get(key);\n\n if (existingVal == null) {\n return null;\n } else {\n nextVersion = existingVal.version + 1;\n }\n\n totalOrderBroadcastOffer((String) key, null, nextVersion);\n\n return existingVal.value;\n }\n\n @Override\n public int size() {\n linearizableRead();\n return data.size();\n }\n\n @Override\n public boolean isEmpty() {\n linearizableRead();\n return data.isEmpty();\n }\n\n @Override\n public boolean containsKey(Object key) {\n linearizableRead();\n return data.containsKey(key);\n }\n\n @Override\n public boolean containsValue(Object value) {\n linearizableRead();\n return data.containsValue(value);\n }\n\n @Override\n public void close() {\n isRunning.set(false);\n }\n}" }, { "identifier": "InMemoryLog", "path": "src/main/java/io/github/sancar/kafkadds/totalorderbrodacast/InMemoryLog.java", "snippet": "public class InMemoryLog {\n\n private final Lock lock = new ReentrantLock();\n public final ArrayList<Message> log = new ArrayList<>();\n private final AtomicInteger offsetGenerator = new AtomicInteger(-1);\n\n public long offer(String key, String value, String header) {\n try {\n lock.lock();\n int offset = offsetGenerator.incrementAndGet();\n log.add(offset, new Message(offset, key, value, header));\n return offset;\n } finally {\n lock.unlock();\n }\n }\n\n public ArrayList<Message> consume(int consumeOffset) {\n try {\n lock.lock();\n ArrayList<Message> list = new ArrayList<>(log.size() - consumeOffset);\n for (; consumeOffset < log.size(); consumeOffset++) {\n list.add(log.get(consumeOffset));\n }\n return list;\n } finally {\n lock.unlock();\n }\n }\n\n}" }, { "identifier": "InmemoryTotalOrderBroadcast", "path": "src/main/java/io/github/sancar/kafkadds/totalorderbrodacast/InmemoryTotalOrderBroadcast.java", "snippet": "public class InmemoryTotalOrderBroadcast implements TotalOrderBroadcast {\n\n private final InMemoryLog log;\n private int consumeOffset = 0;\n\n private final Runnable callback;\n\n // Callback to be called before consume to create artificial latency for tests\n public InmemoryTotalOrderBroadcast(InMemoryLog log, Runnable callback) {\n this.log = log;\n this.callback = callback;\n }\n\n public InmemoryTotalOrderBroadcast(InMemoryLog log) {\n this.log = log;\n this.callback = () -> {\n };\n }\n\n @Override\n public long offer(String key, String value, String header) {\n return log.offer(key, value, header);\n }\n\n @Override\n public Collection<Message> consume() {\n callback.run();\n while (true) {\n ArrayList<Message> messages = log.consume(consumeOffset);\n if (!messages.isEmpty()) {\n Message message = messages.get(messages.size() - 1);\n consumeOffset = (int) message.offset() + 1;\n return messages;\n }\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}" }, { "identifier": "Records", "path": "src/main/java/io/github/sancar/kafkadds/totalorderbrodacast/Records.java", "snippet": "public class Records {\n\n public static final String HEADER_KEY_OPERATION = \"OPERATION\";\n\n public static class HeaderValues {\n public static final String WAIT_KEY = \"WAIT_KEY\";\n public static final String WRITE_ATTEMPT = \"WRITE_ATTEMPT\";\n }\n\n // Wait Key. Value of WaitKey is \"true\"\n public record WaitKey(String waitKey) { private static final String keyType = \"WAIT_KEY\";}\n\n public record WriteAttemptKey(String key) { private static final String keyType = \"WRITE_ATTEMPT\";}\n\n public record WriteAttemptValue(int version, String value) {\n }\n\n}" }, { "identifier": "toJson", "path": "src/main/java/io/github/sancar/kafkadds/util/Json.java", "snippet": "public static String toJson(Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n}" }, { "identifier": "toObject", "path": "src/main/java/io/github/sancar/kafkadds/util/Json.java", "snippet": "public static <T> T toObject(String jsonStr, Class<T> valueType) {\n try {\n return mapper.readValue(jsonStr, valueType);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n}" } ]
import org.apache.kafka.clients.admin.AdminClientConfig; import org.junit.Test; import io.github.sancar.kafkadds.linearizable.Linearizable; import io.github.sancar.kafkadds.linearizable.ReplicatedMap; import io.github.sancar.kafkadds.totalorderbrodacast.InMemoryLog; import io.github.sancar.kafkadds.totalorderbrodacast.InmemoryTotalOrderBroadcast; import io.github.sancar.kafkadds.totalorderbrodacast.Records; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.*; import static io.github.sancar.kafkadds.util.Json.toJson; import static io.github.sancar.kafkadds.util.Json.toObject;
3,337
package io.github.sancar.kafkadds; public class ReplicatedMapTest { // ENTER UPSTASH CREDENTIALS HERE to make tests pass private static final String bootstrap = "127.0.0.1:19091";//upstash private static final String jaas = "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"ups-test\" password=\"123456\";"; @Test public void TestSingleThread_ConcurrentHashMap() { // Just to check that test is correct testSingleThread(new ConcurrentHashMap<>()); } @Test public void TestSingleThread_InMemory() {
package io.github.sancar.kafkadds; public class ReplicatedMapTest { // ENTER UPSTASH CREDENTIALS HERE to make tests pass private static final String bootstrap = "127.0.0.1:19091";//upstash private static final String jaas = "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"ups-test\" password=\"123456\";"; @Test public void TestSingleThread_ConcurrentHashMap() { // Just to check that test is correct testSingleThread(new ConcurrentHashMap<>()); } @Test public void TestSingleThread_InMemory() {
try (ReplicatedMap map = new ReplicatedMap(new InmemoryTotalOrderBroadcast(new InMemoryLog()))) {
3
2023-10-26 11:24:37+00:00
4k
dockyu/VoronoiDiagram
source/src/main/java/dev/dockyu/voronoidiagram/algorithm/ConvexHullAlgo.java
[ { "identifier": "ConvexHull", "path": "source/src/main/java/dev/dockyu/voronoidiagram/datastruct/ConvexHull.java", "snippet": "public class ConvexHull {\n public LinkedList<GeneratorPoint> hull; // 順時針方向\n public Integer right; // convex hull最右邊的點\n public Integer left; // convex hull最左邊的點\n\n public boolean collinear; // 是否所有點共線\n\n public ConvexHull() {\n this.hull = new LinkedList<>();\n this.collinear = false;\n }\n\n public void setCollinear() {\n this.collinear = true;\n }\n\n public GeneratorPoint get(int index) {\n return this.hull.get(index);\n }\n\n public int getNextIndex(int nowIndex) {\n nowIndex++;\n return nowIndex % this.hull.size();\n }\n\n public int getPreviousIndex(int nowIndex) {\n nowIndex--;\n if (nowIndex < 0) {\n nowIndex += this.hull.size(); // 確保索引總是正數\n }\n return nowIndex % this.hull.size();\n }\n\n}" }, { "identifier": "GeneratorPoint", "path": "source/src/main/java/dev/dockyu/voronoidiagram/datastruct/GeneratorPoint.java", "snippet": "public class GeneratorPoint {\n float x; // x座標\n float y; // y座標\n\n public GeneratorPoint(float clickedX, float clickedY) {\n this.x = clickedX;\n this.y = clickedY;\n }\n\n public GeneratorPoint(GeneratorPoint other) {\n this.x = other.x;\n this.y = other.y;\n }\n\n public float getX() { return this.x;}\n public float getY() { return this.y;}\n}" } ]
import dev.dockyu.voronoidiagram.datastruct.ConvexHull; import dev.dockyu.voronoidiagram.datastruct.GeneratorPoint;
3,569
// 左右VoronoiDiagram完全共線 // 左邊有下降就好 // System.out.println("error3"); leftNow = leftNext; // 走一步 leftNext = CHleft.getNextIndex(leftNow); // 走一步 rightStop = false; }else { // 左邊走一步變差 // System.out.println("左邊停"); // System.out.println("左邊停在"+CHleft.get(leftNow).getX()+"因為下一個點"+CHleft.get(leftNext).getX()+"斜率沒有變大"); leftStop = true; // 左邊停止 } }else { // 左邊走一步變差 // System.out.println("左邊停"); // System.out.println("左邊停在"+CHleft.get(leftNow).getX()+"因為下一個點"+CHleft.get(leftNext).getX()+"斜率沒有變大"); leftStop = true; // 左邊停止 } // 右邊往前 if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) < TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow))) { // 右邊走一步變好 rightNow = rightNext; // 走一步 rightNext = CHright.getPreviousIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; } else if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) == TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow)) && isCollinear(CHleft, CHright)) { if (CHright.get(rightNext).getX()>CHright.get(rightNow).getX() ||(CHright.get(rightNext).getX()==CHright.get(rightNow).getX()&&CHright.get(rightNext).getY()>CHright.get(rightNow).getY())){ // 如果都是無限大或無限小 // 右邊有下降就好 // System.out.println("error4"); rightNow = rightNext; // 走一步 rightNext = CHright.getPreviousIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; } else { // 右邊走一步變差 // System.out.println("右邊停"); rightStop = true; // 右邊停止 } } else { // 右邊走一步變差 // System.out.println("右邊停"); rightStop = true; // 右邊停止 } if (leftStop && rightStop) { // 兩邊都停止 break; // 跳出 } } // System.out.println("右邊下點("+CHright.get(rightNow).getX()+","+CHright.get(rightNow).getY()+")"); // 左邊的index 右邊的index return new int[]{leftNow, rightNow}; } public static void merge(ConvexHull CHmerge, ConvexHull CHleft, ConvexHull CHright, int[] upperTangent, int[] lowerTangent) { // 從右圖上切線的點開始,按順時針方向遍歷點,直到下切線的點 int nowIndex; int count = -1; // 計數,紀錄目前是CHmerge第幾個點 nowIndex = upperTangent[1]; // 右邊的上切點 while(true) { CHmerge.hull.addLast(CHright.get(nowIndex)); // 將點加入新的凸包 count++; // 紀錄 if (nowIndex==CHright.right) { // 找到right CHmerge.right = count; } if (nowIndex==lowerTangent[1]) { // 現在是右邊的下切點,且已經放入CHmerge break; } // 下一個 nowIndex = CHright.getNextIndex(nowIndex); } nowIndex = lowerTangent[0]; // 左邊的下切點 while(true) { CHmerge.hull.addLast(CHleft.get(nowIndex)); // 將點加入新的凸包 count++; // 紀錄 if (nowIndex==CHleft.left) { // 找到left CHmerge.left = count; } if (nowIndex==upperTangent[0]) { // 現在是左邊的上切點,且已經放入CHmerge break; } // 下一個 nowIndex = CHleft.getNextIndex(nowIndex); } // TODO: 判斷是否共線 if (isCollinear(CHleft, CHright)) { CHmerge.setCollinear(); } } private static boolean isCollinear(ConvexHull CHleft, ConvexHull CHright) { // TODO: 判斷是否所有點共線
package dev.dockyu.voronoidiagram.algorithm; public class ConvexHullAlgo { // 找上切線 public static int[] getUpperTangent(ConvexHull CHleft, ConvexHull CHright) { boolean leftStop = false; boolean rightStop = false; int leftNow = CHleft.right; int leftNext = CHleft.getPreviousIndex(leftNow); // 走一步就是退一步 int rightNow = CHright.left; int rightNext = CHright.getNextIndex(rightNow); // 走一步就是向前一步 // 左邊升到最高 while (CHleft.get(leftNow).getX()==CHleft.get(leftNext).getX() && CHleft.get(leftNext).getY()>CHleft.get(leftNow).getY()) { leftNow = leftNext; leftNext = CHleft.getPreviousIndex(leftNow); } // 右邊升到最高 while (CHright.get(rightNow).getX()==CHright.get(rightNext).getX() && CHright.get(rightNext).getY()<CHright.get(rightNow).getY()) { rightNow = rightNext; rightNext = CHright.getNextIndex(rightNow); } while(true) { // 左邊往回 if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNext),CHright.get(rightNow)) < TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow))) { // 左邊走一步變好 // System.out.println("左邊走"); leftNow = leftNext; // 走一步 leftNext = CHleft.getPreviousIndex(leftNow); // 走一步 rightStop = false; // 或許走了這步原本停止的右邊又可以繼續走 } else if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNext),CHright.get(rightNow)) == TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow)) && isCollinear(CHleft, CHright)) { // 左右VoronoiDiagram完全共線 // 左邊有上升就好 if (CHleft.get(leftNext).getX()>CHleft.get(leftNow).getX() || (CHleft.get(leftNext).getX()==CHleft.get(leftNow).getX() && CHleft.get(leftNext).getY()>CHleft.get(leftNow).getY())) { // System.out.println("error1"); // System.out.println(CHleft.get(leftNext).getY() +">"+ CHleft.get(leftNow).getY()); leftNow = leftNext; // 走一步 leftNext = CHleft.getPreviousIndex(leftNow); // 走一步 rightStop = false; // 或許走了這步原本停止的右邊又可以繼續走 } else { // 左邊走一步變差 leftStop = true; // 左邊停止 } } else { // 左邊走一步變差 leftStop = true; // 左邊停止 } // 右邊往前 if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) > TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow))) { // 右邊走一步變好 rightNow = rightNext; // 走一步 rightNext = CHright.getNextIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; // 或許走了這步原本停止的左邊又可以繼續走 } else if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) == TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow)) && isCollinear(CHleft, CHright)) { if (CHright.get(rightNext).getX()<CHright.get(rightNow).getX() || (CHright.get(rightNext).getX()==CHright.get(rightNow).getX()&&CHright.get(rightNext).getY()<CHright.get(rightNow).getY())) { // 如果斜率一樣 // 右邊有上升就好 // System.out.println("error2"); rightNow = rightNext; // 走一步 rightNext = CHright.getNextIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; // 或許走了這步原本停止的左邊又可以繼續走 } else { // 右邊走一步變差 // System.out.println("右邊停"); rightStop = true; // 右邊停止 } } else { // 右邊走一步變差 // System.out.println("右邊點"+rightNow); // System.out.println("右邊停"); rightStop = true; // 右邊停止 } if (leftStop && rightStop) { // 兩邊都停止 break; // 跳出 } } // 左邊的index 右邊的index // System.out.println("右邊上點("+CHright.get(rightNow).getX()+","+CHright.get(rightNow).getY()+")"); return new int[]{leftNow, rightNow}; } public static int[] getLowerTangent(ConvexHull CHleft, ConvexHull CHright) { boolean leftStop = false; boolean rightStop = false; int leftNow = CHleft.right; int leftNext = CHleft.getNextIndex(leftNow); // 走一步就是向前一步 int rightNow = CHright.left; int rightNext = CHright.getPreviousIndex(rightNow); // 走一步就是退一步 // 左邊升到最高 while (CHleft.get(leftNow).getX()==CHleft.get(leftNext).getX() && CHleft.get(leftNext).getY()>CHleft.get(leftNow).getY()) { leftNow = leftNext; leftNext = CHleft.getNextIndex(leftNow); } // 右邊升到最高 while (CHright.get(rightNow).getX()==CHright.get(rightNext).getX() && CHright.get(rightNext).getY()<CHright.get(rightNow).getY()) { rightNow = rightNext; rightNext = CHright.getPreviousIndex(rightNow); } while(true) { // 左邊往前 if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNext),CHright.get(rightNow)) > TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow))) { // 左邊走一步變好 // System.out.println("左邊走"); leftNow = leftNext; // 走一步 leftNext = CHleft.getNextIndex(leftNow); // 走一步 rightStop = false; } else if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNext),CHright.get(rightNow)) == TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow)) && isCollinear(CHleft, CHright)) { if (CHleft.get(leftNext).getX()<CHleft.get(leftNow).getX() ||(CHleft.get(leftNext).getX()==CHleft.get(leftNow).getX()&&CHleft.get(leftNext).getY()<CHleft.get(leftNow).getY())) { // 左右VoronoiDiagram完全共線 // 左邊有下降就好 // System.out.println("error3"); leftNow = leftNext; // 走一步 leftNext = CHleft.getNextIndex(leftNow); // 走一步 rightStop = false; }else { // 左邊走一步變差 // System.out.println("左邊停"); // System.out.println("左邊停在"+CHleft.get(leftNow).getX()+"因為下一個點"+CHleft.get(leftNext).getX()+"斜率沒有變大"); leftStop = true; // 左邊停止 } }else { // 左邊走一步變差 // System.out.println("左邊停"); // System.out.println("左邊停在"+CHleft.get(leftNow).getX()+"因為下一個點"+CHleft.get(leftNext).getX()+"斜率沒有變大"); leftStop = true; // 左邊停止 } // 右邊往前 if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) < TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow))) { // 右邊走一步變好 rightNow = rightNext; // 走一步 rightNext = CHright.getPreviousIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; } else if ( TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNext)) == TwoDPlaneAlgo.getSlope(CHleft.get(leftNow),CHright.get(rightNow)) && isCollinear(CHleft, CHright)) { if (CHright.get(rightNext).getX()>CHright.get(rightNow).getX() ||(CHright.get(rightNext).getX()==CHright.get(rightNow).getX()&&CHright.get(rightNext).getY()>CHright.get(rightNow).getY())){ // 如果都是無限大或無限小 // 右邊有下降就好 // System.out.println("error4"); rightNow = rightNext; // 走一步 rightNext = CHright.getPreviousIndex(rightNow); // 走一步 // System.out.println("右邊走"); leftStop = false; } else { // 右邊走一步變差 // System.out.println("右邊停"); rightStop = true; // 右邊停止 } } else { // 右邊走一步變差 // System.out.println("右邊停"); rightStop = true; // 右邊停止 } if (leftStop && rightStop) { // 兩邊都停止 break; // 跳出 } } // System.out.println("右邊下點("+CHright.get(rightNow).getX()+","+CHright.get(rightNow).getY()+")"); // 左邊的index 右邊的index return new int[]{leftNow, rightNow}; } public static void merge(ConvexHull CHmerge, ConvexHull CHleft, ConvexHull CHright, int[] upperTangent, int[] lowerTangent) { // 從右圖上切線的點開始,按順時針方向遍歷點,直到下切線的點 int nowIndex; int count = -1; // 計數,紀錄目前是CHmerge第幾個點 nowIndex = upperTangent[1]; // 右邊的上切點 while(true) { CHmerge.hull.addLast(CHright.get(nowIndex)); // 將點加入新的凸包 count++; // 紀錄 if (nowIndex==CHright.right) { // 找到right CHmerge.right = count; } if (nowIndex==lowerTangent[1]) { // 現在是右邊的下切點,且已經放入CHmerge break; } // 下一個 nowIndex = CHright.getNextIndex(nowIndex); } nowIndex = lowerTangent[0]; // 左邊的下切點 while(true) { CHmerge.hull.addLast(CHleft.get(nowIndex)); // 將點加入新的凸包 count++; // 紀錄 if (nowIndex==CHleft.left) { // 找到left CHmerge.left = count; } if (nowIndex==upperTangent[0]) { // 現在是左邊的上切點,且已經放入CHmerge break; } // 下一個 nowIndex = CHleft.getNextIndex(nowIndex); } // TODO: 判斷是否共線 if (isCollinear(CHleft, CHright)) { CHmerge.setCollinear(); } } private static boolean isCollinear(ConvexHull CHleft, ConvexHull CHright) { // TODO: 判斷是否所有點共線
GeneratorPoint leftGPInCHleft = CHleft.hull.get(CHleft.left);
1
2023-10-26 07:24:43+00:00
4k
oghenevovwerho/yaa
src/main/java/yaa/parser/YaaLexer.java
[ { "identifier": "YaaError", "path": "src/main/java/yaa/pojos/YaaError.java", "snippet": "public class YaaError extends Error {\r\n private final String[] messages;\r\n\r\n public YaaError(String... messages) {\r\n super(messages[0]);\r\n this.messages = messages;\r\n }\r\n\r\n public static String filePath;\r\n\r\n @Override\r\n public String getLocalizedMessage() {\r\n return constructMsg();\r\n }\r\n\r\n @Override\r\n public String getMessage() {\r\n return constructMsg();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return constructMsg();\r\n }\r\n\r\n private String constructMsg() {\r\n var complete_path = \"src\" + separator + \"main\" + separator + \"yaa\" + separator + filePath;\r\n var msb = new StringBuilder();\r\n msb.append(\"\\n\");\r\n int z = 1;\r\n int totalMsgLength = 0;\r\n for (; z < messages.length - 1; z++) {\r\n var message = messages[z];\r\n if (messages[z].length() > totalMsgLength) {\r\n totalMsgLength = messages[z].length();\r\n }\r\n msb.append(\" \").append(message).append(\"\\n\");\r\n }\r\n msb.append(\" \").append(messages[z]).append(\"\\n\");\r\n msb.append(\" \").append(\"+\".repeat(totalMsgLength));\r\n msb.append(\"\\n\");\r\n var l$msg = new StringBuilder();\r\n try {\r\n var indexOfColumn = messages[0].indexOf(':');\r\n var line = parseInt(messages[0].substring(0, indexOfColumn));\r\n var column = getColumn();\r\n var line$list = new String(readAllBytes(of(complete_path))).lines().toList();\r\n if (appendedLinesB4(msb, line$list, line)) {\r\n var unStripped = line$list.get(line - 1);\r\n msb.append(\" \").append(unStripped).append(\"\\n\");\r\n l$msg.append(column == 1 ? \"^\" : \"-\".repeat(column - 1) + \"^\");\r\n l$msg.append(\" \");\r\n l$msg.append(filePath).append(\" \").append(\"[\");\r\n l$msg.append(messages[0]).append(\"]\").append(\"\\n\");\r\n } else {\r\n var unStripped = line$list.get(line$list.size() > 1 ? line - 1 : 0);\r\n var stripped = line$list.get(line$list.size() > 1 ? line - 1 : 0).strip();\r\n msb.append(\" \").append(stripped).append(\"\\n\");\r\n var strip$difference =\r\n (unStripped.length() - (stripped.length() - 1));\r\n l$msg.append(\"-\".repeat(column - strip$difference)).append(\"^\");\r\n l$msg.append(\" \");\r\n l$msg.append(filePath).append(\" \").append(\"[\");\r\n l$msg.append(messages[0]).append(\"]\").append(\"\\n\");\r\n }\r\n msb.append(\" \").append(l$msg);\r\n appendLinesAfter(msb, line$list, line);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n }\r\n return msb.toString();\r\n }\r\n\r\n private boolean appendedLinesB4\r\n (StringBuilder msb, List<String> line$list, int line) {\r\n var max$back = 0;\r\n for (int i = 0; i < 7; i++) {\r\n if (line - i == -1) {\r\n break;\r\n }\r\n max$back = i;\r\n }\r\n for (int i = max$back; i > 1; i--) {\r\n msb.append(\" \").append(line$list.get(line - i)).append(\"\\n\");\r\n }\r\n return max$back != 0;\r\n }\r\n\r\n private void appendLinesAfter\r\n (StringBuilder msb, List<String> line$list, int line) {\r\n var lineSize = line$list.size();\r\n var max$back = 0;\r\n for (int i = 0; i < 7; i++) {\r\n if (lineSize < (line + i)) {\r\n break;\r\n }\r\n max$back = i;\r\n }\r\n for (int i = 0; i < max$back; i++) {\r\n msb.append(\" \").append(line$list.get(line + i)).append(\"\\n\");\r\n }\r\n }\r\n\r\n private int getColumn() {\r\n if (messages[0].contains(\"->\")) {\r\n var indexOfColumn = messages[0].indexOf(':');\r\n var stop$index = messages[0].indexOf('-');\r\n return parseInt(messages[0]\r\n .substring(indexOfColumn + 1, stop$index).strip());\r\n }\r\n var indexOfColumn = messages[0].indexOf(':');\r\n return parseInt(messages[0].substring(indexOfColumn + 1).strip());\r\n }\r\n}\r" }, { "identifier": "TkKind", "path": "src/main/java/yaa/parser/TkKind.java", "snippet": "public enum TkKind {\r\n eof,\r\n dot,\r\n not,\r\n plus,\r\n star,\r\n wavy,\r\n pipe,\r\n id,\r\n minus,\r\n colon,\r\n equal,\r\n caret,\r\n comma,\r\n space,\r\n arrow,\r\n dollar,\r\n modulo,\r\n d_pipe,\r\n l_than,\r\n g_than,\r\n q_mark,\r\n b_tick,\r\n l_equal,\r\n g_equal,\r\n d_colon,\r\n double_literal,\r\n long_literal,\r\n short_literal,\r\n byte_literal,\r\n float_literal,\r\n int_literal,\r\n unknown,\r\n f_slash,\r\n semi_colon,\r\n s_quote,\r\n l_curly,\r\n l_paren,\r\n l_bracket,\r\n r_bracket,\r\n r_curly,\r\n r_paren,\r\n u_score,\r\n df_slash,\r\n d_quote,\r\n star_star,\r\n ampersand,\r\n d_ampersand,\r\n escaped_tab,\r\n escaped_hash,\r\n escaped_b_tick,\r\n escaped_s_quote,\r\n escaped_b_slash,\r\n escaped_newline,\r\n dollar_bunch,\r\n underscore_bunch,\r\n escaped_l_curly,\r\n l_shift,\r\n r_shift,\r\n u_r_shift,\r\n equal_equal,\r\n not_equal,\r\n m_not_equal,\r\n m_equal,\r\n unicode,\r\n basex,\r\n kw_ufuoma,\r\n equal_arrow,\r\n kw_tuli,\r\n kw_ozi,\r\n at,\r\n kw_oka,\r\n kw_interface,\r\n kw_okpetu,\r\n kw_mzazi,\r\n kw_idan,\r\n kw_tesiwaju,\r\n kw_comot,\r\n kw_hii,\r\n kw_naso,\r\n kw_nalie,\r\n kw_final,\r\n kw_ode,\r\n kw_transient,\r\n kw_record,\r\n kw_na,\r\n kw_enum,\r\n kw_fimisile\r\n}" } ]
import yaa.pojos.YaaError; import static java.lang.Character.*; import static yaa.parser.TkKind.*;
3,406
right$token.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return right$token; } if (next$char == '=') { var g$equal$token = new YaaToken(g_equal, ">="); g$equal$token.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return g$equal$token; } } return single_token(g_than); } case '|' -> { return double_tokens(pipe, d_pipe, '|', "||"); } case '/' -> { return double_tokens(f_slash, df_slash, '/', "//"); } case '\\' -> { var possibleNext = source.charAt(indexIntoSource); var col_value = column; switch (possibleNext) { case 'n' -> { indexIntoSource++; var token = new YaaToken(escaped_newline, "\\n"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '{' -> { indexIntoSource++; var token = new YaaToken(escaped_l_curly, "\\{"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case 't' -> { indexIntoSource++; var token = new YaaToken(escaped_tab, "\\t"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '\'' -> { indexIntoSource++; var token = new YaaToken(escaped_s_quote, "\\'"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case 'u' -> { indexIntoSource++; if (!canBeInHex(source.charAt(indexIntoSource))) { throw new YaaError( line + ": " + column, "A value is expected for the unicode literal after \\u" ); } var sb = new StringBuilder(); while (indexIntoSource < source_size) { var currentInID = source.charAt(indexIntoSource); if (canBeInHex(currentInID)) { sb.append(currentInID); } else { break; } column++; indexIntoSource++; } var token = new YaaToken(unicode, sb.toString()); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '`' -> { indexIntoSource++; var token = new YaaToken(escaped_b_tick, "\\`"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '#' -> { indexIntoSource++; var token = new YaaToken(escaped_hash, "\\#"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '\\' -> { indexIntoSource++; var token = new YaaToken(escaped_b_slash, "\\\\"); token.set_line(line).set_column(col_value); column = column + 1; return token; } default -> { throw new YaaError( line + ": " + (column + 1), "a backslash must be followed by a valid escaped character", "\\", "#", "`", "u for unicode", "t", "n", "{" ); } } } case '\'' -> { return single_token(s_quote); } case '?' -> { return single_token(q_mark); } case ':' -> { return double_tokens(colon, d_colon, ':', "::"); } case '"' -> { return single_token(d_quote); } case ';' -> {
package yaa.parser; public class YaaLexer { public boolean allAllowed; protected int column = 0; protected int line = 1; protected int indexIntoSource = 0; private final String source; private final int source_size; private char current_char; public YaaLexer(String source) { this.source = source; this.source_size = source.length(); } public YaaToken nextToken() { while (indexIntoSource < source_size) { current_char = source.charAt(indexIntoSource++); column++; switch (current_char) { case ' ' -> { if (allAllowed) { var token = new YaaToken(space, current_char); return token.set_line(line).set_column(column); } } case '#' -> { comment(); } case '!' -> { if (indexIntoSource + 2 < source_size && source.charAt(indexIntoSource) == '=') { if (source.charAt(indexIntoSource + 1) == '=') { var idToken = new YaaToken(m_not_equal, "!=="); idToken.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 2; column = column + 2; return idToken; } } return double_tokens(not, not_equal, '=', "!="); } case '~' -> { return single_token(wavy); } case '`' -> { return single_token(b_tick); } case '.' -> { return single_token(dot); } case '@' -> { return single_token(at); } case '%' -> { return single_token(modulo); } case '^' -> { return single_token(caret); } case '&' -> { return double_tokens(ampersand, d_ampersand, '&', "&&"); } case '*' -> { return double_tokens(star, star_star, '*', "**"); } case '-' -> { return double_tokens(minus, arrow, '>', "->"); } case '+' -> { return single_token(plus); } case '=' -> { if (indexIntoSource + 2 < source_size && source.charAt(indexIntoSource) == '=') { if (source.charAt(indexIntoSource + 1) == '=') { var idToken = new YaaToken(m_equal, "==="); idToken.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 2; column = column + 2; return idToken; } } if (indexIntoSource + 1 < source_size && source.charAt(indexIntoSource) == '=') { if (source.charAt(indexIntoSource) == '=') { var idToken = new YaaToken(equal_equal, "=="); idToken.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return idToken; } } return double_tokens(equal, equal_arrow, '>', "=>"); } case '<' -> { if (indexIntoSource < source_size && source.charAt(indexIntoSource) == '<') { var idToken = new YaaToken(l_shift, "<<"); idToken.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return idToken; } return double_tokens(l_than, l_equal, '=', "<="); } case '>' -> { if (indexIntoSource + 1 < source_size && source.charAt(indexIntoSource) == '>') { if (source.charAt(indexIntoSource + 1) == '>') { var idToken = new YaaToken(u_r_shift, ">>>"); idToken.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 2; column = column + 1; return idToken; } } if (indexIntoSource < source_size) { var next$char = source.charAt(indexIntoSource); if (next$char == '>') { var right$token = new YaaToken(r_shift, ">>"); right$token.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return right$token; } if (next$char == '=') { var g$equal$token = new YaaToken(g_equal, ">="); g$equal$token.set_line(line).set_column(column); indexIntoSource = indexIntoSource + 1; column = column + 1; return g$equal$token; } } return single_token(g_than); } case '|' -> { return double_tokens(pipe, d_pipe, '|', "||"); } case '/' -> { return double_tokens(f_slash, df_slash, '/', "//"); } case '\\' -> { var possibleNext = source.charAt(indexIntoSource); var col_value = column; switch (possibleNext) { case 'n' -> { indexIntoSource++; var token = new YaaToken(escaped_newline, "\\n"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '{' -> { indexIntoSource++; var token = new YaaToken(escaped_l_curly, "\\{"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case 't' -> { indexIntoSource++; var token = new YaaToken(escaped_tab, "\\t"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '\'' -> { indexIntoSource++; var token = new YaaToken(escaped_s_quote, "\\'"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case 'u' -> { indexIntoSource++; if (!canBeInHex(source.charAt(indexIntoSource))) { throw new YaaError( line + ": " + column, "A value is expected for the unicode literal after \\u" ); } var sb = new StringBuilder(); while (indexIntoSource < source_size) { var currentInID = source.charAt(indexIntoSource); if (canBeInHex(currentInID)) { sb.append(currentInID); } else { break; } column++; indexIntoSource++; } var token = new YaaToken(unicode, sb.toString()); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '`' -> { indexIntoSource++; var token = new YaaToken(escaped_b_tick, "\\`"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '#' -> { indexIntoSource++; var token = new YaaToken(escaped_hash, "\\#"); token.set_line(line).set_column(col_value); column = column + 1; return token; } case '\\' -> { indexIntoSource++; var token = new YaaToken(escaped_b_slash, "\\\\"); token.set_line(line).set_column(col_value); column = column + 1; return token; } default -> { throw new YaaError( line + ": " + (column + 1), "a backslash must be followed by a valid escaped character", "\\", "#", "`", "u for unicode", "t", "n", "{" ); } } } case '\'' -> { return single_token(s_quote); } case '?' -> { return single_token(q_mark); } case ':' -> { return double_tokens(colon, d_colon, ':', "::"); } case '"' -> { return single_token(d_quote); } case ';' -> {
return single_token(TkKind.semi_colon);
1
2023-10-26 17:41:13+00:00
4k
echcz/web-service
src/test/java/cn/echcz/webservice/usecase/EntityUsecaseTests.java
[ { "identifier": "Entity", "path": "src/main/java/cn/echcz/webservice/entity/Entity.java", "snippet": "public interface Entity<K> {\n K getId();\n}" }, { "identifier": "User", "path": "src/main/java/cn/echcz/webservice/entity/User.java", "snippet": "public interface User extends Principal {\n /**\n * 匿名用户\n */\n User ANONYMOUS_USER = new AnonymousUser();\n\n /**\n * 所属的租户名\n */\n String getTenantName();\n /**\n * 全名\n */\n default String getFullName() {\n return getName() + \"@\" + getTenantName();\n }\n /**\n * 获取用户角色\n */\n List<String> getRoles();\n\n /**\n * 是否是匿名用户\n */\n default boolean isAnonymous() {\n return false;\n }\n\n static String toString(User user) {\n if (Objects.isNull(user)) {\n return \"null\";\n }\n return user.getFullName()\n + \"(anonymous=\" + user.isAnonymous()\n + \", roles=\" + user.getRoles()\n + \")\";\n }\n\n /**\n * 匿名用户类\n */\n class AnonymousUser implements User {\n private AnonymousUser() {\n // Singleton pattern\n }\n\n @Override\n public String getName() {\n return \"\";\n }\n\n @Override\n public String getTenantName() {\n return \"\";\n }\n\n @Override\n public String getFullName() {\n return \"\";\n }\n\n @Override\n public List<String> getRoles() {\n return Collections.emptyList();\n }\n\n @Override\n public boolean isAnonymous() {\n return true;\n }\n\n @Override\n public String toString() {\n return User.toString(this);\n }\n }\n}" }, { "identifier": "DataDuplicateException", "path": "src/main/java/cn/echcz/webservice/exception/DataDuplicateException.java", "snippet": "public class DataDuplicateException extends ClientException {\n\n public DataDuplicateException(String message, Throwable cause) {\n super(new ErrorInfo(ErrorCode.DATA_DUPLICATE, message), cause);\n }\n\n public DataDuplicateException(String message) {\n this(message, null);\n }\n\n public DataDuplicateException(Throwable cause) {\n super(new ErrorInfo(ErrorCode.DATA_DUPLICATE), cause);\n }\n\n public DataDuplicateException() {\n this((Throwable) null);\n }\n}" }, { "identifier": "BaseRepository", "path": "src/main/java/cn/echcz/webservice/usecase/repository/BaseRepository.java", "snippet": "public interface BaseRepository<K, D, U extends DataUpdater, F extends QueryFilter<?>> {\n /**\n * 添加一条数据\n *\n * @param data 数据\n * @return 被添加的数据的主键\n */\n K add(D data);\n\n /**\n * 更新数据\n *\n * @param updater 用于设置更新后的数据值\n * @param filter 用于设置查询待更新数据的过滤条件\n * @return 已更新的数据量\n */\n int update(Consumer<U> updater, Consumer<F> filter);\n\n /**\n * 删除数据\n *\n * @param filter 用于设置查询待删除数据的过滤条件\n * @return 已删除的数据量\n */\n int delete(Consumer<F> filter);\n\n /**\n * 获取某条数据,\n * 保证在并发写时是安全的,如持有写锁后进行查询\n *\n * @param filter 用于设置查询待的过滤条件\n */\n Optional<D> getForWrite(Consumer<F> filter);\n\n /**\n * 获取数据列表,\n * 保证在并发写时是安全的,如持有写锁后进行查询\n *\n * @param filter 用于设置查询待的过滤条件\n */\n List<D> listForWrite(Consumer<F> filter);\n\n /**\n * 获取数据计数,\n * 保证在并发写时是安全的,如持有写锁后进行查询\n *\n * @param filter 用于设置查询待的过滤条件\n */\n int countForWrite(Consumer<F> filter);\n\n /**\n * 查询数据是否存在,\n * 保证在并发写时是安全的,如持有写锁后进行查询\n *\n * @param filter 用于设置查询待的过滤条件\n */\n boolean isExistedForWrite(Consumer<F> filter);\n\n /**\n * 生成查询器以进行数据查询\n */\n Querier<D, F> querier();\n}" }, { "identifier": "DataUpdater", "path": "src/main/java/cn/echcz/webservice/usecase/repository/DataUpdater.java", "snippet": "public interface DataUpdater {\n}" }, { "identifier": "Querier", "path": "src/main/java/cn/echcz/webservice/usecase/repository/Querier.java", "snippet": "public interface Querier<D, F extends QueryFilter<?>> {\n /**\n * 过滤\n * @param filter 用于设置查询过滤条件\n * @return this\n */\n void filter(Consumer<F> filter);\n\n /**\n * 查询单个数据\n */\n Optional<D> get();\n\n /**\n * 查询数据列表\n */\n List<D> list();\n\n /**\n * 查询实据列表\n * @param offset 偏移量,跳过此值数量的数据\n * @param limit 限制量,查询出来的数据量不会超过此值\n */\n default List<D> list(int offset, int limit) {\n List<D> list = list();\n return list.stream().skip(offset).limit(limit).toList();\n }\n\n /**\n * 查询数量\n */\n default int count() {\n return list().size();\n }\n\n /**\n * 是否存在\n */\n default boolean isExisted() {\n return get().isPresent();\n }\n}" }, { "identifier": "QueryFilter", "path": "src/main/java/cn/echcz/webservice/usecase/repository/QueryFilter.java", "snippet": "public interface QueryFilter<T extends QueryFilter<?>> {\n /**\n * 与 过滤条件\n * @param filter 用于设置过滤条件\n */\n void and(Consumer<T> filter);\n\n /**\n * 或 过滤条件\n * @param filter 用于设置过滤条件\n */\n void or(Consumer<T> filter);\n\n /**\n * 对当前过滤条件 取非\n */\n void not();\n}" } ]
import cn.echcz.webservice.entity.Entity; import cn.echcz.webservice.entity.User; import cn.echcz.webservice.exception.DataDuplicateException; import cn.echcz.webservice.usecase.repository.BaseRepository; import cn.echcz.webservice.usecase.repository.DataUpdater; import cn.echcz.webservice.usecase.repository.Querier; import cn.echcz.webservice.usecase.repository.QueryFilter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*;
2,050
package cn.echcz.webservice.usecase; @ExtendWith(MockitoExtension.class) public class EntityUsecaseTests { Context context = new DefaultContext(); @Mock ContextProvider contextProvider; @Mock BaseRepository<Integer, TestEntity, TestDataUpdater, TestQueryFilter> repository; @Mock(answer = Answers.CALLS_REAL_METHODS) AbstractEntityUsecase<Integer, TestEntity, TestDataUpdater, TestQueryFilter, BaseRepository<Integer, TestEntity, TestDataUpdater, TestQueryFilter>> usecase; private static class TestEntity implements Entity<Integer> { @Override public Integer getId() { return 1; } } private static class TestDataUpdater implements DataUpdater { } private static class TestQueryFilter implements QueryFilter<TestQueryFilter> { @Override public void and(Consumer<TestQueryFilter> filter) { } @Override public void or(Consumer<TestQueryFilter> filter) { } @Override public void not() { } }
package cn.echcz.webservice.usecase; @ExtendWith(MockitoExtension.class) public class EntityUsecaseTests { Context context = new DefaultContext(); @Mock ContextProvider contextProvider; @Mock BaseRepository<Integer, TestEntity, TestDataUpdater, TestQueryFilter> repository; @Mock(answer = Answers.CALLS_REAL_METHODS) AbstractEntityUsecase<Integer, TestEntity, TestDataUpdater, TestQueryFilter, BaseRepository<Integer, TestEntity, TestDataUpdater, TestQueryFilter>> usecase; private static class TestEntity implements Entity<Integer> { @Override public Integer getId() { return 1; } } private static class TestDataUpdater implements DataUpdater { } private static class TestQueryFilter implements QueryFilter<TestQueryFilter> { @Override public void and(Consumer<TestQueryFilter> filter) { } @Override public void or(Consumer<TestQueryFilter> filter) { } @Override public void not() { } }
private static class TestQuerier implements Querier<TestDataUpdater, TestQueryFilter> {
5
2023-10-30 18:55:49+00:00
4k
tom5454/Toms-Peripherals
Forge/src/main/java/com/tom/peripherals/top/TheOneProbeHandler.java
[ { "identifier": "PeripheralsMod", "path": "Fabric/src/main/java/com/tom/peripherals/PeripheralsMod.java", "snippet": "public class PeripheralsMod implements ModInitializer {\n\tpublic static final String ID = \"toms_peripherals\";\n\tpublic static final Logger LOGGER = LogUtils.getLogger();\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tContent.init();\n\t\tPlatform.register();\n\n\t\tForgeConfigRegistry.INSTANCE.register(ID, ModConfig.Type.COMMON, Config.commonSpec);\n\t\tForgeConfigRegistry.INSTANCE.register(ID, ModConfig.Type.SERVER, Config.serverSpec);\n\n\t\tModConfigEvents.loading(ID).register(c -> {\n\t\t\tLOGGER.info(\"Loaded Tom's Peripherals config file {}\", c.getFileName());\n\t\t\tConfig.load(c);\n\t\t});\n\t\tModConfigEvents.reloading(ID).register(c -> {\n\t\t\tLOGGER.info(\"Tom's Peripherals config just got changed on the file system!\");\n\t\t\tConfig.load(c);\n\t\t});\n\n\t\tPeripheralLookup.get().registerForBlockEntities((b, side) -> {\n\t\t\tif (b instanceof AbstractPeripheralBlockEntity be)\n\t\t\t\treturn be.getCCPeripheral();\n\t\t\treturn null;\n\t\t}, Content.gpuBE.get(), Content.redstonePortBE.get(), Content.wdtBE.get());\n\t}\n\n}" }, { "identifier": "WatchDogTimerBlockEntity", "path": "Forge/src/platform-shared/java/com/tom/peripherals/block/entity/WatchDogTimerBlockEntity.java", "snippet": "public class WatchDogTimerBlockEntity extends AbstractPeripheralBlockEntity implements TickableServer {\n\tprivate ObjectWrapper peripheral;\n\n\tprivate boolean enabled;\n\tprivate int timeLimit;\n\tprivate int timer;\n\n\tpublic WatchDogTimerBlockEntity(BlockEntityType<?> p_155228_, BlockPos p_155229_, BlockState p_155230_) {\n\t\tsuper(p_155228_, p_155229_, p_155230_);\n\t}\n\n\t@Override\n\tpublic void updateServer() {\n\t\tif (!enabled)return;\n\t\tif (timer > timeLimit) {\n\t\t\tenabled = false;\n\t\t\tDirection facting = getBlockState().getValue(BlockStateProperties.FACING);\n\t\t\tBlockPos onPos = getBlockPos().relative(facting);\n\t\t\tComputerControl.restartComputerAt(level, onPos);\n\t\t} else\n\t\t\ttimer++;\n\t}\n\n\t@Override\n\tpublic void load(CompoundTag tag) {\n\t\tsuper.load(tag);\n\t\tenabled = tag.getBoolean(\"enabled\");\n\t\ttimeLimit = tag.getInt(\"timeLimit\");\n\t}\n\n\t@Override\n\tprotected void saveAdditional(CompoundTag tag) {\n\t\tsuper.saveAdditional(tag);\n\t\ttag.putBoolean(\"enabled\", enabled);\n\t\ttag.putInt(\"timeLimit\", timeLimit);\n\t}\n\n\t@Override\n\tpublic ObjectWrapper getPeripheral() {\n\t\tif(peripheral == null)peripheral = new ObjectWrapper(\"tm_wdt\", new WDT());\n\t\treturn peripheral;\n\t}\n\n\tpublic class WDT extends TMLuaObject {\n\n\t\t@LuaMethod\n\t\tpublic boolean isEnabled() {\n\t\t\treturn enabled;\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic int getTimeout() {\n\t\t\treturn timeLimit;\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void setEnabled(Object[] a) throws LuaException {\n\t\t\tif (a.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected enable)\");\n\t\t\t}\n\t\t\tboolean enable = ParamCheck.getBoolean(a, 0);\n\t\t\tPlatform.getServer().execute(() -> {\n\t\t\t\tenabled = enable;\n\t\t\t\ttimer = 0;\n\t\t\t\tsetChanged();\n\t\t\t});\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void setTimeout(Object[] a) throws LuaException {\n\t\t\tif (enabled)throw new LuaException(\"Can't edit timeout value while the timer is enabled\");\n\t\t\tif (a.length < 1) {\n\t\t\t\tthrow new LuaException(\"Too few arguments (expected enable)\");\n\t\t\t}\n\t\t\tint time = ParamCheck.getInt(a, 0);\n\t\t\tif (time < 20) {\n\t\t\t\tthrow new LuaException(\"Bad argument #1 (expected value must be larger than 20 ticks)\");\n\t\t\t}\n\t\t\tPlatform.getServer().execute(() -> {\n\t\t\t\ttimeLimit = time;\n\t\t\t\ttimer = 0;\n\t\t\t\tsetChanged();\n\t\t\t});\n\t\t}\n\n\t\t@LuaMethod\n\t\tpublic void reset() throws LuaException {\n\t\t\tPlatform.getServer().execute(() -> {\n\t\t\t\ttimer = 0;\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic int getTimeLimit() {\n\t\treturn timeLimit;\n\t}\n\n\tpublic int getTimer() {\n\t\treturn timer;\n\t}\n}" } ]
import java.util.function.Function; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import com.tom.peripherals.PeripheralsMod; import com.tom.peripherals.block.entity.WatchDogTimerBlockEntity; import mcjty.theoneprobe.api.CompoundText; import mcjty.theoneprobe.api.ElementAlignment; import mcjty.theoneprobe.api.IIconStyle; import mcjty.theoneprobe.api.ILayoutStyle; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.IProbeInfoProvider; import mcjty.theoneprobe.api.ITheOneProbe; import mcjty.theoneprobe.api.ProbeMode; import mcjty.theoneprobe.api.TextStyleClass; import mcjty.theoneprobe.config.Config;
1,830
package com.tom.peripherals.top; public class TheOneProbeHandler implements Function<ITheOneProbe, Void>, IProbeInfoProvider { private static final ResourceLocation ICONS = new ResourceLocation("theoneprobe", "textures/gui/icons.png"); public static ITheOneProbe theOneProbeImp; public static TheOneProbeHandler create() { return new TheOneProbeHandler(); } @Override public Void apply(ITheOneProbe input) { theOneProbeImp = input; theOneProbeImp.registerProvider(this); return null; } @Override public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, Player player, Level world, BlockState blockState, IProbeHitData data) { BlockEntity te = world.getBlockEntity(data.getPos()); if(te instanceof WatchDogTimerBlockEntity be) { boolean v = Config.harvestStyleVanilla.get(); int offs = v ? 16 : 0; int dim = v ? 13 : 16; ILayoutStyle alignment = probeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER); IIconStyle iconStyle = probeInfo.defaultIconStyle().width(v ? 18 : 20).height(v ? 14 : 16).textureWidth(32) .textureHeight(32); IProbeInfo horizontal = probeInfo.horizontal(alignment); if (be.isEnabled()) { horizontal.icon(ICONS, 0, offs, dim, dim, iconStyle).text(CompoundText.create().style(TextStyleClass.OK).text(Component.translatable("label.toms_peripherals.wdt.enabled"))); } else { horizontal.icon(ICONS, 16, offs, dim, dim, iconStyle).text(CompoundText.create().style(TextStyleClass.WARNING).text(Component.translatable("label.toms_peripherals.wdt.disabled"))); } probeInfo.text(Component.translatable("label.toms_peripherals.wdt.timeLimit", ticksToElapsedTime(be.getTimeLimit()))); probeInfo.text(Component.translatable("label.toms_peripherals.wdt.timer", ticksToElapsedTime(be.getTimer()))); } } public static String ticksToElapsedTime(int ticks) { int i = ticks / 20; int j = i / 60; i = i % 60; return i < 10 ? j + ":0" + i : j + ":" + i; } @Override public ResourceLocation getID() {
package com.tom.peripherals.top; public class TheOneProbeHandler implements Function<ITheOneProbe, Void>, IProbeInfoProvider { private static final ResourceLocation ICONS = new ResourceLocation("theoneprobe", "textures/gui/icons.png"); public static ITheOneProbe theOneProbeImp; public static TheOneProbeHandler create() { return new TheOneProbeHandler(); } @Override public Void apply(ITheOneProbe input) { theOneProbeImp = input; theOneProbeImp.registerProvider(this); return null; } @Override public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, Player player, Level world, BlockState blockState, IProbeHitData data) { BlockEntity te = world.getBlockEntity(data.getPos()); if(te instanceof WatchDogTimerBlockEntity be) { boolean v = Config.harvestStyleVanilla.get(); int offs = v ? 16 : 0; int dim = v ? 13 : 16; ILayoutStyle alignment = probeInfo.defaultLayoutStyle().alignment(ElementAlignment.ALIGN_CENTER); IIconStyle iconStyle = probeInfo.defaultIconStyle().width(v ? 18 : 20).height(v ? 14 : 16).textureWidth(32) .textureHeight(32); IProbeInfo horizontal = probeInfo.horizontal(alignment); if (be.isEnabled()) { horizontal.icon(ICONS, 0, offs, dim, dim, iconStyle).text(CompoundText.create().style(TextStyleClass.OK).text(Component.translatable("label.toms_peripherals.wdt.enabled"))); } else { horizontal.icon(ICONS, 16, offs, dim, dim, iconStyle).text(CompoundText.create().style(TextStyleClass.WARNING).text(Component.translatable("label.toms_peripherals.wdt.disabled"))); } probeInfo.text(Component.translatable("label.toms_peripherals.wdt.timeLimit", ticksToElapsedTime(be.getTimeLimit()))); probeInfo.text(Component.translatable("label.toms_peripherals.wdt.timer", ticksToElapsedTime(be.getTimer()))); } } public static String ticksToElapsedTime(int ticks) { int i = ticks / 20; int j = i / 60; i = i % 60; return i < 10 ? j + ":0" + i : j + ":" + i; } @Override public ResourceLocation getID() {
return new ResourceLocation(PeripheralsMod.ID, "top");
0
2023-10-30 17:05:11+00:00
4k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/pojo/frameworks/MockFramework.java
[ { "identifier": "Parameter", "path": "src/main/java/com/insidious/plugin/pojo/Parameter.java", "snippet": "public class Parameter implements Serializable, BytesMarshallable {\n public static final byte[] COMMA_CHARACTER = \",\".getBytes();\n /**\n * Value is either a long number or a string value if the value was actually a Ljava/lang/String\n */\n long value = 0;\n /**\n * name should be a valid java variable name. this will be used inside the generated test cases\n */\n String type;\n boolean exception;\n DataEventWithSessionId prob;\n private List<String> names = new ArrayList<>();\n private String stringValue = null;\n private int index;\n private DataInfo dataInfo;\n private MethodCallExpression creatorExpression;\n private List<Parameter> templateMap = new ArrayList<>();\n private boolean isContainer = false;\n private boolean isEnum = false;\n\n public Parameter(Long value) {\n this.value = value;\n }\n\n public Parameter() {\n }\n\n public Parameter(Parameter original) {\n\n names = new ArrayList<>(original.names);\n\n List<Parameter> deepCopyTemplateMap = new ArrayList<>();\n for (Parameter p : original.templateMap) {\n deepCopyTemplateMap.add(new Parameter(p));\n }\n templateMap = deepCopyTemplateMap;\n\n\n type = original.type;\n isContainer = original.isContainer;\n dataInfo = original.dataInfo;\n value = original.value;\n prob = original.prob;\n isEnum = original.isEnum;\n }\n\n @Override\n public void readMarshallable(BytesIn bytes) throws IORuntimeException, BufferUnderflowException, IllegalStateException {\n value = bytes.readLong();\n int typeLength = bytes.readInt();\n if (typeLength > 0) {\n byte[] typeBytes = new byte[typeLength];\n bytes.read(typeBytes);\n type = new String(typeBytes);\n } else {\n type = null;\n }\n boolean hasProbe = bytes.readBoolean();\n if (hasProbe) {\n prob = new DataEventWithSessionId();\n prob.readMarshallable(bytes);\n } else {\n prob = null;\n }\n int namesLength = bytes.readInt();\n if (namesLength > 0) {\n byte[] nameBytes = new byte[namesLength];\n bytes.read(nameBytes);\n names = new ArrayList<>(List.of(new String(nameBytes).split(\",\")));\n } else {\n names = new ArrayList<>();\n }\n boolean hasInfo = bytes.readBoolean();\n if (hasInfo) {\n dataInfo = new DataInfo();\n dataInfo.readMarshallable(bytes);\n } else {\n dataInfo = null;\n }\n }\n\n @Override\n public void writeMarshallable(BytesOut bytes) throws IllegalStateException, BufferOverflowException, BufferUnderflowException, ArithmeticException {\n bytes.writeLong(value);\n if (type == null) {\n bytes.writeInt(0);\n } else {\n bytes.writeInt(type.length());\n bytes.write(type.getBytes());\n }\n if (prob != null) {\n bytes.writeBoolean(true);\n prob.writeMarshallable(bytes);\n } else {\n bytes.writeBoolean(false);\n }\n\n int totalLength = 0;\n for (int i = 0; i < names.size(); i++) {\n String name = names.get(i);\n totalLength += name.length();\n if (i > 0) {\n totalLength += 1;\n }\n }\n\n\n bytes.writeInt(totalLength);\n for (int i = 0; i < names.size(); i++) {\n String name = names.get(i);\n if (i > 0) {\n bytes.write(COMMA_CHARACTER);\n }\n bytes.write(name.getBytes());\n }\n\n\n if (dataInfo != null) {\n bytes.writeBoolean(true);\n dataInfo.writeMarshallable(bytes);\n } else {\n bytes.writeBoolean(false);\n }\n\n\n// BytesMarshallable.super.writeMarshallable(bytes);\n }\n\n public boolean getIsEnum() {\n return isEnum;\n }\n\n public void setIsEnum(boolean isEnum) {\n this.isEnum = isEnum;\n }\n\n public boolean isException() {\n return exception;\n }\n\n public boolean isContainer() {\n return isContainer;\n }\n\n public void setContainer(boolean container) {\n isContainer = container;\n }\n\n public List<Parameter> getTemplateMap() {\n return templateMap;\n }\n\n public void setTemplateMap(List<Parameter> transformedTemplateMap) {\n this.templateMap = transformedTemplateMap;\n }\n\n @Override\n public String toString() {\n return\n (names != null ? names.stream()\n .findFirst()\n .orElse(\"<n/a>\") : \"<n/a>\") +\n (type == null ? \"</na>\" : \" = new \" + (type != null ?\n type.substring(type.lastIndexOf('.') + 1) : \"naType\") + \"(); // \") +\n \"{\" + \"value=\" + value +\n \", index=\" + index +\n \", probeInfo=\" + dataInfo +\n \", prob=\" + prob +\n '}';\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n if (type == null) {\n return;\n }\n if (this.type == null\n || this.type.endsWith(\".Object\")\n || this.type.endsWith(\"$1\")\n || this.type.endsWith(\"$2\")\n || this.type.endsWith(\"$3\")\n || this.type.endsWith(\"$4\")\n || this.type.endsWith(\"$5\")\n ) {\n this.type = type;\n }\n }\n\n public void setTypeForced(String type) {\n this.type = type;\n }\n\n public String getName() {\n if (names.size() == 0) {\n return null;\n }\n return names.get(0);\n }\n\n public void setName(String name) {\n if (name == null) {\n return;\n }\n if (name.startsWith(\"(\", 0) || name.startsWith(\"CGLIB\", 0)) {\n return;\n }\n if (!this.names.contains(name)) {\n name = name.replace('$', 'D');\n this.names.add(0, name);\n }\n }\n\n public List<String> getNamesList() {\n return names;\n }\n\n public void setNamesList(List<String> namesList) {\n this.names = namesList;\n }\n\n public void clearNames() {\n this.names.clear();\n }\n\n public void addNames(Collection<String> name) {\n name = name.stream()\n .filter(e -> !e.startsWith(\"(\", 0) && e.length() > 0)\n .collect(Collectors.toList());\n this.names.addAll(name);\n }\n\n public long getValue() {\n return value;\n }\n\n public void setValue(long value) {\n this.value = value;\n }\n\n public void setValue(String value) {\n this.stringValue = value;\n }\n\n public String getStringValue() {\n return stringValue;\n }\n\n public DataEventWithSessionId getProb() {\n return prob;\n }\n\n public int getIndex() {\n return index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n public DataInfo getProbeInfo() {\n return dataInfo;\n }\n\n public void setProbeAndProbeInfo(DataEventWithSessionId prob, DataInfo probeInfo) {\n if (value == 0 && prob != null) {\n this.prob = prob;\n value = prob.getValue();\n } else {\n if (this.prob == null) {\n this.prob = prob;\n }\n }\n if (probeInfo == null) {\n this.dataInfo = null;\n return;\n }\n\n\n if (this.dataInfo == null\n || !this.dataInfo.getEventType().equals(EventType.METHOD_EXCEPTIONAL_EXIT)\n || (probeInfo.getEventType() != null && probeInfo.getEventType()\n .equals(EventType.METHOD_EXCEPTIONAL_EXIT))\n ) {\n this.dataInfo = probeInfo;\n this.prob = prob;\n }\n if (probeInfo.getEventType() == EventType.METHOD_EXCEPTIONAL_EXIT) {\n this.exception = true;\n }\n\n }\n\n public MethodCallExpression getCreatorExpression() {\n return creatorExpression;\n }\n\n public void setCreator(MethodCallExpression createrExpression) {\n\n this.creatorExpression = createrExpression;\n }\n\n\n public void addName(String nameForParameter) {\n if (nameForParameter == null\n || this.names.contains(nameForParameter)\n || nameForParameter.startsWith(\"(\", 0)\n || nameForParameter.length() < 1) {\n return;\n }\n nameForParameter = nameForParameter.replace('$', 'D');\n this.names.add(nameForParameter);\n }\n\n public boolean hasName(String name) {\n if (name == null) {\n return false;\n }\n name = name.replace('$', 'D');\n if (this.names.contains(name) || name.startsWith(\"(\") || name.length() < 1) {\n return true;\n }\n return false;\n }\n\n public List<String> getNames() {\n return names;\n }\n\n\n public boolean isBooleanType() {\n return type != null && (type.equals(\"Z\") || type.equals(\"java.lang.Boolean\"));\n }\n\n public boolean isStringType() {\n return type != null && (type.equals(\"java.lang.String\"));\n }\n\n public boolean isOptionalType() {\n return type != null && type.equals(\"java.util.Optional\");\n }\n\n public boolean isPrimitiveType() {\n // types which are java can build just using their values\n String typeCopy = type;\n while (typeCopy != null && typeCopy.startsWith(\"[\") && typeCopy.length() > 1) {\n typeCopy = typeCopy.substring(1);\n }\n return type != null && (typeCopy.length() == 1 || isBoxedPrimitiveType());\n\n }\n\n public boolean isBoxedPrimitiveType() {\n return type != null && (type.startsWith(\"java.lang.Boolean\")\n || type.startsWith(\"java.lang.Integer\")\n || type.startsWith(\"java.lang.Long\")\n || type.startsWith(\"java.lang.Short\")\n || type.startsWith(\"java.lang.Char\")\n || type.startsWith(\"java.lang.Double\")\n || type.startsWith(\"java.lang.Float\")\n || type.startsWith(\"java.lang.Number\")\n || type.startsWith(\"java.lang.Void\")\n || type.startsWith(\"java.lang.Byte\")\n );\n }\n\n}" }, { "identifier": "makeParameter", "path": "src/main/java/com/insidious/plugin/factory/testcase/expression/MethodCallExpressionFactory.java", "snippet": "public static Parameter makeParameter(String name, String type, long value) {\n Parameter param = new Parameter(value);\n param.setName(name);\n param.setType(type);\n return param;\n}" } ]
import com.insidious.plugin.pojo.Parameter; import com.squareup.javapoet.ClassName; import static com.insidious.plugin.factory.testcase.expression.MethodCallExpressionFactory.makeParameter;
2,785
package com.insidious.plugin.pojo.frameworks; public enum MockFramework { Mockito(ClassName.bestGuess("org.mockito.Mockito"), makeParameter("Mockito", "org.mockito.Mockito", -99885)); private final ClassName className;
package com.insidious.plugin.pojo.frameworks; public enum MockFramework { Mockito(ClassName.bestGuess("org.mockito.Mockito"), makeParameter("Mockito", "org.mockito.Mockito", -99885)); private final ClassName className;
private final Parameter mockClassParameter;
0
2023-10-31 09:07:46+00:00
4k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/api/entity/IRPGEntity.java
[ { "identifier": "EAFloat", "path": "src/main/java/mixac1/dangerrpg/api/entity/EntityAttribute.java", "snippet": "public static class EAFloat extends EntityAttribute<Float> {\n\n public EAFloat(String name) {\n super(ITypeProvider.FLOAT, name);\n }\n\n public void setModificatorValue(Float value, EntityLivingBase entity, UUID ID) {\n\n }\n\n public void removeModificator(EntityLivingBase entity, UUID ID) {\n\n }\n\n protected Float getModificatorValue(EntityLivingBase entity, UUID id) {\n return null;\n }\n}" }, { "identifier": "EntityAttributes", "path": "src/main/java/mixac1/dangerrpg/capability/EntityAttributes.java", "snippet": "public class EntityAttributes {\n\n public static final EALvl LVL = new EALvl(\"lvl\");\n public static final EntityAttributeE HEALTH = new EAHealth(\n \"health\",\n UUID.fromString(\"fd6315bf-9f57-46cb-bb38-4aacb5d2967a\"),\n SharedMonsterAttributes.maxHealth);\n public static final EntityAttribute.EAFloat MELEE_DAMAGE = new EntityAttributeE(\n \"melee_damage\",\n UUID.fromString(\"04a931c2-b0bf-44de-bbed-1a8f0d56c584\"),\n SharedMonsterAttributes.attackDamage);\n public static final EntityAttribute.EAFloat RANGE_DAMAGE = new EntityAttribute.EAFloat(\"range_damage\");\n\n public static final EntityAttribute.EAFloat MELEE_DAMAGE_STAB = new EntityAttribute.EAFloat(\"melee_damage\");\n public static final EAWithIAttr MELEE_DAMAGE_SLIME = new EASlimeDamage (\"melee_damage\", SharedMonsterAttributes.attackDamage);\n}" }, { "identifier": "RPGEntityHelper", "path": "src/main/java/mixac1/dangerrpg/capability/RPGEntityHelper.java", "snippet": "public abstract class RPGEntityHelper {\n\n public static final Multiplier HEALTH_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul);\n\n public static final Multiplier DAMAGE_MUL = new MultiplierMul(EntityConfig.d.entityLvlUpHealthMul);\n\n public static boolean isRPGable(EntityLivingBase entity) {\n return RPGCapability.rpgEntityRegistr.isActivated(entity);\n }\n\n public static boolean registerEntity(Class entityClass) {\n if (EntityLivingBase.class.isAssignableFrom(entityClass)) {\n if (RPGCapability.rpgEntityRegistr.containsKey(entityClass)) {\n return true;\n }\n\n IRPGEntity iRPG = EntityPlayer.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_PLAYER\n : EntityMob.class.isAssignableFrom(entityClass) ? IRPGEntity.DEFAULT_MOB : IRPGEntity.DEFAULT_LIVING;\n\n RPGCapability.rpgEntityRegistr.put(entityClass, new RPGEntityData(iRPG, false));\n return true;\n }\n return false;\n }\n\n public static void registerEntityDefault(Class<? extends EntityLivingBase> entityClass, RPGEntityData map) {\n map.registerEA(EntityAttributes.LVL, 1);\n MinecraftForge.EVENT_BUS.post(new RegEAEvent.DefaultEAEvent(entityClass, map));\n }\n\n public static void registerEntityLiving(Class<? extends EntityLiving> entityClass, RPGEntityData map) {\n map.registerEA(EntityAttributes.HEALTH, 0f, HEALTH_MUL);\n MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyLivingEAEvent(entityClass, map));\n }\n\n public static void registerEntityMob(Class<? extends EntityMob> entityClass, RPGEntityData map) {\n map.registerEA(EntityAttributes.MELEE_DAMAGE, 0f, DAMAGE_MUL);\n MinecraftForge.EVENT_BUS.post(new RegEAEvent.EntytyMobEAEvent(entityClass, map));\n }\n\n public static void registerEntityPlayer(Class<? extends EntityPlayer> entityClass, RPGEntityData map) {\n Multiplier ADD_1 = IMultiplier.ADD_1;\n Multiplier ADD_2 = new MultiplierAdd(2F);\n Multiplier ADD_0d001 = new MultiplierAdd(0.001F);\n Multiplier ADD_0d01 = new MultiplierAdd(0.01F);\n Multiplier ADD_0d025 = new MultiplierAdd(0.025F);\n Multiplier ADD_0d2 = new MultiplierAdd(0.2F);\n\n float q0 = EntityConfig.d.playerStartManaValue;\n float q1 = EntityConfig.d.playerStartManaRegenValue;\n\n map.registerEALvlable(PlayerAttributes.HEALTH, 0f, new DafailtLvlEAProvider(2, 1000, ADD_2));\n map.registerEALvlable(PlayerAttributes.MANA, q0, new DafailtLvlEAProvider(2, 1000, ADD_2));\n map.registerEALvlable(PlayerAttributes.STRENGTH, 0f, new DafailtLvlEAProvider(2, 1000, ADD_1));\n map.registerEALvlable(PlayerAttributes.KNOCKBACK, 0f, new DafailtLvlEAProvider(2, 1000, ADD_0d2));\n map.registerEALvlable(PlayerAttributes.AGILITY, 0f, new DafailtLvlEAProvider(2, 1000, ADD_1));\n map.registerEALvlable(PlayerAttributes.INTELLIGENCE, 0f, new DafailtLvlEAProvider(2, 1000, ADD_1));\n map.registerEALvlable(PlayerAttributes.EFFICIENCY, 0f, new DafailtLvlEAProvider(2, 1000, ADD_2));\n map.registerEALvlable(PlayerAttributes.MANA_REGEN, q1, new DafailtLvlEAProvider(2, 1000, ADD_0d2));\n map.registerEALvlable(PlayerAttributes.HEALTH_REGEN, 0f, new DafailtLvlEAProvider(2, 1000, ADD_0d2));\n\n map.registerEALvlable(PlayerAttributes.MOVE_SPEED, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n map.registerEALvlable(PlayerAttributes.SNEAK_SPEED, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n map.registerEALvlable(PlayerAttributes.FLY_SPEED, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n map.registerEALvlable(PlayerAttributes.SWIM_SPEED, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n map.registerEALvlable(PlayerAttributes.JUMP_HEIGHT, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n map.registerEALvlable(PlayerAttributes.JUMP_RANGE, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d001));\n\n map.registerEALvlable(PlayerAttributes.PHISIC_RESIST, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d01));\n map.registerEALvlable(PlayerAttributes.MAGIC_RESIST, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d01));\n map.registerEALvlable(PlayerAttributes.FALL_RESIST, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d025));\n map.registerEALvlable(PlayerAttributes.FIRE_RESIST, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d025));\n map.registerEALvlable(PlayerAttributes.LAVA_RESIST, 0f, new DafailtLvlEAProvider(2, 20, ADD_0d025));\n\n map.registerEA(PlayerAttributes.CURR_MANA, 0f);\n map.registerEA(PlayerAttributes.SPEED_COUNTER, 0f);\n\n MinecraftForge.EVENT_BUS.post(new RegEAEvent.PlayerEAEvent(entityClass, map));\n }\n}" }, { "identifier": "RPGEntityData", "path": "src/main/java/mixac1/dangerrpg/capability/data/RPGEntityRegister.java", "snippet": "public static class RPGEntityData\n extends RPGDataRegister.ElementData<Class<? extends EntityLivingBase>, HashMap<Integer, EntityTransferData>> {\n\n public HashMap<EntityAttribute, EntityAttrParams> attributes = new LinkedHashMap<EntityAttribute, EntityAttrParams>();\n public List<LvlEAProvider> lvlProviders = new LinkedList<LvlEAProvider>();\n public IRPGEntity rpgComponent;\n\n public RPGEntityData(IRPGEntity rpgComponent, boolean isSupported) {\n this.rpgComponent = rpgComponent;\n this.isSupported = isSupported;\n }\n\n public <T> void registerEALvlable(EntityAttribute<T> attr, T startValue, LvlEAProvider<T> lvlProvider) {\n registerEALvlable(attr, startValue, lvlProvider, null);\n }\n\n public <T> void registerEALvlable(EntityAttribute<T> attr, T startValue, LvlEAProvider<T> lvlProvider,\n Multiplier staticMul) {\n lvlProvider.attr = attr;\n attributes.put(attr, new EntityAttrParams(startValue, lvlProvider, staticMul));\n lvlProviders.add(lvlProvider);\n }\n\n public <T> void registerEA(EntityAttribute<T> attr, T startValue) {\n registerEA(attr, startValue, null);\n }\n\n public <T> void registerEA(EntityAttribute<T> attr, T startValue, Multiplier staticMul) {\n attributes.put(attr, new EntityAttrParams(startValue, null, staticMul));\n }\n\n @Override\n public HashMap<Integer, EntityTransferData> getTransferData(Class<? extends EntityLivingBase> key) {\n if (EntityPlayer.class.isAssignableFrom(key)) {\n HashMap<Integer, EntityTransferData> tmp = new HashMap<Integer, EntityTransferData>();\n for (Entry<EntityAttribute, EntityAttrParams> entry : attributes.entrySet()) {\n if (entry.getValue().lvlProvider != null) {\n tmp.put(entry.getKey().hash, new EntityTransferData(entry.getValue().lvlProvider));\n }\n }\n return tmp;\n }\n return null;\n }\n\n @Override\n public void unpackTransferData(HashMap<Integer, EntityTransferData> data) {\n for (Entry<Integer, EntityTransferData> entry : data.entrySet()) {\n if (RPGCapability.mapIntToEntityAttribute.containsKey(entry.getKey())) {\n EntityAttribute attr = RPGCapability.mapIntToEntityAttribute.get(entry.getKey());\n if (attributes.containsKey(attr)) {\n EntityAttrParams tmp = attributes.get(attr);\n tmp.lvlProvider.mulValue = entry.getValue().mulValue;\n tmp.lvlProvider.startExpCost = entry.getValue().startExpCost;\n tmp.lvlProvider.maxLvl = entry.getValue().maxLvl;\n tmp.lvlProvider.mulExpCost = entry.getValue().mulExpCost;\n }\n }\n }\n }\n}" } ]
import mixac1.dangerrpg.api.entity.EntityAttribute.EAFloat; import mixac1.dangerrpg.capability.EntityAttributes; import mixac1.dangerrpg.capability.RPGEntityHelper; import mixac1.dangerrpg.capability.data.RPGEntityRegister.RPGEntityData; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer;
2,821
package mixac1.dangerrpg.api.entity; public interface IRPGEntity { EAFloat getEAMeleeDamage(EntityLivingBase entity); EAFloat getEARangeDamage(EntityLivingBase entity); void registerAttributes(Class<? extends EntityLivingBase> entityClass, RPGEntityData set); IRPGEntity DEFAULT_PLAYER = new IRPGEntity() { @Override public EAFloat getEAMeleeDamage(EntityLivingBase entity) { return EntityAttributes.MELEE_DAMAGE; } @Override public EAFloat getEARangeDamage(EntityLivingBase entity) { return null; } @Override public void registerAttributes(Class<? extends EntityLivingBase> entityClass, RPGEntityData set) {
package mixac1.dangerrpg.api.entity; public interface IRPGEntity { EAFloat getEAMeleeDamage(EntityLivingBase entity); EAFloat getEARangeDamage(EntityLivingBase entity); void registerAttributes(Class<? extends EntityLivingBase> entityClass, RPGEntityData set); IRPGEntity DEFAULT_PLAYER = new IRPGEntity() { @Override public EAFloat getEAMeleeDamage(EntityLivingBase entity) { return EntityAttributes.MELEE_DAMAGE; } @Override public EAFloat getEARangeDamage(EntityLivingBase entity) { return null; } @Override public void registerAttributes(Class<? extends EntityLivingBase> entityClass, RPGEntityData set) {
RPGEntityHelper.registerEntityPlayer((Class<? extends EntityPlayer>) entityClass, set);
2
2023-10-31 21:00:14+00:00
4k
Tamiflu233/DingVideo
dingvideobackend/src/main/java/com/dataispower/dingvideobackend/controller/UserController.java
[ { "identifier": "UserIndexResponse", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/UserIndexResponse.java", "snippet": "@Data\npublic class UserIndexResponse extends UserResponse{\n private Long id;\n private Integer follows;\n private Integer fans;\n private Integer videoCnts;\n\n// public UserIndexResponse(UserResponse userResponse, Integer id, Integer follows, Integer fans, Integer videoCnts) {\n// super(userResponse); // 调用父类的构造函数\n// // 复制父类的属性\n// this.id = id;\n// this.follows = follows;\n// this.fans = fans;\n// this.videoCnts = videoCnts;\n// }\n}" }, { "identifier": "UserLogin", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/UserLogin.java", "snippet": "@Data\npublic class UserLogin {\n @NotBlank(message = \"用户名不能为空\")\n private String username;\n\n @NotBlank(message = \"密码不能为空\")\n private String password;\n}" }, { "identifier": "UserResponse", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/UserResponse.java", "snippet": "@Data\npublic class UserResponse {\n private Long id;\n private String username;\n\n private String nickname;\n\n private String gender;\n @Email\n private String email;\n\n private String phone;\n\n private String avatar;\n}" }, { "identifier": "ResponseResult", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/dto/ResponseResult.java", "snippet": "@Data\npublic class ResponseResult {\n\n private String code;\n\n private String result;\n\n private String message;\n\n private Object data;\n\n public ResponseResult() {\n this.code = Constants.Internet.OK;\n this.result = \"true\";\n }\n\n public ResponseResult(String code, String result, String message) {\n this.code = code;\n this.result = result;\n this.message = message;\n }\n public ResponseResult(String code, String result, String message,Object data) {\n this.code = code;\n this.result = result;\n this.message = message;\n this.data = data;\n }\n /*\n * 成功返回结果1\n * */\n public static ResponseResult success(String message) {\n return new ResponseResult(Constants.Internet.OK,\"true\",message);\n }\n /*\n * 成功返回结果2\n * */\n public static ResponseResult success(String message,Object data) {\n return new ResponseResult(Constants.Internet.OK,\"true\",message,data);\n }\n /*\n * 失败返回1\n * */\n public static ResponseResult error(String message) {\n return new ResponseResult(Constants.Internet.ERROR,\"false\",message);\n }\n /*\n * 失败返回2\n * */\n public static ResponseResult error(String message,Object data) {\n return new ResponseResult(Constants.Internet.ERROR,\"false\",message,data);\n }\n}" }, { "identifier": "AuthenticationConfigConstants", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/config/AuthenticationConfigConstants.java", "snippet": "public class AuthenticationConfigConstants {\n public static final String SECRET = \"data_is_power\";\n\n public static final String TOKEN_PREFIX = \"Bearer \";\n\n public static final long EXPIRATION_TIME = 1296000000;\n\n public static final String HEADER_STRING = \"Authorization\";\n\n public static final String LIKE_API = \"/api/like\";\n\n public static final String COLLECT_API = \"/api/collect\";\n\n public static final String FOLLOW_API = \"/api/follow\";\n\n public static final String USER_API = \"/api/user\";\n\n public static final String VIDEO_API = \"/api/videos\";\n}" }, { "identifier": "User", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/User.java", "snippet": "@Entity\n@Data\n@Table(name = com.dataispower.dingvideobackend.common.TableColumns.USER)\npublic class User extends CommonEntity implements UserDetails {\n @Id\n @Column(name = USER_ID, unique = true)\n private Long id;\n @Column(name = USERNAME, unique = true)\n private String username;\n @Column(name = NICKNAME)\n private String nickname;\n @Column(name = PHONE)\n private String phone;\n @Column(name = PASSWORD)\n private String password;\n @Column(name = EMAIL)\n private String email;\n @Column(name = AGE)\n private String age;\n @Column(name = FOLLOWS)\n private Long follows;\n @Column(name = GENDER)\n @Enumerated(EnumType.STRING)\n private Gender gender;\n @Column(name = AVATAR, columnDefinition = \"text\")\n private String avatar;\n @OneToMany(mappedBy = \"user\", fetch=FetchType.EAGER)\n @JsonIgnore\n private List<Video> videos;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return null;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return false;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return false;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return false;\n }\n\n @Override\n public boolean isEnabled() {\n return false;\n }\n}" }, { "identifier": "UserMapper", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/mapper/UserMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserMapper {\n UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);\n UserResponse userToUserResponse(User user);\n UserIndexResponse userToUserIndexResponse(User user);\n\n}" }, { "identifier": "UserService", "path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/interfaces/UserService.java", "snippet": "public interface UserService extends UserDetailsService {\n // 用户登录服务\n User login(UserLogin userLogin);\n // 用户注册服务\n User register(UserRegister userRegister);\n // 根据用户名获取当前用户信息\n @Override\n User loadUserByUsername(String username) throws UsernameNotFoundException;\n // 根据用户id获取当前用户信息\n User loadUserById(Integer id) throws UsernameNotFoundException;\n // 获取当前登录用户信息\n User getCurrentUser();\n // 创建用户token信息\n String createToken(UserLogin userLogin);\n // 获取用户信息\n User searchUser(String username);\n User searchUserById(Integer id);\n // 判断当前用户是否存在\n Boolean existUser(String username);\n // 更新用户资料信息\n User updateUser(String username, UserUpdate userUpdate);\n}" } ]
import com.dataispower.dingvideobackend.dto.UserIndexResponse; import com.dataispower.dingvideobackend.dto.UserLogin; import com.dataispower.dingvideobackend.dto.UserResponse; import com.dataispower.dingvideobackend.dto.ResponseResult; import com.auth0.jwt.JWT; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; import com.dataispower.dingvideobackend.config.AuthenticationConfigConstants; import com.dataispower.dingvideobackend.dto.*; import com.dataispower.dingvideobackend.entity.User; import com.dataispower.dingvideobackend.mapper.UserMapper; import com.dataispower.dingvideobackend.service.interfaces.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map;
1,932
package com.dataispower.dingvideobackend.controller; /** * author:heroding * date:2023/10/31 21:02 * description:用户controller **/ @RestController @RequestMapping(value = AuthenticationConfigConstants.USER_API) public class UserController { @Autowired private UserService userService; /** * 用户登录 * @param userLogin * @return */ @PostMapping("/login")
package com.dataispower.dingvideobackend.controller; /** * author:heroding * date:2023/10/31 21:02 * description:用户controller **/ @RestController @RequestMapping(value = AuthenticationConfigConstants.USER_API) public class UserController { @Autowired private UserService userService; /** * 用户登录 * @param userLogin * @return */ @PostMapping("/login")
public ResponseResult login(@Validated @RequestBody UserLogin userLogin) {
3
2023-10-25 07:16:43+00:00
4k
MiguelPereiraDantas/E-commerce-Java
src/main/java/br/com/fourstore/controller/ProductController.java
[ { "identifier": "Product", "path": "src/main/java/br/com/fourstore/model/Product.java", "snippet": "@Document(collection = \"inventory\")\npublic class Product {\n\t\n\t@Id\n\tprivate String id;\n\t\n\tprivate String sku;\n\t\n\tprivate String description;\n\t\n\tprivate Integer theAmount;\n\t\n\tprivate Double price;\n\t\n\tprivate TypeEnum type;\n\t\n\tprivate ColorEnum color;\n\t\n\tprivate DepartmentEnum department;\n\t\n\tprivate SizeEnum size;\n\t\n\tprivate CategoryEnum category;\n\n\n\tpublic Product() {\n\t\tsuper();\n\t}\n\t\n\tpublic Product(String sku, String description, Integer theAmount, Double price) {\n\t\tsuper();\n\t\tthis.sku = sku;\n\t\tthis.description = description;\n\t\tthis.theAmount = theAmount;\n\t\tthis.price = price;\n\t\t\n\t\ttransferringData();\n\t}\n\t\n\t\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getSku() {\n\t\treturn sku;\n\t}\n\tpublic void setSku(String sku) {\n\t\tthis.sku = sku;\n\t\t\n\t\ttransferringData();\n\t}\n\t\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\t\n\tpublic Integer getTheAmount() {\n\t\treturn theAmount;\n\t}\n\tpublic void setTheAmount(Integer theAmount) {\n\t\tthis.theAmount = theAmount;\n\t}\n\t\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic TypeEnum getType() {\n\t\treturn type;\n\t}\n\t\n\tpublic ColorEnum getColor() {\n\t\treturn color;\n\t}\n\t\n\tpublic DepartmentEnum getDepartment() {\n\t\treturn department;\n\t}\n\t\n\tpublic SizeEnum getSize() {\n\t\treturn size;\n\t}\n\t\n\tpublic CategoryEnum getCategory() {\n\t\treturn category;\n\t}\n\t\n\tpublic void transferringData() {\n\t\ttry {\n\t\t\tthis.type = TypeEnum.getTypeEnum(sku.substring(0, 3));\n\t\t\tthis.color = ColorEnum.getColorEnum(Integer.parseInt(sku.substring(3, 4)));\n\t\t\tthis.department = DepartmentEnum.getDepartmentEnum(sku.substring(4, 6));\n\t\t\tthis.size = SizeEnum.getSizeEnum(Integer.parseInt(sku.substring(6, 7)));\n\t\t\tthis.category = CategoryEnum.getCategoryEnum(sku.substring(7));\n\t\t} catch (Exception e) {\n\t\t\tthis.type = null;\n\t\t\tthis.color = null;\n\t\t\tthis.department = null;\n\t\t\tthis.size = null;\n\t\t\tthis.category = null;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"\\nSKU: \"+ sku + \"\\nDescricao: \" + description + \"\\nPreco: R$\" + price + \"\\nQuantidade: \" + theAmount\n\t\t\t\t+ \"\\nDetalhes: \" + type + \", \" + color + \", \" + department + \", \" + size + \", \" + category\n\t\t\t\t+ \"\\n-----------------------------------------------------\";\n\t}\n\t\n}" }, { "identifier": "ServiceProduct", "path": "src/main/java/br/com/fourstore/service/ServiceProduct.java", "snippet": "@Service\npublic class ServiceProduct {\n\t\n\t//Banco de dados dos produtos\n\t@Autowired\n\tprivate DataInventory dataInventory;\n\t\n\t//lista de todos os produtos\n\tpublic List<Product> productList(){\n\t\treturn dataInventory.findAll();\n\t}\n\t\n\t//Procurar produto por SKU\n\tpublic Product searchProductBySku(String sku) {\n\t\treturn dataInventory.findBySku(sku);\n\t}\n\t\n\t//Registrar o produto\n\tpublic String registerProduct(Product product) {\n\t\tif(product.getSku() == null || product.getDescription() == null || product.getTheAmount() == null || product.getPrice() == null) {\n\t\t\treturn \"Informacoes inseridas invalidas\";\n\t\t} else {\n\t\t\tif(product.getType() == null || product.getColor() == null || product.getDepartment() == null || product.getSize() == null || product.getCategory() == null) {\n\t\t\t\treturn \"SKU Inexistente\";\n\t\t\t} else {\n\t\t\t\tProduct productSku = searchProductBySku(product.getSku());\n\t\t\t\tif(productSku == null && product.getTheAmount() > 0) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdataInventory.save(product);\n\t\t\t\t\t\treturn \"Produto cadastrado com sucesso\";\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\treturn \"Cadastro do produto falhou\" + e.getMessage();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn \"SKU ja existente ou Quantidade Invalida\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//Editar o produto\n\tpublic String editProduct(String sku, Product product) {\n\t\tProduct searchProductBySku = searchProductBySku(sku);\n\t\tInteger theAmount = 0;\n\n\t\tif(searchProductBySku != null) {\n\t\t\tproduct.setSku(sku);\n\t\t\tif(product.getDescription() == null) {\n\t\t\t\tproduct.setDescription(searchProductBySku.getDescription());\n\t\t\t}\n\t\t\t\n\t\t\tif(product.getTheAmount() == null) {\n\t\t\t\tproduct.setTheAmount(theAmount);\n\t\t\t}\n\t\t\t\n\t\t\tif(product.getPrice() == null) {\n\t\t\t\tproduct.setPrice(searchProductBySku.getPrice());\n\t\t\t}\n\t\t\t\n\t\t\tif(product.getTheAmount() != 0) {\n\t\t\t\ttheAmount = searchProductBySku.getTheAmount() + (product.getTheAmount());\n\t\t\t\tif(theAmount < 0) {\n\t\t\t\t\treturn \"Quantidade Invalida\";\n\t\t\t\t} else {\n\t\t\t\t\tproduct.setTheAmount(theAmount);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttry {\n\t\t\t\tProduct updatedProduct = dataInventory.findById(searchProductBySku.getId()).orElse(null);\n\t\t\t\tupdatedProduct.setDescription(product.getDescription());\n\t\t\t\tupdatedProduct.setPrice(product.getPrice());\n\t\t\t\tupdatedProduct.setSku(product.getSku());\n\t\t\t\tupdatedProduct.setTheAmount(product.getTheAmount());\n\t\t\t\tdataInventory.save(updatedProduct);\n\t\t\t\treturn \"Produto editado com sucesso\";\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn \"Edição do produto falhou\" + e.getMessage();\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"SKU nao encontrado\";\n\t\t}\t\t\n\t}\n\t\n\t//Deletar o produto pelo SKU\n\tpublic String deleteProduct(String sku) {\n\t\tProduct product = searchProductBySku(sku);\n\t\tif(product != null) {\n\t\t\ttry {\n\t\t\t\tdataInventory.deleteById(product.getId());\n\t\t\t\treturn \"Produto deletado com sucesso\";\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn \"Falha ao deletar o produto\";\n\t\t\t}\t\t\t\n\t\t} else {\n\t\t\treturn \"SKU nao invalido\";\n\t\t}\n\t}\t\n}" } ]
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.fourstore.model.Product; import br.com.fourstore.service.ServiceProduct;
1,761
package br.com.fourstore.controller; @RestController @RequestMapping("/product") public class ProductController { @Autowired
package br.com.fourstore.controller; @RestController @RequestMapping("/product") public class ProductController { @Autowired
ServiceProduct serviceProduct;
1
2023-10-26 15:48:53+00:00
4k
thinhunan/wonder8-promotion-rule
java/src/test/java/com/github/thinhunan/wonder8/promotion/rule/StrategyTest.java
[ { "identifier": "BestMatch", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/strategy/BestMatch.java", "snippet": "public class BestMatch {\n\n MatchType type;\n\n public MatchType getType() {\n return type;\n }\n\n public void setType(MatchType type) {\n this.type = type;\n }\n\n List<Rule> rules;\n\n public List<Rule> getRules() {\n return rules;\n }\n\n List<Item> items;\n\n public List<Item> getItems(){\n return items;\n }\n\n List<Match> matches;\n\n public List<Match> getMatches() {\n return matches;\n }\n\n public void addMatch(Match match){\n if(matches == null){\n matches = new ArrayList<>();\n }\n if(match != null){\n matches.add(match);\n }\n }\n\n RuleValidateResult suggestion;\n\n public RuleValidateResult getSuggestion() {\n return suggestion;\n }\n\n public void setSuggestion(RuleValidateResult suggestion) {\n this.suggestion = suggestion;\n }\n\n public List<Item> chosen() {\n List<Item> chosen = new ArrayList<>();\n for(Match m : matches){\n chosen.addAll(m.getItems());\n }\n return chosen;\n }\n\n public List<Item> left() {\n List<Item> chosen = chosen();\n return items.stream()\n .filter(t->!chosen.contains(t))\n .collect(Collectors.toList());\n }\n\n public BestMatch(List<Rule> rules, List<Item> items, MatchType type) {\n this.rules = rules;\n this.items = items;\n this.type = type;\n this.matches = new ArrayList<>();\n }\n\n\n public int totalPrice() {\n if (this.matches == null || this.matches.size() == 0) {\n return 0;\n }\n return matches.stream()\n .map(Match::totalPrice)\n .reduce(0, Integer::sum);\n }\n\n /**\n * 计算总的打折金额,但请注意只以匹配部分为计算依据,如果需要按所有的商品来计算,可以调用{@link Rule#discount(List)} 来计算\n *\n * @return {int}\n */\n public int totalDiscount() {\n if (this.matches == null || this.matches.size() == 0) {\n return 0;\n }\n return matches.stream()\n .map(Match::totalDiscount)\n .reduce(0, Integer::sum);\n }\n}" }, { "identifier": "Match", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/strategy/Match.java", "snippet": "public class Match {\n Rule rule;\n List<Item> items;\n\n public Rule getRule() {\n return rule;\n }\n\n public void setRule(Rule rule) {\n this.rule = rule;\n }\n\n public List<Item> getItems() {\n return items;\n }\n\n public void setItems(List<Item> items) {\n this.items = items;\n }\n\n public Match(Rule rule, List<Item> items) {\n this.rule = rule;\n this.items = items;\n }\n\n public int totalDiscount(){\n if(items == null || items.size() == 0 || rule == null) return 0;\n return rule.discount(items);\n }\n\n public int count(){\n if(items == null) return 0;\n return items.size();\n }\n\n public int totalPrice(){\n if(items == null) return 0;\n return items.stream().map(Item::getPrice).reduce(0,Integer::sum);\n }\n}" }, { "identifier": "MatchGroup", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/strategy/MatchGroup.java", "snippet": "public enum MatchGroup {\n CrossedMatch,//各组交叉一起匹配最大优惠组合\n SequentialMatch //各组按组号从小到大分批匹配,后一批基于前一批结果,最终求最大优惠\n}" }, { "identifier": "MatchType", "path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/strategy/MatchType.java", "snippet": "public enum MatchType {\n OneTime,\n OneRule,\n MultiRule\n}" } ]
import com.github.thinhunan.wonder8.promotion.rule.model.*; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Match; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup; import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType; import org.junit.Assert; import org.junit.Test; import java.util.*; import java.util.stream.Collectors;
2,183
package com.github.thinhunan.wonder8.promotion.rule; public class StrategyTest { // c01有3个商品70块,其中p01有2张50块,p02有1张20块,其它都只有1张20块,10个商品210块 // k01 30块(3000分),其它都是20块 private static List<Item> _getSelectedItems() { Item[] selectedItems = new Item[]{ new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", 3000), new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000), new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", 5000), new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", 6000), new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", 7000), new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", 8000), new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", 9000), new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", 2000), new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", 3000) }; return Arrays.stream(selectedItems).collect(Collectors.toList()); } private static List<Item> _getRandomPriceItems() { Random r = new Random(); Item[] selectedItems = new Item[]{ new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", (1 + r.nextInt(9)) * 1000), new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", (1 + r.nextInt(9)) * 1000), new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", (1 + r.nextInt(9)) * 1000), new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", (1 + r.nextInt(9)) * 1000), new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", (1 + r.nextInt(9)) * 1000), new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", (1 + r.nextInt(9)) * 1000), new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", (1 + r.nextInt(9)) * 1000), new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", (1 + r.nextInt(9)) * 1000) }; return Arrays.stream(selectedItems).collect(Collectors.toList()); }
package com.github.thinhunan.wonder8.promotion.rule; public class StrategyTest { // c01有3个商品70块,其中p01有2张50块,p02有1张20块,其它都只有1张20块,10个商品210块 // k01 30块(3000分),其它都是20块 private static List<Item> _getSelectedItems() { Item[] selectedItems = new Item[]{ new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", 3000), new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000), new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", 5000), new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", 6000), new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", 7000), new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", 8000), new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", 9000), new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", 2000), new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", 3000) }; return Arrays.stream(selectedItems).collect(Collectors.toList()); } private static List<Item> _getRandomPriceItems() { Random r = new Random(); Item[] selectedItems = new Item[]{ new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", (1 + r.nextInt(9)) * 1000), new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", (1 + r.nextInt(9)) * 1000), new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", (1 + r.nextInt(9)) * 1000), new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", (1 + r.nextInt(9)) * 1000), new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", (1 + r.nextInt(9)) * 1000), new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", (1 + r.nextInt(9)) * 1000), new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", (1 + r.nextInt(9)) * 1000), new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", (1 + r.nextInt(9)) * 1000), new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", (1 + r.nextInt(9)) * 1000) }; return Arrays.stream(selectedItems).collect(Collectors.toList()); }
void _logBestMatch(BestMatch bestMatch){
0
2023-10-28 09:03:45+00:00
4k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/TinyJdbcAutoConfiguration.java
[ { "identifier": "DbType", "path": "src/main/java/org/tinycloud/jdbc/util/DbType.java", "snippet": "public enum DbType {\n /**\n * MYSQL\n */\n MYSQL(\"mysql\", \"MySql 数据库\"),\n /**\n * MARIADB\n */\n MARIADB(\"mariadb\", \"MariaDB 数据库\"),\n /**\n * ORACLE\n */\n ORACLE(\"oracle\", \"Oracle11g 及以下数据库\"),\n /**\n * oracle12c\n */\n ORACLE_12C(\"oracle12c\", \"Oracle12c 及以上数据库\"),\n /**\n * DB2\n */\n DB2(\"db2\", \"DB2 数据库\"),\n /**\n * H2\n */\n H2(\"h2\", \"H2 数据库\"),\n /**\n * HSQL\n */\n HSQL(\"hsql\", \"HSQL 数据库\"),\n /**\n * SQLITE\n */\n SQLITE(\"sqlite\", \"SQLite 数据库\"),\n /**\n * POSTGRE\n */\n POSTGRE_SQL(\"postgresql\", \"PostgreSQL 数据库\"),\n /**\n * SQLSERVER\n */\n SQLSERVER(\"sqlserver\", \"SQLServer 数据库\"),\n /**\n * SqlServer 2005 数据库\n */\n SQLSERVER_2005(\"sqlserver_2005\", \"SQLServer 数据库\"),\n /**\n * DM\n */\n DM(\"dm\", \"达梦数据库\"),\n /**\n * xugu\n */\n XUGU(\"xugu\", \"虚谷数据库\"),\n /**\n * Kingbase\n */\n KINGBASE_ES(\"kingbasees\", \"人大金仓数据库\"),\n /**\n * Phoenix\n */\n PHOENIX(\"phoenix\", \"Phoenix HBase 数据库\"),\n /**\n * Gauss\n */\n GAUSS(\"gauss\", \"Gauss 数据库\"),\n /**\n * ClickHouse\n */\n CLICK_HOUSE(\"clickhouse\", \"clickhouse 数据库\"),\n /**\n * GBase\n */\n GBASE(\"gbase\", \"南大通用(华库)数据库\"),\n /**\n * GBase-8s\n */\n GBASE_8S(\"gbase-8s\", \"南大通用数据库 GBase 8s\"),\n /**\n * Oscar\n */\n OSCAR(\"oscar\", \"神通数据库\"),\n /**\n * Sybase\n */\n SYBASE(\"sybase\", \"Sybase ASE 数据库\"),\n /**\n * OceanBase\n */\n OCEAN_BASE(\"oceanbase\", \"OceanBase 数据库\"),\n /**\n * Firebird\n */\n FIREBIRD(\"Firebird\", \"Firebird 数据库\"),\n /**\n * derby\n */\n DERBY(\"derby\", \"Derby 数据库\"),\n /**\n * HighGo\n */\n HIGH_GO(\"highgo\", \"瀚高数据库\"),\n /**\n * CUBRID\n */\n CUBRID(\"cubrid\", \"CUBRID 数据库\"),\n\n /**\n * GOLDILOCKS\n */\n GOLDILOCKS(\"goldilocks\", \"GOLDILOCKS 数据库\"),\n /**\n * CSIIDB\n */\n CSIIDB(\"csiidb\", \"CSIIDB 数据库\"),\n /**\n * CSIIDB\n */\n SAP_HANA(\"hana\", \"SAP_HANA 数据库\"),\n /**\n * Impala\n */\n IMPALA(\"impala\", \"impala 数据库\"),\n /**\n * Vertica\n */\n VERTICA(\"vertica\", \"vertica数据库\"),\n /**\n * 东方国信 xcloud\n */\n XCloud(\"xcloud\", \"行云数据库\"),\n /**\n * redshift\n */\n REDSHIFT(\"redshift\", \"亚马逊 redshift 数据库\"),\n /**\n * openGauss\n */\n OPENGAUSS(\"openGauss\", \"华为 openGauss 数据库\"),\n /**\n * TDengine\n */\n TDENGINE(\"TDengine\", \"TDengine 数据库\"),\n /**\n * Informix\n */\n INFORMIX(\"informix\", \"Informix 数据库\"),\n /**\n * sinodb\n */\n SINODB(\"sinodb\", \"SinoDB 数据库\"),\n /**\n * uxdb\n */\n UXDB(\"uxdb\", \"优炫数据库\"),\n /**\n * greenplum\n */\n GREENPLUM(\"greenplum\", \"greenplum 数据库\"),\n /**\n * UNKNOWN DB\n */\n OTHER(\"other\", \"其他数据库\");\n\n /**\n * 数据库名称\n */\n private final String name;\n\n /**\n * 描述\n */\n private final String remarks;\n\n\n public String getName() {\n return name;\n }\n\n public String getRemarks() {\n return remarks;\n }\n\n DbType(String name, String remarks) {\n this.name = name;\n this.remarks = remarks;\n }\n}" }, { "identifier": "DbTypeUtils", "path": "src/main/java/org/tinycloud/jdbc/util/DbTypeUtils.java", "snippet": "public class DbTypeUtils {\n private DbTypeUtils() {\n }\n\n\n /**\n * 获取当前配置的 DbType\n */\n public static DbType getDbType(DataSource dataSource) {\n String jdbcUrl = getJdbcUrl(dataSource);\n if (!StringUtils.isEmpty(jdbcUrl)) {\n return parseDbType(jdbcUrl);\n }\n throw new IllegalStateException(\"Can not get dataSource jdbcUrl: \" + dataSource.getClass().getName());\n }\n\n /**\n * 通过数据源中获取 jdbc 的 url 配置\n * 符合 HikariCP, druid, c3p0, DBCP, BEECP 数据源框架 以及 MyBatis UnpooledDataSource 的获取规则\n *\n * @return jdbc url 配置\n */\n public static String getJdbcUrl(DataSource dataSource) {\n String[] methodNames = new String[]{\"getUrl\", \"getJdbcUrl\"};\n for (String methodName : methodNames) {\n try {\n Method method = dataSource.getClass().getMethod(methodName);\n return (String) method.invoke(dataSource);\n } catch (Exception e) {\n //ignore\n }\n }\n\n Connection connection = null;\n try {\n connection = dataSource.getConnection();\n return connection.getMetaData().getURL();\n } catch (Exception e) {\n throw new JdbcException(\"Can not get the dataSource jdbcUrl!\");\n } finally {\n if (connection != null) {\n try {\n connection.close();\n } catch (SQLException e) { //ignore\n }\n }\n }\n }\n\n\n /**\n * 参考 druid 和 MyBatis-plus 的 JdbcUtils\n *\n * @param jdbcUrl jdbcURL\n * @return 返回数据库类型\n */\n public static DbType parseDbType(String jdbcUrl) {\n jdbcUrl = jdbcUrl.toLowerCase();\n if (jdbcUrl.contains(\":mysql:\") || jdbcUrl.contains(\":cobar:\")) {\n return DbType.MYSQL;\n } else if (jdbcUrl.contains(\":mariadb:\")) {\n return DbType.MARIADB;\n } else if (jdbcUrl.contains(\":oracle:\")) {\n return DbType.ORACLE;\n } else if (jdbcUrl.contains(\":sqlserver2012:\")) {\n return DbType.SQLSERVER;\n } else if (jdbcUrl.contains(\":sqlserver:\") || jdbcUrl.contains(\":microsoft:\")) {\n return DbType.SQLSERVER_2005;\n } else if (jdbcUrl.contains(\":postgresql:\")) {\n return DbType.POSTGRE_SQL;\n } else if (jdbcUrl.contains(\":hsqldb:\")) {\n return DbType.HSQL;\n } else if (jdbcUrl.contains(\":db2:\")) {\n return DbType.DB2;\n } else if (jdbcUrl.contains(\":sqlite:\")) {\n return DbType.SQLITE;\n } else if (jdbcUrl.contains(\":h2:\")) {\n return DbType.H2;\n } else if (isMatchedRegex(\":dm\\\\d*:\", jdbcUrl)) {\n return DbType.DM;\n } else if (jdbcUrl.contains(\":xugu:\")) {\n return DbType.XUGU;\n } else if (isMatchedRegex(\":kingbase\\\\d*:\", jdbcUrl)) {\n return DbType.KINGBASE_ES;\n } else if (jdbcUrl.contains(\":phoenix:\")) {\n return DbType.PHOENIX;\n } else if (jdbcUrl.contains(\":zenith:\")) {\n return DbType.GAUSS;\n } else if (jdbcUrl.contains(\":gbase:\")) {\n return DbType.GBASE;\n } else if (jdbcUrl.contains(\":gbasedbt-sqli:\") || jdbcUrl.contains(\":informix-sqli:\")) {\n return DbType.GBASE_8S;\n } else if (jdbcUrl.contains(\":ch:\") || jdbcUrl.contains(\":clickhouse:\")) {\n return DbType.CLICK_HOUSE;\n } else if (jdbcUrl.contains(\":oscar:\")) {\n return DbType.OSCAR;\n } else if (jdbcUrl.contains(\":sybase:\")) {\n return DbType.SYBASE;\n } else if (jdbcUrl.contains(\":oceanbase:\")) {\n return DbType.OCEAN_BASE;\n } else if (jdbcUrl.contains(\":highgo:\")) {\n return DbType.HIGH_GO;\n } else if (jdbcUrl.contains(\":cubrid:\")) {\n return DbType.CUBRID;\n } else if (jdbcUrl.contains(\":goldilocks:\")) {\n return DbType.GOLDILOCKS;\n } else if (jdbcUrl.contains(\":csiidb:\")) {\n return DbType.CSIIDB;\n } else if (jdbcUrl.contains(\":sap:\")) {\n return DbType.SAP_HANA;\n } else if (jdbcUrl.contains(\":impala:\")) {\n return DbType.IMPALA;\n } else if (jdbcUrl.contains(\":vertica:\")) {\n return DbType.VERTICA;\n } else if (jdbcUrl.contains(\":xcloud:\")) {\n return DbType.XCloud;\n } else if (jdbcUrl.contains(\":firebirdsql:\")) {\n return DbType.FIREBIRD;\n } else if (jdbcUrl.contains(\":redshift:\")) {\n return DbType.REDSHIFT;\n } else if (jdbcUrl.contains(\":opengauss:\")) {\n return DbType.OPENGAUSS;\n } else if (jdbcUrl.contains(\":taos:\") || jdbcUrl.contains(\":taos-rs:\")) {\n return DbType.TDENGINE;\n } else if (jdbcUrl.contains(\":informix\")) {\n return DbType.INFORMIX;\n } else if (jdbcUrl.contains(\":sinodb\")) {\n return DbType.SINODB;\n } else if (jdbcUrl.contains(\":uxdb:\")) {\n return DbType.UXDB;\n } else if (jdbcUrl.contains(\":greenplum:\")) {\n return DbType.GREENPLUM;\n } else {\n return DbType.OTHER;\n }\n }\n\n /**\n * 正则匹配,验证成功返回 true,验证失败返回 false\n */\n public static boolean isMatchedRegex(String regex, String jdbcUrl) {\n if (null == jdbcUrl) {\n return false;\n }\n return Pattern.compile(regex).matcher(jdbcUrl).find();\n }\n}" } ]
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.tinycloud.jdbc.page.*; import org.tinycloud.jdbc.util.DbType; import org.tinycloud.jdbc.util.DbTypeUtils; import javax.sql.DataSource;
2,915
package org.tinycloud.jdbc; @Configuration public class TinyJdbcAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(TinyJdbcAutoConfiguration.class); @ConditionalOnMissingBean(IPageHandle.class) @Bean public IPageHandle pageHandle(@Autowired DataSource dataSource) {
package org.tinycloud.jdbc; @Configuration public class TinyJdbcAutoConfiguration { final static Logger logger = LoggerFactory.getLogger(TinyJdbcAutoConfiguration.class); @ConditionalOnMissingBean(IPageHandle.class) @Bean public IPageHandle pageHandle(@Autowired DataSource dataSource) {
DbType dbType = DbTypeUtils.getDbType(dataSource);
1
2023-10-25 14:44:59+00:00
4k
Angular2Guy/AIDocumentLibraryChat
backend/src/main/java/ch/xxx/aidoclibchat/usecase/service/ImportService.java
[ { "identifier": "Artist", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/Artist.java", "snippet": "@Entity\npublic class Artist {\n\t@Id\n\tprivate Long id;\n\tprivate String fullName;\n\tprivate String firstName;\n\tprivate String middleName;\n\tprivate String lastName;\n\tprivate String nationality;\n\tprivate String style;\n\tprivate Integer birth;\n\tprivate Integer death;\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getFullName() {\n\t\treturn fullName;\n\t}\n\tpublic void setFullName(String fullName) {\n\t\tthis.fullName = fullName;\n\t}\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\tpublic String getMiddleName() {\n\t\treturn middleName;\n\t}\n\tpublic void setMiddleName(String middleName) {\n\t\tthis.middleName = middleName;\n\t}\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\tpublic String getNationality() {\n\t\treturn nationality;\n\t}\n\tpublic void setNationality(String nationality) {\n\t\tthis.nationality = nationality;\n\t}\n\tpublic String getStyle() {\n\t\treturn style;\n\t}\n\tpublic void setStyle(String style) {\n\t\tthis.style = style;\n\t}\n\tpublic Integer getBirth() {\n\t\treturn birth;\n\t}\n\tpublic void setBirth(Integer birth) {\n\t\tthis.birth = birth;\n\t}\n\tpublic Integer getDeath() {\n\t\treturn death;\n\t}\n\tpublic void setDeath(Integer death) {\n\t\tthis.death = death;\n\t}\t\n\t\t\n}" }, { "identifier": "ArtistRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/ArtistRepository.java", "snippet": "public interface ArtistRepository {\n\tList<Artist> saveAll(Iterable<Artist> entites);\n\tvoid deleteAll();\n}" }, { "identifier": "DocumentVsRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/DocumentVsRepository.java", "snippet": "public interface DocumentVsRepository {\n\tvoid add(List<Document> documents);\n\tList<Document> retrieve(String query, MetaData.DataType dataType, int k, double threshold);\n\tList<Document> retrieve(String query, MetaData.DataType dataType, int k);\n\tList<Document> retrieve(String query, MetaData.DataType dataType);\n\tList<Document> findAllTableDocuments();\n\tvoid deleteByIds(List<String> ids);\n}" }, { "identifier": "Museum", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/Museum.java", "snippet": "@Entity\npublic class Museum {\n\t@Id\n\tprivate Long id;\n\tprivate String name;\n\tprivate String address;\n\tprivate String city;\n\tprivate String state;\n\tprivate String postal;\n\tprivate String country;\n\tprivate String phone;\n\tprivate String url;\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n\tpublic String getCity() {\n\t\treturn city;\n\t}\n\tpublic void setCity(String city) {\n\t\tthis.city = city;\n\t}\n\tpublic String getState() {\n\t\treturn state;\n\t}\n\tpublic void setState(String state) {\n\t\tthis.state = state;\n\t}\n\tpublic String getPostal() {\n\t\treturn postal;\n\t}\n\tpublic void setPostal(String postal) {\n\t\tthis.postal = postal;\n\t}\n\tpublic String getCountry() {\n\t\treturn country;\n\t}\n\tpublic void setCountry(String country) {\n\t\tthis.country = country;\n\t}\n\tpublic String getPhone() {\n\t\treturn phone;\n\t}\n\tpublic void setPhone(String phone) {\n\t\tthis.phone = phone;\n\t}\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\tpublic void setUrl(String url) {\n\t\tthis.url = url;\n\t}\t\n}" }, { "identifier": "MuseumRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/MuseumRepository.java", "snippet": "public interface MuseumRepository {\n\tList<Museum> saveAll(Iterable<Museum> entities);\n\tvoid deleteAll();\n}" }, { "identifier": "Subject", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/Subject.java", "snippet": "@Entity\npublic class Subject {\n\t@Id\n\tprivate Long workId;\n\tprivate String subject;\n\n\tpublic String getSubject() {\n\t\treturn subject;\n\t}\n\tpublic void setSubject(String subject) {\n\t\tthis.subject = subject;\n\t}\n\tpublic Long getWorkId() {\n\t\treturn workId;\n\t}\n\tpublic void setWorkId(Long workId) {\n\t\tthis.workId = workId;\n\t}\n}" }, { "identifier": "SubjectRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/SubjectRepository.java", "snippet": "public interface SubjectRepository {\n\tList<Subject> saveAll(Iterable<Subject> entities);\n\tvoid deleteAll();\n}" }, { "identifier": "TableMetadata", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/TableMetadata.java", "snippet": "@Entity\npublic class TableMetadata {\n @Id\n @GeneratedValue(strategy=GenerationType.SEQUENCE)\n private Long id;\n\tprivate String tableName;\n\tprivate String tableDescription;\n\tprivate String tableDdl;\n @OneToMany(mappedBy=\"tableMetadata\")\n private Set<ColumnMetadata> columnMetadata;\n \n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getTableName() {\n\t\treturn tableName;\n\t}\n\tpublic void setTableName(String tableName) {\n\t\tthis.tableName = tableName;\n\t}\n\tpublic String getTableDescription() {\n\t\treturn tableDescription;\n\t}\n\tpublic void setTableDescription(String tableDescription) {\n\t\tthis.tableDescription = tableDescription;\n\t}\n\tpublic Set<ColumnMetadata> getColumnMetadata() {\n\t\treturn columnMetadata;\n\t}\n\tpublic void setColumnMetadata(Set<ColumnMetadata> columnMetadata) {\n\t\tthis.columnMetadata = columnMetadata;\n\t}\n\tpublic String getTableDdl() {\n\t\treturn tableDdl;\n\t}\n\tpublic void setTableDdl(String tableDdl) {\n\t\tthis.tableDdl = tableDdl;\n\t}\n}" }, { "identifier": "TableMetadataRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/TableMetadataRepository.java", "snippet": "public interface TableMetadataRepository {\n\tOptional<TableMetadata> findById(Long id);\n\tList<TableMetadata> findAllWithColumns();\n}" }, { "identifier": "MuseumHours", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/MuseumHours.java", "snippet": "@Entity\npublic class MuseumHours {\t\n\t@EmbeddedId\n\tprivate MuseumHoursId museumHoursId;\n\tprivate String open;\n\tprivate String close;\n\t\n\tpublic MuseumHoursId getMuseumHoursId() {\n\t\treturn museumHoursId;\n\t}\n\tpublic void setMuseumHoursId(MuseumHoursId museumHoursId) {\n\t\tthis.museumHoursId = museumHoursId;\n\t}\n\tpublic String getOpen() {\n\t\treturn open;\n\t}\n\tpublic void setOpen(String open) {\n\t\tthis.open = open;\n\t}\n\tpublic String getClose() {\n\t\treturn close;\n\t}\n\tpublic void setClose(String close) {\n\t\tthis.close = close;\n\t}\n}" }, { "identifier": "MuseumHoursRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/MuseumHoursRepository.java", "snippet": "public interface MuseumHoursRepository {\n\tList<MuseumHours> saveAll(Iterable<MuseumHours> entities);\n\tvoid deleteAll();\n}" }, { "identifier": "Work", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/Work.java", "snippet": "@Entity\npublic class Work {\n\t@Id\n\tprivate Long id;\n\tprivate String name;\n\tprivate Long artistId;\n\tprivate String style;\n\tprivate Long museumId;\n\tprivate Integer width;\n\tprivate Integer height;\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic Long getArtistId() {\n\t\treturn artistId;\n\t}\n\tpublic void setArtistId(Long artistId) {\n\t\tthis.artistId = artistId;\n\t}\n\tpublic String getStyle() {\n\t\treturn style;\n\t}\n\tpublic void setStyle(String style) {\n\t\tthis.style = style;\n\t}\n\tpublic Long getMuseumId() {\n\t\treturn museumId;\n\t}\n\tpublic void setMuseumId(Long museumId) {\n\t\tthis.museumId = museumId;\n\t}\n\tpublic Integer getWidth() {\n\t\treturn width;\n\t}\n\tpublic void setWidth(Integer width) {\n\t\tthis.width = width;\n\t}\n\tpublic Integer getHeight() {\n\t\treturn height;\n\t}\n\tpublic void setHeight(Integer height) {\n\t\tthis.height = height;\n\t}\n}" }, { "identifier": "WorkLink", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/WorkLink.java", "snippet": "@Entity\npublic class WorkLink {\n\t@Id\n\tprivate Long workId;\n\tprivate String name;\n\tprivate Long artistId;\n\tprivate String style;\n\tprivate Long museumId;\n\tprivate String imageLink;\n\t\n\tpublic Long getWorkId() {\n\t\treturn workId;\n\t}\n\tpublic void setWorkId(Long workId) {\n\t\tthis.workId = workId;\n\t}\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic Long getArtistId() {\n\t\treturn artistId;\n\t}\n\tpublic void setArtistId(Long artistId) {\n\t\tthis.artistId = artistId;\n\t}\n\tpublic String getStyle() {\n\t\treturn style;\n\t}\n\tpublic void setStyle(String style) {\n\t\tthis.style = style;\n\t}\n\tpublic Long getMuseumId() {\n\t\treturn museumId;\n\t}\n\tpublic void setMuseumId(Long museumId) {\n\t\tthis.museumId = museumId;\n\t}\n\tpublic String getImageLink() {\n\t\treturn imageLink;\n\t}\n\tpublic void setImageLink(String imageLink) {\n\t\tthis.imageLink = imageLink;\n\t}\n}" }, { "identifier": "WorkLinkRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/WorkLinkRepository.java", "snippet": "public interface WorkLinkRepository {\n\tList<WorkLink> saveAll(Iterable<WorkLink> entities);\n\tvoid deleteAll();\n}" }, { "identifier": "WorkRepository", "path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/entity/WorkRepository.java", "snippet": "public interface WorkRepository {\n\tList<Work> saveAll(Iterable<Work> entities);\n\tvoid deleteAll();\n}" } ]
import java.util.List; import org.springframework.ai.document.Document; import org.springframework.stereotype.Service; import ch.xxx.aidoclibchat.domain.model.entity.Artist; import ch.xxx.aidoclibchat.domain.model.entity.ArtistRepository; import ch.xxx.aidoclibchat.domain.model.entity.DocumentVsRepository; import ch.xxx.aidoclibchat.domain.model.entity.Museum; import ch.xxx.aidoclibchat.domain.model.entity.MuseumRepository; import ch.xxx.aidoclibchat.domain.model.entity.Subject; import ch.xxx.aidoclibchat.domain.model.entity.SubjectRepository; import ch.xxx.aidoclibchat.domain.model.entity.TableMetadata; import ch.xxx.aidoclibchat.domain.model.entity.TableMetadataRepository; import ch.xxx.aidoclibchat.domain.model.entity.MuseumHours; import ch.xxx.aidoclibchat.domain.model.entity.MuseumHoursRepository; import ch.xxx.aidoclibchat.domain.model.entity.Work; import ch.xxx.aidoclibchat.domain.model.entity.WorkLink; import ch.xxx.aidoclibchat.domain.model.entity.WorkLinkRepository; import ch.xxx.aidoclibchat.domain.model.entity.WorkRepository; import jakarta.transaction.Transactional; import jakarta.transaction.Transactional.TxType;
3,415
/** * Copyright 2023 Sven Loesekann 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 ch.xxx.aidoclibchat.usecase.service; @Service @Transactional(value = TxType.REQUIRES_NEW) public class ImportService { private final WorkRepository workRepository; private final MuseumHoursRepository museumHoursRepository; private final MuseumRepository museumRepository; private final ArtistRepository artistRepository; private final SubjectRepository subjectRepository; private final WorkLinkRepository workLinkRepository; private final DocumentVsRepository documentVsRepository; private final TableMetadataRepository tableMetadataRepository; public ImportService(WorkRepository zipcodeRepository, MuseumHoursRepository supermarketRepository,WorkLinkRepository workLinkRepository,TableMetadataRepository tableMetadataRepository, MuseumRepository productRepository, ArtistRepository amazonProductRepository, SubjectRepository subjectRepository,DocumentVsRepository documentVsRepository) { this.workRepository = zipcodeRepository; this.museumHoursRepository = supermarketRepository; this.museumRepository = productRepository; this.artistRepository = amazonProductRepository; this.subjectRepository = subjectRepository; this.workLinkRepository = workLinkRepository; this.documentVsRepository = documentVsRepository; this.tableMetadataRepository = tableMetadataRepository; } public void deleteData() { this.subjectRepository.deleteAll(); this.workLinkRepository.deleteAll(); this.museumHoursRepository.deleteAll(); this.workRepository.deleteAll(); this.artistRepository.deleteAll(); this.museumRepository.deleteAll(); } public void saveAllData(List<Work> works, List<MuseumHours> museumHours, List<Museum> museums,
/** * Copyright 2023 Sven Loesekann 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 ch.xxx.aidoclibchat.usecase.service; @Service @Transactional(value = TxType.REQUIRES_NEW) public class ImportService { private final WorkRepository workRepository; private final MuseumHoursRepository museumHoursRepository; private final MuseumRepository museumRepository; private final ArtistRepository artistRepository; private final SubjectRepository subjectRepository; private final WorkLinkRepository workLinkRepository; private final DocumentVsRepository documentVsRepository; private final TableMetadataRepository tableMetadataRepository; public ImportService(WorkRepository zipcodeRepository, MuseumHoursRepository supermarketRepository,WorkLinkRepository workLinkRepository,TableMetadataRepository tableMetadataRepository, MuseumRepository productRepository, ArtistRepository amazonProductRepository, SubjectRepository subjectRepository,DocumentVsRepository documentVsRepository) { this.workRepository = zipcodeRepository; this.museumHoursRepository = supermarketRepository; this.museumRepository = productRepository; this.artistRepository = amazonProductRepository; this.subjectRepository = subjectRepository; this.workLinkRepository = workLinkRepository; this.documentVsRepository = documentVsRepository; this.tableMetadataRepository = tableMetadataRepository; } public void deleteData() { this.subjectRepository.deleteAll(); this.workLinkRepository.deleteAll(); this.museumHoursRepository.deleteAll(); this.workRepository.deleteAll(); this.artistRepository.deleteAll(); this.museumRepository.deleteAll(); } public void saveAllData(List<Work> works, List<MuseumHours> museumHours, List<Museum> museums,
List<Artist> artists, List<Subject> subjects, List<WorkLink> workLinks) {
5
2023-10-25 19:05:07+00:00
4k
Fusion-Flux/Portal-Cubed-Rewrite
src/main/java/io/github/fusionflux/portalcubed/content/portal/manager/ServerPortalManager.java
[ { "identifier": "Portal", "path": "src/main/java/io/github/fusionflux/portalcubed/content/portal/Portal.java", "snippet": "public final class Portal {\n\tpublic final int netId;\n public final Vec3 origin;\n\tpublic final FrontAndTop orientation;\n public final PortalShape shape;\n public final PortalType type;\n\tpublic final int color;\n\n public Portal(int netId, Vec3 origin, FrontAndTop orientation, PortalShape shape, PortalType type, int color) {\n\t\tthis.netId = netId;\n this.origin = origin;\n\t\tthis.orientation = orientation;\n this.shape = shape;\n this.type = type;\n\t\tthis.color = color;\n }\n\n\tpublic void toNetwork(FriendlyByteBuf buf) {\n\t\tbuf.writeVarInt(netId);\n\t\tPacketUtils.writeVec3(buf, origin);\n\t\tbuf.writeEnum(orientation);\n\t\tbuf.writeEnum(shape);\n\t\tbuf.writeEnum(type);\n\t\tbuf.writeVarInt(color);\n\t}\n\n\tpublic static Portal fromNetwork(FriendlyByteBuf buf) {\n\t\tint netId = buf.readVarInt();\n\t\tVec3 origin = PacketUtils.readVec3(buf);\n\t\tFrontAndTop orientation = buf.readEnum(FrontAndTop.class);\n\t\tPortalShape shape = buf.readEnum(PortalShape.class);\n\t\tPortalType type = buf.readEnum(PortalType.class);\n\t\tint color = buf.readVarInt();\n\t\treturn new Portal(netId, origin, orientation, shape, type, color);\n\t}\n}" }, { "identifier": "PortalShape", "path": "src/main/java/io/github/fusionflux/portalcubed/content/portal/PortalShape.java", "snippet": "public enum PortalShape implements StringRepresentable {\n\tSQUARE, ROUND;\n\n\tpublic static final Codec<PortalShape> CODEC = StringRepresentable.fromEnum(PortalShape::values);\n\n\tpublic final String name;\n\tpublic final ResourceLocation texture;\n\tpublic final ResourceLocation tracerTexture;\n\n\tPortalShape() {\n\t\tthis.name = name().toLowerCase(Locale.ROOT);\n\t\tthis.texture = PortalCubed.id(\"textures/entity/portal/\" + name + \".png\");\n\t\tthis.tracerTexture = PortalCubed.id(\"textures/entity/portal/tracer/\" + name + \".png\");\n\t}\n\n\t@Override\n\t@NotNull\n\tpublic String getSerializedName() {\n\t\treturn this.name;\n\t}\n}" }, { "identifier": "PortalType", "path": "src/main/java/io/github/fusionflux/portalcubed/content/portal/PortalType.java", "snippet": "public enum PortalType implements StringRepresentable {\n\tPRIMARY(0xff2492fc),\n\tSECONDARY(0xffff8e1e);\n\n\tpublic static final Codec<PortalType> CODEC = StringRepresentable.fromEnum(PortalType::values);\n\n\tpublic final String name;\n\tpublic final int defaultColor;\n\n\tPortalType(int defaultColor) {\n\t\tthis.name = name().toLowerCase(Locale.ROOT);\n\t\tthis.defaultColor = defaultColor;\n\t}\n\n\t@Override\n\t@NotNull\n\tpublic String getSerializedName() {\n\t\treturn this.name;\n\t}\n}" }, { "identifier": "ServerLevelExt", "path": "src/main/java/io/github/fusionflux/portalcubed/framework/extension/ServerLevelExt.java", "snippet": "public interface ServerLevelExt {\n\tServerPortalManager pc$portalManager();\n}" }, { "identifier": "PortalCubedPackets", "path": "src/main/java/io/github/fusionflux/portalcubed/packet/PortalCubedPackets.java", "snippet": "public class PortalCubedPackets {\n\t// clientbound\n\tpublic static final PacketType<CreatePortalPacket> CREATE_PORTAL = clientbound(\"create_portal\", CreatePortalPacket::new);\n\t// serverbound\n\tpublic static final PacketType<DirectClickItemPacket> DIRECT_CLICK_ITEM = serverbound(\"direct_click_item\", DirectClickItemPacket::new);\n\n\tpublic static void init() {\n\t}\n\n\tprivate static <T extends ClientboundPacket> PacketType<T> clientbound(String name, Function<FriendlyByteBuf, T> factory) {\n\t\tPacketType<T> type = PacketType.create(PortalCubed.id(name), factory);\n\t\tif (MinecraftQuiltLoader.getEnvironmentType() == EnvType.CLIENT) {\n\t\t\tregisterClientReceiver(type);\n\t\t}\n\t\treturn type;\n\t}\n\n\tprivate static <T extends ServerboundPacket> PacketType<T> serverbound(String name, Function<FriendlyByteBuf, T> factory) {\n\t\tPacketType<T> type = PacketType.create(PortalCubed.id(name), factory);\n\t\tServerPlayNetworking.registerGlobalReceiver(type, ServerboundPacket::handle);\n\t\treturn type;\n\t}\n\n\tprivate static <T extends ClientboundPacket> void registerClientReceiver(PacketType<T> type) {\n\t\tClientPlayNetworking.registerGlobalReceiver(type, ClientboundPacket::handle);\n\t}\n\n\tpublic static <T extends FabricPacket> void sendToClient(ServerPlayer player, T packet) {\n\t\tServerPlayNetworking.send(player, packet);\n\t}\n\n\t@ClientOnly\n\tpublic static <T extends FabricPacket> void sendToServer(T packet) {\n\t\tClientPlayNetworking.send(packet);\n\t}\n}" }, { "identifier": "CreatePortalPacket", "path": "src/main/java/io/github/fusionflux/portalcubed/packet/clientbound/CreatePortalPacket.java", "snippet": "public class CreatePortalPacket implements ClientboundPacket {\n\tprivate final Portal portal;\n\n\tpublic CreatePortalPacket(Portal portal) {\n\t\tthis.portal = portal;\n\t}\n\n\tpublic CreatePortalPacket(FriendlyByteBuf buf) {\n\t\tthis.portal = Portal.fromNetwork(buf);\n\t}\n\n\t@Override\n\tpublic void write(FriendlyByteBuf buf) {\n\t\tthis.portal.toNetwork(buf);\n\t}\n\n\t@Override\n\tpublic PacketType<?> getType() {\n\t\treturn PortalCubedPackets.CREATE_PORTAL;\n\t}\n\n\t@Override\n\tpublic void handle(LocalPlayer player, PacketSender responder) {\n\t\tClientPortalManager manager = ClientPortalManager.of(player.clientLevel);\n\t\tmanager.addPortal(this.portal);\n\t}\n}" } ]
import io.github.fusionflux.portalcubed.content.portal.Portal; import io.github.fusionflux.portalcubed.content.portal.PortalShape; import io.github.fusionflux.portalcubed.content.portal.PortalType; import io.github.fusionflux.portalcubed.framework.extension.ServerLevelExt; import io.github.fusionflux.portalcubed.packet.PortalCubedPackets; import io.github.fusionflux.portalcubed.packet.clientbound.CreatePortalPacket; import net.minecraft.core.FrontAndTop; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.phys.Vec3; import org.quiltmc.qsl.networking.api.PlayerLookup; import java.util.concurrent.atomic.AtomicInteger;
1,633
package io.github.fusionflux.portalcubed.content.portal.manager; public class ServerPortalManager extends PortalManager { public final ServerLevel level; private static final AtomicInteger idGenerator = new AtomicInteger(); public ServerPortalManager(ServerLevel level) { this.level = level; } public static ServerPortalManager of(ServerLevel level) {
package io.github.fusionflux.portalcubed.content.portal.manager; public class ServerPortalManager extends PortalManager { public final ServerLevel level; private static final AtomicInteger idGenerator = new AtomicInteger(); public ServerPortalManager(ServerLevel level) { this.level = level; } public static ServerPortalManager of(ServerLevel level) {
return ((ServerLevelExt) level).pc$portalManager();
3
2023-10-25 05:32:39+00:00
4k
RomySaputraSihananda/alquranapi
src/main/java/org/alquranapi/controller/AlquranController.java
[ { "identifier": "SuratDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratDTO.java", "snippet": "@Data\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = true)\npublic class SuratDTO extends SuratPrevNextDTO {\n private String tempatTurun;\n private String arti;\n private String deskripsi;\n private Map<String, String> audioFull;\n\n public SuratDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.tempatTurun = suratDAO.getTempatTurun();\n this.arti = suratDAO.getArti();\n this.deskripsi = suratDAO.getDeskripsi();\n this.audioFull = suratDAO.getAudioFull();\n }\n}" }, { "identifier": "SuratDetailDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratDetailDTO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@NoArgsConstructor\npublic class SuratDetailDTO extends SuratDTO {\n private ArrayList<AyatDTO> ayat;\n private SuratPrevNextDTO suratSelanjutnya;\n private SuratPrevNextDTO suratSebelumnya;\n\n public SuratDetailDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.ayat = suratDAO.getAyat();\n this.suratSelanjutnya = suratDAO.getSuratSelanjutnya();\n this.suratSebelumnya = suratDAO.getSuratSebelumnya();\n }\n}" }, { "identifier": "SuratPrevNextDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratPrevNextDTO.java", "snippet": "@Data\n@NoArgsConstructor\npublic class SuratPrevNextDTO {\n private int nomor;\n private String nama;\n private String namaLatin;\n private int jumlahAyat;\n\n public SuratPrevNextDTO(SuratDAO surat) {\n this.nomor = surat.getNomor();\n this.nama = surat.getNama();\n this.namaLatin = surat.getNamaLatin();\n this.jumlahAyat = surat.getJumlahAyat();\n }\n}" }, { "identifier": "SuratTafsirDTO", "path": "src/main/java/org/alquranapi/model/DTO/SuratTafsirDTO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@NoArgsConstructor\npublic class SuratTafsirDTO extends SuratDTO {\n private ArrayList<TafsirDTO> tafsir;\n private SuratPrevNextDTO suratSelanjutnya;\n private SuratPrevNextDTO suratSebelumnya;\n\n public SuratTafsirDTO(SuratDAO suratDAO) {\n super(suratDAO);\n this.tafsir = suratDAO.getTafsir();\n this.suratSelanjutnya = suratDAO.getSuratSelanjutnya();\n this.suratSebelumnya = suratDAO.getSuratSebelumnya();\n }\n}" }, { "identifier": "AlquranService", "path": "src/main/java/org/alquranapi/service/AlquranService.java", "snippet": "@Service\npublic class AlquranService {\n @Autowired\n private ElasticsearchClient client;\n\n @Value(\"${service.elastic.index}\")\n private String index;\n\n public ArrayList<ElasticHit<SuratDTO>> getAll() throws IOException {\n SearchResponse<SuratDAO> response = this.client.search(search -> search.index(this.index).size(114),\n SuratDAO.class);\n\n return new ArrayList<>(response.hits().hits().stream()\n .map(surat -> new ElasticHit<SuratDTO>(surat.id(), surat.index(),\n new SuratDTO(surat.source())))\n .collect(Collectors.toList()));\n }\n\n public ArrayList<ElasticHit<SuratDetailDTO>> getDetail(int nomor) throws IOException {\n GetResponse<SuratDAO> response = this.client.get(\n get -> get.index(this.index).id(Integer.toString(nomor)),\n SuratDAO.class);\n if (!response.found())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(List.of(new ElasticHit<SuratDetailDTO>(response.id(), response.index(),\n new SuratDetailDTO(response.source()))));\n }\n\n public ArrayList<ElasticHit<SuratTafsirDTO>> getTafsir(int nomor) throws IOException {\n GetResponse<SuratDAO> response = this.client.get(\n get -> get.index(this.index).id(Integer.toString(nomor)),\n SuratDAO.class);\n if (!response.found())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(List.of(\n new ElasticHit<SuratTafsirDTO>(response.id(), response.index(),\n new SuratTafsirDTO(response.source()))));\n }\n\n public ArrayList<ElasticHit<SuratPrevNextDTO>> searchByName(String value) throws IOException {\n return this.search(\"namaLatin\", value);\n }\n\n public ArrayList<ElasticHit<SuratPrevNextDTO>> searchByTempatTurun(String value) throws IOException {\n return this.search(\"tempatTurun\", value);\n }\n\n private ArrayList<ElasticHit<SuratPrevNextDTO>> search(String field, String value) throws IOException {\n SearchResponse<SuratDAO> response = this.client.search(search -> search\n .index(this.index)\n .query(query -> query\n .bool(bool -> bool\n .must(must -> must\n .match(match -> match\n .field(field)\n .query(value)))))\n .size(114),\n SuratDAO.class);\n\n if (response.hits().maxScore().isNaN())\n throw new AlquranException(\"surat not found\");\n\n return new ArrayList<>(response.hits().hits().stream()\n .map(surat -> new ElasticHit<SuratPrevNextDTO>(surat.id(), surat.index(),\n new SuratPrevNextDTO(surat.source())))\n .collect(Collectors.toList()));\n }\n}" } ]
import java.io.IOException; import org.alquranapi.model.DTO.SuratDTO; import org.alquranapi.model.DTO.SuratDetailDTO; import org.alquranapi.model.DTO.SuratPrevNextDTO; import org.alquranapi.model.DTO.SuratTafsirDTO; import org.alquranapi.payload.hit.ElasticHit; import org.alquranapi.payload.response.BodyResponse; import org.alquranapi.service.AlquranService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.Operation;
1,935
package org.alquranapi.controller; @RestController @RequestMapping("/api/v1/alquran") public class AlquranController { @Autowired private AlquranService alquranService; @Operation(summary = "Get all surat", description = "API for get all surat") @GetMapping public ResponseEntity<BodyResponse<ElasticHit<SuratDTO>>> handlerGetAll() throws IOException { return new ResponseEntity<>(new BodyResponse<>("ok", HttpStatus.OK.value(), "all data surat Al-Quran", this.alquranService.getAll()), HttpStatus.OK); } @Operation(summary = "Get detail surat", description = "API for get detail surat") @GetMapping("/{nomorSurat}") public ResponseEntity<BodyResponse<ElasticHit<SuratDetailDTO>>> handlerGetDetail(@PathVariable int nomorSurat) throws IOException { return new ResponseEntity<>( new BodyResponse<>("ok", HttpStatus.OK.value(), "all detail surat Al-Quran nomor " + nomorSurat, this.alquranService.getDetail(nomorSurat)), HttpStatus.OK); } @Operation(summary = "Get tafsir surat", description = "API for get tafsir surat") @GetMapping("/tafsir/{nomorSurat}") public ResponseEntity<BodyResponse<ElasticHit<SuratTafsirDTO>>> handlerGetTafsir(@PathVariable int nomorSurat) throws IOException { return new ResponseEntity<>( new BodyResponse<>("ok", HttpStatus.OK.value(), "all tafsir surat Al-Quran nomor " + nomorSurat, this.alquranService.getTafsir(nomorSurat)), HttpStatus.OK); } @Operation(summary = "Search by name surat", description = "API for search by name surat") @GetMapping("/search/nama/{namaSurat}")
package org.alquranapi.controller; @RestController @RequestMapping("/api/v1/alquran") public class AlquranController { @Autowired private AlquranService alquranService; @Operation(summary = "Get all surat", description = "API for get all surat") @GetMapping public ResponseEntity<BodyResponse<ElasticHit<SuratDTO>>> handlerGetAll() throws IOException { return new ResponseEntity<>(new BodyResponse<>("ok", HttpStatus.OK.value(), "all data surat Al-Quran", this.alquranService.getAll()), HttpStatus.OK); } @Operation(summary = "Get detail surat", description = "API for get detail surat") @GetMapping("/{nomorSurat}") public ResponseEntity<BodyResponse<ElasticHit<SuratDetailDTO>>> handlerGetDetail(@PathVariable int nomorSurat) throws IOException { return new ResponseEntity<>( new BodyResponse<>("ok", HttpStatus.OK.value(), "all detail surat Al-Quran nomor " + nomorSurat, this.alquranService.getDetail(nomorSurat)), HttpStatus.OK); } @Operation(summary = "Get tafsir surat", description = "API for get tafsir surat") @GetMapping("/tafsir/{nomorSurat}") public ResponseEntity<BodyResponse<ElasticHit<SuratTafsirDTO>>> handlerGetTafsir(@PathVariable int nomorSurat) throws IOException { return new ResponseEntity<>( new BodyResponse<>("ok", HttpStatus.OK.value(), "all tafsir surat Al-Quran nomor " + nomorSurat, this.alquranService.getTafsir(nomorSurat)), HttpStatus.OK); } @Operation(summary = "Search by name surat", description = "API for search by name surat") @GetMapping("/search/nama/{namaSurat}")
public ResponseEntity<BodyResponse<ElasticHit<SuratPrevNextDTO>>> handlerSearchByname(
2
2023-10-28 13:09:26+00:00
4k
ansforge/SAMU-Hub-Modeles
src/test/java/com/hubsante/model/utils/EdxlWrapperUtils.java
[ { "identifier": "EDXL_DE_Builder", "path": "src/main/java/com/hubsante/model/builders/EDXL_DE_Builder.java", "snippet": "public class EDXL_DE_Builder {\n\n private String distributionID;\n private String senderID;\n private OffsetDateTime dateTimeSent;\n private OffsetDateTime dateTimeExpires;\n private DistributionStatus distributionStatus;\n private DistributionKind distributionKind;\n private Descriptor descriptor;\n private ContentMessage content;\n\n public EDXL_DE_Builder(@NotNull String distributionID, @NotNull String senderID, @NotNull String recipientId) {\n if (distributionID == null || senderID == null || recipientId == null) {\n throw new IllegalArgumentException(\"distributionID, senderID and recipientId must not be null\");\n }\n this.distributionID = distributionID;\n this.senderID = senderID;\n this.dateTimeSent = OffsetDateTime.now();\n this.dateTimeExpires = this.dateTimeSent.plusDays(1L);\n this.distributionStatus = DistributionStatus.ACTUAL;\n this.distributionKind = DistributionKind.REPORT;\n\n ExplicitAddress recipientAddress = new ExplicitAddress(\"hubex\", recipientId);\n this.descriptor = new Descriptor(\"fr-FR\", recipientAddress);\n\n this.content = null;\n }\n\n public EDXL_DE_Builder dateTimeSent(OffsetDateTime dateTimeSent) {\n this.dateTimeSent = dateTimeSent;\n this.dateTimeExpires = dateTimeSent.plusDays(1L);\n return this;\n }\n\n public EDXL_DE_Builder dateTimeSentNowWithOffsetInSeconds(long offset) {\n this.dateTimeSent = OffsetDateTime.now();\n this.dateTimeExpires = this.dateTimeSent.plusDays(offset);\n return this;\n }\n\n public EDXL_DE_Builder dateTimeSentNowWithOffsetInHours(long offset) {\n this.dateTimeSent = OffsetDateTime.now();\n this.dateTimeExpires = this.dateTimeSent.plusHours(offset);\n return this;\n }\n\n public EDXL_DE_Builder dateTimeSentNowWithOffsetInDays(long offset) {\n this.dateTimeSent = OffsetDateTime.now();\n this.dateTimeExpires = this.dateTimeSent.plusDays(offset);\n return this;\n }\n\n public EDXL_DE_Builder dateTimeExpires(OffsetDateTime dateTimeExpires) {\n if (dateTimeExpires.isBefore(this.dateTimeSent)) {\n throw new IllegalArgumentException(\"dateTimeExpires must be after dateTimeSent\");\n }\n this.dateTimeExpires = dateTimeExpires;\n return this;\n }\n\n public EDXL_DE_Builder dateTimeSentAndExpiresAfterSeconds(OffsetDateTime dateTimeSent, long offset) {\n this.dateTimeSent = dateTimeSent;\n this.dateTimeExpires = dateTimeSent.plusSeconds(offset);\n return this;\n }\n\n public EDXL_DE_Builder dateTimeSentAndExpiresAfterHours(OffsetDateTime dateTimeSent, long offset) {\n this.dateTimeSent = dateTimeSent;\n this.dateTimeExpires = dateTimeSent.plusHours(offset);\n return this;\n }\n public EDXL_DE_Builder dateTimeSentAndExpiresAfterDays(OffsetDateTime dateTimeSent, long offset) {\n this.dateTimeSent = dateTimeSent;\n this.dateTimeExpires = dateTimeSent.plusDays(offset);\n return this;\n }\n\n public EDXL_DE_Builder distributionStatus(DistributionStatus distributionStatus) {\n this.distributionStatus = distributionStatus;\n return this;\n }\n\n public EDXL_DE_Builder distributionKind(DistributionKind distributionKind) {\n this.distributionKind = distributionKind;\n return this;\n }\n\n public EDXL_DE_Builder withLanguage(String language) {\n this.descriptor.setLanguage(language);\n return this;\n }\n\n public EDXL_DE_Builder contentMessage(ContentMessage contentMessage) {\n this.content = contentMessage;\n return this;\n }\n\n public EdxlMessage build() {\n if (this.distributionID == null | this.senderID == null | this.dateTimeSent == null | this.dateTimeExpires == null\n | this.distributionStatus == null | this.distributionKind == null | this.descriptor == null) {\n throw new IllegalArgumentException(\"unprovided mandatory field(s)\");\n }\n this.dateTimeSent = this.dateTimeSent.truncatedTo(SECONDS);\n this.dateTimeExpires = this.dateTimeExpires.truncatedTo(SECONDS);\n\n return new EdxlMessage(this.distributionID, this.senderID, this.dateTimeSent, this.dateTimeExpires,\n this.distributionStatus, this.distributionKind, this.descriptor, this.content);\n }\n}" }, { "identifier": "Recipient", "path": "src/main/java/com/hubsante/model/common/Recipient.java", "snippet": "@JsonPropertyOrder(\n {Recipient.JSON_PROPERTY_NAME, Recipient.JSON_PROPERTY_U_R_I})\n@JsonTypeName(\"recipient\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Recipient {\n public static final String JSON_PROPERTY_NAME = \"name\";\n private String name;\n\n public static final String JSON_PROPERTY_U_R_I = \"URI\";\n private String URI;\n\n public Recipient() {}\n\n public Recipient name(String name) {\n\n this.name = name;\n return this;\n }\n\n /**\n * Get name\n * @return name\n **/\n @JsonProperty(JSON_PROPERTY_NAME)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getName() {\n return name;\n }\n\n @JsonProperty(JSON_PROPERTY_NAME)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setName(String name) {\n this.name = name;\n }\n\n public Recipient URI(String URI) {\n\n this.URI = URI;\n return this;\n }\n\n /**\n * Get URI\n * @return URI\n **/\n @JsonProperty(JSON_PROPERTY_U_R_I)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getURI() {\n return URI;\n }\n\n @JsonProperty(JSON_PROPERTY_U_R_I)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setURI(String URI) {\n this.URI = URI;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Recipient recipient = (Recipient)o;\n return Objects.equals(this.name, recipient.name) &&\n Objects.equals(this.URI, recipient.URI);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, URI);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Recipient {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" URI: \").append(toIndentedString(URI)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}" }, { "identifier": "Sender", "path": "src/main/java/com/hubsante/model/common/Sender.java", "snippet": "@JsonPropertyOrder({Sender.JSON_PROPERTY_NAME, Sender.JSON_PROPERTY_U_R_I})\n@JsonTypeName(\"sender\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Sender {\n public static final String JSON_PROPERTY_NAME = \"name\";\n private String name;\n\n public static final String JSON_PROPERTY_U_R_I = \"URI\";\n private String URI;\n\n public Sender() {}\n\n public Sender name(String name) {\n\n this.name = name;\n return this;\n }\n\n /**\n * Get name\n * @return name\n **/\n @JsonProperty(JSON_PROPERTY_NAME)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getName() {\n return name;\n }\n\n @JsonProperty(JSON_PROPERTY_NAME)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setName(String name) {\n this.name = name;\n }\n\n public Sender URI(String URI) {\n\n this.URI = URI;\n return this;\n }\n\n /**\n * Get URI\n * @return URI\n **/\n @JsonProperty(JSON_PROPERTY_U_R_I)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getURI() {\n return URI;\n }\n\n @JsonProperty(JSON_PROPERTY_U_R_I)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setURI(String URI) {\n this.URI = URI;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Sender sender = (Sender)o;\n return Objects.equals(this.name, sender.name) &&\n Objects.equals(this.URI, sender.URI);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(name, URI);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class Sender {\\n\");\n sb.append(\" name: \").append(toIndentedString(name)).append(\"\\n\");\n sb.append(\" URI: \").append(toIndentedString(URI)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n}" } ]
import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.hubsante.model.builders.EDXL_DE_Builder; import com.hubsante.model.common.Recipient; import com.hubsante.model.common.Sender; import com.hubsante.model.edxl.*; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset;
2,845
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model.utils; public class EdxlWrapperUtils { static ObjectMapper mapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); public static String wrapUseCaseMessage(String useCaseMessage) throws JsonProcessingException { JsonNode contentMessage = mapper.readTree(useCaseMessage); contentMessage = addDistributionElementFields(contentMessage); JsonNode envelope = addEnvelope(contentMessage); return mapper.writeValueAsString(envelope); } public static JsonNode addEnvelope(JsonNode jsonNode) { OffsetDateTime sentAt = OffsetDateTime.of(LocalDateTime.parse("2023-12-15T00:00:00"), ZoneOffset.ofHours(2)).truncatedTo(ChronoUnit.SECONDS); OffsetDateTime expiresAt = sentAt.plusDays(1);
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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.hubsante.model.utils; public class EdxlWrapperUtils { static ObjectMapper mapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); public static String wrapUseCaseMessage(String useCaseMessage) throws JsonProcessingException { JsonNode contentMessage = mapper.readTree(useCaseMessage); contentMessage = addDistributionElementFields(contentMessage); JsonNode envelope = addEnvelope(contentMessage); return mapper.writeValueAsString(envelope); } public static JsonNode addEnvelope(JsonNode jsonNode) { OffsetDateTime sentAt = OffsetDateTime.of(LocalDateTime.parse("2023-12-15T00:00:00"), ZoneOffset.ofHours(2)).truncatedTo(ChronoUnit.SECONDS); OffsetDateTime expiresAt = sentAt.plusDays(1);
EdxlMessage edxlMessage = new EDXL_DE_Builder("sender_123", "sender", "recipient")
0
2023-10-25 14:24:31+00:00
4k
yaroslav318/shop-telegram-bot
telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/OrderEnterCityCommandHandler.java
[ { "identifier": "ActionHandler", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/ActionHandler.java", "snippet": "public interface ActionHandler extends Handler {\n\n boolean canHandleAction(Update update, String action);\n\n void handleAction(AbsSender absSender, Update update, String action) throws TelegramApiException;\n\n}" }, { "identifier": "CommandHandler", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/CommandHandler.java", "snippet": "public interface CommandHandler extends Handler {\n\n void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException;\n\n}" }, { "identifier": "CommandHandlerRegistry", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/registries/CommandHandlerRegistry.java", "snippet": "public interface CommandHandlerRegistry {\n\n void setCommandHandlers(List<CommandHandler> commandHandlers);\n\n CommandHandler find(Command command);\n\n}" }, { "identifier": "Button", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/Button.java", "snippet": "public enum Button {\n\n START(\"/start\"),\n CATALOG(\"\\uD83D\\uDCE6 Catalog\"),\n CART(\"\\uD83D\\uDECD Cart\"),\n SEND_PHONE_NUMBER(\"\\uD83D\\uDCF1 Send Phone Number\"),\n ORDER_STEP_NEXT(\"\\u2714\\uFE0F Correct\"),\n ORDER_STEP_PREVIOUS(\"\\u25C0 Back\"),\n ORDER_STEP_CANCEL(\"\\u274C Cancel order\"),\n ORDER_CONFIRM(\"\\u2705 Confirm\");\n\n private final String alias;\n\n Button(String alias) {\n this.alias = alias;\n }\n\n public String getAlias() {\n return alias;\n }\n\n public static ReplyKeyboardMarkup createGeneralMenuKeyboard() {\n ReplyKeyboardMarkup.ReplyKeyboardMarkupBuilder keyboardBuilder = ReplyKeyboardMarkup.builder();\n keyboardBuilder.resizeKeyboard(true);\n keyboardBuilder.selective(true);\n\n keyboardBuilder.keyboardRow(new KeyboardRow(Arrays.asList(\n builder().text(CATALOG.getAlias()).build(),\n builder().text(CART.getAlias()).build()\n )));\n\n return keyboardBuilder.build();\n }\n\n}" }, { "identifier": "ClientAction", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/ClientAction.java", "snippet": "public class ClientAction implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private final Command command;\n private final String action;\n private final LocalDateTime createdTime = LocalDateTime.now();\n\n public ClientAction(Command command, String action) {\n this.command = command;\n this.action = action;\n }\n\n public Command getCommand() {\n return command;\n }\n\n public String getAction() {\n return action;\n }\n\n public LocalDateTime getCreatedTime() {\n return createdTime;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ClientAction that = (ClientAction) o;\n return Objects.equals(command, that.command) &&\n Objects.equals(action, that.action) &&\n Objects.equals(createdTime, that.createdTime);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(command, action, createdTime);\n }\n\n @Override\n public String toString() {\n return \"ClientAction [command=\" + command +\n \", action=\" + action +\n \", createdTime=\" + createdTime + \"]\";\n }\n\n}" }, { "identifier": "ClientOrder", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/ClientOrder.java", "snippet": "public class ClientOrder implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private List<CartItem> cartItems;\n private String clientName;\n private String phoneNumber;\n private String city;\n private String address;\n\n public long calculateTotalPrice() {\n long totalPrice = 0;\n for (CartItem cartItem : cartItems) {\n totalPrice += cartItem.getTotalPrice();\n }\n return totalPrice;\n }\n\n public List<CartItem> getCartItems() {\n return cartItems;\n }\n\n public void setCartItems(List<CartItem> cartItems) {\n this.cartItems = cartItems;\n }\n\n public String getClientName() {\n return clientName;\n }\n\n public void setClientName(String clientName) {\n this.clientName = clientName;\n }\n\n public String getPhoneNumber() {\n return phoneNumber;\n }\n\n public void setPhoneNumber(String phoneNumber) {\n this.phoneNumber = phoneNumber;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(cartItems, clientName, phoneNumber, city, address);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ClientOrder other = (ClientOrder) obj;\n return Objects.equals(cartItems, other.cartItems) &&\n Objects.equals(clientName, other.clientName) &&\n Objects.equals(phoneNumber, other.phoneNumber) &&\n Objects.equals(city, other.city) &&\n Objects.equals(address, other.address);\n }\n\n @Override\n public String toString() {\n return \"ClientOrder [cartItems=\" + cartItems +\n \", clientName=\" + clientName +\n \", phoneNumber=\" + phoneNumber +\n \", city=\" + city +\n \", address=\" + address + \"]\";\n }\n\n}" }, { "identifier": "Command", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/Command.java", "snippet": "public enum Command {\n\n START,\n CATALOG,\n CART,\n ENTER_NAME,\n ENTER_PHONE_NUMBER,\n ENTER_CITY,\n ENTER_ADDRESS,\n ORDER_STEP_CANCEL,\n ORDER_STEP_PREVIOUS,\n ORDER_CONFIRM;\n\n}" }, { "identifier": "ClientActionRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientActionRepository.java", "snippet": "public interface ClientActionRepository {\n\n ClientAction findByChatId(Long chatId);\n\n void updateByChatId(Long chatId, ClientAction clientAction);\n\n void deleteByChatId(Long chatId);\n\n}" }, { "identifier": "ClientCommandStateRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientCommandStateRepository.java", "snippet": "public interface ClientCommandStateRepository {\n\n void pushByChatId(Long chatId, Command command);\n\n Command popByChatId(Long chatId);\n\n void deleteAllByChatId(Long chatId);\n\n}" }, { "identifier": "ClientOrderStateRepository", "path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientOrderStateRepository.java", "snippet": "public interface ClientOrderStateRepository {\n\n ClientOrder findByChatId(Long chatId);\n\n void updateByChatId(Long chatId, ClientOrder clientOrder);\n\n void deleteByChatId(Long chatId);\n\n}" } ]
import java.util.Arrays; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow; import org.telegram.telegrambots.meta.bots.AbsSender; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import ua.ivanzaitsev.bot.handlers.ActionHandler; import ua.ivanzaitsev.bot.handlers.CommandHandler; import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry; import ua.ivanzaitsev.bot.models.domain.Button; import ua.ivanzaitsev.bot.models.domain.ClientAction; import ua.ivanzaitsev.bot.models.domain.ClientOrder; import ua.ivanzaitsev.bot.models.domain.Command; import ua.ivanzaitsev.bot.repositories.ClientActionRepository; import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository; import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository;
2,221
package ua.ivanzaitsev.bot.handlers.commands; public class OrderEnterCityCommandHandler implements CommandHandler, ActionHandler { private static final String ENTER_CITY_ACTION = "order=enter-client-city"; private static final Pattern CITY_PATTERN = Pattern.compile("[a-zA-Z]"); private final CommandHandlerRegistry commandHandlerRegistry; private final ClientActionRepository clientActionRepository; private final ClientCommandStateRepository clientCommandStateRepository; private final ClientOrderStateRepository clientOrderStateRepository; public OrderEnterCityCommandHandler( CommandHandlerRegistry commandHandlerRegistry, ClientActionRepository clientActionRepository, ClientCommandStateRepository clientCommandStateRepository, ClientOrderStateRepository clientOrderStateRepository) { this.commandHandlerRegistry = commandHandlerRegistry; this.clientActionRepository = clientActionRepository; this.clientCommandStateRepository = clientCommandStateRepository; this.clientOrderStateRepository = clientOrderStateRepository; } @Override
package ua.ivanzaitsev.bot.handlers.commands; public class OrderEnterCityCommandHandler implements CommandHandler, ActionHandler { private static final String ENTER_CITY_ACTION = "order=enter-client-city"; private static final Pattern CITY_PATTERN = Pattern.compile("[a-zA-Z]"); private final CommandHandlerRegistry commandHandlerRegistry; private final ClientActionRepository clientActionRepository; private final ClientCommandStateRepository clientCommandStateRepository; private final ClientOrderStateRepository clientOrderStateRepository; public OrderEnterCityCommandHandler( CommandHandlerRegistry commandHandlerRegistry, ClientActionRepository clientActionRepository, ClientCommandStateRepository clientCommandStateRepository, ClientOrderStateRepository clientOrderStateRepository) { this.commandHandlerRegistry = commandHandlerRegistry; this.clientActionRepository = clientActionRepository; this.clientCommandStateRepository = clientCommandStateRepository; this.clientOrderStateRepository = clientOrderStateRepository; } @Override
public Command getCommand() {
6
2023-10-29 15:49:41+00:00
4k
sschr15/rgml-quilt
client/src/main/java/org/duvetmc/mods/rgmlquilt/plugin/RgmlQuiltPlugin.java
[ { "identifier": "AllOpenModLoadOption", "path": "client/src/main/java/org/duvetmc/mods/rgmlquilt/util/AllOpenModLoadOption.java", "snippet": "public class AllOpenModLoadOption extends ModLoadOption implements ModContainerExt {\n\tprivate final QuiltPluginContext context;\n\tprivate final Path path;\n\tprivate final Path root;\n\tprivate final AllOpenMetadata metadata = new AllOpenMetadata();\n\n\tpublic AllOpenModLoadOption(QuiltPluginContext context, Path path, String currentNamespace) throws IOException {\n\t\tthis.context = context;\n\t\tthis.path = path;\n\n\t\tPath tempRoot = context.manager().createMemoryFileSystem(\"temp\" + System.nanoTime());\n\n\t\tMinecraftEntryViewer.generateAccessWidener(context, tempRoot, currentNamespace);\n\n\t\tthis.root = context.manager().copyToReadOnlyFileSystem(\"rgml-allopen\", tempRoot);\n\t}\n\n\t@Override\n\tpublic QuiltPluginContext loader() {\n\t\treturn context;\n\t}\n\n\t@Override\n\tpublic ModMetadataExt metadata() {\n\t\treturn metadata;\n\t}\n\n\t@Override\n\tpublic Path rootPath() {\n\t\treturn root;\n\t}\n\n\t@Override\n\tpublic List<List<Path>> getSourcePaths() {\n\t\treturn Collections.emptyList();\n\t}\n\n\t@Override\n\tpublic BasicSourceType getSourceType() {\n\t\treturn BasicSourceType.OTHER;\n\t}\n\n\t@Override\n\tpublic String pluginId() {\n\t\treturn context.pluginId();\n\t}\n\n\t@Override\n\tpublic String modType() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean shouldAddToQuiltClasspath() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Path from() {\n\t\treturn path;\n\t}\n\n\t@Override\n\tpublic Path resourceRoot() {\n\t\treturn root;\n\t}\n\n\t@Override\n\tpublic boolean isMandatory() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic @Nullable String namespaceMappingFrom() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean needsTransforming() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic byte[] computeOriginHash(QuiltFileHasher hasher) throws IOException {\n\t\treturn new byte[hasher.getHashLength()];\n\t}\n\n\t@Override\n\tpublic QuiltLoaderIcon modFileIcon() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic QuiltLoaderIcon modTypeIcon() {\n\t\treturn QuiltLoaderGui.iconTextFile();\n\t}\n\n\t@Override\n\tpublic ModContainerExt convertToMod(Path transformedResourceRoot) {\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic String shortString() {\n\t\treturn \"AllOpen\";\n\t}\n\n\t@Override\n\tpublic String getSpecificInfo() {\n\t\treturn \"\";\n\t}\n\n\t@Override\n\tpublic QuiltLoaderText describe() {\n\t\treturn QuiltLoaderText.of(\"RGML AllOpen\");\n\t}\n}" }, { "identifier": "Utils", "path": "client/src/main/java/org/duvetmc/mods/rgmlquilt/util/Utils.java", "snippet": "public class Utils {\n\tprivate static final Unsafe UNSAFE;\n\tprivate static final MethodHandles.Lookup TRUSTED_LOOKUP;\n\tprivate static MethodHandle QuiltPluginManagerImpl_loadZip0;\n\n\tstatic {\n\t\ttry {\n\t\t\tField f = Unsafe.class.getDeclaredField(\"theUnsafe\");\n\t\t\tf.setAccessible(true);\n\t\t\tUNSAFE = (Unsafe) f.get(null);\n\n\t\t\tField f2 = MethodHandles.Lookup.class.getDeclaredField(\"IMPL_LOOKUP\");\n\t\t\tlong offset = UNSAFE.staticFieldOffset(f2);\n\t\t\tObject base = UNSAFE.staticFieldBase(f2);\n\t\t\tTRUSTED_LOOKUP = (MethodHandles.Lookup) UNSAFE.getObject(base, offset);\n\t\t} catch (Throwable t) {\n\t\t\tthrow new RuntimeException(t);\n\t\t}\n\t}\n\n\tpublic static Unsafe unsafe() {\n\t\treturn UNSAFE;\n\t}\n\n\tpublic static MethodHandles.Lookup lookup() {\n\t\treturn TRUSTED_LOOKUP;\n\t}\n\n\tpublic static InputStream fileInputStream(Path p) {\n\t\ttry {\n\t\t\treturn Files.newInputStream(p);\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static void deleteRecursively(Path p) {\n\t\ttry {\n\t\t\tif (!Files.isDirectory(p)) {\n\t\t\t\tFiles.deleteIfExists(p);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tFiles.list(p).forEach(Utils::deleteRecursively);\n\t\t} catch (IOException e) {\n\t\t\tunsafe().throwException(e);\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static Path loadZip(QuiltPluginContext context, Path zip) {\n\t\ttry {\n\t\t\tif (QuiltPluginManagerImpl_loadZip0 == null) {\n\t\t\t\t\tQuiltPluginManagerImpl_loadZip0 = Utils.lookup().findVirtual(\n\t\t\t\t\t\tClass.forName(\"org.quiltmc.loader.impl.plugin.QuiltPluginManagerImpl\"),\n\t\t\t\t\t\t\"loadZip0\",\n\t\t\t\t\t\tMethodType.methodType(Path.class, Path.class)\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn (Path) QuiltPluginManagerImpl_loadZip0.invoke(context.manager(), zip);\n\t\t} catch (Throwable t) {\n\t\t\tunsafe().throwException(t);\n\t\t\tthrow new RuntimeException(t);\n\t\t}\n\t}\n\n\tpublic static Stream<Path> walk(Path path) {\n\t\ttry {\n\t\t\treturn Files.walk(path);\n\t\t} catch (IOException e) {\n\t\t\tunsafe().throwException(e);\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n}" } ]
import org.duvetmc.mods.rgmlquilt.util.AllOpenModLoadOption; import org.duvetmc.mods.rgmlquilt.util.Utils; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodNode; import org.quiltmc.loader.api.LoaderValue; import org.quiltmc.loader.api.QuiltLoader; import org.quiltmc.loader.api.gui.QuiltDisplayedError; import org.quiltmc.loader.api.gui.QuiltLoaderGui; import org.quiltmc.loader.api.gui.QuiltLoaderText; import org.quiltmc.loader.api.plugin.QuiltLoaderPlugin; import org.quiltmc.loader.api.plugin.QuiltPluginContext; import org.quiltmc.loader.api.plugin.gui.PluginGuiTreeNode; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean;
2,034
package org.duvetmc.mods.rgmlquilt.plugin; public class RgmlQuiltPlugin implements QuiltLoaderPlugin { private static final String RGML_GH_LINK = "https://github.com/sschr15/rgml-quilt"; @Override public void load(QuiltPluginContext context, Map<String, LoaderValue> previousData) { // Prior to mod loading, make sure of some things: // 1. We're running on Java 8 (later versions break RGML, earlier versions can't run Quilt) String version = System.getProperty("java.version"); if (!version.startsWith("8") && !version.startsWith("1.8")) { QuiltDisplayedError error = context.reportError(QuiltLoaderText.of("Java " + version + " detected!")); error.addOpenLinkButton(QuiltLoaderText.of("RGML GitHub"), RGML_GH_LINK); error.setIcon(QuiltLoaderGui.iconLevelError()); error.appendDescription( QuiltLoaderText.of("RGML requires Java 8 due to technical limitations in later versions of Java."), QuiltLoaderText.of("You are currently using Java " + version) ); error.appendReportText("RGML-Quilt is incompatible with Java " + version + ". Java 8 is required."); context.haltLoading(); throw new RuntimeException("RGML currently does not support reflective limitations present in Java 9+."); } // 2. Experimental Chasm support is enabled // System.setProperty(SystemProperties.ENABLE_EXPERIMENTAL_CHASM, "true"); // Now, load mods try { PluginGuiTreeNode treeNode = context.manager().getRootGuiNode() .addChild(QuiltLoaderText.of("Risugami's ModLoader")) .mainIcon(QuiltLoaderGui.iconZipFile()); String namespace = QuiltLoader.isDevelopmentEnvironment() ? "named" : "intermediary"; PluginGuiTreeNode namespaceNode = treeNode.addChild(QuiltLoaderText.of("All-Open"));
package org.duvetmc.mods.rgmlquilt.plugin; public class RgmlQuiltPlugin implements QuiltLoaderPlugin { private static final String RGML_GH_LINK = "https://github.com/sschr15/rgml-quilt"; @Override public void load(QuiltPluginContext context, Map<String, LoaderValue> previousData) { // Prior to mod loading, make sure of some things: // 1. We're running on Java 8 (later versions break RGML, earlier versions can't run Quilt) String version = System.getProperty("java.version"); if (!version.startsWith("8") && !version.startsWith("1.8")) { QuiltDisplayedError error = context.reportError(QuiltLoaderText.of("Java " + version + " detected!")); error.addOpenLinkButton(QuiltLoaderText.of("RGML GitHub"), RGML_GH_LINK); error.setIcon(QuiltLoaderGui.iconLevelError()); error.appendDescription( QuiltLoaderText.of("RGML requires Java 8 due to technical limitations in later versions of Java."), QuiltLoaderText.of("You are currently using Java " + version) ); error.appendReportText("RGML-Quilt is incompatible with Java " + version + ". Java 8 is required."); context.haltLoading(); throw new RuntimeException("RGML currently does not support reflective limitations present in Java 9+."); } // 2. Experimental Chasm support is enabled // System.setProperty(SystemProperties.ENABLE_EXPERIMENTAL_CHASM, "true"); // Now, load mods try { PluginGuiTreeNode treeNode = context.manager().getRootGuiNode() .addChild(QuiltLoaderText.of("Risugami's ModLoader")) .mainIcon(QuiltLoaderGui.iconZipFile()); String namespace = QuiltLoader.isDevelopmentEnvironment() ? "named" : "intermediary"; PluginGuiTreeNode namespaceNode = treeNode.addChild(QuiltLoaderText.of("All-Open"));
context.addModLoadOption(new AllOpenModLoadOption(context, context.pluginPath(), namespace), namespaceNode);
0
2023-10-31 14:17:42+00:00
4k
MikiP98/HumilityAFM
src/main/java/io/github/mikip98/helpers/CabinetBlockHelper.java
[ { "identifier": "ModConfig", "path": "src/main/java/io/github/mikip98/config/ModConfig.java", "snippet": "public class ModConfig {\n public static boolean TransparentCabinetBlocks = true;\n public static boolean enableLEDs = false;\n public static boolean enableLEDsBrightening = true;\n public static boolean enableLEDRadiusColorCompensation = true;\n public static boolean enableVanillaColoredLights = false;\n\n public static short LEDColoredLightStrength = 85;\n public static short LEDColoredLightRadius = 9;\n public static short LEDRadiusColorCompensationBias = 0;\n public static int cabinetBlockBurnTime = 24;\n public static int cabinetBlockFireSpread = 9;\n public static float mosaicsAndTilesStrengthMultiplayer = 1.5f;\n\n public static ArrayList<Color> LEDColors = new ArrayList<>();\n static {\n LEDColors.add(new Color(\"white\", 255, 255,255));\n LEDColors.add(new Color(\"light_gray\", 180, 180, 180));\n LEDColors.add(new Color(\"gray\", 90, 90, 90));\n LEDColors.add(new Color(\"black\", 0, 0, 0));\n LEDColors.add(new Color(\"brown\", 139, 69, 19));\n LEDColors.add(new Color(\"red\", 255, 0, 0));\n LEDColors.add(new Color(\"orange\", 255, 165, 0));\n LEDColors.add(new Color(\"yellow\", 255, 255, 0));\n LEDColors.add(new Color(\"lime\", 192, 255, 0));\n LEDColors.add(new Color(\"green\", 0, 255, 0));\n LEDColors.add(new Color(\"cyan\", 0, 255, 255));\n LEDColors.add(new Color(\"light_blue\", 30, 144, 255));\n LEDColors.add(new Color(\"blue\", 0, 0, 255));\n LEDColors.add(new Color(\"purple\", 128, 0, 128));\n LEDColors.add(new Color(\"magenta\", 255, 0, 255));\n LEDColors.add(new Color(\"pink\", 255, 192, 203));\n }\n public static Map<String, Color> pumpkinColors = new HashMap<>();\n static {\n pumpkinColors.put(\"red\", new Color(\"red\", 255, 0, 0));\n pumpkinColors.put(\"light_blue\", new Color(\"light_blue\", 0, 100, 255));\n }\n\n public static boolean shimmerDetected = false;\n public static boolean betterNetherDetected = false;\n}" }, { "identifier": "CabinetBlock", "path": "src/main/java/io/github/mikip98/content/blocks/cabinet/CabinetBlock.java", "snippet": "public class CabinetBlock extends HorizontalFacingBlock implements Waterloggable, BlockEntityProvider {\n public static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED;\n public static final BooleanProperty OPEN = BooleanProperty.of(\"open\");\n\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(OPEN);\n builder.add(Properties.HORIZONTAL_FACING);\n builder.add(WATERLOGGED);\n }\n\n\n public CabinetBlock(Settings settings) {\n super(settings);\n setDefaultState(getStateManager().getDefaultState()\n .with(OPEN, false)\n .with(Properties.HORIZONTAL_FACING, Direction.SOUTH)\n .with(Properties.WATERLOGGED, false));\n }\n\n\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n\n player.playSound(SoundEvents.BLOCK_BAMBOO_BREAK, 1, 1);\n\n if (world.getBlockState(pos).get(OPEN)){\n if (world.isClient) return ActionResult.SUCCESS;\n Inventory cabinetBlockEntity = (Inventory) world.getBlockEntity(pos);\n\n if (!player.getStackInHand(hand).isEmpty()) {\n\n assert cabinetBlockEntity != null;\n if (!cabinetBlockEntity.getStack(0).isEmpty()) {\n // Give the player the stack in the inventory\n player.getInventory().offerOrDrop(cabinetBlockEntity.getStack(0));\n // Remove the stack from the inventory\n cabinetBlockEntity.removeStack(0);\n }\n\n ItemStack stack = player.getStackInHand(hand).copy();\n\n // Remove the stack from the player's hand\n player.getStackInHand(hand).setCount(stack.getCount() - 1);\n\n stack.setCount(1);\n\n // Put one item from the stack the player is holding into the inventory\n cabinetBlockEntity.setStack(0, stack.copy());\n\n //Update block state?\n world.setBlockState(pos, state.with(OPEN, false));\n world.setBlockState(pos, state.with(OPEN, true));\n\n } else {\n if (player.isSneaking()) {\n // Give the player the stack in the inventory\n assert cabinetBlockEntity != null;\n player.getInventory().offerOrDrop(cabinetBlockEntity.getStack(0));\n // Remove the stack from the inventory\n cabinetBlockEntity.removeStack(0);\n\n //Update block state?\n world.setBlockState(pos, state.with(OPEN, false));\n world.setBlockState(pos, state.with(OPEN, true));\n }\n\n world.setBlockState(pos, state.with(OPEN, false));\n }\n } else {\n world.setBlockState(pos, state.with(OPEN, true));\n }\n\n return ActionResult.SUCCESS;\n }\n\n @Override\n public VoxelShape getOutlineShape(BlockState state, BlockView view, BlockPos pos, ShapeContext context) {\n Direction dir = state.get(FACING);\n boolean open = state.get(OPEN);\n\n if (open) {\n\n switch(dir) {\n case NORTH:\n return VoxelShapes.cuboid(0.0625f, 0.0625f, 0.81252f, 0.9375f, 0.9375f, 1.0f); //open, reverse original, second half finished, to do\n case SOUTH:\n return VoxelShapes.cuboid(0.0625f, 0.0625f, 0.0f, 0.9375f, 0.9375f, 0.18748f); //open, original\n case EAST:\n return VoxelShapes.cuboid(0.0f, 0.0625f, 0.0625f, 0.18748f, 0.9375f, 0.9375f); //open, swap z <-> x\n case WEST:\n return VoxelShapes.cuboid(0.81252f, 0.0625f, 0.0625f, 1.0f, 0.9375f, 0.9375f); //open, reverse + swap\n default:\n return VoxelShapes.fullCube();\n }\n\n } else {\n\n switch(dir) {\n case NORTH:\n return VoxelShapes.combine(VoxelShapes.cuboid(0.0625f, 0.0625f, 0.81252f, 0.9375f, 0.9375f, 1.0f), VoxelShapes.cuboid(0.0625f, 0.0625f, 0.75f, 0.9375f, 0.9375f, 0.81248f), BooleanBiFunction.OR); //reverse original, second half finished, to do\n case SOUTH:\n return VoxelShapes.combine(VoxelShapes.cuboid(0.0625f, 0.0625f, 0.0f, 0.9375f, 0.9375f, 0.18748f), VoxelShapes.cuboid(0.0625f, 0.0625f, 0.18752f, 0.9375f, 0.9375f, 0.25f), BooleanBiFunction.OR); //original\n case EAST:\n return VoxelShapes.combine(VoxelShapes.cuboid(0.0f, 0.0625f, 0.0625f, 0.18748f, 0.9375f, 0.9375f), VoxelShapes.cuboid(0.18752f, 0.0625f, 0.0625f, 0.25f, 0.9375f, 0.9375f), BooleanBiFunction.OR); //swap z <-> x\n case WEST:\n return VoxelShapes.combine(VoxelShapes.cuboid(0.81252f, 0.0625f, 0.0625f, 1.0f, 0.9375f, 0.9375f), VoxelShapes.cuboid(0.75f, 0.0625f, 0.0625f, 0.81248f, 0.9375f, 0.9375f), BooleanBiFunction.OR); //reverse + swap\n default:\n return VoxelShapes.fullCube();\n }\n }\n }\n\n @Override\n public BlockState getPlacementState(ItemPlacementContext ctx) {\n return this.getDefaultState()\n .with(Properties.HORIZONTAL_FACING, ctx.getHorizontalPlayerFacing().getOpposite())\n .with(Properties.WATERLOGGED, ctx.getWorld().getFluidState(ctx.getBlockPos()).getFluid() == Fluids.WATER);\n }\n\n @Override\n public FluidState getFluidState(BlockState state) {\n return state.get(WATERLOGGED) ? Fluids.WATER.getStill(false) : Fluids.EMPTY.getDefaultState();\n }\n\n @Override\n public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {\n if (state.getBlock() != newState.getBlock()) {\n BlockEntity blockEntity = world.getBlockEntity(pos);\n if (blockEntity instanceof CabinetBlockEntity cabinetEntity) {\n // Handle item drops and block entity cleanup here\n DefaultedList<ItemStack> inventory = cabinetEntity.getItems();\n for (ItemStack stack : inventory) {\n if (!stack.isEmpty()) {\n Block.dropStack(world, pos, stack);\n }\n }\n }\n super.onStateReplaced(state, world, pos, newState, moved);\n }\n }\n\n\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new CabinetBlockEntity(pos, state);\n }\n}" }, { "identifier": "IlluminatedCabinetBlock", "path": "src/main/java/io/github/mikip98/content/blocks/cabinet/IlluminatedCabinetBlock.java", "snippet": "public class IlluminatedCabinetBlock extends CabinetBlock {\n\n public IlluminatedCabinetBlock(Settings settings) { super(settings); }\n\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new IlluminatedCabinetBlockEntity(pos, state);\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/io/github/mikip98/HumilityAFM.java", "snippet": "public static final String MOD_ID = \"humility-afm\";" } ]
import io.github.mikip98.config.ModConfig; import io.github.mikip98.content.blocks.cabinet.CabinetBlock; import io.github.mikip98.content.blocks.cabinet.IlluminatedCabinetBlock; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.minecraft.block.Block; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroups; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.util.Identifier; import static io.github.mikip98.HumilityAFM.MOD_ID;
3,310
package io.github.mikip98.helpers; public class CabinetBlockHelper { public CabinetBlockHelper() { throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerCabinetBlockVariants()\" instead!"); } private static final float CabinetBlockStrength = 2.0f; public static String[] cabinetBlockVariantsNames; public static Block[] cabinetBlockVariants; public static Item[] cabinetBlockItemVariants; public static Block[] illuminatedCabinetBlockVariants; public static Item[] illuminatedCabinetBlockItemVariants; public static void init() { final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque().sounds(BlockSoundGroup.WOOD); final FabricBlockSettings IlluminatedCabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque().sounds(BlockSoundGroup.WOOD).luminance(2); //Create cabinet variants short cabinetBlockVariantsCount = (short) (MainHelper.vanillaWoodTypes.length * MainHelper.vanillaWoolTypes.length); if (ModConfig.betterNetherDetected) { cabinetBlockVariantsCount += (short) (MainHelper.betterNetherWoodTypes.length * MainHelper.vanillaWoolTypes.length); } cabinetBlockVariantsNames = new String[cabinetBlockVariantsCount]; cabinetBlockVariants = new Block[cabinetBlockVariantsCount]; cabinetBlockItemVariants = new Item[cabinetBlockVariantsCount]; illuminatedCabinetBlockVariants = new Block[cabinetBlockVariantsCount]; illuminatedCabinetBlockItemVariants = new Item[cabinetBlockVariantsCount]; short i = 0; for (String woodType : MainHelper.vanillaWoodTypes) { for (String woolType : MainHelper.vanillaWoolTypes) { String cabinetBlockVariantName = woodType + "_" + woolType; cabinetBlockVariantsNames[i] = cabinetBlockVariantName; //LOGGER.info("Creating cabinet block variant: " + cabinetBlockVariantsNames[i]); // Create cabinet block variant cabinetBlockVariants[i] = new CabinetBlock(CabinetBlockSettings); // Create cabinet block variant item cabinetBlockItemVariants[i] = new BlockItem(cabinetBlockVariants[i], new FabricItemSettings()); // Create illuminated cabinet block variant
package io.github.mikip98.helpers; public class CabinetBlockHelper { public CabinetBlockHelper() { throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerCabinetBlockVariants()\" instead!"); } private static final float CabinetBlockStrength = 2.0f; public static String[] cabinetBlockVariantsNames; public static Block[] cabinetBlockVariants; public static Item[] cabinetBlockItemVariants; public static Block[] illuminatedCabinetBlockVariants; public static Item[] illuminatedCabinetBlockItemVariants; public static void init() { final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque().sounds(BlockSoundGroup.WOOD); final FabricBlockSettings IlluminatedCabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque().sounds(BlockSoundGroup.WOOD).luminance(2); //Create cabinet variants short cabinetBlockVariantsCount = (short) (MainHelper.vanillaWoodTypes.length * MainHelper.vanillaWoolTypes.length); if (ModConfig.betterNetherDetected) { cabinetBlockVariantsCount += (short) (MainHelper.betterNetherWoodTypes.length * MainHelper.vanillaWoolTypes.length); } cabinetBlockVariantsNames = new String[cabinetBlockVariantsCount]; cabinetBlockVariants = new Block[cabinetBlockVariantsCount]; cabinetBlockItemVariants = new Item[cabinetBlockVariantsCount]; illuminatedCabinetBlockVariants = new Block[cabinetBlockVariantsCount]; illuminatedCabinetBlockItemVariants = new Item[cabinetBlockVariantsCount]; short i = 0; for (String woodType : MainHelper.vanillaWoodTypes) { for (String woolType : MainHelper.vanillaWoolTypes) { String cabinetBlockVariantName = woodType + "_" + woolType; cabinetBlockVariantsNames[i] = cabinetBlockVariantName; //LOGGER.info("Creating cabinet block variant: " + cabinetBlockVariantsNames[i]); // Create cabinet block variant cabinetBlockVariants[i] = new CabinetBlock(CabinetBlockSettings); // Create cabinet block variant item cabinetBlockItemVariants[i] = new BlockItem(cabinetBlockVariants[i], new FabricItemSettings()); // Create illuminated cabinet block variant
illuminatedCabinetBlockVariants[i] = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings);
2
2023-10-30 12:11:22+00:00
4k
ewkchong/kafkaesque
src/test/java/SegmentTest.java
[ { "identifier": "LogConfig", "path": "src/main/java/log/LogConfig.java", "snippet": "public class LogConfig {\n\tprivate long segmentSizeBytes;\n\tprivate String storeDir;\n\n\tpublic LogConfig(long segmentSizeBytes, String storeDir) {\n\t\tthis.segmentSizeBytes = segmentSizeBytes;\n\t\tthis.storeDir = storeDir;\n\t}\n\n\tpublic long getSegmentSizeBytes() {\n\t\treturn segmentSizeBytes;\n\t}\n\t\n\tpublic String getStoreDir() {\n\t\treturn storeDir;\n\t}\n}" }, { "identifier": "Segment", "path": "src/main/java/log/Segment.java", "snippet": "public class Segment {\n\tprivate File file;\n\tprivate long baseOffset;\n\tprivate long nextOffset;\n\tprivate RandomAccessFile raf;\n\tprivate LogConfig logConfig;\n\tprivate ArrayList<Integer> index;\n\tprivate int baseIndex;\n\n\tpublic Segment(String baseDirectory, long baseOffset, int baseIndex, LogConfig config) {\n\t\t// create a new file in the baseDirectory\n\t\tthis.file = new File(baseDirectory, String.valueOf(baseOffset) + \".store\");\n\t\t// allow access to file as if it were a byte array\n\t\ttry {\n\t\t\tthis.file.createNewFile();\n\t\t\tthis.raf = new RandomAccessFile(file, \"rw\");\n\t\t} catch (FileNotFoundException e) {\n\t\t\tSystem.err.println(\"Could not find file: \" + file.getAbsolutePath());\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"Could not create file: \" + file.getAbsolutePath());\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tthis.baseOffset = baseOffset;\n\t\tthis.nextOffset = baseOffset;\n\t\tthis.baseIndex = baseIndex;\n\t\tthis.logConfig = config;\n\t\tthis.index = new ArrayList<Integer>();\n\t}\n\n\n\t/**\n\t * Appends record to segment and returns offset of Record\n\t *\n\t * @param record\n\t * @return offset of record\n\t */\n\tpublic long append(Record record) throws SegmentFullException {\n\t\tif (!canFit(record.length())) {\n\t\t\tthrow new SegmentFullException();\n\t\t}\n\n\t\t// append serialized version of record to end of file\n\t\tbyte[] data = record.serialize();\n\n\t\ttry {\n\t\t\t// ensure file pointer is at the end\n\t\t\traf.seek(nextOffset - baseOffset);\n\t\t\traf.write(data);\n\t\t\tindex.add((int) nextOffset);\n\t\t\tnextOffset += data.length;\n\t\t} catch (IOException e) {\n\t\t\tSystem.out.println(\"Segment Append: Could not write to file: \" + file.getAbsolutePath());\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Reads record at logical offset\n\t *\n\t * @param index index of record\n\t * @return\t\t record at offset\n\t */\n\tpublic Record read(long index) {\n\t\t// TODO: do something if offset is out of bounds\n\t\ttry {\n\t\t\traf.seek(this.index.get((int) index) - baseOffset);\n\t\t\t// int recordLength = raf.readInt();\n\t\t\t\n\t\t\t// read the first 4 bytes of the record\n\t\t\tbyte[] recordLengthBytes = new byte[4];\n\t\t\traf.read(recordLengthBytes);\n\t\t\tint recordLength = (recordLengthBytes[0] << 24) | (recordLengthBytes[1] << 16) | (recordLengthBytes[2] << 8) | (recordLengthBytes[3]);\n\n\t\t\tbyte[] data = new byte[recordLength];\n\n\t\t\t// add the first 4 bytes to the data array\n\t\t\tdata[0] = recordLengthBytes[0];\n\t\t\tdata[1] = recordLengthBytes[1];\n\t\t\tdata[2] = recordLengthBytes[2];\n\t\t\tdata[3] = recordLengthBytes[3];\n\n\t\t\traf.read(data, 4, recordLength - 4);\n\t\t\treturn Record.deserialize(data);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (Exception e) {\n\t\t\t// probably an error in deserialization\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Closes the segment, releasing any resources associated with the file\n\t *\n\t * @return void\n\t */\n\tpublic void close() {\n\t\ttry {\n\t\t\traf.close();\n\t\t\tfile.delete();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic long getNextOffset() {\n\t\treturn nextOffset;\n\t}\n\n\tpublic int getBaseIndex() {\n\t\treturn baseIndex;\n\t}\n\n\tpublic int getSize() {\n\t\treturn index.size();\n\t}\n\n\t/**\n\t * Returns true if record can fit in segment, false otherwise\n\t * @param len\n\t * @return true if record can fit in segment, false otherwise\n\t */\n\tprivate boolean canFit(int len) {\n\t\treturn nextOffset - baseOffset + len <= logConfig.getSegmentSizeBytes();\n\t}\n\n}" }, { "identifier": "Message", "path": "src/main/java/messages/Message.java", "snippet": "public class Message implements Record {\n public int identifier;\n public Topic topic;\n // content is json format\n // Depending on topic, attributes of content will differ\n // might need serializer/deserializer to get driver/rider id\n public String content;\n\n public Message(int identifier, Topic topic, String content) {\n this.identifier = identifier;\n this.topic = topic;\n this.content = content;\n }\n \n\tpublic int length() {\n\t\tint topicLength = topic.toString().getBytes().length;\n\t\treturn 4 + 4 + 4 + topicLength + content.getBytes().length;\n\t}\n\t\n\t/**\n\t * serializes the message into a byte array\n\t * @return the serialized message as a byte array\n\t */\n\tpublic byte[] serialize() {\n\t\ttry {\n\t\t\tbyte[] topicBytes = topic.toString().getBytes();\n\t\t\tint topicLength = topicBytes.length;\n\n\t\t\tbyte[] data = new byte[4 + 4 + 4 + topicLength + content.getBytes().length];\n\n\t\t\t// write length to byte array\n\t\t\tdata[0] = (byte) (length() >> 24);\n\t\t\tdata[1] = (byte) (length() >> 16);\n\t\t\tdata[2] = (byte) (length() >> 8);\n\t\t\tdata[3] = (byte) (length());\n\n\t\t\t// write int indentifier to byte array\n\t\t\tdata[4] = (byte) (identifier >> 24);\n\t\t\tdata[5] = (byte) (identifier >> 16);\n\t\t\tdata[6] = (byte) (identifier >> 8);\n\t\t\tdata[7] = (byte) (identifier);\n\n\t\t\t// write length of topic string to byte array\n\t\t\tdata[8] = (byte) (topicBytes.length >> 24);\n\t\t\tdata[9] = (byte) (topicBytes.length >> 16);\n\t\t\tdata[10] = (byte) (topicBytes.length >> 8);\n\t\t\tdata[11] = (byte) (topicBytes.length);\n\n\t\t\t// write topic string to byte array\n\t\t\tfor (int i = 0; i < topicBytes.length; i++) {\n\t\t\t\tdata[i + 12] = topicBytes[i];\n\t\t\t}\n\n\t\t\t// write the content to byte array\n\t\t\tbyte[] contentBytes = content.getBytes(\"UTF-8\");\n\t\t\tfor (int i = 0; i < contentBytes.length; i++) {\n\t\t\t\tdata[i + 4 + 4 + 4 + topicBytes.length] = contentBytes[i];\n\t\t\t}\n\n\t\t\treturn data;\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "Topic", "path": "src/main/java/types/Topic.java", "snippet": "public enum Topic {\n DRIVER_DATA,\n RIDER_DATA,\n RIDER_REQUESTS_RIDE,\n DRIVER_REQUESTS_RIDE,\n RIDER_ACCEPTS_RIDE\n}" } ]
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import log.LogConfig; import log.Segment; import messages.Message; import types.Topic;
2,255
@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SegmentTest { Segment segment; LogConfig config = new LogConfig(100, "segmentTest"); @BeforeAll public static void setUpBeforeClass() throws Exception { File dataDir = new File("data"); if (!dataDir.exists()) { dataDir.mkdir(); } File dataSegmentDir = new File("data/segmentTest"); if (!dataSegmentDir.exists()) { dataSegmentDir.mkdir(); } } @BeforeEach public void setUp() { // init test segment with max 100 byte file size if (segment != null) { segment.close(); } try { segment = new Segment("data/segmentTest", 0, 0, config); } catch (Exception e) { fail(); } } @AfterEach public void tearDown() throws Exception { segment.close(); } @AfterAll public void tearDownAfterClass() throws Exception { File dataDir = new File("data/segmentTest"); if (dataDir.exists()) { dataDir.delete(); } } @Test public void testAppend() {
@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SegmentTest { Segment segment; LogConfig config = new LogConfig(100, "segmentTest"); @BeforeAll public static void setUpBeforeClass() throws Exception { File dataDir = new File("data"); if (!dataDir.exists()) { dataDir.mkdir(); } File dataSegmentDir = new File("data/segmentTest"); if (!dataSegmentDir.exists()) { dataSegmentDir.mkdir(); } } @BeforeEach public void setUp() { // init test segment with max 100 byte file size if (segment != null) { segment.close(); } try { segment = new Segment("data/segmentTest", 0, 0, config); } catch (Exception e) { fail(); } } @AfterEach public void tearDown() throws Exception { segment.close(); } @AfterAll public void tearDownAfterClass() throws Exception { File dataDir = new File("data/segmentTest"); if (dataDir.exists()) { dataDir.delete(); } } @Test public void testAppend() {
Message msg = new Message(1, Topic.DRIVER_DATA, "blah");
3
2023-10-30 21:20:16+00:00
4k
admin4j/admin4j-dict
dict-excel/src/main/java/com/admin4j/dict/excel/autoconfigure/DictExcelAutoconfigure.java
[ { "identifier": "DictCacheManager", "path": "dict-core/src/main/java/com/admin4j/dict/core/DictCacheManager.java", "snippet": "public interface DictCacheManager {\n\n\n /**\n * 开始缓存。对列表的dict 注解数据进行缓存\n *\n * @param data\n * @throws IllegalAccessException\n */\n default void startCache(List<?> data) throws IllegalAccessException {\n if (ObjectUtils.isEmpty(data)) {\n return;\n }\n Object o = data.get(0);\n startCache(data, o.getClass());\n }\n\n /**\n * 开始缓存。对列表的dict 注解数据进行缓存\n * 请保证 data 中的元素类型 和 TClass 一致\n */\n void startCache(List<?> data, Class<?> tClass) throws IllegalAccessException;\n\n /**\n * 根据字段开始翻译开始翻译数据\n */\n <T> void startCache(List<T> data, Field field) throws IllegalAccessException;\n\n /**\n * 清理缓存\n */\n void clearCache();\n\n}" }, { "identifier": "CachedDictProviderManager", "path": "dict-core/src/main/java/com/admin4j/dict/core/impl/CachedDictProviderManager.java", "snippet": "public class CachedDictProviderManager extends DefaultDictProviderManager implements DictCacheManager {\n\n /**\n * 字典key/value缓存\n */\n private static final ThreadLocal<Map<Field, Map<Object, String>>> THREAD_LOCAL_CACHE = new ThreadLocal<>();\n /**\n * 读缓存\n */\n private static final ThreadLocal<Map<Field, Map<Object, Object>>> THREAD_LOCAL_READ_CACHE = new ThreadLocal<>();\n /**\n * 缓存 字典 字段\n * key model 对象\n * value 该model的所有 带有 @Dict 的字段\n */\n private static final Map<Class<?>, List<Field>> DICT_FIELDS = new ConcurrentHashMap<>(64);\n /**\n * 批量读取数\n */\n private static final int BATCH_NUM = 500;\n\n /**\n * 缓存结果值\n *\n * @return\n */\n @Override\n public Object dictCode(Field field, String strategy, String dictType, String dictLabel) {\n\n Map<Field, Map<Object, Object>> fieldMapMap = THREAD_LOCAL_READ_CACHE.get();\n if (fieldMapMap == null) {\n fieldMapMap = new HashMap<>(32);\n THREAD_LOCAL_READ_CACHE.set(fieldMapMap);\n }\n Map<Object, Object> codeMap = fieldMapMap.computeIfAbsent(field, k -> new HashMap<>(32));\n\n return codeMap.computeIfAbsent(dictLabel, key -> super.dictCode(field, strategy, dictType, dictLabel));\n }\n\n /**\n * 根据dictCode获取字典显示值\n *\n * @param field 字段\n * @param strategy 字典策略\n * @param dictType 字典分类\n * @param dictCode 字典code\n * @return 获取字典显示值\n */\n @Override\n public String dictLabel(Field field, String strategy, String dictType, Object dictCode) {\n Map<Field, Map<Object, String>> fieldMapMap = THREAD_LOCAL_CACHE.get();\n if (fieldMapMap == null) {\n fieldMapMap = new HashMap<>(32);\n THREAD_LOCAL_CACHE.set(fieldMapMap);\n }\n\n Map<Object, String> labelMap = fieldMapMap.computeIfAbsent(field, k -> new HashMap<>(32));\n return labelMap.computeIfAbsent(dictCode, key -> super.dictLabel(field, strategy, dictType, dictCode));\n }\n\n /**\n * 开始翻译数据\n */\n @Override\n public void startCache(List<?> data, Class<?> tClass) throws IllegalAccessException {\n\n List<Field> fields = dictFields(tClass);\n for (Field field : fields) {\n\n startCache(data, field);\n }\n }\n\n /**\n * 缓存/获取该Class所有的带有 @Dict 注解的字段\n *\n * @param tClass\n * @param <T>\n * @return\n */\n private <T> List<Field> dictFields(Class<T> tClass) {\n\n return DICT_FIELDS.computeIfAbsent(tClass, key -> {\n\n Field[] fields = tClass.getDeclaredFields();\n List<Field> fs = new ArrayList<>();\n for (Field field : fields) {\n boolean annotationPresent = field.isAnnotationPresent(Dict.class);\n if (annotationPresent) {\n fs.add(field);\n }\n }\n\n // 查找父类\n Class<? super T> superclass = tClass.getSuperclass();\n while (superclass != null && superclass != Object.class) {\n fields = superclass.getDeclaredFields();\n for (Field field : fields) {\n boolean annotationPresent = field.isAnnotationPresent(Dict.class);\n if (annotationPresent) {\n fs.add(field);\n }\n }\n\n superclass = superclass.getSuperclass();\n }\n return fs;\n });\n }\n\n /**\n * 开始翻译数据\n */\n @Override\n public <T> void startCache(List<T> data, Field field) throws IllegalAccessException {\n\n if (ObjectUtils.isEmpty(data)) {\n return;\n }\n Map<Field, Map<Object, String>> dictCache = THREAD_LOCAL_CACHE.get();\n if (dictCache == null) {\n dictCache = new HashMap<>();\n }\n\n Dict dict = field.getAnnotation(Dict.class);\n\n field.setAccessible(true);\n // 提取key数据\n Collection<Object> codes = new HashSet<>(data.size());\n // 所有的结果缓存\n Map<Object, String> dictFieldCacheAll = null;\n for (T row : data) {\n\n Object code = field.get(row);\n if (code instanceof Collection) {\n codes.addAll((Collection<?>) code);\n } else {\n codes.add(code);\n }\n if (codes.size() >= BATCH_NUM) {\n Map<Object, String> dictFieldCache = super.dictLabels(field, dict.dictStrategy(), dict.dictType(), codes);\n if (dictFieldCacheAll == null) {\n dictFieldCacheAll = new HashMap<>(dictFieldCache.size());\n dictFieldCacheAll.putAll(dictFieldCache);\n }\n codes.clear();\n }\n }\n\n if (dictFieldCacheAll == null) {\n dictFieldCacheAll = super.dictLabels(field, dict.dictStrategy(), dict.dictType(), codes);\n } else {\n Map<Object, String> dictFieldCache = super.dictLabels(field, dict.dictStrategy(), dict.dictType(), codes);\n dictFieldCacheAll.putAll(dictFieldCache);\n }\n dictCache.put(field, dictFieldCacheAll);\n THREAD_LOCAL_CACHE.set(dictCache);\n }\n\n public String dictLabel(Field field, Object code) {\n if (THREAD_LOCAL_CACHE.get().get(field) == null) {\n return null;\n }\n\n if (code instanceof Collection) {\n List<String> strings = dictLabels(field, (Collection) code);\n DictList dictList = field.getAnnotation(DictList.class);\n return StringUtils.join(strings, dictList == null ? \",\" : dictList.separator());\n }\n return THREAD_LOCAL_CACHE.get().get(field).get(code);\n }\n\n public List<String> dictLabels(Field field, Collection<Object> codes) {\n if (THREAD_LOCAL_CACHE.get().get(field) == null) {\n return Collections.emptyList();\n }\n\n DictList dictList = field.getAnnotation(DictList.class);\n boolean unique = dictList == null || dictList.unique();\n boolean filterBlank = dictList == null || dictList.filterBlank();\n // List<String> labels = dictList == null || dictList.unique() ? new ArrayList<>(codes.size()) : new LinkedHashSet<>(codes.size());\n List<String> labels = new ArrayList<>(codes.size());\n for (Object code : codes) {\n\n String label = THREAD_LOCAL_CACHE.get().get(field).get(code);\n if (filterBlank) {\n if (StringUtils.isBlank(label)) {\n continue;\n }\n }\n if (unique) {\n if (!labels.contains(label)) {\n labels.add(label);\n }\n } else {\n labels.add(label);\n }\n }\n return labels;\n }\n\n @Override\n public void clearCache() {\n THREAD_LOCAL_CACHE.remove();\n THREAD_LOCAL_READ_CACHE.remove();\n }\n}" }, { "identifier": "DictExcelReadListener", "path": "dict-excel/src/main/java/com/admin4j/dict/excel/DictExcelReadListener.java", "snippet": "@AllArgsConstructor\npublic class DictExcelReadListener implements ReadListener<Object> {\n\n\n private final CachedDictProviderManager cachedDictProviderManager;\n\n @Override\n public void doAfterAllAnalysed(AnalysisContext analysisContext) {\n cachedDictProviderManager.clearCache();\n }\n\n @Override\n public void onException(Exception exception, AnalysisContext context) throws Exception {\n\n cachedDictProviderManager.clearCache();\n }\n\n @Override\n public void invoke(Object o, AnalysisContext analysisContext) {\n\n }\n}" }, { "identifier": "DictEnhanceService", "path": "dict-excel/src/main/java/com/admin4j/dict/excel/enhance/DictEnhanceService.java", "snippet": "@Order(1)\npublic class DictEnhanceService implements ExcelEnhanceService {\n\n /**\n * Convert excel objects to Java objects\n * Params:\n * cellData – Excel cell data.NotNull. contentProperty – Content property.Nullable. globalConfiguration – Global configuration.NotNull.\n * Returns:\n * Data to put into a Java object\n * Throws:\n * Exception – Exception.\n *\n * @param cellData\n * @param contentProperty\n * @param globalConfiguration\n */\n @Override\n public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {\n if (cellData.getStringValue() == null) {\n return null;\n }\n Field field = contentProperty.getField();\n Dict dict = field.getAnnotation(Dict.class);\n if (dict == null) {\n return null;\n } else {\n if (Collection.class.isAssignableFrom(field.getType())) {\n\n boolean isList = List.class.isAssignableFrom(field.getType());\n DictList dictList = field.getAnnotation(DictList.class);\n String[] split = StringUtils.split(cellData.getStringValue(), dictList == null ? \",\" : dictList.separator());\n if (split.length == 1) {\n Object dictCode = SpringUtils.getBean(DictProviderManager.class).dictCode(field, dict.dictStrategy(), dict.dictType(), cellData.getStringValue());\n return isList ? Collections.singletonList(dictCode) : Collections.singleton(dictCode);\n }\n\n Collection<Object> splitList = isList ? new ArrayList<>(split.length) : new HashSet<>(split.length);\n for (int i = 0; i < split.length; i++) {\n Object dictCode = SpringUtils.getBean(DictProviderManager.class).dictCode(field, dict.dictStrategy(), dict.dictType(), split[i]);\n\n splitList.add(dictCode);\n }\n\n return splitList;\n } else {\n Object dictCode = SpringUtils.getBean(DictProviderManager.class).dictCode(field, dict.dictStrategy(), dict.dictType(), cellData.getStringValue());\n if (dictCode == null) {\n return null;\n }\n return ObjectCast.cast(dictCode, field.getType());\n }\n }\n }\n\n @Override\n public String convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {\n Field field = contentProperty.getField();\n Dict dict = field.getAnnotation(Dict.class);\n if (dict == null) {\n return null;\n } else {\n\n String label = SpringUtils.getBean(DictProviderManager.class).dictLabel(field, dict.dictStrategy(), dict.dictType(), value);\n return StringUtils.defaultString(label);\n }\n }\n}" }, { "identifier": "SensitivityEnhanceService", "path": "dict-excel/src/main/java/com/admin4j/dict/excel/enhance/SensitivityEnhanceService.java", "snippet": "@Order(2)\npublic class SensitivityEnhanceService implements ExcelEnhanceService {\n\n /**\n * Convert excel objects to Java objects\n * Params:\n * cellData – Excel cell data.NotNull. contentProperty – Content property.Nullable. globalConfiguration – Global configuration.NotNull.\n * Returns:\n * Data to put into a Java object\n * Throws:\n * Exception – Exception.\n *\n * @param cellData\n * @param contentProperty\n * @param globalConfiguration\n */\n @Override\n public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {\n return null;\n }\n\n @Override\n public String convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {\n Field field = contentProperty.getField();\n Sensitivity sensitivity = field.getAnnotation(Sensitivity.class);\n if (sensitivity == null) {\n return null;\n } else {\n return sensitivity.strategy().desensitizer().apply((String) value);\n }\n }\n}" } ]
import com.admin4j.dict.core.DictCacheManager; import com.admin4j.dict.core.impl.CachedDictProviderManager; import com.admin4j.dict.excel.DictExcelReadListener; import com.admin4j.dict.excel.enhance.DictEnhanceService; import com.admin4j.dict.excel.enhance.SensitivityEnhanceService; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean;
3,340
package com.admin4j.dict.excel.autoconfigure; /** * @author andanyang * @since 2022/10/25 16:55 */ public class DictExcelAutoconfigure { @Bean @ConditionalOnBean(CachedDictProviderManager.class)
package com.admin4j.dict.excel.autoconfigure; /** * @author andanyang * @since 2022/10/25 16:55 */ public class DictExcelAutoconfigure { @Bean @ConditionalOnBean(CachedDictProviderManager.class)
DictExcelReadListener dictExcelReadListener(CachedDictProviderManager cachedDictProviderManager) {
2
2023-10-26 08:36:17+00:00
4k
Nolij/Zume
src/main/java/dev/nolij/zume/FabricZumeBootstrapper.java
[ { "identifier": "Zume", "path": "common/src/main/java/dev/nolij/zume/common/Zume.java", "snippet": "public class Zume {\n\t\n\tpublic static final String MOD_ID = \"zume\";\n\tpublic static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\tpublic static final String CONFIG_FILE_NAME = MOD_ID + \".json5\";\n\t\n\tpublic static ZumeVariant ZUME_VARIANT = null;\n\t\n\tprivate static final ClassLoader classLoader = Zume.class.getClassLoader();\n\tpublic static void calculateZumeVariant() {\n\t\tif (ZUME_VARIANT != null)\n\t\t\treturn;\n\t\t\n\t\tvar connectorPresent = false;\n\t\ttry {\n\t\t\tClass.forName(\"dev.su5ed.sinytra.connector.service.ConnectorLoaderService\");\n\t\t\tconnectorPresent = true;\n\t\t} catch (ClassNotFoundException ignored) {}\n\t\t\n\t\tif (!connectorPresent && \n\t\t\tclassLoader.getResource(\"net/fabricmc/fabric/api/client/keybinding/v1/KeyBindingHelper.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.MODERN;\n\t\telse if (classLoader.getResource(\"net/legacyfabric/fabric/api/client/keybinding/v1/KeyBindingHelper.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.LEGACY;\n\t\telse if (classLoader.getResource(\"net/modificationstation/stationapi/api/client/event/option/KeyBindingRegisterEvent.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.PRIMITIVE;\n\t\telse if (classLoader.getResource(\"cpw/mods/fml/client/registry/ClientRegistry.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.ARCHAIC_FORGE;\n\t\telse if (classLoader.getResource(\"net/minecraftforge/oredict/OreDictionary.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.VINTAGE_FORGE;\n\t\telse if (classLoader.getResource(\"net/neoforged/neoforge/common/NeoForge.class\") != null)\n\t\t\tZUME_VARIANT = ZumeVariant.NEOFORGE;\n\t\telse {\n\t\t\ttry {\n\t\t\t\tfinal Class<?> forgeVersionClass = Class.forName(\"net.minecraftforge.versions.forge.ForgeVersion\");\n\t\t\t\tfinal Method getVersionMethod = forgeVersionClass.getMethod(\"getVersion\");\n\t\t\t\tfinal String forgeVersion = (String) getVersionMethod.invoke(null);\n\t\t\t\tfinal int major = Integer.parseInt(forgeVersion.substring(0, forgeVersion.indexOf('.')));\n\t\t\t\tif (major > 40)\n\t\t\t\t\tZUME_VARIANT = ZumeVariant.LEXFORGE;\n\t\t\t\telse if (major > 36)\n\t\t\t\t\tZUME_VARIANT = ZumeVariant.LEXFORGE18;\n\t\t\t\telse \n\t\t\t\t\tZUME_VARIANT = ZumeVariant.LEXFORGE16;\n\t\t\t} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {}\n\t\t}\n\t}\n\t\n\tpublic static IZumeProvider ZUME_PROVIDER;\n\t\n\tpublic static ZumeConfig CONFIG;\n\tpublic static File CONFIG_FILE;\n\tprivate static double inverseSmoothness = 1D;\n\t\n\tpublic static void init(final IZumeProvider zumeProvider, final File configFile) {\n\t\tif (ZUME_PROVIDER != null)\n\t\t\tthrow new AssertionError(\"Zume already initialized!\");\n\t\t\n\t\tZUME_PROVIDER = zumeProvider;\n\t\tCONFIG_FILE = configFile;\n\t\t\n\t\tZumeConfig.create(configFile, config -> {\n\t\t\tCONFIG = config;\n\t\t\tinverseSmoothness = 1D / CONFIG.zoomSmoothnessMs;\n\t\t});\n\t}\n\t\n\tpublic static void openConfigFile() throws IOException {\n\t\tDesktop.getDesktop().open(Zume.CONFIG_FILE);\n\t}\n\t\n\tprivate static double fromZoom = -1D;\n\tprivate static double zoom = 1D;\n\tprivate static long tweenStart = 0L;\n\tprivate static long tweenEnd = 0L;\n\t\n\tprivate static double getZoom() {\n\t\tif (tweenEnd != 0L && CONFIG.zoomSmoothnessMs != 0) {\n\t\t\tfinal long timestamp = System.currentTimeMillis();\n\t\t\t\n\t\t\tif (tweenEnd >= timestamp) {\n\t\t\t\tfinal long delta = timestamp - tweenStart;\n\t\t\t\tfinal double progress = 1 - delta * inverseSmoothness;\n\t\t\t\t\n\t\t\t\tvar easedProgress = progress;\n\t\t\t\tfor (var i = 1; i < CONFIG.easingExponent; i++)\n\t\t\t\t\teasedProgress *= progress;\n\t\t\t\teasedProgress = 1 - easedProgress;\n\t\t\t\t\n\t\t\t\treturn fromZoom + ((zoom - fromZoom) * easedProgress);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn zoom;\n\t}\n\t\n\tpublic static double transformFOV(final double original) {\n\t\tvar zoom = getZoom();\n\t\t\n\t\tif (CONFIG.useQuadratic) {\n\t\t\tzoom *= zoom;\n\t\t}\n\t\t\n\t\treturn CONFIG.minFOV + ((Math.max(CONFIG.maxFOV, original) - CONFIG.minFOV) * zoom);\n\t}\n\t\n\tpublic static boolean transformCinematicCamera(final boolean original) {\n\t\tif (Zume.CONFIG.enableCinematicZoom && ZUME_PROVIDER.isZoomPressed()) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn original;\n\t}\n\t\n\tpublic static double transformMouseSensitivity(final double original) {\n\t\tif (!ZUME_PROVIDER.isZoomPressed())\n\t\t\treturn original;\n\t\t\n\t\tfinal double zoom = getZoom();\n\t\tvar result = original;\n\t\t\n\t\tresult *= CONFIG.mouseSensitivityFloor + (zoom * (1 - CONFIG.mouseSensitivityFloor));\n\t\t\n\t\treturn result;\n\t}\n\t\n\tprivate static int sign(final int input) {\n\t\treturn input >> (Integer.SIZE - 1) | 1;\n\t}\n\t\n\tpublic static boolean transformHotbarScroll(final int scrollDelta) {\n\t\tif (Zume.CONFIG.enableZoomScrolling)\n\t\t\tZume.scrollDelta += sign(scrollDelta);\n\t\t\n\t\treturn !(Zume.CONFIG.enableZoomScrolling && ZUME_PROVIDER.isZoomPressed());\n\t}\n\t\n\tprivate static double clamp(final double value, final double min, final double max) {\n\t\treturn Math.max(Math.min(value, max), min);\n\t}\n\t\n\tprivate static void setZoom(final double targetZoom) {\n\t\tif (CONFIG.zoomSmoothnessMs == 0) {\n\t\t\tsetZoomNoTween(targetZoom);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfinal double currentZoom = getZoom();\n\t\ttweenStart = System.currentTimeMillis();\n\t\ttweenEnd = tweenStart + CONFIG.zoomSmoothnessMs;\n\t\tfromZoom = currentZoom;\n\t\tzoom = clamp(targetZoom, 0D, 1D);\n\t}\n\t\n\tprivate static void setZoomNoTween(final double targetZoom) {\n\t\ttweenStart = 0L;\n\t\ttweenEnd = 0L;\n\t\tfromZoom = -1D;\n\t\tzoom = clamp(targetZoom, 0D, 1D);\n\t}\n\t\n\tpublic static boolean isActive() {\n\t\tif (ZUME_PROVIDER == null)\n\t\t\treturn false;\n\t\t\n\t\treturn ZUME_PROVIDER.isZoomPressed() || (zoom == 1D && tweenEnd != 0L && System.currentTimeMillis() < tweenEnd);\n\t}\n\t\n\tpublic static int scrollDelta = 0;\n\tprivate static boolean wasZooming = false;\n\tprivate static long prevTimestamp;\n\t\n\tpublic static void render() {\n\t\tfinal long timestamp = System.currentTimeMillis();\n\t\tfinal boolean zooming = ZUME_PROVIDER.isZoomPressed();\n\t\t\n\t\tif (zooming) {\n\t\t\tif (!wasZooming) {\n\t\t\t\tZUME_PROVIDER.onZoomActivate();\n\t\t\t\tsetZoom(CONFIG.defaultZoom);\n\t\t\t}\n\t\t\t\n\t\t\tfinal long timeDelta = timestamp - prevTimestamp;\n\t\t\t\n\t\t\tif (CONFIG.enableZoomScrolling && scrollDelta != 0) {\n\t\t\t\tsetZoom(zoom - scrollDelta * CONFIG.zoomSpeed * 4E-3D);\n\t\t\t} else if (ZUME_PROVIDER.isZoomInPressed() ^ ZUME_PROVIDER.isZoomOutPressed()) {\n\t\t\t\tfinal double interpolatedIncrement = CONFIG.zoomSpeed * 1E-4D * timeDelta;\n\t\t\t\t\n\t\t\t\tif (ZUME_PROVIDER.isZoomInPressed())\n\t\t\t\t\tsetZoom(zoom - interpolatedIncrement);\n\t\t\t\telse if (ZUME_PROVIDER.isZoomOutPressed())\n\t\t\t\t\tsetZoom(zoom + interpolatedIncrement);\n\t\t\t}\n\t\t} else if (wasZooming) {\n\t\t\tsetZoom(1D);\n\t\t}\n\t\t\n\t\tscrollDelta = 0;\n\t\tprevTimestamp = timestamp;\n\t\twasZooming = zooming;\n\t}\n\t\n}" }, { "identifier": "ModernZume", "path": "modern/src/main/java/dev/nolij/zume/modern/ModernZume.java", "snippet": "public class ModernZume implements ClientModInitializer, IZumeProvider {\n\t\n\t@Override\n\tpublic void onInitializeClient() {\n\t\tZume.LOGGER.info(\"Loading Modern Zume...\");\n\t\t\n\t\tfor (final ZumeKeyBind keyBind : ZumeKeyBind.values()) {\n\t\t\tKeyBindingHelper.registerKeyBinding(keyBind.value);\n\t\t}\n\t\t\n\t\tZume.init(this, FabricLoader.getInstance().getConfigDir().resolve(Zume.CONFIG_FILE_NAME).toFile());\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomPressed() {\n\t\treturn ZumeKeyBind.ZOOM.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomInPressed() {\n\t\treturn ZumeKeyBind.ZOOM_IN.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomOutPressed() {\n\t\treturn ZumeKeyBind.ZOOM_OUT.isPressed();\n\t}\n\t\n}" }, { "identifier": "PrimitiveZume", "path": "primitive/src/main/java/dev/nolij/zume/primitive/PrimitiveZume.java", "snippet": "public class PrimitiveZume implements ClientModInitializer, IZumeProvider {\n\t\n\t@Override\n\tpublic void onInitializeClient() {\n\t\tZume.LOGGER.info(\"Loading Primitive Zume...\");\n\t\t\n\t\tZume.init(this, FabricLoader.getInstance().getConfigDir().resolve(Zume.CONFIG_FILE_NAME).toFile());\n\t}\n\t\n\t\n\t@Override\n\tpublic boolean isZoomPressed() {\n\t\treturn ZumeKeyBind.ZOOM.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomInPressed() {\n\t\treturn ZumeKeyBind.ZOOM_IN.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomOutPressed() {\n\t\treturn ZumeKeyBind.ZOOM_OUT.isPressed();\n\t}\n\t\n\t@Override\n\tpublic void onZoomActivate() {\n\t\t//noinspection ConstantValue\n\t\tif (Zume.CONFIG.enableCinematicZoom && !MinecraftAccessor.getInstance().options.cinematicMode) {\n\t\t\tfinal GameRendererAccessor gameRenderer = (GameRendererAccessor) MinecraftAccessor.getInstance().field_2818;\n\t\t\tgameRenderer.setCinematicYawSmoother(new SmoothUtil());\n\t\t\tgameRenderer.setCinematicPitchSmoother(new SmoothUtil());\n\t\t}\n\t}\n\t\n}" }, { "identifier": "LegacyZume", "path": "legacy/src/main/java/dev/nolij/zume/legacy/LegacyZume.java", "snippet": "public class LegacyZume implements ClientModInitializer, IZumeProvider {\n\t\n\t@Override\n\tpublic void onInitializeClient() {\n\t\tZume.LOGGER.info(\"Loading Legacy Zume...\");\n\t\t\n\t\tZume.init(this, FabricLoader.getInstance().getConfigDir().resolve(Zume.CONFIG_FILE_NAME).toFile());\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomPressed() {\n\t\treturn ZumeKeyBind.ZOOM.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomInPressed() {\n\t\treturn ZumeKeyBind.ZOOM_IN.isPressed();\n\t}\n\t\n\t@Override\n\tpublic boolean isZoomOutPressed() {\n\t\treturn ZumeKeyBind.ZOOM_OUT.isPressed();\n\t}\n\t\n\t@Override\n\tpublic void onZoomActivate() {\n\t\tif (Zume.CONFIG.enableCinematicZoom && !MinecraftClient.getInstance().options.smoothCameraEnabled) {\n\t\t\tfinal GameRendererAccessor gameRenderer = (GameRendererAccessor) MinecraftClient.getInstance().gameRenderer;\n\t\t\tgameRenderer.setCursorXSmoother(new SmoothUtil());\n\t\t\tgameRenderer.setCursorYSmoother(new SmoothUtil());\n\t\t\tgameRenderer.setCursorDeltaX(0F);\n\t\t\tgameRenderer.setCursorDeltaY(0F);\n\t\t\tgameRenderer.setSmoothedCursorDeltaX(0F);\n\t\t\tgameRenderer.setSmoothedCursorDeltaY(0F);\n\t\t\tgameRenderer.setLastTickDelta(0F);\n\t\t}\n\t}\n\t\n}" } ]
import dev.nolij.zume.common.Zume; import dev.nolij.zume.modern.ModernZume; import dev.nolij.zume.primitive.PrimitiveZume; import dev.nolij.zume.legacy.LegacyZume; import net.fabricmc.api.ClientModInitializer;
3,089
package dev.nolij.zume; public class FabricZumeBootstrapper implements ClientModInitializer { @Override public void onInitializeClient() { if (Zume.ZUME_VARIANT == null) throw new AssertionError(""" Failed to detect which variant of Zume to load! Ensure all dependencies are installed: Fabric (14.4+): fabric-key-binding-api-v1 Legacy Fabric (7.10-12.2): legacy-fabric-keybinding-api-v1-common Babric (b7.3): station-keybindings-v0"""); switch (Zume.ZUME_VARIANT) { case MODERN -> new ModernZume().onInitializeClient();
package dev.nolij.zume; public class FabricZumeBootstrapper implements ClientModInitializer { @Override public void onInitializeClient() { if (Zume.ZUME_VARIANT == null) throw new AssertionError(""" Failed to detect which variant of Zume to load! Ensure all dependencies are installed: Fabric (14.4+): fabric-key-binding-api-v1 Legacy Fabric (7.10-12.2): legacy-fabric-keybinding-api-v1-common Babric (b7.3): station-keybindings-v0"""); switch (Zume.ZUME_VARIANT) { case MODERN -> new ModernZume().onInitializeClient();
case LEGACY -> new LegacyZume().onInitializeClient();
3
2023-10-25 21:00:22+00:00
4k
sanxiaoshitou/tower-boot
tower-boot-rockermq/src/main/java/com/hxl/rocker/processor/RocketMQConsumerProcessor.java
[ { "identifier": "RocketProperties", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/RocketProperties.java", "snippet": "@ConfigurationProperties(RocketProperties.ROCKET_PREFIX)\n@Data\npublic class RocketProperties {\n\n public static final String ROCKET_PREFIX = \"tower.rocket\";\n\n private static final String CUE = \"RocketMq配置\";\n\n /**\n * 命名服务地址\n */\n private String namesrvAddr;\n\n /**\n * 开源版:默认超时时间\n * 商用版:商用版的api没有单个消息的API超时时间,故此配置在商业版RocketMQ是全局\n */\n private long sendTimeout = 3000;\n\n /**\n *\n */\n private String accessKey;\n\n /**\n *\n */\n private String secretKey;\n\n /**\n * 扫描包 列:com.hxl\n */\n private String packageName;\n\n /**\n * @see com.hxl.rocker.enums.RockerMqVersions\n * 阿里版本号 目前支持 4.x 5.x 版本\n */\n private Integer versions;\n}" }, { "identifier": "RockerConstants", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/constants/RockerConstants.java", "snippet": "public class RockerConstants {\n\n public static final String FILTER_EXPRESSION = \"*\";\n}" }, { "identifier": "RockerMqVersions", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/enums/RockerMqVersions.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum RockerMqVersions {\n\n ALI_4(4,\"阿里云4.x\"),\n ALI_5(5,\"阿里云5.x\"),\n ;\n\n private final Integer code;\n\n private final String desc;\n}" }, { "identifier": "OnsRocketMQConsumerClient", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/processor/ali/OnsRocketMQConsumerClient.java", "snippet": "@Configuration\npublic class OnsRocketMQConsumerClient {\n\n private RocketProperties properties;\n\n private AutowireCapableBeanFactory autowireCapableBeanFactory;\n\n public OnsRocketMQConsumerClient(RocketProperties properties, AutowireCapableBeanFactory autowireCapableBeanFactory) {\n this.properties = properties;\n this.autowireCapableBeanFactory = autowireCapableBeanFactory;\n }\n\n public void start(BeanDefinition beanDefinition) {\n try {\n //动态监听器 支持注入bean\n Class<?> annotatedClass = Class.forName(beanDefinition.getBeanClassName());\n RocketConsumer consumerAnnotation = annotatedClass.getAnnotation(RocketConsumer.class);\n MessageListener listener = (MessageListener) autowireCapableBeanFactory.createBean(annotatedClass);\n consumerStart(consumerAnnotation, listener);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private Properties getProperties(RocketProperties rocketProperties, RocketConsumer consumer) {\n Properties properties = new Properties();\n properties.put(PropertyKeyConst.AccessKey, rocketProperties.getAccessKey());\n properties.put(PropertyKeyConst.SecretKey, rocketProperties.getSecretKey());\n properties.put(PropertyKeyConst.NAMESRV_ADDR, rocketProperties.getNamesrvAddr());\n properties.put(PropertyKeyConst.ConsumeTimeout, 15);\n properties.put(PropertyKeyConst.ConsumeThreadNums, 10);\n // 订阅方式\n properties.put(PropertyKeyConst.MessageModel, consumer.consumeMode() == ConsumeMode.RADIO ? PropertyValueConst.BROADCASTING : PropertyValueConst.CLUSTERING);\n properties.put(PropertyKeyConst.ConsumeMessageBatchMaxSize, consumer.pullBatchSize());\n properties.put(PropertyKeyConst.MaxReconsumeTimes, consumer.maxReconsumeTimes());\n properties.put(PropertyKeyConst.MAX_BATCH_MESSAGE_COUNT, consumer.pullBatchSize());\n String consumerGroup = consumer.consumerGroup();\n properties.put(PropertyKeyConst.GROUP_ID, consumerGroup);\n return properties;\n }\n\n public void consumerStart(RocketConsumer rocketConsumer, MessageListener listener){\n String topic = rocketConsumer.topic();\n String group = rocketConsumer.consumerGroup();\n String tag = rocketConsumer.tag();\n\n Consumer consumer = ONSFactory.createConsumer(getProperties(this.properties, rocketConsumer));\n consumer.subscribe(topic, tag,listener);\n consumer.start();\n System.out.println(\"RocketMQ Consumer started. Topic: \" + topic + \", Group: \" + group);\n }\n\n}" }, { "identifier": "RocketMQConsumerClient", "path": "tower-boot-rockermq/src/main/java/com/hxl/rocker/processor/ali/RocketMQConsumerClient.java", "snippet": "@Configuration\npublic class RocketMQConsumerClient {\n\n private RocketProperties properties;\n\n private AutowireCapableBeanFactory autowireCapableBeanFactory;\n\n public RocketMQConsumerClient(RocketProperties properties, AutowireCapableBeanFactory autowireCapableBeanFactory) {\n this.properties = properties;\n this.autowireCapableBeanFactory = autowireCapableBeanFactory;\n }\n\n\n public void start(BeanDefinition beanDefinition) {\n try {\n //动态监听器 支持注入bean\n Class<?> annotatedClass = Class.forName(beanDefinition.getBeanClassName());\n RocketConsumer consumerAnnotation = annotatedClass.getAnnotation(RocketConsumer.class);\n MessageListener listener = (MessageListener) autowireCapableBeanFactory.createBean(annotatedClass);\n consumerStart(consumerAnnotation, listener);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public ClientConfiguration initClientConfiguration(RocketProperties properties) {\n ClientConfigurationBuilder configBuilder = ClientConfiguration.newBuilder().setEndpoints(properties.getNamesrvAddr());\n configBuilder.setCredentialProvider(\n new StaticSessionCredentialsProvider(properties.getAccessKey(), properties.getSecretKey())\n );\n return configBuilder.build();\n }\n\n public void consumerStart(RocketConsumer rocketConsumer, MessageListener listener) throws ClientException {\n ClientConfiguration clientConfiguration = initClientConfiguration(this.properties);\n String TOPIC_NAME = rocketConsumer.topic();\n String CONSUMER_GROUP_ID = rocketConsumer.consumerGroup();\n String TAG = StringUtils.isEmpty(rocketConsumer.tag()) ? RockerConstants.FILTER_EXPRESSION : rocketConsumer.tag();\n ClientServiceProvider provider = ClientServiceProvider.loadService();\n // 订阅消息的过滤规则。* 代表订阅全部消息。\n FilterExpression filterExpression = new FilterExpression(TAG, FilterExpressionType.TAG);\n\n PushConsumer pushConsumer = provider.newPushConsumerBuilder()\n .setClientConfiguration(clientConfiguration)\n .setConsumerGroup(CONSUMER_GROUP_ID)\n .setSubscriptionExpressions(Collections.singletonMap(TOPIC_NAME, filterExpression))\n .setMessageListener(listener)\n .build();\n// Thread.sleep(Long.MAX_VALUE);\n//\n// pushConsumer.close();\n }\n}" } ]
import com.hxl.rocker.RocketConsumer; import com.hxl.rocker.RocketProperties; import com.hxl.rocker.constants.RockerConstants; import com.hxl.rocker.enums.RockerMqVersions; import com.hxl.rocker.processor.ali.OnsRocketMQConsumerClient; import com.hxl.rocker.processor.ali.RocketMQConsumerClient; import org.apache.rocketmq.client.apis.ClientConfiguration; import org.apache.rocketmq.client.apis.ClientConfigurationBuilder; import org.apache.rocketmq.client.apis.ClientServiceProvider; import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider; import org.apache.rocketmq.client.apis.consumer.FilterExpression; import org.apache.rocketmq.client.apis.consumer.FilterExpressionType; import org.apache.rocketmq.client.apis.consumer.MessageListener; import org.apache.rocketmq.client.apis.consumer.PushConsumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Import; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.util.StringUtils; import java.util.Collections; import java.util.Objects; import java.util.Set;
1,954
package com.hxl.rocker.processor; /** * @Description 消费组监听器处理器 * @Author hxl * @Date 2023/11/23 17:09 */ @Configuration public class RocketMQConsumerProcessor { @Autowired private RocketMQConsumerClient rocketMQConsumerClient; @Autowired
package com.hxl.rocker.processor; /** * @Description 消费组监听器处理器 * @Author hxl * @Date 2023/11/23 17:09 */ @Configuration public class RocketMQConsumerProcessor { @Autowired private RocketMQConsumerClient rocketMQConsumerClient; @Autowired
private OnsRocketMQConsumerClient onsRocketMQConsumerClient;
3
2023-10-30 06:30:41+00:00
4k
lipinskipawel/maelstrom-java
src/main/java/com/github/lipinskipawel/maelstrom/internal/JsonSupport.java
[ { "identifier": "Event", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Event.java", "snippet": "public final class Event<T extends BaseWorkload> {\n @JsonProperty(\"id\")\n public int id;\n @JsonProperty(\"src\")\n public String src;\n @JsonProperty(\"dest\")\n public String dst;\n @JsonProperty(\"body\")\n public T body;\n\n Event(T body) {\n this.body = body;\n }\n\n private Event(int id, String src, String dest, T body) {\n this.id = id;\n this.src = src;\n this.dst = dest;\n this.body = body;\n }\n\n public static <T extends BaseWorkload> Event<T> createEvent(int id, String src, String dest, T body) {\n return new Event<>(id, src, dest, body);\n }\n\n public <E extends EventType> Event<E> reply(E body) {\n final var response = new Event<>(body);\n response.id = this.id;\n response.src = this.dst;\n response.dst = this.src;\n response.body.inReplyTo = this.body.msgId();\n response.body.msgId = this.body.msgId() + 1;\n return response;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n Event<?> event = (Event<?>) o;\n return id == event.id && Objects.equals(src, event.src) && Objects.equals(dst, event.dst) && Objects.equals(body, event.body);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, src, dst, body);\n }\n}" }, { "identifier": "BaseWorkload", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/BaseWorkload.java", "snippet": "public sealed interface BaseWorkload permits EventType,\n EchoWorkload, UniqueWorkload, BroadcastWorkload {\n\n int msgId();\n\n int inReplyTo();\n}" }, { "identifier": "EventType", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/EventType.java", "snippet": "public non-sealed class EventType implements BaseWorkload {\n public String type;\n @JsonProperty(\"msg_id\")\n public int msgId;\n @JsonProperty(\"in_reply_to\")\n public int inReplyTo;\n\n public EventType(String type) {\n this.type = type;\n }\n\n @Override\n public int msgId() {\n return msgId;\n }\n\n @Override\n public int inReplyTo() {\n return inReplyTo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n EventType eventType = (EventType) o;\n return msgId == eventType.msgId && inReplyTo == eventType.inReplyTo && Objects.equals(type, eventType.type);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(type, msgId, inReplyTo);\n }\n}" }, { "identifier": "Init", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Init.java", "snippet": "public final class Init extends EventType implements EchoWorkload, UniqueWorkload, BroadcastWorkload {\n @JsonProperty(\"node_id\")\n public String nodeId;\n @JsonProperty(\"node_ids\")\n public List<String> nodeIds;\n\n public Init() {\n super(\"init\");\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Init init = (Init) o;\n return Objects.equals(nodeId, init.nodeId) && Objects.equals(nodeIds, init.nodeIds);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), nodeId, nodeIds);\n }\n}" }, { "identifier": "InitOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/InitOk.java", "snippet": "public final class InitOk extends EventType {\n\n public InitOk() {\n super(\"init_ok\");\n }\n}" }, { "identifier": "Quit", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/Quit.java", "snippet": "public final class Quit extends EventType implements EchoWorkload, UniqueWorkload, BroadcastWorkload {\n public Quit() {\n super(\"quit\");\n }\n}" }, { "identifier": "Broadcast", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/Broadcast.java", "snippet": "public final class Broadcast extends EventType implements BroadcastWorkload {\n @JsonProperty(\"message\")\n public Integer message;\n\n public Broadcast() {\n super(\"broadcast\");\n }\n\n public Broadcast(Integer message) {\n super(\"broadcast\");\n this.message = message;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Broadcast broadcast = (Broadcast) o;\n return Objects.equals(message, broadcast.message);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), message);\n }\n}" }, { "identifier": "BroadcastOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/BroadcastOk.java", "snippet": "public final class BroadcastOk extends EventType {\n public BroadcastOk() {\n super(\"broadcast_ok\");\n }\n}" }, { "identifier": "Read", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/Read.java", "snippet": "public final class Read extends EventType implements BroadcastWorkload {\n public Read() {\n super(\"read\");\n }\n}" }, { "identifier": "ReadOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/ReadOk.java", "snippet": "public final class ReadOk extends EventType {\n @JsonProperty(\"messages\")\n public List<Integer> messages;\n\n public ReadOk() {\n super(\"read_ok\");\n }\n\n public ReadOk(List<Integer> messages) {\n super(\"read_ok\");\n this.messages = messages;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n ReadOk readOk = (ReadOk) o;\n return Objects.equals(messages, readOk.messages);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), messages);\n }\n}" }, { "identifier": "Topology", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/Topology.java", "snippet": "public final class Topology extends EventType implements BroadcastWorkload {\n @JsonProperty(\"topology\")\n public Map<String, List<String>> topology;\n\n public Topology() {\n super(\"topology\");\n }\n\n public Topology(Map<String, List<String>> topology) {\n super(\"topology\");\n this.topology = topology;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Topology topology1 = (Topology) o;\n return Objects.equals(topology, topology1.topology);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), topology);\n }\n}" }, { "identifier": "TopologyOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/broadcast/TopologyOk.java", "snippet": "public final class TopologyOk extends EventType {\n public TopologyOk() {\n super(\"topology_ok\");\n }\n}" }, { "identifier": "Echo", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/echo/Echo.java", "snippet": "public final class Echo extends EventType implements EchoWorkload {\n @JsonProperty(\"echo\")\n public String echo;\n\n public Echo() {\n super(\"echo\");\n }\n\n public Echo(String echo) {\n super(\"echo\");\n this.echo = echo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Echo echo1 = (Echo) o;\n return Objects.equals(echo, echo1.echo);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), echo);\n }\n}" }, { "identifier": "EchoOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/echo/EchoOk.java", "snippet": "public final class EchoOk extends EventType {\n @JsonProperty(\"echo\")\n public String echo;\n\n public EchoOk() {\n super(\"echo_ok\");\n }\n\n public EchoOk(String echo) {\n super(\"echo_ok\");\n this.echo = echo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n EchoOk echoOk = (EchoOk) o;\n return Objects.equals(echo, echoOk.echo);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), echo);\n }\n}" }, { "identifier": "Unique", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/unique/Unique.java", "snippet": "public final class Unique extends EventType implements UniqueWorkload {\n public Unique() {\n super(\"generate\");\n }\n}" }, { "identifier": "UniqueOk", "path": "src/main/java/com/github/lipinskipawel/maelstrom/api/protocol/unique/UniqueOk.java", "snippet": "public final class UniqueOk extends EventType {\n public UUID id;\n\n public UniqueOk(UUID uuid) {\n super(\"generate_ok\");\n this.id = uuid;\n }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.github.lipinskipawel.maelstrom.api.protocol.Event; import com.github.lipinskipawel.maelstrom.api.protocol.BaseWorkload; import com.github.lipinskipawel.maelstrom.api.protocol.EventType; import com.github.lipinskipawel.maelstrom.api.protocol.Init; import com.github.lipinskipawel.maelstrom.api.protocol.InitOk; import com.github.lipinskipawel.maelstrom.api.protocol.Quit; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.Broadcast; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.BroadcastOk; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.Read; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.ReadOk; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.Topology; import com.github.lipinskipawel.maelstrom.api.protocol.broadcast.TopologyOk; import com.github.lipinskipawel.maelstrom.api.protocol.echo.Echo; import com.github.lipinskipawel.maelstrom.api.protocol.echo.EchoOk; import com.github.lipinskipawel.maelstrom.api.protocol.unique.Unique; import com.github.lipinskipawel.maelstrom.api.protocol.unique.UniqueOk; import java.util.HashMap; import java.util.Map;
2,884
package com.github.lipinskipawel.maelstrom.internal; public final class JsonSupport { private static final Map<String, Class<? extends EventType>> POSSIBLE_TYPES = createMappings(); private static ObjectMapper staticMapper = createObjectMapper(POSSIBLE_TYPES); private JsonSupport() { } public static void jsonSupportRegisterCustomTypes(Map<String, Class<? extends EventType>> customTypes) { POSSIBLE_TYPES.putAll(customTypes); staticMapper = createObjectMapper(POSSIBLE_TYPES); } @SuppressWarnings("unchecked")
package com.github.lipinskipawel.maelstrom.internal; public final class JsonSupport { private static final Map<String, Class<? extends EventType>> POSSIBLE_TYPES = createMappings(); private static ObjectMapper staticMapper = createObjectMapper(POSSIBLE_TYPES); private JsonSupport() { } public static void jsonSupportRegisterCustomTypes(Map<String, Class<? extends EventType>> customTypes) { POSSIBLE_TYPES.putAll(customTypes); staticMapper = createObjectMapper(POSSIBLE_TYPES); } @SuppressWarnings("unchecked")
public static <T extends BaseWorkload> Event<T> readEvent(String event) {
1
2023-10-31 17:56:28+00:00
4k
simply-kel/AlinLib
src/main/java/ru/kelcuprum/alinlib/gui/components/selector/SelectorStringButton.java
[ { "identifier": "Colors", "path": "src/main/java/ru/kelcuprum/alinlib/Colors.java", "snippet": "public class Colors {\r\n // @YonKaGor OC Colors\r\n // Uhh\r\n public static Integer SEADRIVE = 0xFF79c738;\r\n // Circus Hop\r\n public static Integer CLOWNFISH = 0xFFf1ae31;\r\n // You'll be gone\r\n public static Integer SELFISH = 0xFFff366e;\r\n // Trash Talkin'\r\n public static Integer GROUPIE = 0xFFfc1a47;\r\n public static Integer KENNY = 0xFF627921;\r\n // Fallacy\r\n public static Integer CONVICT = 0xFFffdc32;\r\n // Good morning Mr.Sunfish!\r\n public static Integer SEABIRD = 0xFFf1ae31;\r\n // You're just like pop music\r\n public static Integer TETRA = 0xFFff67d1;\r\n // I Forgot That You Exist !!\r\n public static Integer FORGOT = 0xFF4f3e60;\r\n\r\n // Default color\r\n public static int DARK_PURPLE_ALPHA = FORGOT - 0xC0000000;\r\n\r\n}\r" }, { "identifier": "Config", "path": "src/main/java/ru/kelcuprum/alinlib/config/Config.java", "snippet": "public class Config {\r\n private String _filePath;\r\n private JsonObject _jsonConfiguration = new JsonObject();\r\n private final boolean _isFile;\r\n public Config(String filePath){\r\n this._filePath = filePath;\r\n this._isFile = true;\r\n }\r\n public Config(JsonObject jsonConfiguration){\r\n this._jsonConfiguration = jsonConfiguration;\r\n this._isFile = false;\r\n }\r\n /**\r\n * Сохранение конфигурации\r\n */\r\n public void save(){\r\n if(!_isFile) return;\r\n Minecraft mc = Minecraft.getInstance();\r\n final Path configFile = mc.gameDirectory.toPath().resolve(_filePath);\r\n\r\n try {\r\n Files.createDirectories(configFile.getParent());\r\n Files.writeString(configFile, _jsonConfiguration.toString());\r\n } catch (IOException e) {\r\n AlinLib.log(e.getLocalizedMessage(), Level.ERROR);\r\n }\r\n }\r\n\r\n /**\r\n * Загрузка файла конфигов\r\n */\r\n public void load(){\r\n if(!_isFile) return;\r\n Minecraft mc = Minecraft.getInstance();\r\n final Path configFile = mc.gameDirectory.toPath().resolve(_filePath);\r\n try{\r\n _jsonConfiguration = configFile.toFile().exists() ? GsonHelper.parse(Files.readString(configFile)) : new JsonObject();\r\n } catch (Exception e){\r\n AlinLib.log(e.getLocalizedMessage(), Level.ERROR);\r\n save();\r\n }\r\n\r\n }\r\n /**\r\n * Сброс конфигурации\r\n */\r\n public void reset(){\r\n this._jsonConfiguration = new JsonObject();\r\n save();\r\n }\r\n /**\r\n * Преобразование в JSON\r\n */\r\n public JsonObject toJSON(){\r\n return this._jsonConfiguration;\r\n }\r\n\r\n /**\r\n * Преобразование в JSON\r\n */\r\n public String toString(){\r\n return this._jsonConfiguration.toString();\r\n }\r\n\r\n /**\r\n * Проверка мембера на нул\r\n */\r\n public boolean isJsonNull(String type) {\r\n if(this._jsonConfiguration == null) this._jsonConfiguration = new JsonObject();\r\n\r\n if (!this._jsonConfiguration.has(type))\r\n return true;\r\n\r\n return this._jsonConfiguration.get(type).isJsonNull();\r\n }\r\n\r\n /**\r\n * Получение Boolean значения\r\n */\r\n public boolean getBoolean(String type, boolean defaultValue) {\r\n if(this._jsonConfiguration == null) this._jsonConfiguration = new JsonObject();\r\n if(!isJsonNull(type) && !(this._jsonConfiguration.get(type).getAsJsonPrimitive().isBoolean())) setBoolean(type, defaultValue);\r\n return isJsonNull(type) ? defaultValue : this._jsonConfiguration.get(type).getAsBoolean();\r\n }\r\n /**\r\n * Задать значения Boolean\r\n */\r\n public void setBoolean(String type, boolean newValue){\r\n this._jsonConfiguration.addProperty(type, newValue);\r\n save();\r\n }\r\n /**\r\n * Получение String значения\r\n */\r\n\r\n public String getString(String type, String defaultValue) {\r\n if(this._jsonConfiguration == null) this._jsonConfiguration = new JsonObject();\r\n if(!isJsonNull(type) && !(this._jsonConfiguration.get(type).getAsJsonPrimitive().isString())) setString(type, defaultValue);\r\n return isJsonNull(type) ? defaultValue : this._jsonConfiguration.get(type).getAsString();\r\n }\r\n /**\r\n * Задать значения String\r\n */\r\n public void setString(String type, String newValue){\r\n this._jsonConfiguration.addProperty(type, newValue);\r\n save();\r\n }\r\n\r\n /**\r\n * Получение Number значения\r\n */\r\n\r\n public Number getNumber(String type, Number defaultValue) {\r\n if(this._jsonConfiguration == null) this._jsonConfiguration = new JsonObject();\r\n if(!isJsonNull(type) && !(this._jsonConfiguration.get(type).getAsJsonPrimitive().isNumber())) setNumber(type, defaultValue);\r\n return isJsonNull(type) ? defaultValue : this._jsonConfiguration.get(type).getAsNumber();\r\n }\r\n /**\r\n * Задать значения Number\r\n */\r\n public void setNumber(String type, Number newValue){\r\n this._jsonConfiguration.addProperty(type, newValue);\r\n save();\r\n }\r\n}" }, { "identifier": "InterfaceUtils", "path": "src/main/java/ru/kelcuprum/alinlib/gui/InterfaceUtils.java", "snippet": "public class InterfaceUtils {\r\n private static final WidgetSprites SPRITES = new WidgetSprites(new ResourceLocation(\"widget/button\"), new ResourceLocation(\"widget/button_disabled\"), new ResourceLocation(\"widget/button_highlighted\"));\r\n public static final ResourceLocation BACKGROUND_LOCATION = new ResourceLocation(\"textures/gui/options_background.png\");\r\n\r\n // BACKGROUND\r\n public static void renderBackground(GuiGraphics guiGraphics, Minecraft minecraft){\r\n if(minecraft.level == null) renderTextureBackground(guiGraphics);\r\n else guiGraphics.fillGradient(0, 0, guiGraphics.guiWidth(), guiGraphics.guiHeight(), -1072689136, -804253680);\r\n }\r\n public static void renderTextureBackground(GuiGraphics guiGraphics){\r\n float alpha = 0.25F;\r\n guiGraphics.setColor(alpha, alpha, alpha, 1.0F);\r\n guiGraphics.blit(BACKGROUND_LOCATION, 0, 0, 0, 0.0F, 0.0F, guiGraphics.guiWidth(), guiGraphics.guiHeight(), 32, 32);\r\n guiGraphics.setColor(1.0F, 1.0F, 1.0F, 1.0F);\r\n }\r\n\r\n\r\n // LEFT PANEL\r\n public static void renderTextureLeftPanel(GuiGraphics guiGraphics, int width, int height, float alpha, ResourceLocation texture){\r\n guiGraphics.setColor(alpha, alpha, alpha, 1.0F);\r\n guiGraphics.blit(texture, 0, 0, 0, 0.0F, 0.0F, width, height, 32, 32);\r\n guiGraphics.setColor(1.0F, 1.0F, 1.0F, 1.0F);\r\n }\r\n public static void renderTextureLeftPanel(GuiGraphics guiGraphics, float alpha , int width, int height){\r\n renderTextureLeftPanel(guiGraphics, width, height, alpha, BACKGROUND_LOCATION);\r\n }\r\n public static void renderTextureLeftPanel(GuiGraphics guiGraphics, int width, int height){\r\n renderTextureLeftPanel(guiGraphics, width, height, 0.5F ,BACKGROUND_LOCATION);\r\n }\r\n // RIGHT PANEL\r\n public static void renderTextureRightPanel(GuiGraphics guiGraphics, int screenWidth, int width, int height, float alpha, ResourceLocation texture){\r\n guiGraphics.setColor(alpha, alpha, alpha, 1.0F);\r\n guiGraphics.blit(texture, screenWidth-width, 0, 0, 0.0F, 0.0F, screenWidth, height, 32, 32);\r\n guiGraphics.setColor(1.0F, 1.0F, 1.0F, 1.0F);\r\n }\r\n public static void renderTextureRightPanel(GuiGraphics guiGraphics, int screenWidth, float alpha, int width, int height){\r\n renderTextureRightPanel(guiGraphics, screenWidth, width, height, alpha, BACKGROUND_LOCATION);\r\n }\r\n public static void renderTextureRightPanel(GuiGraphics guiGraphics, int screenWidth, int width, int height){\r\n renderTextureRightPanel(guiGraphics, screenWidth, width, height, 0.5F, BACKGROUND_LOCATION);\r\n }\r\n\r\n // LEFT PANEL\r\n public static void renderLeftPanel(GuiGraphics guiGraphics, int width, int height, Color color){\r\n guiGraphics.fill(0, 0, width, height, color.getRGB());\r\n }\r\n public static void renderLeftPanel(GuiGraphics guiGraphics, int width, int height, int color){\r\n renderLeftPanel(guiGraphics, width, height, new Color(color, true));\r\n }\r\n public static void renderLeftPanel(GuiGraphics guiGraphics, int width, int height){\r\n renderLeftPanel(guiGraphics, width, height, new Color(Colors.DARK_PURPLE_ALPHA, true));\r\n }\r\n // RIGHT PANEL\r\n public static void renderRightPanel(GuiGraphics guiGraphics, int screenWidth, int width, int height, Color color){\r\n guiGraphics.fill(screenWidth-width, 0, screenWidth, height, color.getRGB());\r\n }\r\n public static void renderRightPanel(GuiGraphics guiGraphics, int screenWidth, int width, int height, int color){\r\n renderRightPanel(guiGraphics, screenWidth, width, height, new Color(color, true));\r\n }\r\n public static void renderRightPanel(GuiGraphics guiGraphics, int screenWidth, int width, int height){\r\n renderRightPanel(guiGraphics, screenWidth, width, height, new Color(Colors.DARK_PURPLE_ALPHA, true));\r\n }\r\n\r\n // String\r\n public static void drawCenteredString(GuiGraphics guiGraphics, Font font, Component component, int x, int y, int color, boolean shadow) {\r\n FormattedCharSequence formattedCharSequence = component.getVisualOrderText();\r\n guiGraphics.drawString(font, formattedCharSequence, x - font.width(formattedCharSequence) / 2, y, color, shadow);\r\n }\r\n\r\n public enum DesignType {\r\n ALINA(0),\r\n FLAT(1),\r\n VANILLA(2);\r\n\r\n\r\n public final Integer type;\r\n\r\n DesignType(Integer type) {\r\n this.type = type;\r\n }\r\n public void renderBackground(GuiGraphics guiGraphics, int x, int y, int width, int height, boolean active, boolean isHoveredOrFocused, int color){\r\n float state = !active ? 3 : isHoveredOrFocused ? 2 : 1;\r\n final float f = state / 2 * 0.9F + 0.1F;\r\n final int background = (int) (255.0F * f);\r\n switch (this.type){\r\n case 0 -> {\r\n guiGraphics.fill(x, y, x + width, y + height-1, background / 2 << 24);\r\n guiGraphics.fill(x, y+height-1, x + width, y + height, color);\r\n }\r\n case 1 -> {\r\n guiGraphics.fill(x, y, x + width, y + height, background / 2 << 24);\r\n }\r\n default -> guiGraphics.blitSprite(SPRITES.get(active, isHoveredOrFocused), x, y, width, height);\r\n }\r\n }\r\n public void renderSliderBackground(GuiGraphics guiGraphics, int x, int y, int width, int height, boolean active, boolean isHoveredOrFocused, int color, double position, AbstractSliderButton component){\r\n float state = !active ? 3 : isHoveredOrFocused ? 2 : 1;\r\n final float f = state / 2 * 0.9F + 0.1F;\r\n final int background = (int) (255.0F * f);\r\n\r\n switch (this.type){\r\n case 0 -> {\r\n guiGraphics.fill(x, y, x + width, y + height-1, background / 2 << 24);\r\n guiGraphics.fill(x, y + height-1, x + width, y + height, new Color(isHoveredOrFocused ? Colors.CLOWNFISH : Colors.SEADRIVE, true).getRGB());\r\n if(isHoveredOrFocused){\r\n int xS = x + (int)(position * (double)(width - 4));\r\n int yS = y+(height - 8) / 2;\r\n guiGraphics.fill(xS, yS, xS+4, yS+Minecraft.getInstance().font.lineHeight, new Color(Colors.CLOWNFISH, true).getRGB());\r\n }\r\n }\r\n case 1 -> {\r\n guiGraphics.fill(x, y, x + width, y + height, background / 2 << 24);\r\n if(isHoveredOrFocused){\r\n int xS = x + (int)(position * (double)(width - 4));\r\n int yS = y+(height - 8) / 2;\r\n guiGraphics.fill(xS, yS, xS+4, yS+Minecraft.getInstance().font.lineHeight, new Color(Colors.CLOWNFISH, true).getRGB());\r\n }\r\n }\r\n default -> {\r\n guiGraphics.blitSprite(component.getSprite(), x, y, width, height);\r\n if(isHoveredOrFocused){\r\n guiGraphics.blitSprite(component.getHandleSprite(), x + (int)(position * (double)(width - 8)), y, 8, height);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r" } ]
import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.network.chat.Component; import ru.kelcuprum.alinlib.Colors; import ru.kelcuprum.alinlib.config.Config; import ru.kelcuprum.alinlib.gui.InterfaceUtils; import java.util.Arrays;
3,346
package ru.kelcuprum.alinlib.gui.components.selector; public class SelectorStringButton extends AbstractButton { private final InterfaceUtils.DesignType type; public int currentPosition = 0; public String[] list;
package ru.kelcuprum.alinlib.gui.components.selector; public class SelectorStringButton extends AbstractButton { private final InterfaceUtils.DesignType type; public int currentPosition = 0; public String[] list;
public Config config;
1
2023-10-29 13:30:26+00:00
4k
sergei-nazarov/friend-s_letter
src/main/java/com/example/friendsletter/controllers/ApiController.java
[ { "identifier": "LetterRequestDto", "path": "src/main/java/com/example/friendsletter/data/LetterRequestDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class LetterRequestDto {\n\n @Size(message = \"Letter too big. Max 2147483647 symbols\")\n @NotBlank(message = \"{letter.validation.text_is_mandatory}\")\n private String message;\n @Future(message = \"{letter.validation.expiry_date_in_past}\")\n private LocalDateTime expirationDate;\n private String timeZone;\n @Size(max = 100, message = \"{letter.validation.title_too_long}\")\n private String title;\n @Size(max = 100, message = \"{letter.validation.author_too_long}\")\n private String author;\n private boolean singleRead;\n private boolean publicLetter;\n}" }, { "identifier": "LetterResponseDto", "path": "src/main/java/com/example/friendsletter/data/LetterResponseDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class LetterResponseDto {\n\n private String message;\n private String letterShortCode;\n private LocalDateTime created;\n private LocalDateTime expirationDate;\n private String title;\n private String author;\n private boolean singleRead;\n private boolean publicLetter;\n}" }, { "identifier": "PopularLetterResponseDto", "path": "src/main/java/com/example/friendsletter/data/PopularLetterResponseDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PopularLetterResponseDto {\n\n private String message;\n private String letterShortCode;\n private LocalDateTime created;\n private LocalDateTime expirationDate;\n private String title;\n private String author;\n private boolean singleRead;\n private boolean publicLetter;\n private long countVisits;\n @JsonIgnore\n private String messageId;\n\n public PopularLetterResponseDto(LetterMetadata letter, long countVisits) {\n this.letterShortCode = letter.getLetterShortCode();\n this.created = letter.getCreated();\n this.expirationDate = letter.getExpirationDate();\n this.title = letter.getTitle();\n this.author = letter.getAuthor();\n this.singleRead = letter.isSingleRead();\n this.publicLetter = letter.isPublicLetter();\n this.messageId = letter.getMessageId();\n this.countVisits = countVisits;\n }\n}" }, { "identifier": "LetterNotAvailableException", "path": "src/main/java/com/example/friendsletter/errors/LetterNotAvailableException.java", "snippet": "@Getter\npublic class LetterNotAvailableException extends Throwable {\n\n private final String letterShortCode;\n private final LETTER_ERROR_STATUS status;\n\n\n public LetterNotAvailableException(String letterShortCode, LETTER_ERROR_STATUS status) {\n this.letterShortCode = letterShortCode;\n this.status = status;\n }\n\n}" }, { "identifier": "LetterService", "path": "src/main/java/com/example/friendsletter/services/LetterService.java", "snippet": "@Component\n@Slf4j\npublic class LetterService {\n private static final ZoneId UTC = ZoneId.of(\"UTC\");\n private final MessageStorage messageStorage;\n private final MessageCache messageCache;\n private final SequenceGenerator urlGenerator;\n private final LetterMetadataRepository letterRepository;\n private final LetterStatisticsRepository letterStatRepository;\n\n private final ExecutorService executor = Executors.newWorkStealingPool(6);\n private volatile List<PopularLetterResponseDto> mostPopularMessages = new ArrayList<>();\n\n\n @Autowired\n public LetterService(MessageStorage messageStorage, MessageCache messageCache,\n SequenceGenerator urlGenerator, LetterMetadataRepository repository,\n LetterStatisticsRepository letterStatRepository) {\n this.messageStorage = messageStorage;\n this.messageCache = messageCache;\n this.urlGenerator = urlGenerator;\n this.letterRepository = repository;\n this.letterStatRepository = letterStatRepository;\n }\n\n private static ZoneId getZoneId(String timezone) {\n ZoneId tz;\n try {\n tz = ZoneId.of(timezone);\n } catch (Exception ignore) {\n tz = UTC;\n }\n return tz;\n }\n\n public List<LetterResponseDto> getLettersByUser(User user, Pageable pageable) {\n List<LetterMetadata> letters = letterRepository.findByUser(user, pageable);\n return letters.parallelStream().map(letter -> {\n String message;\n try {\n message = getMessageText(letter.getMessageId());\n } catch (FileNotFoundException e) {\n message = null;\n }\n return letter.toLetterResponseDto(message);\n }).toList();\n }\n\n /**\n * @param letterDto - message info to save\n * @return response with letterShortCode\n * Letter metadata will be stored in DB, message in messageStore and cache\n */\n public LetterResponseDto saveLetter(User user, LetterRequestDto letterDto) {\n //generating unique code\n String letterShortCode;\n do {\n letterShortCode = urlGenerator.generate();\n } while (letterRepository.findById(letterShortCode).isPresent());\n\n //put message in storage and cache\n String message = letterDto.getMessage();\n String messageId = messageStorage.save(message);\n messageCache.save(new MessageCacheDto(messageId, message));\n\n LocalDateTime utcExpDate = toUtc(letterDto.getExpirationDate(), getZoneId(letterDto.getTimeZone()));\n LocalDateTime utcCreated = LocalDateTime.now(ZoneOffset.UTC);\n\n LetterMetadata letter = new LetterMetadata(letterShortCode, letterDto.isSingleRead(), letterDto.isPublicLetter(),\n letterDto.getTitle(), letterDto.getAuthor(),\n utcCreated, utcExpDate, messageId);\n letter.setUser(user);\n letterRepository.save(letter);\n return letter.toLetterResponseDto(message);\n }\n\n public LetterResponseDto updateLetter(String letterShortCode, LetterRequestDto letterDto) throws LetterNotAvailableException {\n Optional<LetterMetadata> letterMetadataOptional = letterRepository.findById(letterShortCode);\n if (letterMetadataOptional.isEmpty()) {\n throw new LetterNotAvailableException(letterShortCode, LETTER_ERROR_STATUS.LETTER_NOT_FOUND);//todo another exception\n }\n LetterMetadata letter = letterMetadataOptional.get();\n\n letter.setAuthor(letterDto.getAuthor());\n letter.setTitle(letterDto.getTitle());\n letter.setPublicLetter(letterDto.isPublicLetter());\n letter.setSingleRead(letterDto.isSingleRead());\n letter.setExpirationDate(toUtc(letterDto.getExpirationDate(), getZoneId(letterDto.getTimeZone())));\n letterRepository.save(letter);\n\n //update message in storage and cache\n String message = letterDto.getMessage();\n String fileId = letter.getMessageId();\n messageStorage.update(fileId, message);\n messageCache.save(new MessageCacheDto(fileId, message));\n\n return letter.toLetterResponseDto(message);\n }\n\n /**\n * @param letterShortCode - letterShortCode\n * @return Data for displaying letter\n * Read the message in the letter. The message will be searched in the cache first.\n * If it is not found, it will be requested in messageStore\n * @throws LetterNotAvailableException - different errors with letter.\n */\n public LetterResponseDto readLetter(String letterShortCode, boolean validate) throws LetterNotAvailableException {\n\n Optional<LetterMetadata> letterOptional = letterRepository.findByLetterShortCode(letterShortCode);\n if (letterOptional.isEmpty()) {\n throw new LetterNotAvailableException(letterShortCode, LETTER_ERROR_STATUS.LETTER_NOT_FOUND);\n }\n LetterMetadata letter = letterOptional.get();\n\n if (validate) {\n if (LocalDateTime.now(UTC).isAfter(letter.getExpirationDate())) {\n throw new LetterNotAvailableException(letterShortCode, LETTER_ERROR_STATUS.EXPIRED);\n } else if (letter.isSingleRead() && letterStatRepository.countAllByLetterShortCodeIs(letterShortCode) > 0) {\n throw new LetterNotAvailableException(letterShortCode, LETTER_ERROR_STATUS.HAS_BEEN_READ);\n }\n }\n\n String messageId = letter.getMessageId();\n String message;\n try {\n message = getMessageText(messageId);\n } catch (FileNotFoundException e) {\n throw new LetterNotAvailableException(letterShortCode, LETTER_ERROR_STATUS.MESSAGE_NOT_FOUND);\n }\n\n return letter.toLetterResponseDto(message);\n }\n\n public LetterResponseDto readLetter(String letterShortCode) throws LetterNotAvailableException {\n return readLetter(letterShortCode, true);\n }\n\n\n /**\n * @param messageId - message id\n * Looking for message in cache, then in message store\n * @return message text\n * @throws FileNotFoundException if message not found\n */\n public String getMessageText(String messageId) throws FileNotFoundException {\n Optional<MessageCacheDto> cachedMessage = messageCache.get(messageId);\n String message;\n if (cachedMessage.isPresent()) {\n message = cachedMessage.get().getMessage();\n log.info(\"Message with id \" + messageId + \" has been found in cache\");\n } else {\n message = messageStorage.read(messageId);\n messageCache.save(new MessageCacheDto(messageId, message));\n }\n return message;\n }\n\n /**\n * Write letter visit to DB\n * Write only if there are no visits for last 5 minutes\n * with same ip and letter code\n */\n public void writeVisit(String letterShortCode, String ip) {\n executor.execute(() -> {\n Optional<LetterStat> letterStat = letterStatRepository\n .findFirstByLetterShortCodeIsAndIpIsAndVisitTimestampIsAfter(\n letterShortCode,\n ip,\n LocalDateTime.now(ZoneOffset.UTC).minusMinutes(5));\n if (letterStat.isEmpty()) {\n letterStatRepository.save(new LetterStat(LocalDateTime.now(UTC), ip, letterShortCode));\n }\n });\n }\n\n public void writeVisitUnfair(String letterShortCode) {\n letterStatRepository.save(new LetterStat(LocalDateTime.now(UTC), \"unknown\", letterShortCode));\n }\n\n public LocalDateTime toUtc(LocalDateTime dateTime, ZoneId timeZone) {\n if (dateTime == null) {\n return LocalDateTime.of(2100, 1, 1, 0, 0, 0);\n }\n return dateTime.atZone(timeZone)\n .withZoneSameInstant(UTC).toLocalDateTime();\n }\n\n /**\n * @return List of public letters\n */\n public Slice<LetterResponseDto> getPublicLetters(Pageable pageable) {\n Slice<LetterMetadata> letterMetadata = letterRepository\n .findAllByPublicLetterIsAndSingleReadIs(true, false, pageable);\n List<LetterResponseDto> letterResponseDtos = letterMetadata.getContent().parallelStream().map(letter -> {\n String message;\n try {\n message = getMessageText(letter.getMessageId());\n } catch (FileNotFoundException e) {\n message = null;\n }\n return letter.toLetterResponseDto(message);\n }).toList();\n return new SliceImpl<>(letterResponseDtos, letterMetadata.getPageable(), letterMetadata.hasNext());\n }\n\n /**\n * @return - List of the most popular letters with count of visits\n */\n public List<PopularLetterResponseDto> getMostPopular() {\n return new ArrayList<>(mostPopularMessages);\n }\n\n\n /**\n * Finding the most popular messages every 5 minutes\n */\n @Scheduled(fixedDelay = 5 * 60 * 1000)\n void findingPopularMessages() {\n log.debug(\"Start looking for popular messages...\");\n List<PopularLetterResponseDto> letters = letterRepository\n .getPopular(PageRequest.of(0, 10));\n mostPopularMessages = letters.stream().peek(letterDto -> {\n try {\n letterDto.setMessage(getMessageText(letterDto.getMessageId()));\n } catch (FileNotFoundException ignore) {\n }\n }).filter(letterDto -> letterDto.getMessage() != null).toList();\n }\n\n @Transactional\n public boolean doesUserOwnLetter(User user, String letterShortCode) {\n Optional<LetterMetadata> letterMetadataOptional = letterRepository.findById(letterShortCode);\n if (letterMetadataOptional.isEmpty() || letterMetadataOptional.get().getUser() == null) {\n return false;\n }\n return user.getId().equals(letterMetadataOptional.get().getUser().getId());\n }\n}" } ]
import com.example.friendsletter.data.LetterRequestDto; import com.example.friendsletter.data.LetterResponseDto; import com.example.friendsletter.data.PopularLetterResponseDto; import com.example.friendsletter.errors.LetterNotAvailableException; import com.example.friendsletter.services.LetterService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import org.springdoc.core.annotations.ParameterObject; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
3,045
package com.example.friendsletter.controllers; /** * API Controller */ @RestController @RequestMapping("api1") @Tag(name = "Friend's letter", description = "publish and read letters") public class ApiController { final private LetterService letterService; public ApiController(LetterService letterService) { this.letterService = letterService; } @Operation(summary = "Get list of the latest letters") @GetMapping("/letters")
package com.example.friendsletter.controllers; /** * API Controller */ @RestController @RequestMapping("api1") @Tag(name = "Friend's letter", description = "publish and read letters") public class ApiController { final private LetterService letterService; public ApiController(LetterService letterService) { this.letterService = letterService; } @Operation(summary = "Get list of the latest letters") @GetMapping("/letters")
Slice<LetterResponseDto> getPublicLetters(@ParameterObject @PageableDefault(sort = "created",
1
2023-10-31 09:53:27+00:00
4k
LiedsonLB/ImovelCRUDApp
LuxuriousBreeze/pages/ImovelGUI.java
[ { "identifier": "ImovelCSVHandler", "path": "LuxuriousBreeze/db/ImovelCSVHandler.java", "snippet": "public class ImovelCSVHandler {\n private static final String CSV_FILE = \"imoveis.csv\";\n\n public static void salvarImovel(Imovel imovel) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(CSV_FILE, true))) {\n writer.println(imovel.toCSV());\n } catch (IOException e) {\n System.err.println(\"Erro ao salvar o imóvel no arquivo CSV: \" + e.getMessage());\n }\n }\n\n public static List<String> lerDadosCSV() {\n List<String> linhas = new ArrayList<>();\n try (BufferedReader reader = new BufferedReader(new FileReader(CSV_FILE))) {\n String linha;\n while ((linha = reader.readLine()) != null) {\n linhas.add(linha);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return linhas;\n }\n\n public static List<Imovel> listarImoveis() {\n List<Imovel> imoveis = new ArrayList<>();\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n try (BufferedReader reader = new BufferedReader(new FileReader(CSV_FILE))) {\n String line;\n while ((line = reader.readLine()) != null) {\n String[] parts = line.split(\",\");\n if (parts.length <= 13) {\n try {\n int imovelID = Integer.parseInt(parts[0]);\n String nomeImovel = parts[1];\n String localizacao = parts[2];\n String descricao = parts[3];\n double preco = Double.parseDouble(parts[4]);\n int userID = Integer.parseInt(parts[5]);\n\n java.util.Date dataPublicacao = null;\n if (!parts[6].isEmpty()) {\n dataPublicacao = sdf.parse(parts[6]);\n }\n\n String nomeUsuario = parts[7];\n String contatoUsuario = parts[8];\n String tipoImovel = parts[9];\n boolean comodidadePiscina = Boolean.parseBoolean(parts[10]);\n boolean comodidadeAcademia = Boolean.parseBoolean(parts[11]);\n boolean comodidadeEstacionamento = Boolean.parseBoolean(parts[12]);\n\n Imovel imovel = new Imovel(imovelID, nomeImovel, localizacao, descricao, preco, userID, dataPublicacao, nomeUsuario, contatoUsuario, tipoImovel, comodidadePiscina, comodidadeAcademia, comodidadeEstacionamento);\n imoveis.add(imovel);\n } catch (NumberFormatException ex) {\n System.err.println(\"Erro de formato numérico: \" + ex.getMessage());\n } catch (ParseException ex) {\n System.err.println(\"Erro de análise: \" + ex.getMessage());\n }\n }\n }\n } catch (IOException e) {\n System.err.println(\"Erro ao ler o arquivo CSV: \" + e.getMessage());\n }\n return imoveis;\n }\n\n public static void atualizarImoveis(List<Imovel> imoveis) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(CSV_FILE))) {\n for (Imovel imovel : imoveis) {\n writer.println(imovel.toCSV());\n }\n } catch (IOException e) {\n System.err.println(\"Erro ao atualizar o arquivo CSV: \" + e.getMessage());\n }\n }\n\n public static void removerImovel(int indice) {\n List<String> linhasCSV = lerDadosCSV();\n \n if (indice >= 0 && indice < linhasCSV.size()) {\n linhasCSV.remove(indice);\n atualizarCSVFile(linhasCSV);\n }\n }\n \n private static void atualizarCSVFile(List<String> linhas) {\n try (PrintWriter writer = new PrintWriter(new FileWriter(CSV_FILE))) {\n for (String linha : linhas) {\n writer.println(linha);\n }\n } catch (IOException e) {\n System.err.println(\"Erro ao atualizar o arquivo CSV: \" + e.getMessage());\n }\n }\n \n}" }, { "identifier": "Imovel", "path": "LuxuriousBreeze/components/Imovel.java", "snippet": "public class Imovel {\n private int imovelID;\n private String nomeImovel;\n private String localizacao;\n private String descricao;\n private double preco;\n private Date dataPublicacao;\n private String nomeUsuario;\n private int userID;\n private String contatoUsuario;\n private String tipoImovel;\n private boolean comodidadePiscina;\n private boolean comodidadeAcademia;\n private boolean comodidadeEstacionamento;\n\n public Imovel(int imovelID, String nomeImovel, String localizacao, String descricao, double preco, int userID, Date dataPublicacao, String nomeUsuario, String contatoUsuario, String tipoImovel, boolean comodidadePiscina, boolean comodidadeAcademia, boolean comodidadeEstacionamento) {\n this.imovelID = imovelID;\n this.nomeImovel = nomeImovel;\n this.localizacao = localizacao;\n this.descricao = descricao;\n this.preco = preco;\n this.dataPublicacao = dataPublicacao;\n this.nomeUsuario = nomeUsuario;\n this.userID = userID;\n this.contatoUsuario = contatoUsuario;\n this.tipoImovel = tipoImovel;\n this.comodidadePiscina = comodidadePiscina;\n this.comodidadeAcademia = comodidadeAcademia;\n this.comodidadeEstacionamento = comodidadeEstacionamento;\n }\n\n public int getImovelID() {\n return imovelID;\n }\n\n public String getNomeImovel() {\n return nomeImovel;\n }\n\n public void setNomeImovel(String nomeImovel) {\n this.nomeImovel = nomeImovel;\n }\n\n public String getLocalizacao() {\n return localizacao;\n }\n\n public void setLocalizacao(String localizacao) {\n this.localizacao = localizacao;\n }\n\n public String getDescricao() {\n return descricao;\n }\n\n public void setDescricao(String descricao) {\n this.descricao = descricao;\n }\n\n public double getPreco() {\n return preco;\n }\n\n public void setPreco(double preco) {\n this.preco = preco;\n }\n\n public String getNomeUsuario() {\n return nomeUsuario;\n }\n\n public void setNomeUsuario(String nomeUsuario) {\n this.nomeUsuario = nomeUsuario;\n }\n\n public int getUserID(){\n return userID;\n }\n\n public String getContatoUsuario() {\n return contatoUsuario;\n }\n\n public void setContatoUsuario(String contato) {\n this.contatoUsuario = contato;\n }\n\n public Date getDataPublicacao() {\n return dataPublicacao;\n }\n\n public void setDataPublicacao(Date dataPublicacao) {\n this.dataPublicacao = dataPublicacao;\n }\n \n public String getTipoImovel() {\n return tipoImovel;\n }\n\n public void setTipoImovel(String tipoImovel) {\n this.tipoImovel = tipoImovel;\n }\n\n public boolean hasComodidadePiscina() {\n return comodidadePiscina;\n }\n public boolean hasComodidadeAcademia(){\n return comodidadeAcademia;\n }\n public boolean hasComodidadeEstacionamento(){\n return comodidadeEstacionamento;\n }\n\n public String toCSV() {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n String dataPublicacaoStr = (dataPublicacao != null) ? sdf.format(dataPublicacao) : \"\";\n return imovelID + \",\" + nomeImovel + \",\" + localizacao + \",\" + descricao + \",\" + preco + \",\" + dataPublicacaoStr + \",\" + nomeUsuario + \",\" + contatoUsuario + \",\" + tipoImovel + \",\" + comodidadePiscina + \",\" + comodidadeAcademia + \",\" + comodidadeEstacionamento;\n } \n}" } ]
import LuxuriousBreeze.db.ImovelCSVHandler; import LuxuriousBreeze.components.Imovel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.util.List; import java.util.ArrayList;
2,825
package LuxuriousBreeze.pages; public class ImovelGUI extends JFrame { private JPanel formPanel; private JTextField nomeField; private JTextField descricaoField; private JTextField precoField; private JTextField localizacaoField; private JTextField nomeUsuarioField; private JTextField contatoUsuarioField; private JComboBox<String> tipoImovelComboBox; private JCheckBox comodidadePiscinaCheckBox; private JCheckBox comodidadeAcademiaCheckBox; private JCheckBox comodidadeEstacionamentoCheckBox; private JList<String> imovelList; private List<Imovel> listaDeImoveis; private DefaultListModel<String> listModel; private JButton adicionarButton; private JButton listarButton; private JButton alterarButton; private JButton excluirButton; public ImovelGUI() { setTitle("LuxuriousBreeze - Hospedagem de Imóveis by Liedson Barros"); setSize(1200, 700); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLocationRelativeTo(null); try { BufferedImage iconImage = ImageIO.read(ImovelGUI.class.getResource("../img/luxuriousBreezeLogo.png")); setIconImage(iconImage); } catch (IOException e) { e.printStackTrace(); } listModel = new DefaultListModel<>(); imovelList = new JList<>(listModel); listaDeImoveis = new ArrayList<>(); imovelList.setFixedCellHeight(120); formPanel = new JPanel(new GridLayout(11, 2)); formPanel.add(new JLabel("Nome do Imóvel:")); nomeField = new JTextField(); formPanel.add(nomeField); formPanel.add(new JLabel("Localização:")); localizacaoField = new JTextField(); formPanel.add(localizacaoField); formPanel.add(new JLabel("Descrição:")); descricaoField = new JTextField(); formPanel.add(descricaoField); formPanel.add(new JLabel("Preço: R$")); precoField = new JTextField(); formPanel.add(precoField); formPanel.add(new JLabel("Proprietário:")); nomeUsuarioField = new JTextField(); formPanel.add(nomeUsuarioField); formPanel.add(new JLabel("Contato do Proprietário:")); contatoUsuarioField = new JTextField(); formPanel.add(contatoUsuarioField); String[] tiposImovel = {"Casa", "Apartamento", "Condominio", "Sitio", "Chacara", "Terreno", "Comercio", "Outro"}; tipoImovelComboBox = new JComboBox<>(tiposImovel); adicionarButton = new JButton("Adicionar"); comodidadePiscinaCheckBox = new JCheckBox("Piscina"); comodidadeAcademiaCheckBox = new JCheckBox("Academia"); comodidadeEstacionamentoCheckBox = new JCheckBox("Estacionamento"); formPanel.add(new JLabel("Tipo de Imóvel:")); formPanel.add(tipoImovelComboBox); formPanel.add(new JLabel("Comodidades:")); formPanel.add(comodidadePiscinaCheckBox); formPanel.add(comodidadeAcademiaCheckBox); formPanel.add(comodidadeEstacionamentoCheckBox); listarButton = new JButton("Atualizar Lista de Imoveis Disponíevis"); formPanel.add(adicionarButton); formPanel.add(listarButton); alterarButton = new JButton("Alterar"); excluirButton = new JButton("Excluir"); formPanel.add(alterarButton); formPanel.add(excluirButton); add(formPanel, BorderLayout.NORTH); add(new JScrollPane(imovelList), BorderLayout.CENTER); adicionarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addImovel(); } }); listarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {
package LuxuriousBreeze.pages; public class ImovelGUI extends JFrame { private JPanel formPanel; private JTextField nomeField; private JTextField descricaoField; private JTextField precoField; private JTextField localizacaoField; private JTextField nomeUsuarioField; private JTextField contatoUsuarioField; private JComboBox<String> tipoImovelComboBox; private JCheckBox comodidadePiscinaCheckBox; private JCheckBox comodidadeAcademiaCheckBox; private JCheckBox comodidadeEstacionamentoCheckBox; private JList<String> imovelList; private List<Imovel> listaDeImoveis; private DefaultListModel<String> listModel; private JButton adicionarButton; private JButton listarButton; private JButton alterarButton; private JButton excluirButton; public ImovelGUI() { setTitle("LuxuriousBreeze - Hospedagem de Imóveis by Liedson Barros"); setSize(1200, 700); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setLocationRelativeTo(null); try { BufferedImage iconImage = ImageIO.read(ImovelGUI.class.getResource("../img/luxuriousBreezeLogo.png")); setIconImage(iconImage); } catch (IOException e) { e.printStackTrace(); } listModel = new DefaultListModel<>(); imovelList = new JList<>(listModel); listaDeImoveis = new ArrayList<>(); imovelList.setFixedCellHeight(120); formPanel = new JPanel(new GridLayout(11, 2)); formPanel.add(new JLabel("Nome do Imóvel:")); nomeField = new JTextField(); formPanel.add(nomeField); formPanel.add(new JLabel("Localização:")); localizacaoField = new JTextField(); formPanel.add(localizacaoField); formPanel.add(new JLabel("Descrição:")); descricaoField = new JTextField(); formPanel.add(descricaoField); formPanel.add(new JLabel("Preço: R$")); precoField = new JTextField(); formPanel.add(precoField); formPanel.add(new JLabel("Proprietário:")); nomeUsuarioField = new JTextField(); formPanel.add(nomeUsuarioField); formPanel.add(new JLabel("Contato do Proprietário:")); contatoUsuarioField = new JTextField(); formPanel.add(contatoUsuarioField); String[] tiposImovel = {"Casa", "Apartamento", "Condominio", "Sitio", "Chacara", "Terreno", "Comercio", "Outro"}; tipoImovelComboBox = new JComboBox<>(tiposImovel); adicionarButton = new JButton("Adicionar"); comodidadePiscinaCheckBox = new JCheckBox("Piscina"); comodidadeAcademiaCheckBox = new JCheckBox("Academia"); comodidadeEstacionamentoCheckBox = new JCheckBox("Estacionamento"); formPanel.add(new JLabel("Tipo de Imóvel:")); formPanel.add(tipoImovelComboBox); formPanel.add(new JLabel("Comodidades:")); formPanel.add(comodidadePiscinaCheckBox); formPanel.add(comodidadeAcademiaCheckBox); formPanel.add(comodidadeEstacionamentoCheckBox); listarButton = new JButton("Atualizar Lista de Imoveis Disponíevis"); formPanel.add(adicionarButton); formPanel.add(listarButton); alterarButton = new JButton("Alterar"); excluirButton = new JButton("Excluir"); formPanel.add(alterarButton); formPanel.add(excluirButton); add(formPanel, BorderLayout.NORTH); add(new JScrollPane(imovelList), BorderLayout.CENTER); adicionarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addImovel(); } }); listarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {
List<String> linhasCSV = ImovelCSVHandler.lerDadosCSV();
0
2023-10-28 22:06:39+00:00
4k
footcricket05/Whisp
src/GUI/ChatView.java
[ { "identifier": "Client", "path": "src/chat/Client.java", "snippet": "public class Client {\n // Properties\n private String clientName;\n // Socket\n private Socket clientSocket ;\n // Streams\n private InputStream inputStream;\n private OutputStream outputStream;\n private DataInputStream inData;\n private DataOutputStream outData;\n \n private boolean option = true;\n private ChatView chatView;\n\n public Client(ChatView chatView) {\n this.chatView = chatView;\n }\n \n public String getUsername() {\n return clientName;\n }\n \n public void SetConnection(String ip, int port) {\n try {\n clientSocket = new Socket(ip, port);\n Thread th1 = new Thread(new Runnable() {\n @Override\n public void run() {\n while (option) {\n ListenData(chatView);\n }\n }\n });\n th1.start();\n System.out.println(\"Successfully connected to \" + ip + \":\" + port);\n } catch (IOException ex) {\n System.err.println(\"ERROR: connection error\");\n System.exit(0);\n }\n }\n \n public void SendMessage(String msg) {\n try {\n outputStream = clientSocket.getOutputStream();\n outData = new DataOutputStream(outputStream);\n outData.writeUTF(msg);\n outData.flush();\n } catch (IOException ex) {\n System.err.println(\"ERROR: error sending data\");\n }\n }\n \n public void ListenData(ChatView chatView) {\n try {\n inputStream = clientSocket.getInputStream();\n inData = new DataInputStream(inputStream);\n chatView.AddRemoteMessage(inData.readUTF());\n } catch (IOException ex) {\n System.err.println(\"ERROR: error listening data\");\n }\n }\n \n public void CloseConnection() {\n try {\n outData.close();\n inData.close();\n clientSocket.close();\n } catch (IOException ex) {\n System.err.println(\"ERROR: error closing connection\");\n }\n }\n \n public void SetClientProperties(String name) {\n clientName = name;\n }\n \n public static void main(String [] args) {\n ChatView chatView = new ChatView();\n Client cli = new Client(chatView);\n \n CaptureView captureView = new CaptureView(chatView, true);\n captureView.SetTitleText(\"Client login\");\n captureView.SetIpEnable(true);\n captureView.setVisible(true);\n \n String cliName = captureView.GetUsername();\n cli.SetClientProperties(cliName);\n \n String ipMachine = captureView.GetIP();\n int portMachine = captureView.GetPort();\n cli.SetConnection(ipMachine, portMachine);\n \n chatView.SetClient(cli);\n chatView.SetUsername(cliName);\n \n chatView.setVisible(true);\n }\n}" }, { "identifier": "Message", "path": "src/chat/Message.java", "snippet": "public class Message {\n private String username;\n private String text;\n private String time;\n\n public Message(String username, String text) {\n this.username = username;\n this.text = text;\n Date date = new Date();\n Calendar calendar = GregorianCalendar.getInstance();\n calendar.setTime(date);\n int hour = calendar.get(Calendar.HOUR_OF_DAY);\n int min = calendar.get(Calendar.MINUTE);\n time = Integer.toString(hour) + \":\" + Integer.toString(min);\n }\n\n // SET METHODS\n public void setUsername(String username) {\n this.username = username;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n \n // GET METHODS\n public String getUsername() {\n return username;\n }\n\n public String getText() {\n return text;\n }\n \n public String getTime() {\n return time;\n }\n \n}" }, { "identifier": "Server", "path": "src/chat/Server.java", "snippet": "public class Server {\n // Properties\n private String serverName;\n // Sockets\n private Socket myService;\n private ServerSocket serviceSocket;\n \n private OutputStream outputStream;\n private InputStream inputStream;\n \n private DataOutputStream outputData;\n private DataInputStream inputData;\n \n private boolean option = true;\n private ChatView chatView;\n \n public Server(ChatView chatView) {\n this.chatView = chatView;\n }\n \n public String getUsername() {\n return serverName;\n }\n \n public void SetConnection(int port) {\n try {\n serviceSocket = new ServerSocket(port);\n System.out.println(\"Server listening on port \" + port);\n myService = serviceSocket.accept();\n Thread th1 = new Thread(new Runnable() {\n @Override\n public void run() {\n while (option) {\n ListenData(chatView);\n }\n }\n });\n th1.start();\n System.out.println(\"Successfully connected\");\n } catch (IOException ex) {\n System.err.println(\"ERROR: connection error\");\n System.exit(0);\n }\n }\n \n public void ListenData(ChatView chatView) {\n try {\n inputStream = myService.getInputStream();\n inputData = new DataInputStream(inputStream);\n chatView.AddRemoteMessage(inputData.readUTF());\n } catch (IOException ex) {\n System.err.println(\"ERROR: error listening data\");\n }\n }\n \n public void SendMessage(String msg) {\n try {\n outputStream = myService.getOutputStream();\n outputData = new DataOutputStream(outputStream);\n outputData.writeUTF(msg);\n outputData.flush();\n } catch (IOException ex) {\n System.err.println(\"ERROR: error sending data\");\n }\n }\n \n public void SetServerProperties(String name) {\n serverName = name;\n }\n \n public void CloseConnection() {\n try {\n outputData.close();\n inputData.close();\n serviceSocket.close();\n myService.close();\n } catch (IOException ex) {\n System.err.println(\"ERROR: error closing connection\");\n }\n }\n \n public static void main(String [] args) {\n ChatView chatView = new ChatView();\n Server srv = new Server(chatView);\n \n CaptureView captureView = new CaptureView(chatView, true);\n captureView.SetTitleText(\"Server login\");\n captureView.SetIpField(\"This computer\");\n captureView.SetPortField(5555);\n captureView.SetIpEnable(false);\n captureView.setVisible(true);\n \n String srvName = captureView.GetUsername();\n srv.SetServerProperties(srvName);\n \n int portMachine = captureView.GetPort();\n srv.SetConnection(portMachine);\n \n chatView.SetServer(srv);\n chatView.SetUsername(srvName);\n \n chatView.setVisible(true); \n }\n}" } ]
import chat.Client; import chat.Message; import chat.Server; import java.awt.Color; import javax.swing.BoxLayout;
1,899
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; /** * * @author dvcarrillo */ public class ChatView extends javax.swing.JFrame { private Client client; private Server server; private int mode; /** * Creates new form ChatView */ public ChatView() { initComponents(); this.setTitle("Chatroom"); messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS)); mode = 0; } /** * Set the users name that is displayed at the title */ public void SetUsername(String username) { chatroomTitle.setText("Chatroom: " + username); this.repaint(); } /** * Set client class */ public void SetClient(Client cli) { mode = 1; client = cli; } /** * Set server class */ public void SetServer(Server srv) { mode = 2; server = srv; } /** * Add a message sent from this host */ public void AddClientMessage(String msg) { if (mode == 1) {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; /** * * @author dvcarrillo */ public class ChatView extends javax.swing.JFrame { private Client client; private Server server; private int mode; /** * Creates new form ChatView */ public ChatView() { initComponents(); this.setTitle("Chatroom"); messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS)); mode = 0; } /** * Set the users name that is displayed at the title */ public void SetUsername(String username) { chatroomTitle.setText("Chatroom: " + username); this.repaint(); } /** * Set client class */ public void SetClient(Client cli) { mode = 1; client = cli; } /** * Set server class */ public void SetServer(Server srv) { mode = 2; server = srv; } /** * Add a message sent from this host */ public void AddClientMessage(String msg) { if (mode == 1) {
Message message = new Message(client.getUsername(), msg);
1
2023-10-31 07:52:11+00:00
4k
USSEndeavour/MultithreadedHarborSimulator
src/port/Main.java
[ { "identifier": "DockPool", "path": "src/port/concurrent/DockPool.java", "snippet": "public class DockPool<T extends AbstractDock> {\n // The maximum number of docks that can be simultaneously allocated.\n private static final int MAX_AVAILABLE = Port.DOCK_NUMBER;\n // Semaphore to control access to the docks.\n private Semaphore semaphore = new Semaphore(MAX_AVAILABLE, true);\n // The list of dock resources managed by this pool.\n private List<T> resources;\n\n // Constructor to create a pool with a list of dock resources.\n public DockPool(List<T> source) {\n resources = new ArrayList<>(source); // Initialize the resources list with the given source list.\n }\n\n // Method to get a resource from the pool, waiting for a maximum time if necessary.\n public T getResource(DockClient dockClient, long maxWaitMillis) throws ResourceException {\n try {\n // Try to acquire a permit from the semaphore within the given waiting time.\n if (semaphore.tryAcquire(maxWaitMillis, TimeUnit.SECONDS)) {\n for (T resource : resources) {\n // Check if the current resource is not busy.\n if (!resource.isBusy()) {\n resource.setBusy(true); // Mark the resource as busy.\n System.out.println(\"DockClient #\" + dockClient.getId() + \" took dock \" + resource);\n return resource; // Return the acquired resource.\n }\n }\n }\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt(); // Handle the InterruptedException.\n }\n // If a resource is not acquired, throw a ResourceException.\n throw new ResourceException(\"Could not acquire a dock within \" + maxWaitMillis + \" seconds.\");\n }\n\n // Method to release a resource back to the pool.\n public void releaseResource(DockClient dockClient, T resource) {\n resource.setBusy(false); // Mark the resource as not busy.\n System.out.println(\"DockClient #\" + dockClient.getId() + \": \" + resource + \" --> released\");\n semaphore.release(); // Release the permit back to the semaphore.\n }\n\n // Static method to get the maximum number of docks available in the pool.\n public static int getMaxAvailable() {\n return MAX_AVAILABLE;\n }\n}" }, { "identifier": "DockClient", "path": "src/port/concurrent/DockClient.java", "snippet": "public class DockClient implements Runnable {\n private int id;\n private DockPool<AbstractDock> pool; // Dock pool from which this client will request docks.\n Ship ship;\n public Thread t;\n Random rand = new Random();\n\n // Constructor for creating a new dock client with a specific dock pool.\n public DockClient(DockPool<AbstractDock> pool) {\n id = rand.nextInt(1000); // Assign a random unique ID to this dock client.\n int currentCapacity = rand.nextInt(10); // Assign a random capacity to this dock client's ship.\n t = new Thread(this, \"DockClient\");\n ship = new Ship(id, currentCapacity);\n this.pool = pool;\n }\n\n // Getter method to retrieve the ID of the dock client.\n public int getId() {\n return id;\n }\n\n // The main execution method for the dock client thread.\n @Override\n public void run() {\n AbstractDock dock = null;\n try {\n dock = pool.getResource(this, 8); // Try to acquire a dock from the pool with a maximum wait time.\n dock.using(ship); // Utilize the dock for ship operations such as loading or unloading.\n } catch (IndexOutOfBoundsException e) {\n // This exception is thrown if the operation on the ship is not permissible (like unloading from an empty ship).\n System.out.println(e.getMessage());\n } catch (Exception e) {\n // General catch block for any other exceptions that occur during dock usage.\n System.err.println(\"DockClient #\" + this.getId() + \" encountered an issue -> \" + e.getMessage());\n } finally {\n // Finally block ensures that the dock is released back to the pool even if an exception is thrown.\n if (dock != null) {\n pool.releaseResource(this, dock);\n }\n }\n }\n}" }, { "identifier": "AbstractDock", "path": "src/port/models/AbstractDock.java", "snippet": "public abstract class AbstractDock {\n private volatile boolean busy; // indicates if the dock is currently being used\n\n /**\n * Checks if the dock is busy.\n * @return true if the dock is in use, false otherwise.\n */\n public boolean isBusy() {\n return busy;\n }\n\n /**\n * Sets the dock's busy status.\n * @param busy the new busy status to be set.\n */\n public void setBusy(boolean busy) {\n this.busy = busy;\n }\n\n /**\n * An abstract method to be implemented by subclasses to define how a ship is handled\n * when it uses the dock. This method could involve unloading or loading containers,\n * refueling the ship, or any other process relevant to the dock's function.\n *\n * @param ship The ship to be handled at the dock.\n * @throws ContainerUnderflowException If the operation would result in fewer than zero containers.\n * @throws ContainerOverflowException If the operation would exceed the maximum number of containers.\n */\n public abstract void using(Ship ship) throws ContainerUnderflowException, ContainerOverflowException;\n}" }, { "identifier": "Port", "path": "src/port/models/Port.java", "snippet": "public class Port<T extends AbstractDock> {\n private final int MAX_PORT_CAPACITY = 50; // The maximum number of containers the port can handle.\n public static final int DOCK_NUMBER = 4; // The number of docks available in the port.\n private volatile int currentCapacity; // The current number of containers in the port.\n private Random rand; // Random generator for initializing current capacity.\n private DockPool<Dock> dockPool; // The pool managing the docks.\n private List<Dock> docks; // The list of docks.\n\n /**\n * Constructs a port and initializes its current capacity randomly.\n */\n public Port() {\n rand = new Random();\n currentCapacity = rand.nextInt(20); // Initialize to a random capacity at startup.\n }\n\n /**\n * This inner class represents a dock in the port.\n */\n public class Dock extends AbstractDock {\n private int id; // The identifier for the dock.\n\n // Inherited method to check if the dock is busy.\n @java.lang.Override\n public boolean isBusy() {\n return super.isBusy();\n }\n\n /**\n * Constructs a dock with a specified identifier.\n * @param id The identifier for the dock.\n */\n public Dock(int id) {\n this.id = id;\n }\n\n // Gets the identifier of the dock.\n public int getId() {\n return id;\n }\n\n // Sets the identifier of the dock.\n public void setId(int id) {\n this.id = id;\n }\n\n // Handles the process of using the dock by a ship, specifically unloading containers.\n @java.lang.Override\n public void using(Ship ship) throws ContainerUnderflowException, ContainerOverflowException {\n System.out.println(\"Unloading Ship#\" + ship.getId() + \" ...\");\n\n for (int i = 0; i < ship.getCurrentCapacity(); i++) {\n System.out.println(\"Unloading container # \" + i + \"\\n\");\n ship.unloadContainer();\n addContainer(); // Add the container to the port's capacity.\n\n try {\n TimeUnit.SECONDS.sleep(1); // Simulate time taken to unload one container.\n } catch (InterruptedException e) {\n e.printStackTrace(); // Handle the interrupted exception.\n }\n }\n\n System.out.println(\"Ship#\" + ship.getId() + \" unloaded.\");\n }\n\n // Represents the dock information as a String.\n public String toString() {\n StringBuilder sb = new StringBuilder(\"Dock{\");\n sb.append(\"id=\").append(id).append(\", busy=\").append(isBusy()).append('}');\n return sb.toString();\n }\n }\n\n /**\n * Adds a container to the port's current capacity, ensuring the capacity does not exceed the maximum.\n * @throws ContainerOverflowException If adding a container exceeds the port's maximum capacity.\n */\n private synchronized void addContainer() throws ContainerOverflowException {\n if (currentCapacity == MAX_PORT_CAPACITY) {\n throw new ContainerOverflowException(\"The port storage is full of containers\");\n }\n this.currentCapacity++; // Increment the port's container count.\n }\n\n /**\n * Initializes the dock pool with docks and returns it for use.\n * @return The initialized dock pool.\n */\n public DockPool getDockPool() {\n docks = new ArrayList<>();\n for (int i = 1; i <= DOCK_NUMBER; i++) {\n docks.add(new Dock(i)); // Add new docks to the list.\n }\n dockPool = new DockPool<>(docks); // Create a new DockPool with the list of docks.\n return dockPool;\n }\n}" } ]
import port.concurrent.DockPool; import port.concurrent.DockClient; import port.models.AbstractDock; import port.models.Port; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit;
2,205
package port; public class Main { private static final int NUM_OF_CLIENTS = 20; // Define the number of dock clients public static void main(String[] args) { // Prepare the port with its docks Port port = new Port();
package port; public class Main { private static final int NUM_OF_CLIENTS = 20; // Define the number of dock clients public static void main(String[] args) { // Prepare the port with its docks Port port = new Port();
DockPool<AbstractDock> pool = port.getDockPool(); // Retrieve the pool of docks
2
2023-10-27 12:56:39+00:00
4k
HeitorLouzeiro/gerenciador-disciplinas-java
core/src/test/java/com/project/SecretarioDAOTest.java
[ { "identifier": "Aluno", "path": "core/src/main/java/com/project/Classes/Aluno.java", "snippet": "public class Aluno extends Usuario {\n /**\n * Construtor padrão da classe Aluno.\n \n */\n public Aluno() {\n \n }\n\n // A classe Aluno herda os atributos e métodos da classe Usuario.\n // Não são necessários métodos ou atributos adicionais nesta classe específica.\n}" }, { "identifier": "SecretarioDAO", "path": "core/src/main/java/com/project/Dao/SecretarioDAO.java", "snippet": "public class SecretarioDAO {\n private Connection connection;\n\n /**\n * Construtor da classe SecretarioDAO. Obtém uma conexão com o banco de dados utilizando a classe DataBase.\n *\n * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados.\n */\n\n public SecretarioDAO() throws IOException {\n connection = DataBase.getInstance().getConnection();\n }\n\n /**\n * Recupera informações sobre os alunos do banco de dados e imprime na saída padrão.\n *\n * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL.\n */\n\n public void getAlunos() throws SQLException {\n Statement statement = connection.createStatement();\n \n String sql = \"SELECT * FROM usuario WHERE tipoUsuario = 'Aluno'\";\n \n ResultSet resultSet = statement.executeQuery(sql);\n\n while (resultSet.next()) {\n System.out.println(\"ID: \" + resultSet.getString(\"codUsuario\") + \" \" + resultSet.getString(\"nome\") + \" Usuario:\" + resultSet.getString(\"tipoUsuario\"));\n\n }\n statement.close();\n }\n /**\n * Seleciona um aluno do banco de dados com base no código do usuário.\n *\n * @param codUsuario O código do usuário do aluno a ser selecionado.\n * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados.\n * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL.\n */\n\n public void SelectAlunoGetByCod(int codUsuario ) throws IOException, SQLException {\n System.out.println(\"Selecionando Aluno...\");\n\n PreparedStatement statement = connection.prepareStatement(\"SELECT * FROM Usuario WHERE codUsuario = ?\");\n\n statement.setInt(1, codUsuario);\n\n ResultSet resultSet = statement.executeQuery();\n\n while (resultSet.next()) {\n System.out.println(\"Nome: \" + resultSet.getString(\"nome\") + \" Usuario:\" + resultSet.getString(\"tipoUsuario\"));\n }\n\n\n statement.close();\n }\n /**\n * Insere um novo aluno no banco de dados.\n *\n * @param aluno O objeto Aluno a ser inserido no banco de dados.\n * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados.\n * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL.\n */\n\n public void InsertAluno(Aluno aluno) throws IOException, SQLException {\n System.out.println(\"Inserindo Aluno...\");\n\n\n\n PreparedStatement statement = connection.prepareStatement(\"INSERT INTO Usuario (nome, cpf, dataNascimento, dataEntrada, senha, codCurso, tipoUsuario) VALUES (?, ?, ?, ?, ?, ?, ?)\");\n\n statement.setString(1, aluno.getNome());\n statement.setString(2, aluno.getCpf());\n statement.setString(3, aluno.getDataNascimento().getData());\n statement.setString(4, aluno.getDataEntrada().getData());\n statement.setString(5, aluno.getSenha());\n statement.setInt(6, aluno.getCodCurso());\n statement.setString(7, \"Aluno\");\n\n statement.executeUpdate();\n\n System.out.println(\"Aluno Cadastrado com sucesso!\");\n\n statement.close();\n }\n /**\n * Atualiza as informações de um aluno no banco de dados.\n *\n * @param aluno O objeto Aluno com as informações atualizadas.\n * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados.\n * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL.\n */\n\n public void UpdateAluno(Aluno aluno) throws IOException, SQLException {\n System.out.println(\"Atualizando Aluno...\");\n\n PreparedStatement statement = connection.prepareStatement(\"UPDATE Usuario SET nome = ?, cpf = ?, dataNascimento = ?, dataEntrada = ?, senha = ? WHERE codUsuario = ?\");\n\n statement.setString(1, aluno.getNome());\n statement.setString(2, aluno.getCpf());\n statement.setString(3, aluno.getDataNascimento().getData());\n statement.setString(4, aluno.getDataEntrada().getData());\n statement.setString(5, aluno.getSenha());\n statement.setInt(6, aluno.getCodUsuario());\n\n statement.executeUpdate();\n\n System.out.println(\"Aluno Atualizado!\");\n\n statement.close();\n }\n /**\n * Deleta um aluno do banco de dados com base no código do usuário.\n *\n * @param codUsuario O código do usuário do aluno a ser deletado.\n * @throws IOException Se ocorrer um erro de leitura durante a obtenção da conexão com o banco de dados.\n * @throws SQLException Se ocorrer um erro durante a execução da consulta SQL.\n */\n \n public void DeleteAluno(int codUsuario ) throws IOException, SQLException {\n System.out.println(\"Deletando Aluno...\");\n\n PreparedStatement statement = connection.prepareStatement(\"DELETE FROM Usuario WHERE codUsuario = ?\");\n\n statement.setInt(1, codUsuario);\n\n statement.executeUpdate();\n\n statement.close();\n\n System.out.println(\"Aluno Deletado!\");\n }\n\n\n}" }, { "identifier": "DataBase", "path": "core/src/main/java/com/project/DataBase/DataBase.java", "snippet": "public class DataBase {\n // Variável para armazenar a conexão com o banco de dados.\n private Connection connection = null;\n\n // Variável para armazenar a instância do banco de dados.\n private static DataBase INSTANCE = null;\n\n /**\n * Construtor privado da classe DataBase. Inicia a conexão com o banco de dados e executa uma instrução SQL.\n *\n * @throws IOException Se ocorrer um erro de leitura durante o carregamento do arquivo SQL.\n */\n private DataBase() throws IOException {\n try {\n // Estabelece uma conexão com o banco de dados e armazena em uma variavel.\n connection = DriverManager.getConnection(\"jdbc:sqlite:core/sample.db\");\n\n // Cria uma instrução SQL que será executada.\n Statement statement = connection.createStatement();\n \n statement.setQueryTimeout(30); // Tempo limite de 30 segundos.\n\n // Ler o arquivo de texto e armazena em uma variável.\n String sql = FileUltils.loadTextFile(\"core/src/main/java/com/project/Resource/Description.sql\");\n\n // Executa a instrução SQL.\n statement.executeUpdate(sql);\n\n } catch (SQLException e) {\n // Em caso de erro, imprime o erro no console.\n System.err.println(\"Error connecting to the database\");\n e.printStackTrace();\n }\n }\n\n \n /**\n * Obtém a conexão com o banco de dados.\n *\n * @return A conexão com o banco de dados.\n */\n public Connection getConnection() {\n // Permite que outras classes acessem a conexão com o banco de dados.\n return this.connection;\n }\n\n /**\n * Fecha a conexão com o banco de dados.\n */\n\n // Permite que outras classes fechem a conexão com o banco de dados.\n public void closeConnection() {\n try {\n if (connection != null)\n connection.close();\n } catch (SQLException e) {\n System.err.println(\"Error closing database connection\");\n e.printStackTrace();\n }\n }\n /**\n * Obtém a instância da classe DataBase. Implementa o padrão Singleton.\n *\n * Esse padrão garante que apenas uma instância da classe DataBase seja criada durante a execução do programa.\n * \n * @return A instância única da classe DataBase.\n * @throws IOException Se ocorrer um erro de leitura durante o carregamento do arquivo SQL.\n */\n // Permite que outras classes acessem a instância do banco de dados.\n public static DataBase getInstance() throws IOException {\n // Se a instância for nula, cria uma nova instância.\n if (INSTANCE == null) {\n INSTANCE = new DataBase();\n }\n // Retorna a instância.\n return INSTANCE;\n }\n}" }, { "identifier": "Data", "path": "core/src/main/java/com/project/Classes/Data.java", "snippet": "public class Data {\n private int dia;\n private int mes;\n private int ano;\n\n /**\n * Define a data com base na representação de string fornecida.\n *\n * @param dataString A representação de string da data no formato \"dd-MM-yyyy\".\n * @throws DateTimeParseException Se a string não puder ser convertida para uma\n * data válida.\n */\n public void setData(String dataString) throws DateTimeParseException {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd-MM-yyyy\");\n try {\n LocalDate data = LocalDate.parse(dataString, formatter);\n\n verificaAno(data.getYear());\n\n this.dia = data.getDayOfMonth();\n this.mes = data.getMonthValue();\n this.ano = data.getYear();\n } catch (DateTimeParseException e) {\n // Relança a exceção para que possa ser tratada no bloco catch externo\n throw e;\n }\n }\n\n public String getDataAtual() {\n LocalDate dataAtual = LocalDate.now();\n this.dia = dataAtual.getDayOfMonth();\n this.mes = dataAtual.getMonthValue();\n this.ano = dataAtual.getYear();\n\n return this.dia + \"-\" + this.mes + \"-\" + this.ano;\n }\n\n public void verificaAno(int ano) {\n int anoAtual = LocalDate.now().getYear();\n if (ano > anoAtual) {\n throw new IllegalArgumentException(\"Ano inválido. Você não pode inserir uma data futura.\");\n }\n }\n\n /**\n * Converte a instância Data para LocalDate.\n *\n * @return Um objeto LocalDate representando a data.\n */\n public LocalDate toLocalDate() {\n return LocalDate.of(this.ano, this.mes, this.dia);\n }\n\n /**\n * Obtém a representação de string da data no formato \"dd-MM-yyyy\".\n *\n * @return A representação de string da data.\n */\n public String getData() {\n return this.dia + \"-\" + this.mes + \"-\" + this.ano;\n }\n\n /**\n * Calcula o tempo total em anos desde uma data de entrada até a data atual.\n *\n * @param dataEntrada A data de entrada a ser considerada no cálculo.\n * @return O tempo total em anos.\n */\n public long calcularTempoTotal(LocalDate dataEntrada) {\n LocalDate dataAtual = LocalDate.now();\n\n // Calcula o tempo total em anos usando a diferença em dias e dividindo por 365\n long anosTrabalhados = Duration.between(dataEntrada.atStartOfDay(), dataAtual.atStartOfDay()).toDays() / 365;\n\n return anosTrabalhados;\n }\n\n /**\n * Calcula a idade com base na data de nascimento armazenada na instância.\n *\n * @return A idade calculada.\n */\n public int calcularIdade() {\n LocalDate dataNascimento = LocalDate.of(this.ano, this.mes, this.dia);\n LocalDate dataAtual = LocalDate.now();\n return dataAtual.getYear() - dataNascimento.getYear();\n }\n}" } ]
import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.time.format.DateTimeParseException; import com.project.Classes.Aluno; import com.project.Dao.SecretarioDAO; import com.project.DataBase.DataBase; import com.project.Classes.Data;
3,034
package com.project; /** * Classe de teste para as operações CRUD na classe SecretarioDAO para a * entidade Aluno. * * Este código é destinado apenas para fins de teste e não faz parte do projeto * principal. * * @author Heitor Louzeiro */ public class SecretarioDAOTest { /** * Método principal para execução do teste. * * @param args Argumentos de linha de comando (não utilizados neste exemplo). * @throws IOException Se ocorrer um erro de leitura durante a execução do * teste. */ public static void main(String[] args) throws IOException { Connection connection = null; try { // Obtém uma conexão com o banco de dados
package com.project; /** * Classe de teste para as operações CRUD na classe SecretarioDAO para a * entidade Aluno. * * Este código é destinado apenas para fins de teste e não faz parte do projeto * principal. * * @author Heitor Louzeiro */ public class SecretarioDAOTest { /** * Método principal para execução do teste. * * @param args Argumentos de linha de comando (não utilizados neste exemplo). * @throws IOException Se ocorrer um erro de leitura durante a execução do * teste. */ public static void main(String[] args) throws IOException { Connection connection = null; try { // Obtém uma conexão com o banco de dados
connection = DataBase.getInstance().getConnection();
2
2023-10-30 18:29:39+00:00
4k
thinhunan/wonder8-captcha
src/main/java/com/github/thinhunan/wonder8/captchaservice/controllers/CaptchaController.java
[ { "identifier": "CaptchaConfig", "path": "src/main/java/com/github/thinhunan/wonder8/captchaservice/CaptchaConfig.java", "snippet": "@Component\npublic class CaptchaConfig {\n @Value(\"${captcha.prepareSize}\")\n public int prepareSize;\n @Value(\"${captcha.renewSize}\")\n public int renewSize;\n @Value(\"${captcha.width}\")\n public int width;\n @Value(\"${captcha.height}\")\n public int height;\n @Value(\"${captcha.image.quality}\")\n public float image_quality;\n @Value(\"${captcha.verify.distance}\")\n public int verify_distance;\n @Value(\"${captcha.checkKey}\")\n public String checkKey;\n @Value(\"${captcha.backgroundImage.dir}\")\n public String backgroundImage_dir;\n @Value(\"${captcha.log.enabled}\")\n public boolean logEnabled;\n}" }, { "identifier": "CaptchaRxRepository", "path": "src/main/java/com/github/thinhunan/wonder8/captchaservice/modules/CaptchaRxRepository.java", "snippet": "@Repository\npublic class CaptchaRxRepository {\n\n private static final Logger logger = LoggerFactory.getLogger(\"CaptchaRxRepository\");\n private RedisClient redisClient;\n private CaptchaConfig captchaConfig;\n private CaptchaUtils captchaUtils;\n\n public CaptchaRxRepository(CaptchaConfig captchaConfig, RedisClient redisClient, CaptchaUtils captchaUtils){\n this.captchaConfig = captchaConfig;\n this.redisClient = redisClient;\n this.captchaUtils = captchaUtils;\n }\n\n // region get captcha\n public Mono<Captcha> getCaptcha(double captchaId){\n RedisReactiveCommands<byte[], byte[]> commands = redisClient.getReactiveByteArrayCommands();\n Mono<byte[]> info = commands.zrangebyscore(Constants.INFO_KEY,Range.create(captchaId,captchaId)).singleOrEmpty();\n Mono<byte[]> image = commands.zrangebyscore(Constants.IMAGE_KEY,Range.create(captchaId,captchaId)).singleOrEmpty();\n return Mono.zip(info,image,(i1,i2)->Captcha.fromRedis(captchaId,i1,i2));\n }\n\n private Mono<Captcha> getRandomCaptchaWithoutImage(){\n RedisReactiveCommands<byte[], byte[]> commands = redisClient.getReactiveByteArrayCommands();\n return commands.zrandmemberWithScores(Constants.INFO_KEY,1).singleOrEmpty()\n .map(v->Captcha.fromRedis(v.getScore(),v.getValue()));\n }\n\n public Mono<Captcha> linkCodeToRandomCaptcha(String code){\n return getRandomCaptchaWithoutImage().doOnNext(captcha -> {\n String key = \"captcha:link:\"+code;\n long seconds = 5*60; // exists 5 minutes\n redisClient.getReactiveStringCommands()\n .setex(key,seconds,Double.toString(captcha.id))\n .subscribe();\n if(this.captchaConfig.logEnabled) {\n logger.info(\"register:\" + code + \" with \" + (long) captcha.id);\n }\n });\n }\n\n public Mono<Captcha> getLinkedCaptcha(String code){\n String key = \"captcha:link:\"+code;\n return redisClient.getReactiveStringCommands().get(key).flatMap(id->getCaptcha(Double.parseDouble(id)));\n }\n\n //#endregion\n\n // region verify\n public Mono<Boolean> verify(String code,int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){\n int distanceThreshold = this.captchaConfig.verify_distance;\n String key = \"captcha:link:\"+code;\n RedisReactiveCommands<String, String> cmd = redisClient.getReactiveStringCommands();\n return cmd.get(key).defaultIfEmpty(\"\").flatMap(id->{\n if(Strings.isEmpty(id)){\n return Mono.just(false);\n }\n cmd.del(key).subscribe();\n double captchaId = Double.parseDouble(id);\n return getCaptcha(captchaId).map(c->{\n if(c == null || c.getInfo() == null){\n return false;\n }\n boolean verified = isNear(x1,y1,c.getInfo().get(0),distanceThreshold) &&\n isNear(x2,y2,c.getInfo().get(1),distanceThreshold)&&\n isNear(x3,y3,c.getInfo().get(2),distanceThreshold)&&\n isNear(x4,y4,c.getInfo().get(3),distanceThreshold);\n if(verified){\n String v_key = \"captcha:verify:\"+code;\n long seconds = 5*60; // exists 5 minutes\n cmd.setex(v_key,seconds,\"1\").subscribe();\n }\n if(this.captchaConfig.logEnabled) {\n logger.info(String.format(\"verify %s %s\", code, verified));\n }\n return verified;\n });\n });\n }\n\n boolean isNear(int x1, int y1, CaptchaText info, int distanceThreshold){\n double threshold = distanceThreshold + info.fontSize/2.0;\n double distance = Math.sqrt(Math.pow(x1-info.x,2) + Math.pow(y1 - info.y,2));\n if(this.captchaConfig.logEnabled) {\n logger.info(String.format(\"(x1:%d,y1:%d),(x2:%d,y2:%d,font:%d),dist:%.2f,thresh:%.2f %s\",\n x1,y1,info.getX(),info.getY(),info.getFontSize(),distance,threshold,distance<threshold?\"pass\":\"no pass\"));\n }\n return distance < threshold;\n }\n // endregion\n\n // region check\n public Mono<Boolean> check(String code,String key){\n if(!this.captchaConfig.checkKey.equals(key)){\n throw new IllegalArgumentException(\"Illegal check key.\");\n }\n String id = \"captcha:verify:\"+code;\n RedisReactiveCommands<String, String> cmd = redisClient.getReactiveStringCommands();\n return cmd.get(id).defaultIfEmpty(\"0\").map(v->{\n cmd.del(id).subscribe();\n boolean verified = \"1\".equals(v);\n if(this.captchaConfig.logEnabled) {\n logger.info(String.format(\"check verify %s %s\", code, verified));\n }\n return verified;\n });\n }\n // endregion\n\n //#region prepare data\n\n public void prepareCaptcha(int count) {\n CaptchaUtils utils = this.captchaUtils;\n RedisReactiveCommands<byte[], byte[]> cmd = redisClient.getReactiveByteArrayCommands();\n Flux.range(0,count).subscribe(integer -> utils.getCaptchaIdRx(cmd).subscribe(id->{\n Captcha captcha = utils.generateCaptchaImage();\n cmd.zadd(Constants.IMAGE_KEY,id,captcha.getImage()).subscribe();\n cmd.zadd(Constants.INFO_KEY,id,captcha.toRedisInfoValue()).subscribe();\n }));\n }\n\n public void refreshCaptcha(int count){\n this.prepareCaptcha(count);\n\n RedisReactiveCommands<byte[], byte[]> cmd = redisClient.getReactiveByteArrayCommands();\n long idBeforeHalfHour = captchaUtils.getEpochSeconds(LocalDateTime.now().minusMinutes(30));\n long idBeforeAnHour = captchaUtils.getEpochSeconds(LocalDateTime.now().minusMinutes(60));\n cmd.zrangebyscoreWithScores(\n Constants.IMAGE_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeHalfHour)),\n Limit.unlimited())\n .doOnComplete(() -> cmd.zremrangebyscore(\n Constants.IMAGE_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeHalfHour)))\n .subscribe())\n .subscribe(i -> cmd.zadd(Constants.OLD_IMAGE_KEY, i.getScore(), i.getValue()).subscribe());\n\n cmd.zrangebyscoreWithScores(\n Constants.INFO_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeHalfHour)),\n Limit.unlimited())\n .doOnComplete(() -> cmd.zremrangebyscore(\n Constants.INFO_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeHalfHour)))\n .subscribe())\n .subscribe(i -> cmd.zadd(Constants.OLD_INFO_KEY, i.getScore(), i.getValue()).subscribe());\n\n cmd.zremrangebyscore(\n Constants.OLD_INFO_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeAnHour)))\n .subscribe();\n cmd.zremrangebyscore(\n Constants.OLD_IMAGE_KEY,\n Range.from(Range.Boundary.including(0), Range.Boundary.including(idBeforeAnHour)))\n .subscribe();\n }\n\n //#endregion\n}" } ]
import com.github.thinhunan.wonder8.captchaservice.CaptchaConfig; import com.github.thinhunan.wonder8.captchaservice.modules.CaptchaRxRepository; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import java.io.IOException; import java.util.stream.Collectors;
2,121
package com.github.thinhunan.wonder8.captchaservice.controllers; @RequestMapping(value = "/api/v2") @RestController public class CaptchaController { private CaptchaRxRepository captchaRxRepository;
package com.github.thinhunan.wonder8.captchaservice.controllers; @RequestMapping(value = "/api/v2") @RestController public class CaptchaController { private CaptchaRxRepository captchaRxRepository;
private CaptchaConfig captchaConfig;
0
2023-10-30 12:36:16+00:00
4k
llllllxy/tiny-security-boot-starter
src/main/java/org/tinycloud/security/provider/SingleAuthProvider.java
[ { "identifier": "AuthProperties", "path": "src/main/java/org/tinycloud/security/AuthProperties.java", "snippet": "@ConfigurationProperties(prefix = \"tiny-security\")\npublic class AuthProperties {\n\n private String storeType = \"redis\";\n\n private String tokenName = \"token\";\n\n private Integer timeout = 3600;\n\n private String tokenStyle = \"uuid\";\n\n private String tokenPrefix;\n\n private String tableName = \"s_auth_token\";\n\n public String getStoreType() {\n return storeType;\n }\n\n public void setStoreType(String storeType) {\n this.storeType = storeType;\n }\n\n public String getTokenName() {\n return tokenName;\n }\n\n public void setTokenName(String tokenName) {\n this.tokenName = tokenName;\n }\n\n public Integer getTimeout() {\n return timeout;\n }\n\n public void setTimeout(Integer timeout) {\n this.timeout = timeout;\n }\n\n public String getTokenStyle() {\n return tokenStyle;\n }\n\n public void setTokenStyle(String tokenStyle) {\n this.tokenStyle = tokenStyle;\n }\n\n public String getTokenPrefix() {\n return tokenPrefix;\n }\n\n public void setTokenPrefix(String tokenPrefix) {\n this.tokenPrefix = tokenPrefix;\n }\n\n public String getTableName() {\n return tableName;\n }\n\n public void setTableName(String tableName) {\n this.tableName = tableName;\n }\n}" }, { "identifier": "AuthConsts", "path": "src/main/java/org/tinycloud/security/consts/AuthConsts.java", "snippet": "public class AuthConsts {\n\n /**\n * 登录用户 令牌 Redis Key 前缀\n */\n public static final String AUTH_TOKEN_KEY = \"tinysecurity:auth:token:\";\n\n // 无权限访问\n public static int CODE_NO_PERMISSION = 403;\n\n // 未登录或会话已失效\n public static int CODE_UNAUTHORIZED = 401;\n}" }, { "identifier": "CommonUtil", "path": "src/main/java/org/tinycloud/security/util/CommonUtil.java", "snippet": "public class CommonUtil {\n\n private final static String TIME_FORMAT = \"yyyyMMddHHmmss\";\n\n\n /**\n * 获取当前时间 比如 DateTool.getCurrentTime(); 返回值为 20120515234420\n *\n * @return dateTimeStr yyyyMMddHHmmss\n */\n public static String getCurrentTime() {\n LocalDateTime dateTime = LocalDateTime.now();\n DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT);\n return dateTimeFormatter.format(dateTime);\n }\n\n /**\n * 在当前时间上增加 若干秒\n *\n * @param secondsCount 要增加的秒数\n * @return 固定格式 yyyyMMddHHmmss\n */\n public static String currentTimePlusSeconds(int secondsCount) {\n LocalDateTime time = LocalDateTime.now();\n LocalDateTime newTime = time.plusSeconds(secondsCount); // 增加几秒\n DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT);\n return dateTimeFormatter.format(newTime);\n }\n\n /**\n * 在当前时间上减少 若干秒\n *\n * @param secondsCount 要减少的秒数\n * @return 固定格式 yyyyMMddHHmmss\n */\n public static String currentTimeMinusSeconds(int secondsCount) {\n LocalDateTime time = LocalDateTime.now();\n LocalDateTime newTime = time.minusSeconds(secondsCount); // 减少几秒\n DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT);\n return dateTimeFormatter.format(newTime);\n }\n\n\n /**\n * 生成指定长度的随机字符串(包括大小写字母,数字和下划线)\n *\n * @param length 字符串的长度\n * @return 一个随机字符串\n */\n public static String getRandomString(int length) {\n String str = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n int number = ThreadLocalRandom.current().nextInt(63);\n sb.append(str.charAt(number));\n }\n return sb.toString();\n }\n\n /**\n * 字符串转时间 然后比较大小\n *\n * @param tempTime 要比较的时间字符串,格式为yyyyMMddHHmmss,\n * @return true:输入时间大于当前时间 ,false:输入时间小于当前时间\n */\n public static boolean timeCompare(String tempTime) {\n DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(TIME_FORMAT);\n LocalDateTime localDateTime = LocalDateTime.parse(tempTime, dtf2);\n return localDateTime.isAfter(LocalDateTime.now());\n }\n\n}" }, { "identifier": "TokenGenUtil", "path": "src/main/java/org/tinycloud/security/util/TokenGenUtil.java", "snippet": "public class TokenGenUtil {\n\n final static String TOKEN_STYLE_UUID = \"uuid\";\n\n final static String TOKEN_STYLE_SNOWFLAKE = \"snowflake\";\n\n final static String TOKEN_STYLE_OBJECTID = \"objectid\";\n\n final static String TOKEN_STYLE_RANDOM128 = \"random128\";\n\n final static String TOKEN_STYLE_NANOID = \"nanoid\";\n\n /**\n * 根据参数生存不同风格的token字符串\n *\n * @param tokenStyle token风格\n * @return token字符串\n */\n public static String genTokenStr(String tokenStyle) {\n String token;\n switch (tokenStyle) {\n case TOKEN_STYLE_UUID:\n token = UUID.randomUUID().toString().replace(\"-\", \"\");\n break;\n case TOKEN_STYLE_SNOWFLAKE:\n token = Snowflake.nextId();\n break;\n case TOKEN_STYLE_OBJECTID:\n token = ObjectId.nextId();\n break;\n case TOKEN_STYLE_RANDOM128:\n token = CommonUtil.getRandomString(128);\n break;\n case TOKEN_STYLE_NANOID:\n token = NanoId.INSTANCE.randomNanoId();\n break;\n default:\n token = UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n break;\n }\n return token;\n }\n\n}" } ]
import org.springframework.util.Assert; import org.tinycloud.security.AuthProperties; import org.tinycloud.security.consts.AuthConsts; import org.tinycloud.security.util.CommonUtil; import org.tinycloud.security.util.TokenGenUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*;
3,570
} } /** * 获取指定key的剩余存活时间 (单位:秒) * * @param key 键 */ private long getKeyTimeout(String key) { // 先检查是否已经过期 clearKeyByTimeout(key); // 获取过期时间 Long expire = expireMap.get(key); // 如果根本没有这个值,则直接返回NOT_VALUE_EXPIRE if (expire == null) { return SingleAuthProvider.NOT_VALUE_EXPIRE; } // 计算剩余时间并返回 long timeout = (expire - System.currentTimeMillis()) / 1000; // 小于零时,视为不存在,返回NOT_VALUE_EXPIRE if (timeout < 0) { dataMap.remove(key); expireMap.remove(key); return SingleAuthProvider.NOT_VALUE_EXPIRE; } return timeout; } // ------------------------ 定时清理过期数据 ------------------------ // /** * 线程池核心线程数最大值 */ private static final int corePoolSize = 5; /** * 用于定时执行数据清理的线程池 */ private volatile ScheduledExecutorService executorService; /** * 是否继续执行数据清理的线程标记 */ private volatile boolean refreshFlag; /** * 清理所有已经过期的key */ public void refreshDataMap() { for (String key : expireMap.keySet()) { clearKeyByTimeout(key); } } /** * 初始化定时任务 */ public void initRefreshThread() { // 启动定时刷新 this.refreshFlag = true; // 双重校验构造一个单例的ScheduledThreadPool if (this.executorService == null) { synchronized (SingleAuthProvider.class) { if (this.executorService == null) { this.executorService = Executors.newScheduledThreadPool(corePoolSize); this.executorService.scheduleWithFixedDelay(() -> { log.info("SingleAuthProvider - refreshSession - at :{}", CommonUtil.getCurrentTime()); try { // 如果已经被标记为结束 if (!refreshFlag) { return; } // 执行清理方法 refreshDataMap(); } catch (Exception e2) { log.error("SingleAuthProvider - refreshSession - Exception:{e2}", e2); } }, 10/*首次延迟多长时间后执行*/, DATA_REFRESH_PERIOD/*间隔时间*/, TimeUnit.SECONDS); } } } log.info("SingleAuthProvider - refreshThread - init successful!"); } /** * 结束定时任务,不再定时清理过期数据 */ public void endRefreshThread() { this.refreshFlag = false; } // ------------------------ 实现AuthProvider接口开始 ------------------------ // private final AuthProperties authProperties; /** * 构造函数 */ public SingleAuthProvider(AuthProperties authProperties) { this.authProperties = authProperties; // 同时初始化定时任务 this.initRefreshThread(); } @Override protected AuthProperties getAuthProperties() { return this.authProperties; } /** * 刷新token * * @param token 令牌 * @return true成功,false失败 */ @Override public boolean refreshToken(String token) { Assert.hasText(token, "The token cannot be empty!"); try {
package org.tinycloud.security.provider; /** * 操作token和会话的接口(通过单机内存Map实现,系统重启后数据会丢失) * 部分代码实现参考自 https://gitee.com/dromara/sa-token/blob/dev/sa-token-core/src/main/java/cn/dev33/satoken/dao/SaTokenDaoDefaultImpl.java * * @author liuxingyu01 * @version 2023-01-06-9:33 **/ public class SingleAuthProvider extends AbstractAuthProvider implements AuthProvider { final static Logger log = LoggerFactory.getLogger(SingleAuthProvider.class); /** * 常量,每次清理过期数据间隔的时间 (单位: 秒) ,默认值30秒 */ final static int DATA_REFRESH_PERIOD = 30; /** * 常量,表示系统中不存在这个缓存 (在对不存在的key获取剩余存活时间时返回此值) */ final static long NOT_VALUE_EXPIRE = -1L; /** * 数据存储集合 */ public final static Map<String, Object> dataMap = new ConcurrentHashMap<>(); /** * 数据的过期时间存储集合 (单位: 毫秒) , 记录所有key的到期时间 [注意不是剩余存活时间] */ public final static Map<String, Long> expireMap = new ConcurrentHashMap<>(); // ------------------------ String 读写操作开始 ------------------------ // /** * 从缓存中获取数据(String) * * @param key 键 * @return 值 */ public String get(String key) { clearKeyByTimeout(key); return (String) dataMap.get(key); } /** * 往缓存中存入数据(String) * * @param key 键 * @param value 值 * @param timeout 有效时间(秒) */ public void set(String key, String value, long timeout) { if (timeout == 0) { return; } dataMap.put(key, value); expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); } /** * 更新缓存数据(String) * * @param key 键 * @param value 值 */ public void update(String key, String value) { if (getKeyTimeout(key) == SingleAuthProvider.NOT_VALUE_EXPIRE) { return; } dataMap.put(key, value); } /** * 删除缓存 * * @param key 键 */ public void delete(String key) { dataMap.remove(key); expireMap.remove(key); } /** * 获取缓存剩余存活时间 (单位:秒) * * @param key 键 * @return 剩余存活时间 (单位:秒) */ public long getTimeout(String key) { return getKeyTimeout(key); } /** * 更新缓存剩余存活时间 (单位:秒) * * @param key 键 * @param timeout 有效时间(秒) */ public void updateTimeout(String key, long timeout) { expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); } // ------------------------ Object 读写操作开始 ------------------------ // /** * 从缓存中获取数据(Object) * * @param key 键 * @return 值 */ public Object getObject(String key) { clearKeyByTimeout(key); return dataMap.get(key); } /** * 往缓存中存入数据(Object) * * @param key 键 * @param object 值 * @param timeout 有效时间(秒) */ public void setObject(String key, Object object, long timeout) { if (timeout == 0) { return; } dataMap.put(key, object); expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); } /** * 更新缓存数据(Object) * * @param key 键 * @param object 值 */ public void updateObject(String key, Object object) { if (getKeyTimeout(key) == SingleAuthProvider.NOT_VALUE_EXPIRE) { return; } dataMap.put(key, object); } /** * 删除缓存 * * @param key 键 */ public void deleteObject(String key) { dataMap.remove(key); expireMap.remove(key); } /** * 获取缓存剩余存活时间 (单位:秒) * * @param key 键 * @return 剩余存活时间 (单位:秒) */ public long getObjectTimeout(String key) { return getKeyTimeout(key); } /** * 更新缓存剩余存活时间 (单位:秒) * * @param key 键 * @param timeout 有效时间(秒) */ public void updateObjectTimeout(String key, long timeout) { expireMap.put(key, (System.currentTimeMillis() + timeout * 1000)); } // ------------------------ 过期时间相关操作开始 ------------------------ // /** * 如果指定key已经过期,则立即清除它 * * @param key 键 */ private void clearKeyByTimeout(String key) { Long expirationTime = expireMap.get(key); // 清除条件:如果不为空 && 已经超过过期时间 if (expirationTime != null && expirationTime < System.currentTimeMillis()) { dataMap.remove(key); expireMap.remove(key); } } /** * 获取指定key的剩余存活时间 (单位:秒) * * @param key 键 */ private long getKeyTimeout(String key) { // 先检查是否已经过期 clearKeyByTimeout(key); // 获取过期时间 Long expire = expireMap.get(key); // 如果根本没有这个值,则直接返回NOT_VALUE_EXPIRE if (expire == null) { return SingleAuthProvider.NOT_VALUE_EXPIRE; } // 计算剩余时间并返回 long timeout = (expire - System.currentTimeMillis()) / 1000; // 小于零时,视为不存在,返回NOT_VALUE_EXPIRE if (timeout < 0) { dataMap.remove(key); expireMap.remove(key); return SingleAuthProvider.NOT_VALUE_EXPIRE; } return timeout; } // ------------------------ 定时清理过期数据 ------------------------ // /** * 线程池核心线程数最大值 */ private static final int corePoolSize = 5; /** * 用于定时执行数据清理的线程池 */ private volatile ScheduledExecutorService executorService; /** * 是否继续执行数据清理的线程标记 */ private volatile boolean refreshFlag; /** * 清理所有已经过期的key */ public void refreshDataMap() { for (String key : expireMap.keySet()) { clearKeyByTimeout(key); } } /** * 初始化定时任务 */ public void initRefreshThread() { // 启动定时刷新 this.refreshFlag = true; // 双重校验构造一个单例的ScheduledThreadPool if (this.executorService == null) { synchronized (SingleAuthProvider.class) { if (this.executorService == null) { this.executorService = Executors.newScheduledThreadPool(corePoolSize); this.executorService.scheduleWithFixedDelay(() -> { log.info("SingleAuthProvider - refreshSession - at :{}", CommonUtil.getCurrentTime()); try { // 如果已经被标记为结束 if (!refreshFlag) { return; } // 执行清理方法 refreshDataMap(); } catch (Exception e2) { log.error("SingleAuthProvider - refreshSession - Exception:{e2}", e2); } }, 10/*首次延迟多长时间后执行*/, DATA_REFRESH_PERIOD/*间隔时间*/, TimeUnit.SECONDS); } } } log.info("SingleAuthProvider - refreshThread - init successful!"); } /** * 结束定时任务,不再定时清理过期数据 */ public void endRefreshThread() { this.refreshFlag = false; } // ------------------------ 实现AuthProvider接口开始 ------------------------ // private final AuthProperties authProperties; /** * 构造函数 */ public SingleAuthProvider(AuthProperties authProperties) { this.authProperties = authProperties; // 同时初始化定时任务 this.initRefreshThread(); } @Override protected AuthProperties getAuthProperties() { return this.authProperties; } /** * 刷新token * * @param token 令牌 * @return true成功,false失败 */ @Override public boolean refreshToken(String token) { Assert.hasText(token, "The token cannot be empty!"); try {
this.updateTimeout(AuthConsts.AUTH_TOKEN_KEY + token, this.getAuthProperties().getTimeout());
1
2023-10-26 08:13:08+00:00
4k
n0rb33rt/TwainCards
customer/src/main/java/com/norbert/customer/authentication/AuthenticationService.java
[ { "identifier": "RabbitMQMessageProducer", "path": "customer/src/main/java/com/norbert/customer/config/RabbitMQMessageProducer.java", "snippet": "@Service\n@AllArgsConstructor\npublic class RabbitMQMessageProducer {\n private final AmqpTemplate amqpTemplate;\n public void publish(String exchange, String routingKey, Object payload){\n amqpTemplate.convertAndSend(exchange,routingKey,payload);\n }\n}" }, { "identifier": "BadRequestException", "path": "customer/src/main/java/com/norbert/customer/exception/BadRequestException.java", "snippet": "public class BadRequestException extends RuntimeException{\n public BadRequestException(String message) {\n super(message);\n }\n}" }, { "identifier": "JwtService", "path": "customer/src/main/java/com/norbert/customer/jwt/JwtService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class JwtService {\n @Value(\"${jwt.secret.key}\")\n private String SECRET_KEY;\n private final static Integer BEARER_PREFIX_LENGTH = 7;\n private final static String BEARER_PREFIX = \"Bearer \";\n private final JwtTokenService jwtTokenService;\n\n private final static long HOUR = 1000*60*60;\n public boolean isTokenValid(String token) {\n return !isTokenRevoked(token) && !isTokenExpired(token);\n }\n\n private boolean isTokenRevoked(String token) {\n return jwtTokenService.findByToken(token).isRevoked();\n }\n private boolean isTokenExpired(String token){\n return extractExpiration(token).before(new Date(System.currentTimeMillis()));\n }\n private Date extractExpiration(String token){\n return extractClaim(token,Claims::getExpiration);\n }\n public String generateToken(User user){\n return generateToken(new HashMap<>(),user);\n }\n public String generateToken(\n Map<String,Object> extraClaims,\n User user\n ){\n String jwtToken = Jwts.builder()\n .setClaims(extraClaims)\n .setSubject(user.getEmail())\n .setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis()+HOUR))\n .signWith(getSignInKey(), SignatureAlgorithm.HS512)\n .compact();\n jwtTokenService.save(JwtToken.builder()\n .token(jwtToken)\n .revoked(false)\n .user(user)\n .build());\n return jwtToken;\n }\n public String extractEmail(String token){\n return extractClaim(token,Claims::getSubject);\n }\n private <T> T extractClaim(String token, Function<Claims,T> claimsResolver){\n final Claims claims = extractAllClaims(token);\n return claimsResolver.apply(claims);\n }\n private Claims extractAllClaims(String token){\n return Jwts\n .parserBuilder()\n .setSigningKey(getSignInKey())\n .build()\n .parseClaimsJws(token)\n .getBody();\n }\n private Key getSignInKey(){\n byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);\n return Keys.hmacShaKeyFor(keyBytes);\n }\n\n public boolean isAuthHeaderValid(String authHeader){\n return authHeader == null || !authHeader.startsWith(BEARER_PREFIX);\n }\n public String extractJwtTokenFromHeader(String authHeader){\n return authHeader.substring(BEARER_PREFIX_LENGTH);\n }\n}" }, { "identifier": "Role", "path": "customer/src/main/java/com/norbert/customer/user/Role.java", "snippet": "public enum Role {\n USER,\n PREMIUM\n}" }, { "identifier": "User", "path": "customer/src/main/java/com/norbert/customer/user/User.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@Builder\n@EqualsAndHashCode\n@Entity(name = \"User\")\n@Table(\n name = \"\\\"user\\\"\",\n uniqueConstraints = @UniqueConstraint(name = \"unique_email\", columnNames = \"email\")\n)\npublic class User {\n @Id\n @SequenceGenerator(\n name = \"user_id_seq\",\n sequenceName = \"user_id_seq\",\n allocationSize = 1\n )\n @GeneratedValue(\n strategy = GenerationType.SEQUENCE,\n generator = \"user_id_seq\"\n )\n @Column(\n name = \"id\",\n updatable = false,\n columnDefinition = \"BIGINT\"\n )\n private Long id;\n\n @Column(\n name = \"email\",\n length = 319,\n nullable = false,\n columnDefinition = \"VARCHAR(319)\"\n )\n private String email;\n\n @Column(\n name = \"password\",\n columnDefinition = \"VARCHAR(61)\"\n )\n private String password;\n\n @Column(\n name = \"role\",\n nullable = false,\n columnDefinition = \"VARCHAR(8)\"\n )\n @Enumerated(EnumType.STRING)\n private Role role;\n\n @Column(\n name = \"enabled\",\n nullable = false,\n columnDefinition = \"BOOLEAN\"\n )\n private Boolean enabled;\n\n @Column(\n name = \"set_password\",\n nullable = false,\n columnDefinition = \"BOOLEAN\"\n )\n private Boolean setPassword;\n\n @OneToMany(\n orphanRemoval = true,\n cascade = CascadeType.ALL,\n mappedBy = \"user\",\n fetch = FetchType.EAGER\n )\n private List<Deck> decks;\n\n @OneToMany(\n orphanRemoval = true,\n cascade = CascadeType.ALL,\n mappedBy = \"user\"\n )\n private List<JwtToken> jwtTokens;\n\n @Column(\n name = \"subscription_until\",\n columnDefinition = \"TIMESTAMP WITHOUT TIME ZONE\"\n )\n private LocalDateTime subscriptionUntil;\n\n @Column(\n name = \"created_at\",\n updatable = false,\n nullable = false,\n columnDefinition = \"TIMESTAMP WITHOUT TIME ZONE\"\n )\n private LocalDateTime createdAt;\n}" }, { "identifier": "UserService", "path": "customer/src/main/java/com/norbert/customer/user/UserService.java", "snippet": "@Service\n@AllArgsConstructor\npublic class UserService {\n private final UserDAO userDAO;\n private final PasswordEncoder passwordEncoder;\n\n public User findUserByEmail(String email){\n return userDAO.findUserByEmail(email);\n }\n\n public boolean isUserPresent(String email){\n return userDAO.isUserPresent(email);\n }\n\n public void save(User user){\n userDAO.save(user);\n }\n\n public UserDTO getUserProfile(){\n User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n UserDTOMapper userDTOMapper = new UserDTOMapper();\n return userDTOMapper.apply(user);\n }\n\n public void updatePassword(PasswordUpdatingRequest request) {\n User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();\n String newHashedPassword = passwordEncoder.encode(request.password());\n user.setPassword(newHashedPassword);\n save(user);\n }\n}" } ]
import com.norbert.customer.authentication.request.SimpleFormAuthenticationRequest; import com.norbert.customer.authentication.request.SimpleFormRegistrationRequest; import com.norbert.customer.authentication.response.AuthenticationResponse; import com.norbert.customer.config.RabbitMQMessageProducer; import com.norbert.customer.exception.BadRequestException; import com.norbert.customer.jwt.JwtService; import com.norbert.customer.user.Role; import com.norbert.customer.user.User; import com.norbert.customer.user.UserService; import lombok.AllArgsConstructor; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.ArrayList;
1,787
package com.norbert.customer.authentication; @Service @AllArgsConstructor public class AuthenticationService { private final UserService userJPAService; private final PasswordEncoder passwordEncoder;
package com.norbert.customer.authentication; @Service @AllArgsConstructor public class AuthenticationService { private final UserService userJPAService; private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
2
2023-10-30 19:00:07+00:00
4k
0-Gixty-0/Grupp-11-OOPP
sailinggame/src/test/java/modeltest/utility/UEntityMatrixGeneratorTest.java
[ { "identifier": "EntityDirector", "path": "sailinggame/src/main/java/com/group11/model/builders/EntityDirector.java", "snippet": "public class EntityDirector {\n private IEntityBuilder builder;\n\n public EntityDirector(IEntityBuilder builder) {\n this.builder = builder;\n }\n\n /**\n * Changes the currently active builder for the director\n * @param builder The desired concrete builder class\n */\n public void changeBuilder(IEntityBuilder builder) {\n this.builder = builder;\n }\n\n /**\n * Creates the model representation of a player based on active builder\n * @param position The position of the body at creation\n * @return Object of type AEntity representing the player with body decided by active builder\n */\n public AEntity createPlayer(Point position) {\n builder.reset();\n builder.setName(\"Player\");\n builder.setFriendlyStatus(true);\n builder.setPosition(position);\n builder.setAttributesForLevel(0);\n builder.setAttributesForLevel(5);\n builder.setBody();\n return builder.createEntity();\n }\n\n /**\n * Creates the model representation of an enemy based on active builder\n * @param position The position of the body at creation\n * @return Object of type AEntity representing the enemy with body decided by active builder\n */\n public AEntity createEnemy(Point position, int lvl) {\n builder.reset();\n builder.setName(\"Enemy\");\n builder.setFriendlyStatus(false);\n builder.setPosition(position);\n builder.setAttributesForLevel(lvl);\n builder.setBody();\n return builder.createEntity();\n }\n}" }, { "identifier": "ShipBuilder", "path": "sailinggame/src/main/java/com/group11/model/builders/ShipBuilder.java", "snippet": "public class ShipBuilder implements IEntityBuilder {\n\n private static double hpScalingFactor = 1.5;\n private static double armorScalingFactor = 1.5;\n private AMovableBody body = null;\n private String name = null;\n private Boolean friendly = null;\n private int shipLevel = 0;\n private double armor = 0;\n private AWeapon weapon = null;\n private Point position = null;\n private double hp = 0;\n\n @Override\n public void setBody() {\n this.body = new Ship(this.position, this.shipLevel, this.armor, this.weapon, this.hp);\n }\n\n @Override\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n public void setFriendlyStatus(Boolean status) {\n this.friendly = status;\n }\n\n @Override\n public AEntity createEntity() {\n return new CommandableEntity(this.body, this.name, this.friendly);\n }\n\n @Override\n public void reset() {\n this.body = null;\n this.name = null;\n this.friendly = true;\n this.hp = 0;\n this.weapon = null;\n this.armor = 0;\n this.position = null;\n this.shipLevel = 0;\n }\n\n @Override\n public void setPosition(Point position) {\n this.position = position;\n }\n\n /**\n * Sets the attributes of the builder based on level and scaling factor where applicable\n * @param lvl The desired level or \"difficulty\" of the entity\n */\n @Override\n public void setAttributesForLevel(int lvl) {\n this.setHp(lvl * ShipBuilder.hpScalingFactor * 15);\n this.setArmor(lvl * ShipBuilder.armorScalingFactor * 4);\n this.setShipLevel(lvl);\n this.setWeapon(new BasicCannon(BasicCannonBall.class));\n }\n\n /**\n * Sets the level for the ship\n * @param shipLevel The level of the ship\n */\n private void setShipLevel(int shipLevel) {\n this.shipLevel = shipLevel;\n }\n\n /**\n * Sets the armor for the ship\n * @param armor The armor stat for the ship\n */\n private void setArmor(double armor) {\n this.armor = armor;\n }\n\n /**\n * Sets the weapon for the ship\n * @param weapon The weapon stat for the ship\n */\n private void setWeapon(AWeapon weapon) {\n this.weapon = weapon;\n }\n\n /**\n * Sets the hp for the ship\n * @param hp The hp stat for the ship\n */\n private void setHp(double hp) {\n this.hp = hp;\n }\n}" }, { "identifier": "AEntity", "path": "sailinggame/src/main/java/com/group11/model/gameentites/AEntity.java", "snippet": "public abstract class AEntity {\n \n private String name;\n private Boolean friendly;\n private ABody body;\n\n /**\n * Used to construct an entity\n * @param name The entity's name\n * @param friendly A single factor which assigns the lifelong allegiance of the entity\n * @param body The body of the entity\n */\n protected AEntity(ABody body, String name, Boolean friendly) {\n this.body = body;\n this.name = name;\n this.friendly = friendly;\n }\n\n /**\n * \n * @return (String) Name of the entity\n */\n public String getName() {\n return name;\n }\n\n /**\n * \n * @return (Boolean) The Allegiance of the entity\n */\n public Boolean isFriendly() {\n return friendly;\n }\n\n /**\n * \n * @param friendly The allegiance of the entity\n */\n public void setFriendly(Boolean friendly) {\n this.friendly = friendly;\n }\n\n /**\n * @return (ABody) The class of the entities body\n */\n public Class<? extends ABody> getBodyType() {\n return body.getClass();\n }\n\n /**\n * returns the body of the entity\n * @return (ABody) The body of the entity\n */\n protected ABody getBody() {\n return this.body;\n }\n\n /**\n * Make the body of the entity take damage\n */\n public void takeDamage(int damage) {\n this.body.takeDamage(damage);\n }\n\n /**\n * Returns the hitpoints of the body\n * @return (int) The hitpoints of the body\n */\n public int getHitPoints() {\n return (int) this.body.getHitPoints();\n }\n\n /**\n * Sets the hitpoints of the body\n * @param hp The new hitpoints of the body\n */\n public void setHitPoints(int hp) {\n this.body.setHitPoints(hp);\n }\n\n /**\n * sets the body of the entity\n * @param body The new body of the entity\n */\n protected void setBody(ABody body) {\n this.body = body;\n }\n\n /**\n * A safe (without giving outside access and possibility to modify position)\n * way to return the position of the entity body.\n * @return (Point) The position of the entity body\n */\n public Point getPos() {\n return this.body.getPos();\n }\n}" }, { "identifier": "UEntityMatrixGenerator", "path": "sailinggame/src/main/java/com/group11/model/utility/UEntityMatrixGenerator.java", "snippet": "public final class UEntityMatrixGenerator {\n\n private static List<Point> occupiedPositions = new ArrayList<>();\n private static List<List<AEntity>> entityMatrixInstance;\n\n /**\n * Utility class does not need to be instantiated\n */\n private UEntityMatrixGenerator() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n /**\n * Creates a 2D matrix of AEntity objects with the specified width and height, and populates it with the entities from the provided list.\n * The position of each entity in the matrix corresponds to its position in the game world.\n * The most recently created matrix is stored as an instance variable and can be updated by calling updateEntityMatrix.\n *\n * @param width the number of columns in the matrix\n * @param height the number of rows in the matrix\n * @param entityList the list of entities to be added to the matrix\n * @return the populated matrix of AEntity objects\n * @throws IllegalArgumentException if an entity's position is out of bounds for the matrix dimensions\n */\n public static List<List<AEntity>> createEntityMatrix(int width, int height, List<AEntity> entityList) {\n\n // Check that entity positions are within the bounds of entity matrix.\n // Adding entities to occupiedPositions list to easier update.\n for (AEntity entity : entityList) {\n if (entity.getPos().x >= height || entity.getPos().y >= width) {\n throw new IllegalArgumentException(\"Entity position out of bounds for entityMatrix dimensions\");\n }\n }\n updateOccupiedPositions(entityList);\n\n List<List<AEntity>> entityMatrix = new ArrayList<>();\n\n for (int rowIndex = 0; rowIndex < height; rowIndex++) {\n List<AEntity> row = new ArrayList<>();\n for (int columnIndex = 0; columnIndex < width; columnIndex++) {\n row.add(null);\n }\n entityMatrix.add(row);\n }\n addEntitiesToMatrix(entityMatrix, entityList);\n\n entityMatrixInstance = entityMatrix;\n\n return entityMatrix;\n }\n\n /**\n * Updates the most recently created matrix with the entities from the provided list.\n * The position of each entity in the matrix corresponds to its position in the game world.\n * The list of occupied positions is updated accordingly.\n *\n * @param entityList the list of entities to be added to the matrix\n * @throws IllegalStateException if createEntityMatrix has not been called before this method\n */\n public static void updateEntityMatrix(List<AEntity> entityList) {\n \n if (occupiedPositions == null) {\n throw new IllegalStateException(\"Call createEntityMatrix before trying to update one\");\n }\n\n // Clear formerly occupied positions\n for (int i = 0; i < occupiedPositions.size(); i++) {\n entityMatrixInstance.get(occupiedPositions.get(i).x).set(occupiedPositions.get(i).y, null);\n }\n\n // Add new occupied positions\n updateOccupiedPositions(entityList);\n\n addEntitiesToMatrix(entityMatrixInstance, entityList);\n }\n\n /**\n * Adds entities to the entity matrix\n *\n * @param entityMatrix The entity matrix to add entities to\n * @param entities The entities to add to the entity matrix\n */\n private static void addEntitiesToMatrix(List<List<AEntity>> entityMatrix, List<AEntity> entities) {\n for (AEntity entity : entities) {\n int entityX = entity.getPos().x;\n int entityY = entity.getPos().y;\n entityMatrix.get(entityX).set(entityY, entity);\n }\n }\n\n /**\n * Updates the list of occupied positions with the positions of the entities from the provided list.\n *\n * @param entities the list of entities whose positions are to be added to the list of occupied positions\n */\n private static void updateOccupiedPositions(List<AEntity> entities) {\n occupiedPositions.clear();\n for (AEntity entity : entities) {\n occupiedPositions.add(entity.getPos());\n }\n }\n}" } ]
import static junit.framework.TestCase.assertEquals; import java.awt.Point; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.group11.model.builders.EntityDirector; import com.group11.model.builders.ShipBuilder; import com.group11.model.gameentites.AEntity; import com.group11.model.utility.UEntityMatrixGenerator;
2,806
package modeltest.utility; public class UEntityMatrixGeneratorTest { @Test public void testCreationOfEmptyMatrix() {
package modeltest.utility; public class UEntityMatrixGeneratorTest { @Test public void testCreationOfEmptyMatrix() {
List<List<AEntity>> entityMatrix = UEntityMatrixGenerator.createEntityMatrix(5,5, new ArrayList<>());
3
2023-10-31 11:40:56+00:00
4k
MattiDragon/JsonPatcher
src/main/java/io/github/mattidragon/jsonpatcher/mixin/LifecycledResourceManagerImplMixin.java
[ { "identifier": "MetapatchResourcePack", "path": "src/main/java/io/github/mattidragon/jsonpatcher/metapatch/MetapatchResourcePack.java", "snippet": "public class MetapatchResourcePack implements ResourcePack {\n public static final Gson GSON = new Gson();\n\n public final ResourceType type;\n private final Map<Identifier, JsonObject> files = new HashMap<>();\n private final Set<Identifier> deletedFiles = new HashSet<>();\n private final Set<String> namespaces = new HashSet<>();\n\n public MetapatchResourcePack(ResourceType type) {\n this.type = type;\n }\n\n public void clear() {\n files.clear();\n deletedFiles.clear();\n namespaces.clear();\n }\n\n public void set(Map<Identifier, JsonObject> files, Collection<Identifier> deletedFiles) {\n this.files.clear();\n this.files.putAll(files);\n this.deletedFiles.clear();\n this.deletedFiles.addAll(deletedFiles);\n namespaces.clear();\n files.keySet().forEach(id -> namespaces.add(id.getNamespace()));\n }\n\n public Set<Identifier> getDeletedFiles() {\n return deletedFiles;\n }\n\n public Map<Identifier, Resource> findResources(String startingPath, Predicate<Identifier> allowedPathPredicate) {\n var map = new HashMap<Identifier, Resource>();\n files.forEach((id, file) -> {\n if (id.getPath().startsWith(startingPath) && allowedPathPredicate.test(id)) {\n map.put(id, makeResource(id));\n }\n });\n return map;\n }\n\n @Nullable\n @Override\n public InputSupplier<InputStream> openRoot(String... segments) {\n return null;\n }\n\n @Nullable\n @Override\n public InputSupplier<InputStream> open(ResourceType type, Identifier id) {\n if (type != this.type) return null;\n var file = files.get(id);\n if (file == null) return null;\n\n return () -> {\n var out = new ByteArrayOutputStream();\n var writer = new OutputStreamWriter(out);\n GSON.toJson(file, writer);\n writer.close();\n return new ByteArrayInputStream(out.toByteArray());\n };\n }\n\n @Override\n public void findResources(ResourceType type, String namespace, String prefix, ResultConsumer consumer) {\n if (type != this.type) return;\n\n files.forEach((id, file) -> {\n if (id.getNamespace().equals(namespace) && id.getPath().startsWith(prefix)) {\n consumer.accept(id, open(type, id));\n }\n });\n }\n\n @Override\n public Set<String> getNamespaces(ResourceType type) {\n return namespaces;\n }\n\n @Nullable\n @Override\n public <T> T parseMetadata(ResourceMetadataReader<T> metaReader) {\n var metadata = getMetadata(type);\n var stream = new ByteArrayInputStream(metadata.getBytes());\n\n return AbstractFileResourcePack.parseMetadata(metaReader, stream);\n }\n\n @Override\n public String getName() {\n return \"JsonPatcher MetaPatch Resource Pack\";\n }\n\n @Override\n public void close() {\n\n }\n\n private static String getMetadata(ResourceType type) {\n return \"\"\"\n {\n \"pack\": {\n \"pack_format\": %s,\n \"description\": \"JsonPatcher MetaPatch Resource Pack\"\n }\n }\n \"\"\".formatted(SharedConstants.getGameVersion().getResourceVersion(type));\n }\n\n @Nullable\n public Resource makeResource(Identifier id) {\n var supplier = open(type, id);\n if (supplier != null) {\n return new Resource(this, supplier);\n }\n return null;\n }\n}" }, { "identifier": "MetapatchSingleResourceManager", "path": "src/main/java/io/github/mattidragon/jsonpatcher/metapatch/MetapatchSingleResourceManager.java", "snippet": "public class MetapatchSingleResourceManager implements ResourceManager {\n private final Identifier id;\n @Nullable\n private final ResourceManager delegate;\n private final boolean delete;\n private final MetapatchResourcePack metaPatchPack;\n\n public MetapatchSingleResourceManager(Identifier id, @Nullable ResourceManager delegate, MetapatchResourcePack metaPatchPack) {\n this.id = id;\n this.delegate = delegate;\n this.metaPatchPack = metaPatchPack;\n this.delete = this.metaPatchPack.getDeletedFiles().contains(id);\n }\n\n @Override\n public Set<String> getAllNamespaces() {\n throw new UnsupportedOperationException(\"This method should not be called on this hack. Someone is doing something unexpected.\");\n }\n\n @Override\n public List<Resource> getAllResources(Identifier id) {\n if (!this.id.equals(id)) {\n return delegate == null ? new ArrayList<>() : delegate.getAllResources(id);\n }\n\n if (delete) return new ArrayList<>();\n\n var resources = delegate == null ? new ArrayList<Resource>() : new ArrayList<>(delegate.getAllResources(id));\n var resource = metaPatchPack.makeResource(id);\n if (resource != null) resources.add(resource);\n return resources;\n }\n\n @Override\n public Optional<Resource> getResource(Identifier id) {\n if (!this.id.equals(id)) {\n return Optional.ofNullable(delegate).flatMap(rm -> rm.getResource(id));\n }\n\n if (delete) return Optional.empty();\n\n var resource = this.metaPatchPack.makeResource(id);\n if (resource != null) return Optional.of(resource);\n if (delegate != null) return delegate.getResource(id);\n return Optional.empty();\n }\n\n @Override\n public Map<Identifier, Resource> findResources(String startingPath, Predicate<Identifier> allowedPathPredicate) {\n throw new UnsupportedOperationException(\"This method should not be called on this hack. Someone is doing something unexpected.\");\n }\n\n @Override\n public Map<Identifier, List<Resource>> findAllResources(String startingPath, Predicate<Identifier> allowedPathPredicate) {\n throw new UnsupportedOperationException(\"This method should not be called on this hack. Someone is doing something unexpected.\");\n }\n\n @Override\n public Stream<ResourcePack> streamResourcePacks() {\n throw new UnsupportedOperationException(\"This method should not be called on this hack. Someone is doing something unexpected.\");\n }\n}" }, { "identifier": "MetaPatchPackAccess", "path": "src/main/java/io/github/mattidragon/jsonpatcher/misc/MetaPatchPackAccess.java", "snippet": "public interface MetaPatchPackAccess {\n MetapatchResourcePack jsonpatcher$getMetaPatchPack();\n}" } ]
import com.llamalad7.mixinextras.injector.ModifyReturnValue; import io.github.mattidragon.jsonpatcher.metapatch.MetapatchResourcePack; import io.github.mattidragon.jsonpatcher.metapatch.MetapatchSingleResourceManager; import io.github.mattidragon.jsonpatcher.misc.MetaPatchPackAccess; import net.minecraft.resource.*; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Debug; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.*; import java.util.function.Predicate;
1,708
package io.github.mattidragon.jsonpatcher.mixin; @Debug(export = true) @Mixin(LifecycledResourceManagerImpl.class)
package io.github.mattidragon.jsonpatcher.mixin; @Debug(export = true) @Mixin(LifecycledResourceManagerImpl.class)
public class LifecycledResourceManagerImplMixin implements MetaPatchPackAccess {
2
2023-10-30 14:09:36+00:00
4k
ThomasGorisseGit/ERP_Essence_BUT
backend/src/main/java/fr/gorisse/erp/backend/services/UserCheckingService.java
[ { "identifier": "User", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/User.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@ToString\n@EqualsAndHashCode(callSuper = true)\n@Entity\npublic class User extends Person implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private int id;\n\n @Convert(converter = LoginConverter.class)\n private Login login;\n\n @Convert(converter = PasswordConverter.class)\n @Getter(AccessLevel.NONE)\n private Password password;\n\n @Convert(converter = StatusConverter.class)\n private Status status;\n\n private Double salary;\n\n\n public User (String firstname, String lastname, String password){\n super(firstname,lastname);\n this.login = Login.create(firstname+\"@\"+lastname);\n this.password = Password.create(password);\n this.status = Status.create(\"Employee\");\n this.salary = Status.getSalary(\"Employee\");\n }\n public void setLogin(){\n this.login = Login.create(this.getFirstName() + \"@\" + this.getLastName());\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return Collections.singletonList(new SimpleGrantedAuthority(\"ROLE_USER\"));\n }\n\n @Override\n public String getUsername() {\n return this.getLogin().toString();\n }\n @Override\n public String getPassword(){\n return this.password.getPassword();\n }\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}" }, { "identifier": "Login", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Login.java", "snippet": "@Value\npublic class Login {\n String login;\n\n private Login(String login){\n this.login = login;\n }\n public static Login create(String login){\n final int maxSize = 30;\n if(login.length()>maxSize) {\n throw new InvalidInput(\" Login must be less than \"+maxSize+\" characters\");\n }\n if(!hasValidChar(login))\n {\n throw new InvalidInput(\" The login contains invalid characters. \");\n }\n\n return new Login(login);\n\n }\n private static boolean hasValidChar(String login){\n boolean isValid = true;\n for(int i =0;i<login.length();i++){\n char currentChar = login.charAt(i);\n if (!contains(currentChar)) {\n isValid = false;\n break;\n }\n }\n return isValid;\n }\n private static boolean contains(char character){\n boolean founded = false;\n int i =0 ;\n final char[] authorizedChar = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_./#*@&éàùè'-123456789\".toCharArray();\n\n while (i<authorizedChar.length && !founded){\n if(authorizedChar[i]==character) founded = true;\n i++;\n }\n return founded;\n }\n public String toString(){\n return this.login;\n }\n}" }, { "identifier": "Password", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Password.java", "snippet": "@Value\npublic class Password {\n String password;\n\n private Password(String password) {\n this.password = password;\n }\n\n public static Password create(String password){\n final int maxSize = 400;\n if (password.length() > maxSize) {\n throw new InvalidInput(\" Password must be less than \"+maxSize+\" characters \");\n }\n else{\n return new Password(password);\n }\n }\n\n public String toString(){\n return this.password;\n }\n\n\n\n}" }, { "identifier": "Status", "path": "backend/src/main/java/fr/gorisse/erp/backend/entity/valueObject/Status.java", "snippet": "@Value\npublic class Status {\n String userStatus;\n private Status(String userStatus ){\n this.userStatus = userStatus;\n }\n public static Status create(String userStatus){\n if(Arrays.stream(StatusSalary.values()).anyMatch(word -> Objects.equals(word.toString(), userStatus))){\n return new Status(userStatus);\n }\n throw new InvalidInput(\"Status is incorrect\");\n }\n\n public static double getSalary(String userStatus){\n if(Arrays.stream(StatusSalary.values()).anyMatch(word -> Objects.equals(word.toString(), userStatus))){\n return StatusSalary.valueOf(userStatus).getSalary();\n }\n throw new InvalidInput(\"Status is incorrect\");\n }\n public String toString(){\n return this.userStatus;\n }\n}" }, { "identifier": "DataNotFounded", "path": "backend/src/main/java/fr/gorisse/erp/backend/exceptions/DataNotFounded.java", "snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = \"Data not founded\")\n\npublic class DataNotFounded extends NoSuchElementException {\n public DataNotFounded(String message){\n super(message);\n }\n}" }, { "identifier": "UserRepository", "path": "backend/src/main/java/fr/gorisse/erp/backend/repository/UserRepository.java", "snippet": "public interface UserRepository extends DefaultRepository<User> {\n Optional<User> findByLogin(Login login);\n}" }, { "identifier": "UserCheckingServiceInterface", "path": "backend/src/main/java/fr/gorisse/erp/backend/services/interfaces/UserCheckingServiceInterface.java", "snippet": "public interface UserCheckingServiceInterface {\n User getUserByLogin(String login);\n\n}" } ]
import fr.gorisse.erp.backend.entity.User; import fr.gorisse.erp.backend.entity.valueObject.Login; import fr.gorisse.erp.backend.entity.valueObject.Password; import fr.gorisse.erp.backend.entity.valueObject.Status; import fr.gorisse.erp.backend.exceptions.DataNotFounded; import fr.gorisse.erp.backend.repository.UserRepository; import fr.gorisse.erp.backend.services.interfaces.UserCheckingServiceInterface; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.Optional;
1,651
package fr.gorisse.erp.backend.services; @Service @NoArgsConstructor public class UserCheckingService extends ServiceMethods<User> implements UserCheckingServiceInterface , UserDetailsService { private UserRepository userRepository; private PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override public User create(User user){ user.setLogin(); user.setPassword(Password.create(this.passwordEncoder().encode(user.getPassword()))); if(this.userRepository.findByLogin(user.getLogin()).isPresent()){ throw new RuntimeException("" + "\n#########################################\n" + "########## User already exists ##########\n" + "#########################################\n"); } if(user.getStatus()==null || user.getStatus().toString().isEmpty()){ user.setStatus(Status.create("Employee")); user.setSalary(Status.getSalary("Employee")); } if(user.getSalary() == 0){ user.setSalary(Status.getSalary(user.getStatus().getUserStatus())); } return super.create(user); } @Override public User getUserByLogin(String login) {
package fr.gorisse.erp.backend.services; @Service @NoArgsConstructor public class UserCheckingService extends ServiceMethods<User> implements UserCheckingServiceInterface , UserDetailsService { private UserRepository userRepository; private PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override public User create(User user){ user.setLogin(); user.setPassword(Password.create(this.passwordEncoder().encode(user.getPassword()))); if(this.userRepository.findByLogin(user.getLogin()).isPresent()){ throw new RuntimeException("" + "\n#########################################\n" + "########## User already exists ##########\n" + "#########################################\n"); } if(user.getStatus()==null || user.getStatus().toString().isEmpty()){ user.setStatus(Status.create("Employee")); user.setSalary(Status.getSalary("Employee")); } if(user.getSalary() == 0){ user.setSalary(Status.getSalary(user.getStatus().getUserStatus())); } return super.create(user); } @Override public User getUserByLogin(String login) {
Optional<User> optUser = this.userRepository.findByLogin(Login.create(login));
1
2023-10-29 20:50:47+00:00
4k
DavidPerezAntonio51/calculadora-distribuida-con-rmi
calculadora/src/main/java/mx/tese/BusMensajes.java
[ { "identifier": "RequestWorker", "path": "calculadora/src/main/java/mx/tese/BusMensajesCore/RequestWorker.java", "snippet": "public class RequestWorker implements Runnable {\n private final ServerRegistryManager serverRegistry;\n private final Socket clienteRequest;\n\n public RequestWorker(Socket clienteRequest, ServerRegistryManager serverRegistry) {\n this.serverRegistry = serverRegistry;\n this.clienteRequest = clienteRequest;\n }\n\n @Override\n public void run() {\n Optional<Replica<ServidorReplica>> server = serverRegistry.getServer();\n try {\n ObjectOutputStream output = new ObjectOutputStream(clienteRequest.getOutputStream());\n ObjectInputStream input = new ObjectInputStream(clienteRequest.getInputStream());\n String operacion = input.readUTF();\n if (!server.isPresent()) {\n output.writeObject(new Respuesta(\"No hay servidores disponibles para procesar la solicitud.\"));\n System.out.println(\"No hay servidores disponibles para procesar la solicitud.\");\n return;\n }\n Replica<ServidorReplica> replica = server.get();\n System.out.println(\"Enviando solicitud al servidor con puerto: \" + replica.getPort());\n ServidorReplica servidorReplica = replica.getReplica();\n Respuesta calcular = servidorReplica.calcular(operacion);\n output.writeObject(calcular);\n } catch (IOException e) {\n System.out.println(e.getMessage());\n throw new RuntimeException(e);\n } finally {\n try {\n if (server.isPresent()&&server.get().getReplica().healthCheck()) {\n serverRegistry.regresarServer(server.get());\n }\n } catch (RemoteException e) {\n System.out.println(\"Servidor no disponible, ya no se encola de nuevo.\");\n }\n }\n }\n}" }, { "identifier": "ServerRegistryManager", "path": "calculadora/src/main/java/mx/tese/BusMensajesCore/ServerRegistryManager.java", "snippet": "public interface ServerRegistryManager {\n Optional<Replica<ServidorReplica>> getServer();\n void regresarServer(Replica<ServidorReplica> server);\n}" }, { "identifier": "ServerRegistry", "path": "calculadora/src/main/java/mx/tese/RMI/ServerRegistry.java", "snippet": "public interface ServerRegistry extends Remote {\n boolean registrarServidor(String ip, Integer puerto) throws RemoteException;\n}" }, { "identifier": "ServerRegistryImpl", "path": "calculadora/src/main/java/mx/tese/RMI_Impl/ServerRegistryImpl.java", "snippet": "public class ServerRegistryImpl extends UnicastRemoteObject implements ServerRegistry, ServerRegistryManager {\n\n private Queue<Replica<ServidorReplica>> replicas;\n\n public ServerRegistryImpl() throws RemoteException {\n this.replicas = new ConcurrentLinkedQueue<>();\n }\n\n @Override\n public boolean registrarServidor(String ip, Integer puerto) {\n System.out.println(\"Registrando servidor: \" + ip + \":\" + puerto);\n String servidorRemotoURL = \"rmi://\" + ip + \":\" + puerto + \"/ServidorReplica\";\n try {\n ServidorReplica nuevaReplica = (ServidorReplica) Naming.lookup(servidorRemotoURL);\n Replica<ServidorReplica> replica = new Replica<>(nuevaReplica, puerto, ip);\n replicas.offer(replica);\n System.out.println(\"Servidor registrado correctamente, en linea: \" + nuevaReplica.healthCheck());\n return true;\n } catch (NotBoundException | RemoteException | MalformedURLException e) {\n System.err.println(\"Error al registrar el servidor con puerto: \" + puerto);\n System.err.println(\"Message: \" + e.getMessage() + \" Cause: \" + e.getCause());\n }\n return false;\n }\n\n @Override\n public synchronized Optional<Replica<ServidorReplica>> getServer() {\n if (replicas.isEmpty()) {\n // Si la cola está vacía, no hay elementos disponibles\n return Optional.empty();\n }\n while (true) {\n // Obtiene el elemento de la cola\n Replica<ServidorReplica> elemento = replicas.poll();\n if (elemento != null) {\n try {\n System.out.println(\"Verificando la salud del servidor con puerto:\"+elemento.getPort()+\"...\");\n // Verifica si el servidor está activo llamando a checkHealt\n if (elemento.getReplica().healthCheck()) {\n // Si el servidor está activo, regresa el elemento\n System.out.println(\"Servidor con puerto:\"+elemento.getPort()+\" En linea:\" + elemento.getReplica().healthCheck());\n return Optional.of(elemento);\n } else {\n System.out.println(\"El servidor ya no está activo. Descartando elemento.\");\n }\n } catch (RemoteException e) {\n // Si se produce una excepción, el servidor no está activo, por lo que quitamos el elemento\n System.err.println(\"Error al verificar la salud del servidor. Descartando elemento.\");\n }\n } else {\n // La cola está vacía, no hay elementos válidos disponibles\n return Optional.empty();\n }\n }\n }\n\n @Override\n public void regresarServer(Replica<ServidorReplica> server) {\n replicas.offer(server);\n }\n}" } ]
import mx.tese.BusMensajesCore.RequestWorker; import mx.tese.BusMensajesCore.ServerRegistryManager; import mx.tese.RMI.ServerRegistry; import mx.tese.RMI_Impl.ServerRegistryImpl; import java.net.ServerSocket; import java.net.Socket; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
1,675
package mx.tese; public class BusMensajes { public static void main(String[] args,Scanner scanner) throws InterruptedException { int puertoRMI = obtenerPuertoRMIValido(scanner); // Solicita al usuario el puerto RMI int puertoServerSocket = obtenerPuertoServerSocketValido(scanner); // Solicita al usuario el puerto del servidor de sockets int maxThreads = 10; // Establece el límite máximo de threads // Solicita al usuario la cantidad de threads int numThreads = solicitarNumeroThreads(maxThreads,scanner); // Crea el ExecutorService con la cantidad de threads especificada ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { System.out.println("INICIANDO BUS DE MENSAJES..."); // Crea un registro RMI en el puerto por defecto Registry registry = LocateRegistry.createRegistry(puertoRMI); // Crea una instancia de la calculadora ServerRegistry serverRegistry = new ServerRegistryImpl(); // Registra la instancia en el registro RMI registry.rebind("ServerRegistry", serverRegistry); System.out.println("El ServerRegisty escucha en el puerto " + puertoRMI + "."); ServerRegistryManager serverRegistryManager = (ServerRegistryManager) serverRegistry; System.out.println("Iniciando socket listener en el puerto " + puertoServerSocket + "..."); ServerSocket serverSocket = new ServerSocket(puertoServerSocket); System.out.println("El socket listener está listo."); System.out.println("EL BUS SE INICIO CORRECTAMENTE"); while (true) { // Espera a que se conecte un cliente System.out.println("Esperando Conexiones..."); Socket clienteRequest = serverSocket.accept(); System.out.println("Cliente conectado desde:" + clienteRequest.getRemoteSocketAddress());
package mx.tese; public class BusMensajes { public static void main(String[] args,Scanner scanner) throws InterruptedException { int puertoRMI = obtenerPuertoRMIValido(scanner); // Solicita al usuario el puerto RMI int puertoServerSocket = obtenerPuertoServerSocketValido(scanner); // Solicita al usuario el puerto del servidor de sockets int maxThreads = 10; // Establece el límite máximo de threads // Solicita al usuario la cantidad de threads int numThreads = solicitarNumeroThreads(maxThreads,scanner); // Crea el ExecutorService con la cantidad de threads especificada ExecutorService executor = Executors.newFixedThreadPool(numThreads); try { System.out.println("INICIANDO BUS DE MENSAJES..."); // Crea un registro RMI en el puerto por defecto Registry registry = LocateRegistry.createRegistry(puertoRMI); // Crea una instancia de la calculadora ServerRegistry serverRegistry = new ServerRegistryImpl(); // Registra la instancia en el registro RMI registry.rebind("ServerRegistry", serverRegistry); System.out.println("El ServerRegisty escucha en el puerto " + puertoRMI + "."); ServerRegistryManager serverRegistryManager = (ServerRegistryManager) serverRegistry; System.out.println("Iniciando socket listener en el puerto " + puertoServerSocket + "..."); ServerSocket serverSocket = new ServerSocket(puertoServerSocket); System.out.println("El socket listener está listo."); System.out.println("EL BUS SE INICIO CORRECTAMENTE"); while (true) { // Espera a que se conecte un cliente System.out.println("Esperando Conexiones..."); Socket clienteRequest = serverSocket.accept(); System.out.println("Cliente conectado desde:" + clienteRequest.getRemoteSocketAddress());
executor.execute(new RequestWorker(clienteRequest, serverRegistryManager));
0
2023-10-27 02:16:18+00:00
4k
Abbas-Rizvi/p2p-social
src/test/network/NodeTest.java
[ { "identifier": "Node", "path": "src/main/network/Node.java", "snippet": "public class Node implements Serializable {\n\n private static final long serialVersionUID = 123456789L;\n\n // constant for port\n private final int PORT = 5687;\n\n private String username;\n private PublicKey pubKey;\n private String pubKeyStr;\n private String ip;\n\n Selector selector;\n\n public Node(String username, String pubKeyStr, String ip) {\n\n // store variables\n this.username = username;\n this.ip = ip;\n this.pubKeyStr = pubKeyStr;\n\n }\n\n // create node with ip\n public Node(String ip) {\n this.ip = ip;\n }\n\n // get the public key\n public PublicKey getPublicKey() {\n\n // decode public key\n KeyGen KeyDecode = new KeyGen();\n pubKey = KeyDecode.convertPublicKey(pubKeyStr);\n\n return pubKey;\n }\n\n ////////////////////////////////////////////////////////////////////////////////////////////\n // listen for connections, handle in non-blocking manner\n public void listener() {\n\n try {\n\n // create selector for connecting hosts\n Selector selector = Selector.open();\n\n ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();\n serverSocketChannel.socket().bind(new InetSocketAddress(PORT));\n serverSocketChannel.configureBlocking(false);\n\n // OP_ACCEPT is for when the server accepts connection from the client\n serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);\n\n // System.out.println(\"Server started on port \" + PORT);\n\n // receive connections\n while (true) {\n\n // ignore empty selector\n if (selector.select() == 0) {\n continue;\n }\n\n Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();\n\n // queue for incoming requests\n while (keyIterator.hasNext()) {\n // remove from the queue\n SelectionKey key = keyIterator.next();\n keyIterator.remove();\n\n if (key.isAcceptable()) {\n // handle connect request\n handleAccept(key, selector);\n } else if (key.isReadable()) {\n // handle read request\n handleRead(key);\n }\n }\n }\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n // handle accept of new connections\n // pass the currently stored blockchain\n private static void handleAccept(SelectionKey key, Selector selector) throws IOException {\n\n ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();\n SocketChannel socketChannel = serverSocketChannel.accept();\n socketChannel.configureBlocking(false);\n socketChannel.register(selector, SelectionKey.OP_READ);\n System.out.println(\"### Connection accepted from: \" + socketChannel.getRemoteAddress());\n\n // // utilize file sender to send the blockchain and node list\n // FileSender fileSender = new FileSender();\n // fileSender.sendAllAssets(socketChannel);\n\n }\n\n // handle send requests from connection\n // parse message type\n private static void handleRead(SelectionKey key) throws IOException {\n SocketChannel socketChannel = (SocketChannel) key.channel();\n int bufferSize = 1024 * 1024 * 1024; // 1 KB, adjust as needed\n ByteBuffer buffer = ByteBuffer.allocate(bufferSize);\n\n // Track the total number of bytes read\n int totalBytesRead = 0;\n\n while (totalBytesRead < bufferSize) {\n int bytesRead = socketChannel.read(buffer);\n\n if (bytesRead == -1) {\n // Connection closed by the client\n System.out.println(\"Connection closed by: \" + socketChannel.getRemoteAddress());\n socketChannel.close();\n key.cancel();\n return;\n }\n\n if (bytesRead > 0) {\n totalBytesRead += bytesRead;\n } else if (bytesRead == 0) {\n // No more data to read\n break;\n }\n }\n\n // Reset the position and limit to read the entire buffer\n buffer.flip();\n\n // Check if any data was received\n if (buffer.remaining() > 0) {\n byte[] data = new byte[buffer.remaining()];\n buffer.get(data);\n\n // System.out.println(\"Received message from \" + socketChannel.getRemoteAddress());\n decodeMessage(data, socketChannel);\n }\n }\n ////////////////////////////////////////////////////////////////////////////////////////////\n\n public static String decodeMessage(byte[] data, SocketChannel socketChannel) {\n\n SockMessage msg = null;\n\n try (ByteArrayInputStream byteStream = new ByteArrayInputStream(data);\n ObjectInputStream objectStream = new ObjectInputStream(byteStream)) {\n \n Object obj = objectStream.readObject();\n if (obj instanceof SockMessage) {\n msg = (SockMessage) obj;\n }\n \n } catch (IOException | ClassNotFoundException e) {\n e.printStackTrace();\n }\n \n if (msg != null) {\n try {\n System.out.println(\"Received \" + msg.getType() + \" From \" + socketChannel.getRemoteAddress());\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n // if the message passed was blockchain\n if (msg.getType().equalsIgnoreCase(\"BLOCKCHAIN\")) {\n // send to blockchain to handle conflicts and merge\n Blockchain blockchain = new Blockchain();\n blockchain.manageConflicts(blockchain.deserialize(msg.getFile()));\n return \"BLOCKCHAIN\";\n\n } else if (msg.getType().equalsIgnoreCase(\"NODELIST\")) {\n // send the node list to the database to merge\n PeersDatabase db = new PeersDatabase();\n db.mergeDatabase(msg.getFile());\n return \"NODELIST\";\n\n } else if (msg.getType().equalsIgnoreCase(\"HANDSHAKE\")) {\n // indicates that the node is joining the network\n // send all assets back\n FileSender fileSender = new FileSender();\n fileSender.sendAllAssets(socketChannel);\n return \"HANDSHAKE\";\n\n } else if (msg.getType().equalsIgnoreCase(\"HANDSHAKE-RECV\")) {\n // respond to a node joining the network sending own files\n FileSender fileSender = new FileSender();\n fileSender.sendBlockChain(socketChannel);\n fileSender.sendNodeList(socketChannel);\n return \"HANDSHAKE-RECV\";\n }\n\n }\n return null;\n }\n\n public PublicKey getPubKey() {\n return pubKey;\n }\n\n public String getPubKeyStr() {\n return pubKeyStr;\n }\n\n public int getPORT() {\n return PORT;\n }\n\n public String getIp() {\n return ip;\n }\n\n public String getUsername() {\n return username;\n }\n\n}" }, { "identifier": "SockMessage", "path": "src/main/network/SockMessage.java", "snippet": "public class SockMessage implements Serializable {\n\n private static final long serialVersionUID = 123456789L;\n\n\n private String type;\n private Long time;\n private byte[] file;\n\n private Blockchain blockchain = new Blockchain();\n private PeersDatabase db = new PeersDatabase();\n\n // define message for sending packets over network\n public SockMessage(String type, Long time, byte[] file) {\n this.type = type;\n this.time = time;\n this.file = file;\n\n }\n\n // types of messages:\n // Blockchain\n // Database\n\n public SockMessage(String type, long time) {\n this.type = type;\n this.time = time;\n\n if (type == \"BLOCKCHAIN\") {\n this.file = blockchain.serialize();\n } else if (type == \"NODELIST\") {\n this.file = db.serialize();\n } else if (type == \"HANDSHAKE\"){\n this.file = null;\n }\n\n }\n\n public String getType() {\n return type;\n }\n\n public Long getTime() {\n return time;\n }\n\n public byte[] getFile() {\n return file;\n }\n\n // read message from byte[]\n public SockMessage deserialize(byte[] msgBytes) {\n\n try {\n ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(msgBytes);\n ObjectInputStream ois = new ObjectInputStream(byteArrayIn);\n\n // cast input to object\n Object obj = ois.readObject();\n\n if (obj instanceof SockMessage) {\n return (SockMessage) obj;\n } else {\n return null;\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n // convert message to a byte[]\n public byte[] serialize() {\n\n try {\n\n // create output streams\n ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(byteArrayOut);\n\n // Write the object to the byte array stream\n oos.writeObject(this);\n\n // get byte array from the output stream\n byte[] byteArray = byteArrayOut.toByteArray();\n\n return byteArray;\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n}" } ]
import static org.junit.Assert.assertEquals; import org.junit.Test; import network.Node; import network.SockMessage;
2,277
package test.network; public class NodeTest { @Test public void testDecodeMessage() { SockMessage msg = new SockMessage("BLOCKCHAIN", 0); byte[] testMsg = msg.serialize();
package test.network; public class NodeTest { @Test public void testDecodeMessage() { SockMessage msg = new SockMessage("BLOCKCHAIN", 0); byte[] testMsg = msg.serialize();
Node node = new Node("127.0.0.1");
0
2023-10-28 06:29:00+00:00
4k
nailuj1992/OracionesCatolicas
app/src/main/java/com/prayers/app/mapper/NinthMapper.java
[ { "identifier": "AbstractActivity", "path": "app/src/main/java/com/prayers/app/activity/AbstractActivity.java", "snippet": "public abstract class AbstractActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n protected String initialLocale;\n\n /**\n * Get the view layout id bound to this activity object.\n *\n * @return\n */\n public abstract int getActivity();\n\n /**\n * Prepare all view fields.\n */\n public abstract void prepareActivity();\n\n /**\n * Update all fields on the view.\n */\n public abstract void updateViewState();\n\n /**\n * Does the back action.\n */\n public abstract void backAction();\n\n /**\n * Does the next action.\n */\n public abstract void nextAction();\n\n @Override\n protected final void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initialLocale = LocaleHelper.getPersistedLocale(this);\n overridePendingTransition(R.anim.enter_activity, R.anim.exit_activity);\n\n setContentView(getActivity());\n prepareActivity();\n updateViewState();\n }\n\n @Override\n public final void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n\n setContentView(getActivity());\n prepareActivity();\n updateViewState();\n }\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(LocaleHelper.onAttach(base));\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n if (initialLocale != null && !initialLocale.equals(LocaleHelper.getPersistedLocale(this))) {\n recreate();\n }\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key) {\n switch (key) {\n case GeneralConstants.KEY_PREF_LANGUAGE:\n LocaleHelper.setLocale(getApplicationContext(), PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString(key, \"\"));\n recreate(); // necessary here because this Activity is currently running and thus a recreate() in onResume() would be too late\n break;\n }\n }\n\n @Override\n public final void onBackPressed() {\n backAction();\n }\n\n}" }, { "identifier": "GeneralConstants", "path": "app/src/main/java/com/prayers/app/constants/GeneralConstants.java", "snippet": "public class GeneralConstants {\n\n public static final int FIRST_MYSTERY = 0;\n public static final int SECOND_MYSTERY = 1;\n public static final int THIRD_MYSTERY = 2;\n public static final int FOURTH_MYSTERY = 3;\n public static final int FIFTH_MYSTERY = 4;\n public static final int MAX_MYSTERIES = 5;\n\n public static final int FIRST_DAY_NINTH = 0;\n public static final int SECOND_DAY_NINTH = 1;\n public static final int THIRD_DAY_NINTH = 2;\n public static final int FOURTH_DAY_NINTH = 3;\n public static final int FIFTH_DAY_NINTH = 4;\n public static final int SIXTH_DAY_NINTH = 5;\n public static final int SEVENTH_DAY_NINTH = 6;\n public static final int EIGHTH_DAY_NINTH = 7;\n public static final int NINTH_DAY_NINTH = 8;\n public static final int MAX_DAYS_NINTH = 9;\n\n public static final String FIRST_ITEM = \"1. \";\n public static final String SECOND_ITEM = \"2. \";\n public static final String THIRD_ITEM = \"3. \";\n public static final String FOURTH_ITEM = \"4. \";\n public static final String FIFTH_ITEM = \"5. \";\n\n public static final int JOYFUL_MYSTERIES = 0;\n public static final int SORROWFUL_MYSTERIES = 1;\n public static final int GLORIOUS_MYSTERIES = 2;\n public static final int LUMINOUS_MYSTERIES = 3;\n public static final int MAX_GROUP_MYSTERIES = 4;\n\n public static final int MIN_HAIL_MARY = 1;\n public static final int HAIL_MARY_2 = 2;\n public static final int HAIL_MARY_3 = 3;\n public static final int HAIL_MARY_4 = 4;\n public static final int HAIL_MARY_5 = 5;\n public static final int HAIL_MARY_6 = 6;\n public static final int HAIL_MARY_7 = 7;\n public static final int HAIL_MARY_8 = 8;\n public static final int HAIL_MARY_9 = 9;\n public static final int HAIL_MARY_10 = 10;\n\n public static final int MAX_HAIL_MARY_NINTH = 9;\n public static final int MAX_HAIL_MARY_ROSARY_SHORT = 3;\n public static final int MAX_HAIL_MARY_ROSARY_LONG = 10;\n\n public static final int MIN_GLORY_BE = 1;\n public static final int MAX_GLORY_BE_NINTH = 3;\n\n public static final String MYSTERIES_ITEMS_LENGTH_5 = \"A mysteries group should have only 5 mysteries\";\n public static final String MYSTERY_WITH_PARAGRAPHS = \"A mystery should have at least one paragraph\";\n\n public static final String CONSIDERATION_WITH_PARAGRAPHS = \"A consideration should have at least one paragraph\";\n public static final String DAY_WITH_PARAGRAPHS = \"A day should have at least one paragraph\";\n\n public static final String JOY_WITHOUT_LINES = \"A Joy should have at least one line\";\n public static final String JOYS_NOT_NULL = \"The list of joys should not be empty\";\n\n public static final String COUNT_OUT_OF_BOUNDS = \"The progress is out of bounds on the list\";\n public static final String COUNT_NOT_INCREASE_MORE = \"The progress cannot exceed the total %s\";\n public static final String COUNT_NOT_DECREASE_MORE = \"The progress cannot be lesser than %s\";\n\n public static final String KEY_PREF_LANGUAGE = \"pref_key_language\";\n\n private GeneralConstants() {\n }\n\n}" }, { "identifier": "PrayersException", "path": "app/src/main/java/com/prayers/app/exception/PrayersException.java", "snippet": "public class PrayersException extends Exception {\n\n public PrayersException(String message) {\n super(message);\n }\n\n}" }, { "identifier": "Joy", "path": "app/src/main/java/com/prayers/app/model/ninth/Joy.java", "snippet": "public class Joy implements Serializable {\n\n private String[] lines;\n\n public Joy(String... lines) throws PrayersException {\n if (lines == null || lines.length == 0) {\n throw new PrayersException(GeneralConstants.JOY_WITHOUT_LINES);\n }\n this.lines = lines;\n }\n\n public String[] getLines() {\n return lines;\n }\n\n}" }, { "identifier": "JoysForEveryday", "path": "app/src/main/java/com/prayers/app/model/ninth/JoysForEveryday.java", "snippet": "public class JoysForEveryday implements Serializable {\n\n private int current;\n private List<Joy> joys;\n\n public JoysForEveryday(List<Joy> joys, boolean end) throws PrayersException {\n if (joys == null || joys.isEmpty()) {\n throw new PrayersException(GeneralConstants.JOYS_NOT_NULL);\n }\n this.joys = joys;\n\n if (end) {\n this.current = getTotal() - 1;\n } else {\n this.current = 0;\n }\n }\n\n public int getCurrent() {\n return current;\n }\n\n public int getTotal() {\n return joys.size();\n }\n\n public Joy getCurrentJoy() throws PrayersException {\n if (current < 0 || current > getTotal() - 1) {\n throw new PrayersException(GeneralConstants.COUNT_OUT_OF_BOUNDS);\n }\n return joys.get(current);\n }\n\n public void increaseValue() throws PrayersException {\n if (current >= getTotal() - 1) {\n throw new PrayersException(String.format(GeneralConstants.COUNT_NOT_INCREASE_MORE, getTotal()));\n }\n current++;\n }\n\n public void decreaseValue() throws PrayersException {\n if (current <= 0) {\n throw new PrayersException(String.format(GeneralConstants.COUNT_NOT_DECREASE_MORE, 0));\n }\n current--;\n }\n\n}" }, { "identifier": "NinthDay", "path": "app/src/main/java/com/prayers/app/model/ninth/NinthDay.java", "snippet": "public class NinthDay implements Serializable {\n\n private int value;\n private String name;\n private String schedule;\n\n private List<String> considerations;\n private List<String> paragraphs;\n\n public NinthDay(int value, String name, String schedule, String[] considerations, String[] paragraphs) throws PrayersException {\n setValue(value);\n setName(name);\n setSchedule(schedule);\n setConsiderations(considerations);\n setParagraphs(paragraphs);\n }\n\n public int getValue() {\n return value;\n }\n\n public void setValue(int value) {\n this.value = value;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getSchedule() {\n return schedule;\n }\n\n public void setSchedule(String schedule) {\n this.schedule = schedule;\n }\n\n public List<String> getConsiderations() {\n if (considerations == null) {\n considerations = new ArrayList<>();\n }\n return considerations;\n }\n\n public void setConsiderations(String[] considerations) throws PrayersException {\n if (considerations == null || considerations.length == 0) {\n throw new PrayersException(GeneralConstants.CONSIDERATION_WITH_PARAGRAPHS);\n }\n getConsiderations().addAll(Arrays.asList(considerations));\n }\n\n public List<String> getParagraphs() {\n if (paragraphs == null) {\n paragraphs = new ArrayList<>();\n }\n return paragraphs;\n }\n\n public void setParagraphs(String[] paragraphs) throws PrayersException {\n if (paragraphs == null || paragraphs.length == 0) {\n throw new PrayersException(GeneralConstants.DAY_WITH_PARAGRAPHS);\n }\n getParagraphs().addAll(Arrays.asList(paragraphs));\n }\n\n}" } ]
import com.prayers.app.activity.AbstractActivity; import com.prayers.app.activity.R; import com.prayers.app.constants.GeneralConstants; import com.prayers.app.exception.PrayersException; import com.prayers.app.model.ninth.Joy; import com.prayers.app.model.ninth.JoysForEveryday; import com.prayers.app.model.ninth.NinthDay; import java.util.ArrayList; import java.util.List;
2,629
package com.prayers.app.mapper; public class NinthMapper { public static NinthDay prepopulateFirstDay(AbstractActivity activity) throws PrayersException { String[] considerations = {activity.getString(R.string.txt_ninth_1_consideration_1), activity.getString(R.string.txt_ninth_1_consideration_2)}; String[] paragraphs = {activity.getString(R.string.txt_ninth_1_paragraph_1)};
package com.prayers.app.mapper; public class NinthMapper { public static NinthDay prepopulateFirstDay(AbstractActivity activity) throws PrayersException { String[] considerations = {activity.getString(R.string.txt_ninth_1_consideration_1), activity.getString(R.string.txt_ninth_1_consideration_2)}; String[] paragraphs = {activity.getString(R.string.txt_ninth_1_paragraph_1)};
return new NinthDay(GeneralConstants.FIRST_DAY_NINTH, activity.getString(R.string.title_ninth_day_1), activity.getString(R.string.title_ninth_day_1_only_days), considerations, paragraphs);
1
2023-10-25 17:17:47+00:00
4k
llllllxy/tiny-mybatis-paginate
src/main/java/org/tinycloud/paginate/utils/DialectUtils.java
[ { "identifier": "Dialect", "path": "src/main/java/org/tinycloud/paginate/dialect/Dialect.java", "snippet": "public interface Dialect {\n\n /**\n * 获取分页sql\n *\n * @param sql 原始sql\n * @param page 分页响应对象实例\n * @return 获取分页sql\n */\n String getPageSql(String sql, Page<?> page);\n\n /**\n * 获取总条数sql\n *\n * @param sql 原始sql\n * @return 获取查询总数sql\n */\n String getCountSql(String sql);\n}" }, { "identifier": "DialectEnum", "path": "src/main/java/org/tinycloud/paginate/dialect/DialectEnum.java", "snippet": "public enum DialectEnum {\n /**\n * MYSQL\n */\n MYSQL(\"mysql\", MySqlDialect.class),\n /**\n * MARIADB\n */\n MARIADB(\"mariadb\", MySqlDialect.class),\n /**\n * ORACLE\n */\n ORACLE(\"oracle\", OracleDialect.class),\n /**\n * oracle12c\n */\n ORACLE_12C(\"oracle12c\", Oracle12cDialect.class),\n /**\n * DB2\n */\n DB2(\"db2\", Db2Dialect.class),\n /**\n * H2\n */\n H2(\"h2\", HsqlDialect.class),\n /**\n * HSQL\n */\n HSQL(\"hsql\", HsqlDialect.class),\n /**\n * SQLITE\n */\n SQLITE(\"sqlite\", HsqlDialect.class),\n /**\n * POSTGRE\n */\n POSTGRE_SQL(\"postgresql\", PostgresDialect.class),\n /**\n * SQLSERVER\n */\n SQLSERVER(\"sqlserver\", SqlServerDialect.class),\n /**\n * SqlServer 2005 数据库\n */\n SQLSERVER_2005(\"sqlserver_2005\", SqlServer2005Dialect.class),\n /**\n * DM\n */\n DM(\"dm\", OracleDialect.class),\n /**\n * xugu\n */\n XUGU(\"xugu\", MySqlDialect.class),\n /**\n * Kingbase\n */\n KINGBASE_ES(\"kingbasees\", PostgresDialect.class),\n /**\n * Phoenix\n */\n PHOENIX(\"phoenix\", HsqlDialect.class),\n /**\n * Gauss\n */\n GAUSS(\"gauss\", OracleDialect.class),\n /**\n * ClickHouse\n */\n CLICK_HOUSE(\"clickhouse\", MySqlDialect.class),\n /**\n * GBase\n */\n GBASE(\"gbase\", MySqlDialect.class),\n /**\n * GBase-8s\n */\n GBASE_8S(\"gbase-8s\", GBase8sDialect.class),\n /**\n * Oscar\n */\n OSCAR(\"oscar\", MySqlDialect.class),\n /**\n * Sybase\n */\n SYBASE(\"sybase\", SybaseDialect.class),\n /**\n * OceanBase\n */\n OCEAN_BASE(\"oceanbase\", MySqlDialect.class),\n /**\n * Firebird\n */\n FIREBIRD(\"Firebird\", FirebirdDialect.class),\n /**\n * derby\n */\n DERBY(\"derby\", MySqlDialect.class),\n /**\n * HighGo\n */\n HIGH_GO(\"highgo\", HsqlDialect.class),\n /**\n * CUBRID\n */\n CUBRID(\"cubrid\", MySqlDialect.class),\n\n /**\n * GOLDILOCKS\n */\n GOLDILOCKS(\"goldilocks\", MySqlDialect.class),\n /**\n * CSIIDB\n */\n CSIIDB(\"csiidb\", MySqlDialect.class),\n /**\n * CSIIDB\n */\n SAP_HANA(\"hana\", MySqlDialect.class),\n /**\n * Impala\n */\n IMPALA(\"impala\", HsqlDialect.class),\n /**\n * Vertica\n */\n VERTICA(\"vertica\", HsqlDialect.class),\n /**\n * 东方国信 xcloud\n */\n XCloud(\"xcloud\", XCloudDialect.class),\n /**\n * redshift\n */\n REDSHIFT(\"redshift\", HsqlDialect.class),\n /**\n * openGauss\n */\n OPENGAUSS(\"openGauss\", PostgresDialect.class),\n /**\n * TDengine\n */\n TDENGINE(\"TDengine\", HsqlDialect.class),\n /**\n * Informix\n */\n INFORMIX(\"informix\", InforMixDialect.class),\n /**\n * sinodb\n */\n SINODB(\"sinodb\", GBase8sDialect.class),\n /**\n * uxdb\n */\n UXDB(\"uxdb\", HsqlDialect.class),\n /**\n * greenplum\n */\n GREENPLUM(\"greenplum\", PostgresDialect.class),\n /**\n * UNKNOWN DB\n */\n OTHER(\"other\", MySqlDialect.class);\n\n /**\n * 数据库名称\n */\n private final String name;\n\n /**\n * 实现类\n */\n private final Class<? extends Dialect> value;\n\n public String getName() {\n return name;\n }\n\n public Class<? extends Dialect> getValue() {\n return value;\n }\n\n DialectEnum(String name, Class<? extends Dialect> value) {\n this.name = name;\n this.value = value;\n }\n\n public static Class<? extends Dialect> getDialect(String name) {\n DialectEnum[] enums = values();\n for (DialectEnum item : enums) {\n if (item.name.equals(name)) {\n return item.value;\n }\n }\n return MYSQL.value;\n }\n}" }, { "identifier": "PaginateException", "path": "src/main/java/org/tinycloud/paginate/exception/PaginateException.java", "snippet": "public class PaginateException extends RuntimeException {\n private static final long serialVersionUID = 5423027429182629901L;\n\n /**\n * Constructs a new runtime exception with {@code null} as its detail\n * message. The cause is not initialized, and may subsequently be\n * initialized by a call to {@link #initCause}.\n */\n public PaginateException() {\n super();\n }\n\n /**\n * Constructs a new runtime exception with the specified detail message. The\n * cause is not initialized, and may subsequently be initialized by a call\n * to {@link #initCause}.\n *\n * @param message the detail message. The detail message is saved for later\n * retrieval by the {@link #getMessage()} method.\n */\n public PaginateException(String message) {\n super(message);\n }\n\n /**\n * Constructs a new runtime exception with the specified detail message and\n * cause.\n * <p>\n * Note that the detail message associated with {@code cause} is <i>not</i>\n * automatically incorporated in this runtime exception's detail message.\n *\n * @param message the detail message (which is saved for later retrieval by the\n * {@link #getMessage()} method).\n * @param cause the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public PaginateException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a new runtime exception with the specified cause and a detail\n * message of <tt>(cause==null ? null : cause.toString())</tt> (which\n * typically contains the class and detail message of <tt>cause</tt>). This\n * constructor is useful for runtime exceptions that are little more than\n * wrappers for other throwables.\n *\n * @param cause the cause (which is saved for later retrieval by the\n * {@link #getCause()} method). (A <tt>null</tt> value is\n * permitted, and indicates that the cause is nonexistent or\n * unknown.)\n * @since 1.4\n */\n public PaginateException(Throwable cause) {\n super(cause);\n }\n}" } ]
import org.tinycloud.paginate.dialect.Dialect; import org.tinycloud.paginate.dialect.DialectEnum; import org.tinycloud.paginate.exception.PaginateException; import org.apache.ibatis.mapping.MappedStatement; import javax.sql.DataSource; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.util.regex.Pattern;
2,310
package org.tinycloud.paginate.utils; public class DialectUtils { private DialectUtils() { } /** * 动态获取方言实例 * * @param dialect 方言实现类 * @param statement mappedStatement对象 * @return 获取数据库方言 */ public static Dialect newInstance(MappedStatement statement, String dialect) { try { // 如果没有传递枚举参数 // 则自动根据数据库 if (dialect == null) { return getDialectEnum(statement).getValue().newInstance(); } // 反射获取方言实现实例
package org.tinycloud.paginate.utils; public class DialectUtils { private DialectUtils() { } /** * 动态获取方言实例 * * @param dialect 方言实现类 * @param statement mappedStatement对象 * @return 获取数据库方言 */ public static Dialect newInstance(MappedStatement statement, String dialect) { try { // 如果没有传递枚举参数 // 则自动根据数据库 if (dialect == null) { return getDialectEnum(statement).getValue().newInstance(); } // 反射获取方言实现实例
return (Dialect) DialectEnum.getDialect(dialect).newInstance();
1
2023-10-26 06:05:58+00:00
4k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/backend/voting/ADRReview.java
[ { "identifier": "Opt", "path": "src/main/java/com/buschmais/backend/utils/Opt.java", "snippet": "public class Opt <T> {\n\tprivate T value;\n\n\t@PersistenceConstructor\n\tprivate Opt(){}\n\n\tstatic public<T> Opt<T> Empty(){\n\t\treturn new Opt<>();\n\t}\n\n\tstatic public <T> Opt<T> of(T value){\n\t\tOpt<T> res = new Opt<>();\n\t\tres.value = value;\n\t\treturn res;\n\t}\n\n\tstatic public <T> Opt<T> ofNullable(T value){\n\t\treturn of(value);\n\t}\n\n\tpublic void ifPresent(Consumer<T> action) {\n\t\tif (value != null) {\n\t\t\taction.accept(value);\n\t\t}\n\t}\n\n\tpublic <Ret> Ret ifPresent(Ret defaultValue, Function<T, Ret> action) {\n\t\tif (value != null) return action.apply(value);\n\t\treturn defaultValue;\n\t}\n\n\tpublic void ifElse(Consumer<T> action, Runnable elseAction) {\n\t\tif (value != null) {\n\t\t\taction.accept(value);\n\t\t}else{\n\t\t\telseAction.run();\n\t\t}\n\t}\n\n\tpublic boolean isPresent(){\n\t\treturn value != null;\n\t}\n\n\tpublic T get(){\n\t\treturn value;\n\t}\n\n\tpublic Optional<T> stdOpt(){\n\t\treturn Optional.ofNullable(value);\n\t}\n}" }, { "identifier": "VotingPendingNotification", "path": "src/main/java/com/buschmais/backend/notifications/VotingPendingNotification.java", "snippet": "@Data\npublic class VotingPendingNotification implements Notification {\n\tprivate final ADRReview adrReview;\n\tprivate final LocalDateTime creationTime;\n\n\tpublic VotingPendingNotification(\n\t\t\t@NonNull final ADRReview adrReview,\n\t\t\t@NonNull final LocalDateTime creationTime\n\t)\n\t{\n\t\tthis.adrReview = adrReview;\n\t\tthis.creationTime = creationTime;\n\t}\n\n\[email protected]\n\t@Override\n\tpublic NotificationType getType() {\n\t\treturn NotificationType.VOTING_PENDING;\n\t}\n}" }, { "identifier": "User", "path": "src/main/java/com/buschmais/backend/users/User.java", "snippet": "@Document\n@Data\npublic class User implements Comparable<User> {\n\n\t@Setter(AccessLevel.NONE)\n\[email protected]\n\t@Id\n\tprivate String id;\n\n\t@NonNull\n\t@Indexed\n\t@Unique\n\tprivate String userName;\n\n\t@NonNull\n\t@Indexed\n\tprivate Password password;\n\n\tprivate Image profilePicture;\n\n\t@NonNull\n\t@Indexed\n\tprivate UserRights rights;\n\n\t@NonNull\n\t@Setter(AccessLevel.PRIVATE)\n\tprivate List<Notification> notifications;\n\n\t@PersistenceConstructor\n\tprivate User(){ }\n\n\tpublic User(@NonNull final String username, @NonNull final String password) {\n\t\tthis.userName = username;\n\t\tthis.password = new Password(password);\n\t\tthis.rights = new UserRights();\n\t\tthis.notifications = new ArrayList<>();\n\t}\n\n\tpublic void changePassword(@NonNull final String newPassword) {\n\t\tthis.password.changePassword(newPassword);\n\t}\n\n\tpublic boolean checkPassword(@NonNull final String password) {\n\t\treturn this.password.checkPassword(password);\n\t}\n\n\t/**\n\t * Gibt zurück, ob der Nutzer mindestens alle gegebenen Rechte besitzt.\n\t * Es wird also auch true zurückgegeben, wenn der Nutzer mehr als die angeforderten Rechte besitzt.\n\t * @param rights UserRights Element für zu überprüfende Rechte (entsprechendes Element kann über new UserRights(boolean, boolean, boolean) erstellt werden)\n\t * @return boolean, ob der Nutzer mindestens die entsprechenden Rechte besitzt\n\t */\n\tpublic boolean hasRights(@NonNull final UserRights rights){\n\t\treturn this.rights.hasAtLeast(rights);\n\t}\n\n\t/**\n\t * Returns whether the user has access to the UserControl Menu and can create/delete/modify Users\n\t * @return true, if user has at least one of the following rights:\n\t * <ul>\n\t * <li>can manage Users</li>\n\t * </ul>\n\t */\n\tpublic boolean canManageUsers() {\n\t\treturn this.rights.hasAtLeast(new UserRights(true, false));\n\t}\n\n\t/**\n\t * Returns whether the user can generally start/end all votings\n\t * @return true, if user has at least one of the following rights:\n\t * <ul>\n\t * <li>can manage Votings</li>\n\t * </ul>\n\t */\n\tpublic boolean canManageVotes() {\n\t\treturn this.rights.hasAtLeast(new UserRights(false, true, false, false));\n\t}\n\n\t/**\n\t * Returns whether the user can generally see all ADRs regardless of his AccessGroup\n\t * @return true, if user has at least one of the following rights:\n\t * <ul>\n\t * <li>can see all adrs</li>\n\t * </ul>\n\t */\n\tpublic boolean canSeeAllAdrs() {\n\t\treturn this.rights.hasAtLeast(new UserRights(false, false, true, false));\n\t}\n\n\t/**\n\t * Returns whether the user can generally edit the AccessGroups of all ADRs\n\t * @return true, if user has at least one of the following rights:\n\t * <ul>\n\t * <li>can manage adr access groups</li>\n\t * </ul>\n\t */\n\tpublic boolean canManageAdrAccess() {\n\t\treturn this.rights.hasAtLeast(new UserRights(false, false, false, true));\n\t}\n\n\tpublic void pushNotification(@NonNull final Notification notification){\n\t\tnotifications.add(notification);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User{\" +\n\t\t\t\t\"id='\" + id + '\\'' +\n\t\t\t\t\", userName='\" + userName + '\\'' +\n\t\t\t\t\", password=\" + password +\n\t\t\t\t\", rights=\" + rights +\n\t\t\t\t'}';\n\t}\n\n\t@Override\n\tpublic int compareTo(@NonNull User user) {\n\t\treturn user.getUserName().compareTo(this.getUserName());\n\t}\n}" } ]
import com.buschmais.backend.utils.Opt; import com.buschmais.backend.config.RecursiveSaving; import com.buschmais.backend.notifications.VotingPendingNotification; import com.buschmais.backend.users.User; import lombok.*; import org.springframework.data.mongodb.core.mapping.DBRef; import java.time.LocalDateTime; import java.util.*;
1,630
package com.buschmais.backend.voting; @Data public class ADRReview { @RecursiveSaving @Setter(AccessLevel.PRIVATE) @DBRef private Set<User> invitedVoters; @Setter(AccessLevel.PRIVATE) @Getter(AccessLevel.PRIVATE)
package com.buschmais.backend.voting; @Data public class ADRReview { @RecursiveSaving @Setter(AccessLevel.PRIVATE) @DBRef private Set<User> invitedVoters; @Setter(AccessLevel.PRIVATE) @Getter(AccessLevel.PRIVATE)
private Map<String, @NonNull Opt<VoteType>> votes;
0
2023-10-25 15:18:06+00:00
4k
rafaelrok/ms-order-pattern-saga-choreography
payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/service/PaymentService.java
[ { "identifier": "ValidationException", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/config/exception/ValidationException.java", "snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class ValidationException extends RuntimeException {\n\n public ValidationException(String message) {\n super(message);\n }\n}" }, { "identifier": "Payment", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/domain/Payment.java", "snippet": "@Data\n@Builder\n@Entity\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = \"payment\")\npublic class Payment {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer id;\n\n @Column(nullable = false)\n private String orderId;\n\n @Column(nullable = false)\n private String transactionId;\n\n @Column(nullable = false)\n private int totalItems;\n\n @Column(nullable = false)\n private double totalAmount;\n\n @Column(nullable = false)\n @Enumerated(EnumType.STRING)\n private EPaymentStatus status;\n\n @Column(nullable = false, updatable = false)\n private LocalDateTime createdAt;\n\n @Column(nullable = false)\n private LocalDateTime updatedAt;\n\n @PrePersist\n public void prePersist() {\n var now = LocalDateTime.now();\n createdAt = now;\n updatedAt = now;\n status = EPaymentStatus.PENDING;\n }\n\n @PreUpdate\n public void preUpdate() {\n updatedAt = LocalDateTime.now();\n }\n}" }, { "identifier": "Event", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/dto/Event.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Event {\n\n private String id;\n private String orderId;\n private String transactionId;\n private Order payload;\n private String source;\n private ESagaStatus status;\n private List<History> eventHistory;\n private LocalDateTime createdAt;\n\n public void addToHistory(History history) {\n if (isEmpty(eventHistory)) {\n eventHistory = new ArrayList<>();\n }\n eventHistory.add(history);\n }\n}" }, { "identifier": "History", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/dto/History.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class History {\n\n private String source;\n private ESagaStatus status;\n private String message;\n private LocalDateTime createdAt;\n}" }, { "identifier": "OrderProducts", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/dto/OrderProducts.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class OrderProducts {\n\n private Product product;\n private int quantity;\n}" }, { "identifier": "EPaymentStatus", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/enums/EPaymentStatus.java", "snippet": "public enum EPaymentStatus {\n PENDING,\n SUCCESS,\n REFUND\n}" }, { "identifier": "ESagaStatus", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/enums/ESagaStatus.java", "snippet": "public enum ESagaStatus {\n SUCCESS,\n ROLLBACK_PENDING,\n FAIL\n}" }, { "identifier": "PaymentRepository", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/repository/PaymentRepository.java", "snippet": "public interface PaymentRepository extends JpaRepository<Payment, Integer> {\n\n Boolean existsByOrderIdAndTransactionId(String orderId, String transactionId);\n Optional<Payment> findByOrderIdAndTransactionId(String orderId, String transactionId);\n}" }, { "identifier": "SagaExecutionController", "path": "payment-service/src/main/java/br/com/rafaelvieira/ms/choreography/paymentservice/core/saga/SagaExecutionController.java", "snippet": "@Slf4j\n@Component\n@RequiredArgsConstructor\npublic class SagaExecutionController {\n\n private static final String SAGA_LOG_ID = \"ORDER ID: %s | TRANSACTION ID %s | EVENT ID %s\";\n\n private final JsonUtil jsonUtil;\n private final KafkaProducer producer;\n\n @Value(\"${spring.kafka.topic.inventory-success}\")\n private String inventorySuccessTopic;\n\n @Value(\"${spring.kafka.topic.payment-fail}\")\n private String paymentFailTopic;\n\n @Value(\"${spring.kafka.topic.product-validation-fail}\")\n private String productValidationFailTopic;\n\n public void handleSaga(Event event) {\n switch (event.getStatus()) {\n case SUCCESS -> handleSuccess(event);\n case ROLLBACK_PENDING -> handleRollbackPending(event);\n case FAIL -> handleFail(event);\n }\n }\n\n private void handleSuccess(Event event) {\n log.info(\"### CURRENT SAGA: {} | SUCCESS | NEXT TOPIC {} | {}\",\n event.getSource(), inventorySuccessTopic, createSagaId(event));\n sendEvent(event, inventorySuccessTopic);\n }\n\n private void handleRollbackPending(Event event) {\n log.info(\"### CURRENT SAGA: {} | SENDING TO ROLLBACK CURRENT SERVICE | NEXT TOPIC {} | {}\",\n event.getSource(), paymentFailTopic, createSagaId(event));\n sendEvent(event, paymentFailTopic);\n }\n\n private void handleFail(Event event) {\n log.info(\"### CURRENT SAGA: {} | SENDING TO ROLLBACK PREVIOUS SERVICE | NEXT TOPIC {} | {}\",\n event.getSource(), productValidationFailTopic, createSagaId(event));\n sendEvent(event, productValidationFailTopic);\n }\n\n private void sendEvent(Event event, String topic) {\n var json = jsonUtil.toJson(event);\n producer.sendEvent(json, topic);\n }\n\n private String createSagaId(Event event) {\n return format(SAGA_LOG_ID, event.getPayload().getId(), event.getTransactionId(), event.getId());\n }\n}" } ]
import br.com.rafaelvieira.ms.choreography.paymentservice.config.exception.ValidationException; import br.com.rafaelvieira.ms.choreography.paymentservice.core.domain.Payment; import br.com.rafaelvieira.ms.choreography.paymentservice.core.dto.Event; import br.com.rafaelvieira.ms.choreography.paymentservice.core.dto.History; import br.com.rafaelvieira.ms.choreography.paymentservice.core.dto.OrderProducts; import br.com.rafaelvieira.ms.choreography.paymentservice.core.enums.EPaymentStatus; import br.com.rafaelvieira.ms.choreography.paymentservice.core.enums.ESagaStatus; import br.com.rafaelvieira.ms.choreography.paymentservice.core.repository.PaymentRepository; import br.com.rafaelvieira.ms.choreography.paymentservice.core.saga.SagaExecutionController; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.time.LocalDateTime;
2,145
package br.com.rafaelvieira.ms.choreography.paymentservice.core.service; @Slf4j @Service @AllArgsConstructor public class PaymentService { private static final String CURRENT_SOURCE = "PAYMENT_SERVICE"; private static final Double REDUCE_SUM_VALUE = 0.0; private static final Double MIN_VALUE_AMOUNT = 0.1; private final PaymentRepository paymentRepository; private final SagaExecutionController sagaExecutionController; public void realizePayment(Event event) { try { checkCurrentValidation(event); createPendingPayment(event); var payment = findByOrderIdAndTransactionId(event); validateAmount(payment.getTotalAmount()); changePaymentToSuccess(payment); handleSuccess(event); } catch (Exception ex) { log.error("Error trying to make payment: ", ex); handleFailCurrentNotExecuted(event, ex.getMessage()); } sagaExecutionController.handleSaga(event); } private void checkCurrentValidation(Event event) { if (paymentRepository.existsByOrderIdAndTransactionId(event.getPayload().getId(), event.getTransactionId())) { throw new ValidationException("There's another transactionId for this validation."); } } private void createPendingPayment(Event event) { var totalAmount = calculateAmount(event); var totalItems = calculateTotalItems(event); var payment = Payment .builder() .orderId(event.getPayload().getId()) .transactionId(event.getTransactionId()) .totalAmount(totalAmount) .totalItems(totalItems) .build(); save(payment); setEventAmountItems(event, payment); } private double calculateAmount(Event event) { return event .getPayload() .getProducts() .stream() .map(product -> product.getQuantity() * product.getProduct().getUnitValue()) .reduce(REDUCE_SUM_VALUE, Double::sum); } private int calculateTotalItems(Event event) { return event .getPayload() .getProducts() .stream() .map(OrderProducts::getQuantity) .reduce(REDUCE_SUM_VALUE.intValue(), Integer::sum); } private void setEventAmountItems(Event event, Payment payment) { event.getPayload().setTotalAmount(payment.getTotalAmount()); event.getPayload().setTotalItems(payment.getTotalItems()); } private void validateAmount(double amount) { if (amount < MIN_VALUE_AMOUNT) { throw new ValidationException("The minimal amount available is ".concat(String.valueOf(MIN_VALUE_AMOUNT))); } } private void changePaymentToSuccess(Payment payment) {
package br.com.rafaelvieira.ms.choreography.paymentservice.core.service; @Slf4j @Service @AllArgsConstructor public class PaymentService { private static final String CURRENT_SOURCE = "PAYMENT_SERVICE"; private static final Double REDUCE_SUM_VALUE = 0.0; private static final Double MIN_VALUE_AMOUNT = 0.1; private final PaymentRepository paymentRepository; private final SagaExecutionController sagaExecutionController; public void realizePayment(Event event) { try { checkCurrentValidation(event); createPendingPayment(event); var payment = findByOrderIdAndTransactionId(event); validateAmount(payment.getTotalAmount()); changePaymentToSuccess(payment); handleSuccess(event); } catch (Exception ex) { log.error("Error trying to make payment: ", ex); handleFailCurrentNotExecuted(event, ex.getMessage()); } sagaExecutionController.handleSaga(event); } private void checkCurrentValidation(Event event) { if (paymentRepository.existsByOrderIdAndTransactionId(event.getPayload().getId(), event.getTransactionId())) { throw new ValidationException("There's another transactionId for this validation."); } } private void createPendingPayment(Event event) { var totalAmount = calculateAmount(event); var totalItems = calculateTotalItems(event); var payment = Payment .builder() .orderId(event.getPayload().getId()) .transactionId(event.getTransactionId()) .totalAmount(totalAmount) .totalItems(totalItems) .build(); save(payment); setEventAmountItems(event, payment); } private double calculateAmount(Event event) { return event .getPayload() .getProducts() .stream() .map(product -> product.getQuantity() * product.getProduct().getUnitValue()) .reduce(REDUCE_SUM_VALUE, Double::sum); } private int calculateTotalItems(Event event) { return event .getPayload() .getProducts() .stream() .map(OrderProducts::getQuantity) .reduce(REDUCE_SUM_VALUE.intValue(), Integer::sum); } private void setEventAmountItems(Event event, Payment payment) { event.getPayload().setTotalAmount(payment.getTotalAmount()); event.getPayload().setTotalItems(payment.getTotalItems()); } private void validateAmount(double amount) { if (amount < MIN_VALUE_AMOUNT) { throw new ValidationException("The minimal amount available is ".concat(String.valueOf(MIN_VALUE_AMOUNT))); } } private void changePaymentToSuccess(Payment payment) {
payment.setStatus(EPaymentStatus.SUCCESS);
5
2023-10-26 11:12:21+00:00
4k
MultiDuels/MultiDuels
common/src/main/java/dev/kafein/multiduels/common/menu/misc/contexts/ClickContext.java
[ { "identifier": "MultiDuels", "path": "common/src/main/java/dev/kafein/multiduels/common/MultiDuels.java", "snippet": "public interface MultiDuels {\n void load();\n\n void enable();\n\n void disable();\n\n MenuManager getMenuManager();\n\n ServerComponent.Factory getServerComponentFactory();\n\n PlayerComponent.Wrapper<?> getPlayerComponentWrapper();\n\n ItemComponent.Factory getItemComponentFactory();\n\n ItemComponent.Wrapper<?> getItemComponentWrapper();\n\n InventoryComponent.Factory getInventoryComponentFactory();\n\n interface Wrapper<T> {\n T wrap(MultiDuels plugin);\n }\n}" }, { "identifier": "ItemComponent", "path": "common/src/main/java/dev/kafein/multiduels/common/components/ItemComponent.java", "snippet": "public interface ItemComponent {\n String getMaterial();\n\n int getAmount();\n\n String getName();\n\n List<String> getLore();\n\n Builder toBuilder();\n\n interface Builder {\n Builder amount(int amount);\n\n Builder name(@NotNull String name);\n\n Builder name(@NotNull String name, @NotNull Map<String, String> placeholders);\n\n Builder name(@NotNull ConfigurationNode node);\n\n Builder name(@NotNull ConfigurationNode node, @NotNull Map<String, String> placeholders);\n\n Builder lore(@NotNull String... lore);\n\n Builder lore(@NotNull Iterable<String> lore);\n\n Builder lore(@NotNull Iterable<String> lore, @NotNull Map<String, String> placeholders);\n\n Builder lore(@NotNull ConfigurationNode node);\n\n Builder lore(@NotNull ConfigurationNode node, @NotNull Map<String, String> placeholders);\n\n Builder enchantments(@NotNull Map<String, Integer> enchantments);\n\n Builder enchantments(@NotNull ConfigurationNode node);\n\n Builder enchantment(@NotNull String enchantment, int level);\n\n Builder flags(@NotNull Set<String> flags);\n\n Builder flags(@NotNull ConfigurationNode node);\n\n Builder flag(@NotNull String flag);\n\n Builder skullOwner(@NotNull String skullOwner);\n\n Builder skullOwner(@NotNull ConfigurationNode node);\n\n Builder headTexture(@NotNull String headTexture);\n\n Builder headTexture(@NotNull ConfigurationNode node);\n\n ItemComponent build();\n }\n\n interface Wrapper<T> {\n ItemComponent unwrap(@NotNull T wrapped);\n\n T wrap(@NotNull ItemComponent item);\n }\n\n interface Factory {\n ItemComponent create(@NotNull String material);\n\n ItemComponent create(@NotNull String material, int amount);\n\n ItemComponent create(@NotNull ConfigurationNode node);\n\n ItemComponent create(@NotNull ConfigurationNode node, @NotNull Map<String, String> placeholders);\n }\n}" }, { "identifier": "PlayerComponent", "path": "common/src/main/java/dev/kafein/multiduels/common/components/PlayerComponent.java", "snippet": "public interface PlayerComponent {\n UUID getUniqueId();\n\n String getName();\n\n boolean isOnline();\n\n LocationComponent getLocation();\n\n void teleport(@NotNull LocationComponent location);\n\n InventoryComponent.View openInventory(@NotNull InventoryComponent inventory);\n\n InventoryComponent.View openInventory(@NotNull InventoryComponent.Properties properties);\n\n void closeInventory();\n\n void performCommand(@NotNull String command);\n\n void playSound(@NotNull String sound);\n\n void playSound(@NotNull String sound, float volume, float pitch);\n\n void hidePlayer(@NotNull PlayerComponent player);\n\n void hidePlayer(@NotNull PlayerComponent... players);\n\n void hidePlayer(@NotNull Iterable<PlayerComponent> players);\n\n void showPlayer(@NotNull PlayerComponent player);\n\n void showPlayer(@NotNull PlayerComponent... players);\n\n void showPlayer(@NotNull Iterable<PlayerComponent> players);\n\n void hideAllPlayers();\n\n void showAllPlayers();\n\n void sendMessage(@NotNull Component message);\n\n void sendMessage(@NotNull Component... messages);\n\n void sendMessage(@NotNull String message);\n\n void sendMessage(@NotNull String message, @Nullable Map<String, String> placeholders);\n\n void sendMessage(@NotNull String... messages);\n\n void sendMessage(@NotNull Iterable<String> messages);\n\n void sendMessage(@NotNull Iterable<String> messages, @Nullable Map<String, String> placeholders);\n\n void sendActionBar(@NotNull Component message);\n\n void sendActionBar(@NotNull String message);\n\n void sendActionBar(@NotNull String message, @Nullable Map<String, String> placeholders);\n\n void sendTitle(@NotNull String title, @NotNull String subtitle);\n\n void sendTitle(@NotNull String title, @NotNull String subtitle, @Nullable Map<String, String> placeholders);\n\n void sendTitle(@NotNull String title, @NotNull String subtitle, @Nullable Title.Times times);\n\n void sendTitle(@NotNull String title, @NotNull String subtitle, @Nullable Title.Times times, @Nullable Map<String, String> placeholders);\n\n interface Wrapper<T> {\n PlayerComponent unwrap(@NotNull T wrapped);\n\n T wrap(@NotNull PlayerComponent player);\n }\n}" }, { "identifier": "Menu", "path": "common/src/main/java/dev/kafein/multiduels/common/menu/Menu.java", "snippet": "public interface Menu {\n static Menu fromConfig(String name, Config config) {\n return fromNode(name, config.getNode());\n }\n\n static Menu fromConfig(String name, Class<?> clazz, String resource, String... path) {\n Config config = ConfigBuilder.builder(path)\n .resource(clazz, resource)\n .build();\n return fromConfig(name, config);\n }\n\n static Menu fromNode(String name, ConfigurationNode node) {\n return new MenuBuilder()\n .name(name)\n .node(node)\n .propertiesFromNode(node)\n .buttonsFromNode(node)\n .build();\n }\n\n static MenuBuilder newBuilder() {\n return new MenuBuilder();\n }\n\n Viewer open(@NotNull PlayerComponent player);\n\n Viewer open(@NotNull PlayerComponent player, int page);\n\n Viewer open(@NotNull PlayerComponent player, int page, @NotNull OpenCause cause);\n\n @Nullable Viewer nextPage(@NotNull UUID uniqueId);\n\n Viewer nextPage(@NotNull PlayerComponent player);\n\n Viewer nextPage(@NotNull Viewer viewer);\n\n @Nullable Viewer previousPage(@NotNull UUID uniqueId);\n\n Viewer previousPage(@NotNull PlayerComponent player);\n\n Viewer previousPage(@NotNull Viewer viewer);\n\n @Nullable Viewer refresh(@NotNull UUID uniqueId);\n\n Viewer refresh(@NotNull PlayerComponent player);\n\n Viewer refresh(@NotNull Viewer viewer);\n\n @Nullable Viewer refreshButton(@NotNull UUID uniqueId, int slot);\n\n @Nullable Viewer refreshButton(@NotNull UUID uniqueId, @NotNull String buttonName);\n\n @Nullable Viewer refreshButton(@NotNull PlayerComponent player, int slot);\n\n @Nullable Viewer refreshButton(@NotNull PlayerComponent player, @NotNull String buttonName);\n\n Viewer refreshButton(@NotNull Viewer viewer, int slot);\n\n Viewer refreshButton(@NotNull Viewer viewer, @NotNull String buttonName);\n\n @Nullable Viewer close(@NotNull UUID uniqueId);\n\n @Nullable Viewer close(@NotNull PlayerComponent player);\n\n Viewer close(@NotNull Viewer viewer);\n\n ClickResult click(@NotNull ClickContext context);\n\n ClickResult clickEmptySlot(@NotNull ClickContext context);\n\n ClickResult clickBottomInventory(@NotNull ClickContext context);\n\n ClickActionCollection getClickActions();\n\n void registerClickAction(@NotNull String key, @NotNull ClickAction action);\n\n void unregisterClickAction(@NotNull String key);\n\n ViewersHolder getViewers();\n\n boolean isViewing(@NotNull PlayerComponent player);\n\n boolean isViewing(@NotNull UUID uniqueId);\n\n void stopViewing();\n\n MenuProperties getProperties();\n\n @Nullable ConfigurationNode getNode();\n\n String getName();\n\n InventoryComponent.Factory getInventoryFactory();\n\n InventoryComponent.Properties getInventoryProperties();\n\n String getTitle();\n\n int getSize();\n\n ItemComponent.Factory getItemFactory();\n\n @Nullable Set<Button> loadButtonsFromNode();\n\n @Nullable Set<Button> loadButtonsFromNode(@NotNull ConfigurationNode node);\n\n Set<Button> getButtons();\n\n Optional<Button> findButton(@NotNull String name);\n\n Optional<Button> findButton(int slot);\n\n void putButtons(@NotNull Button... buttons);\n\n void putButtons(@NotNull Iterable<Button> buttons);\n\n void putButton(@NotNull Button button);\n\n void removeButtons(@NotNull Button... buttons);\n\n void removeButtons(@NotNull Iterable<Button> buttons);\n\n void removeButton(@NotNull Button button);\n\n void removeButton(@NotNull String name);\n\n @Nullable Button registerClickHandler(@NotNull String buttonName, @NotNull ClickHandler handler);\n\n @Nullable Button registerClickHandler(@NotNull Button button, @NotNull ClickHandler handler);\n\n @Nullable String getOpenSound();\n\n @Nullable String getCloseSound();\n}" }, { "identifier": "Button", "path": "common/src/main/java/dev/kafein/multiduels/common/menu/button/Button.java", "snippet": "public interface Button {\n static Button fromNode(@NotNull ConfigurationNode node) {\n return DefaultButton.newBuilder()\n .node(node)\n .propertiesFromNode()\n .clickActionsFromNode()\n .build();\n }\n\n static @NotNull DefaultButton.Builder newBuilder() {\n return DefaultButton.newBuilder();\n }\n\n static @NotNull <T> PaginatedButton.Builder<T> newPaginatedBuilder() {\n return PaginatedButton.newBuilder();\n }\n\n Map<Integer, ItemComponent> createItems(@NotNull OpenContext context);\n\n ClickResult click(@NotNull ClickContext context);\n\n void setClickHandler(@NotNull ClickHandler clickHandler);\n\n Set<RegisteredClickAction> getClickActions();\n\n void putClickActions(@NotNull Set<RegisteredClickAction> actions);\n\n void putClickAction(@NotNull RegisteredClickAction action);\n\n void removeClickAction(@NotNull RegisteredClickAction action);\n\n void clearClickActions();\n\n ButtonProperties getProperties();\n\n @Nullable ConfigurationNode getNode();\n\n String getName();\n\n ButtonType getType();\n\n int[] getSlots();\n\n boolean hasSlot(int slot);\n\n @Nullable String getClickSound();\n}" }, { "identifier": "ClickType", "path": "common/src/main/java/dev/kafein/multiduels/common/menu/misc/ClickType.java", "snippet": "public enum ClickType {\n LEFT,\n RIGHT,\n SHIFT_LEFT,\n SHIFT_RIGHT,\n DROP,\n CONTROL_DROP\n}" } ]
import dev.kafein.multiduels.common.MultiDuels; import dev.kafein.multiduels.common.components.ItemComponent; import dev.kafein.multiduels.common.components.PlayerComponent; import dev.kafein.multiduels.common.menu.Menu; import dev.kafein.multiduels.common.menu.button.Button; import dev.kafein.multiduels.common.menu.misc.ClickType;
2,856
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.multiduels.common.menu.misc.contexts; public final class ClickContext { private final MultiDuels plugin; private final PlayerComponent player; private final Menu menu;
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.multiduels.common.menu.misc.contexts; public final class ClickContext { private final MultiDuels plugin; private final PlayerComponent player; private final Menu menu;
private final Button button;
4
2023-10-31 10:55:38+00:00
4k
aerospike/graph-synth
graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/EdgeGenerator.java
[ { "identifier": "EdgeSchema", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/definition/EdgeSchema.java", "snippet": "public class EdgeSchema {\n public String name;\n public String inVertex;\n public String outVertex;\n\n public String label() {\n return name;\n }\n\n public List<PropertySchema> properties;\n public boolean joiningEdge = false;\n public GeneratorConfig joiningConfig = null;\n\n public Optional<GeneratorConfig> getJoiningConfig(){\n return Optional.ofNullable(joiningConfig);\n }\n @Override\n public boolean equals(Object o) {\n if (!o.getClass().isAssignableFrom(EdgeSchema.class))\n return false;\n EdgeSchema other = (EdgeSchema) o;\n if (!name.equals(other.name))\n return false;\n if (!inVertex.equals(other.inVertex))\n return false;\n if (!outVertex.equals(other.outVertex))\n return false;\n for (PropertySchema p : properties) {\n final Iterator<PropertySchema> i = other.properties.stream().filter(it -> it.name.equals(p.name)).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(p))\n return false;\n }\n return true;\n }\n}" }, { "identifier": "GraphSchema", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/definition/GraphSchema.java", "snippet": "public class GraphSchema {\n public List<EdgeSchema> edgeTypes;\n public List<VertexSchema> vertexTypes;\n public List<RootVertexSpec> rootVertexTypes;\n public JoiningConfig joining;\n\n @Override\n public boolean equals(Object o) {\n if (!GraphSchema.class.isAssignableFrom(o.getClass()))\n return false;\n final GraphSchema other = (GraphSchema) o;\n for (final EdgeSchema e : edgeTypes) {\n final Iterator<EdgeSchema> i = other.edgeTypes.stream()\n .filter(it -> it.label().equals(e.label())).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(e))\n return false;\n }\n for (final VertexSchema v : vertexTypes) {\n final Iterator<VertexSchema> i = other.vertexTypes.stream()\n .filter(it -> it.label().equals(v.label())).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(v))\n return false;\n }\n for (final RootVertexSpec rvs : rootVertexTypes) {\n final Iterator<RootVertexSpec> i = other.rootVertexTypes.stream()\n .filter(it -> it.name.equals(rvs.name)).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(rvs))\n return false;\n }\n return true;\n }\n}" }, { "identifier": "VertexSchema", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/definition/VertexSchema.java", "snippet": "public class VertexSchema {\n public String name;\n public List<OutEdgeSpec> outEdges;\n\n public String label() {\n return name;\n }\n public List<PropertySchema> properties;\n\n @Override\n public boolean equals(Object o) {\n if (!o.getClass().isAssignableFrom(VertexSchema.class))\n return false;\n VertexSchema other = (VertexSchema) o;\n if (!name.equals(other.name))\n return false;\n for (OutEdgeSpec e : outEdges) {\n final Iterator<OutEdgeSpec> i = other.outEdges.stream().filter(it -> it.name.equals(e.name)).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(e))\n return false;\n }\n for (PropertySchema p : properties) {\n final Iterator<PropertySchema> i = other.properties.stream().filter(it -> it.name.equals(p.name)).iterator();\n if (!i.hasNext())\n return false;\n if (!i.next().equals(p))\n return false;\n }\n return true;\n }\n}" }, { "identifier": "SchemaUtil", "path": "graph-synth/src/main/java/com/aerospike/graph/synth/util/generator/SchemaUtil.java", "snippet": "public class SchemaUtil {\n public static Map<Long, Long> getDistributionConfig(VertexSchema vs, EdgeSchema es) {\n final Map<String, Object> rawConfig;\n rawConfig = es.getJoiningConfig()\n .map(it -> {\n return (Map<String, Object>) it.args.get(es.inVertex.equals(vs.label()) ? SchemaBuilder.Keys.IN_VERTEX_DISTRIBUTION : SchemaBuilder.Keys.OUT_VERTEX_DISTRIBUTION);\n })\n .orElse(new HashMap<>());\n\n es.getJoiningConfig().map(it -> it.args).orElse(new HashMap<>());\n final Map<Long, Long> parsedConfig = new HashMap<>();\n for (Map.Entry<String, Object> entry : rawConfig.entrySet()) {\n parsedConfig.put(Long.valueOf(entry.getKey()), (Long) entry.getValue());\n }\n return parsedConfig;\n }\n\n public static EdgeSchema getSchemaFromEdgeName(final GraphSchema schema, final String edgeTypeName) {\n return schema.edgeTypes.stream()\n .filter(edgeSchema ->\n edgeSchema.name.equals(edgeTypeName)).findFirst()\n .orElseThrow(() -> new NoSuchElementException(\"No edge type found for \" + edgeTypeName));\n }\n\n public static EdgeSchema getSchemaFromEdgeLabel(final GraphSchema schema, final String edgeTypeLabel) {\n return schema.edgeTypes.stream()\n .filter(edgeSchema ->\n edgeSchema.label().equals(edgeTypeLabel)).findFirst()\n .orElseThrow(() -> new NoSuchElementException(\"No edge type found for \" + edgeTypeLabel));\n }\n\n public static VertexSchema getSchemaFromVertexName(final GraphSchema schema, final String vertexTypeName) {\n return schema.vertexTypes.stream()\n .filter(vertexSchema ->\n vertexSchema.name.equals(vertexTypeName)).findFirst()\n .orElseThrow(() ->\n new NoSuchElementException(\"No vertex type found for \" + vertexTypeName));\n }\n\n public static VertexSchema getSchemaFromVertexLabel(final GraphSchema schema, final String vertexTypeLabel) {\n return schema.vertexTypes.stream()\n .filter(vertexSchema ->\n vertexSchema.label().equals(vertexTypeLabel)).findFirst()\n .orElseThrow(() -> new NoSuchElementException(\"No vertex type found for \" + vertexTypeLabel));\n }\n\n public static RootVertexSpec getRootVertexSpecByLabel(final GraphSchema schema, final String rootVertexLabel) {\n return schema.rootVertexTypes.stream()\n .filter(rvs ->\n rvs.name.equals(rootVertexLabel)).findFirst()\n .orElseThrow(() -> new NoSuchElementException(\"No root vertex spec type found for \" + rootVertexLabel));\n }\n\n public static Map<String, VertexSchema> getRootVertexSchemas(final GraphSchema schema) {\n return schema.rootVertexTypes.stream()\n .map(it -> Map.of(it.name, it.toVertexSchema(schema)))\n .reduce(new HashMap<>(), RuntimeUtil::mapReducer);\n }\n\n public static List<EdgeSchema> getJoiningEdgeSchemas(GraphSchema graphSchema) {\n return graphSchema.edgeTypes.stream().filter(it -> it.joiningEdge).collect(Collectors.toList());\n }\n}" } ]
import com.aerospike.graph.synth.emitter.generator.schema.definition.EdgeSchema; import com.aerospike.graph.synth.emitter.generator.schema.definition.GraphSchema; import com.aerospike.graph.synth.emitter.generator.schema.definition.VertexSchema; import com.aerospike.movement.emitter.core.Emitable; import com.aerospike.movement.structure.core.graph.EmittedEdge; import com.aerospike.movement.output.core.Output; import com.aerospike.movement.runtime.core.driver.OutputId; import com.aerospike.movement.runtime.core.driver.OutputIdDriver; import com.aerospike.movement.structure.core.EmittedId; import com.aerospike.graph.synth.util.generator.SchemaUtil; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream;
2,595
/* * @author Grant Haywood <[email protected]> * Developed May 2023 - Oct 2023 * Copyright (c) 2023 Aerospike Inc. */ package com.aerospike.graph.synth.emitter.generator; /** * @author Grant Haywood (<a href="http://iowntheinter.net">http://iowntheinter.net</a>) */ /* there is an eager and a passive way of creating an edge the eager way of creating an edge is traversal. the iterator way walks over the edge and emits it and walks to the next vertex across the edge the passive way takes 2 emitted vertex ids and just emits an edge for them */ public class EdgeGenerator { public final EdgeSchema edgeSchema; public final GraphSchema graphSchema; private GeneratedVertex nextVertex; private boolean emitted = false; public EdgeGenerator(final EdgeSchema edgeSchema, final GraphSchema graphSchema) { this.graphSchema = graphSchema; this.edgeSchema = edgeSchema; } public static EdgeGenerator create(final EdgeSchema edgeSchema, final GraphSchema graphSchema) { return new EdgeGenerator(edgeSchema, graphSchema); } //Step from the generated vertex out over the edge to the next vertex, emit it, then create the edge. public Stream<Emitable> walk(final Long outVid, final OutputIdDriver outputIdDriver) { return Stream.of(new Path(outVid, this, outputIdDriver)); } public static class GeneratedEdge extends EdgeGenerator implements EmittedEdge { private final Long inV; private final Long outV; private final AtomicBoolean written = new AtomicBoolean(false); public GeneratedEdge(final EdgeGenerator edgeGenerator, final Long inV, final Long outV) { this(edgeGenerator.edgeSchema, edgeGenerator.graphSchema, inV, outV); } public GeneratedEdge(final EdgeSchema edgeSchema, final GraphSchema graphSchema, final Long inV, final Long outV) { super(edgeSchema, graphSchema); this.inV = inV; this.outV = outV; } @Override public EmittedId fromId() { return EmittedId.from(outV); } @Override public EmittedId toId() { return EmittedId.from(inV); } @Override public Stream<String> propertyNames() { return edgeSchema.properties.stream().map(p -> p.name); } @Override public Optional<Object> propertyValue(final String name) { return Optional.of(EdgeGenerator.getFieldFromEdge(this, name)); } @Override public String label() { return edgeSchema.label(); } @Override public Stream<Emitable> emit(final Output output) { if (written.compareAndSet(false, true)) { output .writer(EmittedEdge.class, edgeSchema.label()) .writeToOutput(this); } return Stream.empty(); } @Override public Stream<Emitable> stream() { throw new IllegalStateException(); } } private class Path implements Emitable { private final EdgeGenerator edgeGenerator; private final OutputIdDriver outputIdDriver; private final Long outVid; public Path(final Long outVid, final EdgeGenerator edgeGenerator, OutputIdDriver outputIdDriver) { this.outVid = outVid; this.edgeGenerator = edgeGenerator; this.outputIdDriver = outputIdDriver; } public Stream<Emitable> createNextVertex() {
/* * @author Grant Haywood <[email protected]> * Developed May 2023 - Oct 2023 * Copyright (c) 2023 Aerospike Inc. */ package com.aerospike.graph.synth.emitter.generator; /** * @author Grant Haywood (<a href="http://iowntheinter.net">http://iowntheinter.net</a>) */ /* there is an eager and a passive way of creating an edge the eager way of creating an edge is traversal. the iterator way walks over the edge and emits it and walks to the next vertex across the edge the passive way takes 2 emitted vertex ids and just emits an edge for them */ public class EdgeGenerator { public final EdgeSchema edgeSchema; public final GraphSchema graphSchema; private GeneratedVertex nextVertex; private boolean emitted = false; public EdgeGenerator(final EdgeSchema edgeSchema, final GraphSchema graphSchema) { this.graphSchema = graphSchema; this.edgeSchema = edgeSchema; } public static EdgeGenerator create(final EdgeSchema edgeSchema, final GraphSchema graphSchema) { return new EdgeGenerator(edgeSchema, graphSchema); } //Step from the generated vertex out over the edge to the next vertex, emit it, then create the edge. public Stream<Emitable> walk(final Long outVid, final OutputIdDriver outputIdDriver) { return Stream.of(new Path(outVid, this, outputIdDriver)); } public static class GeneratedEdge extends EdgeGenerator implements EmittedEdge { private final Long inV; private final Long outV; private final AtomicBoolean written = new AtomicBoolean(false); public GeneratedEdge(final EdgeGenerator edgeGenerator, final Long inV, final Long outV) { this(edgeGenerator.edgeSchema, edgeGenerator.graphSchema, inV, outV); } public GeneratedEdge(final EdgeSchema edgeSchema, final GraphSchema graphSchema, final Long inV, final Long outV) { super(edgeSchema, graphSchema); this.inV = inV; this.outV = outV; } @Override public EmittedId fromId() { return EmittedId.from(outV); } @Override public EmittedId toId() { return EmittedId.from(inV); } @Override public Stream<String> propertyNames() { return edgeSchema.properties.stream().map(p -> p.name); } @Override public Optional<Object> propertyValue(final String name) { return Optional.of(EdgeGenerator.getFieldFromEdge(this, name)); } @Override public String label() { return edgeSchema.label(); } @Override public Stream<Emitable> emit(final Output output) { if (written.compareAndSet(false, true)) { output .writer(EmittedEdge.class, edgeSchema.label()) .writeToOutput(this); } return Stream.empty(); } @Override public Stream<Emitable> stream() { throw new IllegalStateException(); } } private class Path implements Emitable { private final EdgeGenerator edgeGenerator; private final OutputIdDriver outputIdDriver; private final Long outVid; public Path(final Long outVid, final EdgeGenerator edgeGenerator, OutputIdDriver outputIdDriver) { this.outVid = outVid; this.edgeGenerator = edgeGenerator; this.outputIdDriver = outputIdDriver; } public Stream<Emitable> createNextVertex() {
final VertexSchema vertexSchema = SchemaUtil.getSchemaFromVertexName(graphSchema, edgeSchema.inVertex);
2
2023-10-27 22:54:12+00:00
4k
SUFIAG/ATM-Machine-Using-Java
source-code/src/presentationLayer/WithdrawInfo.java
[ { "identifier": "ATM", "path": "source-code/src/logicLayer/ATM.java", "snippet": "public class ATM {\n private Vector<User> users;\n private writerAndReader readAndWrite;\n private static ATM instance;\n private Amount amountInATM;\n\n //constructor\n private ATM() {\n //initializing data members\n users = new Vector<>();\n readAndWrite = new writerAndReader();\n\n //initializing users from file\n try {\n File myObj = new File(\"./src/dataLayer/users.csv\");\n if (!myObj.createNewFile()) { //if file has already created\n readAndWrite.readUsersFromFile(users);\n } else {\n readAndWrite.writeHeadersInFile();\n }\n } catch (Exception e) {//Catch exception if any\n System.err.println(\"Error: \" + e.getMessage());\n }\n\n //initializing ATM data from file\n try {\n File myObj = new File(\"./src/dataLayer/atm_data.csv\");\n if (!myObj.createNewFile()) { //if file has already created\n amountInATM = readAndWrite.readAtmData();\n } else {\n readAndWrite.writeAtmHeadersInFile();\n }\n } catch (Exception e) {//Catch exception if any\n System.err.println(\"Error: \" + e.getMessage());\n }\n }\n\n //getters\n public Vector<User> getUsers() {\n return users;\n }\n public writerAndReader getReadAndWrite() {\n return readAndWrite;\n }\n public Amount getAmountInATM() {return amountInATM;}\n\n //setters\n public void setUsers(Vector<User> users) {\n this.users = users;\n }\n public void setReadAndWrite(writerAndReader readAndWrite) {\n this.readAndWrite = readAndWrite;\n }\n public void setAmountInATM(Amount amountInATM) {this.amountInATM = amountInATM;}\n\n //function to get instance of this class\n public static ATM getInstance(){\n if (instance == null) {\n instance = new ATM();\n }\n return instance;\n }\n\n //function to check if the account number and pin is valid or not\n public boolean validateAccount(String accNo, String pin) {\n for (User user : users) {\n if (accNo.equals(user.getAccNo()) && pin.equals(user.getPin())) {\n return true;\n }\n }\n return false;\n }\n\n // function to check whether the money is withdrawable or not\n public int canWithdrawMoney(String accNo, int money) {\n for (User user : users) {\n if (accNo.equals(user.getAccNo())) {\n if (user.getBalance() >= money || user.getBalance() + user.getOverdraft() >= money) {\n if (amountInATM.getTotalAmount() >= money) {\n return 1; // good to go\n } else {\n return 2; // not enough money in ATM\n }\n\n } else {\n return 0; // not enough money in account\n }\n }\n }\n return 0; // accNo didn't match\n }\n\n // function to get balance\n public int getBalance(String accNo) {\n for (User user : users) {\n if (accNo.equals(user.getAccNo())) {\n return user.getBalance();\n }\n }\n return -1;\n }\n\n // function to get maximum withdraw amount\n public int getMaximumWithdrawAmount(String accNo) {\n for (User user : users) {\n if (accNo.equals(user.getAccNo())) {\n return user.getBalance() + user.getOverdraft();\n }\n }\n return -1;\n }\n\n //function to withdraw money\n public Amount withdrawMoney(String accNo, int money) {\n // counting and deducting notes for withdrawing money\n int money_copy = money, note = 50, fiftyNotes = 0, twentyNotes = 0, tenNotes = 0, fiveNotes = 0;\n int notes = money_copy / note;\n\n if (notes == 0 && note > money_copy)\n {\n note = 20;\n notes = money_copy / note;\n }\n if (notes == 0 && note > money_copy)\n {\n note = 10;\n notes = money_copy / note;\n }\n if (notes == 0 && note > money_copy)\n {\n note = 5;\n notes = money_copy / note;\n }\n\n while (notes != 0 && money_copy != 0) {\n if (note == 50) {\n if (amountInATM.getFiftyNotes() >= notes) {\n fiftyNotes = notes;\n amountInATM.setFiftyNotes(amountInATM.getFiftyNotes() - notes);\n } else {\n fiftyNotes = amountInATM.getFiftyNotes();\n amountInATM.setFiftyNotes(0);\n }\n\n money_copy -= fiftyNotes * 50;\n note = 20;\n }\n else if (note == 20) {\n if (note <= money_copy) {\n if (amountInATM.getTwentyNotes() >= notes) {\n twentyNotes = notes;\n amountInATM.setTwentyNotes((amountInATM.getTwentyNotes() - notes));\n } else {\n twentyNotes = amountInATM.getTwentyNotes();\n amountInATM.setTwentyNotes(0);\n }\n\n money_copy -= twentyNotes * 20;\n }\n\n note = 10;\n }\n else if (note == 10) {\n if (note <= money_copy) {\n if (amountInATM.getTenNotes() >= notes) {\n tenNotes = notes;\n amountInATM.setTenNotes((amountInATM.getTenNotes() - notes));\n } else {\n tenNotes = amountInATM.getTenNotes();\n amountInATM.setTenNotes(0);\n }\n\n money_copy -= tenNotes * 10;\n }\n\n note = 5;\n }\n else if (note == 5) {\n if (amountInATM.getFiveNotes() >= notes) {\n fiveNotes = notes;\n amountInATM.setFiveNotes((amountInATM.getFiveNotes() - notes));\n } else {\n fiveNotes = amountInATM.getFiveNotes();\n amountInATM.setFiveNotes(0);\n }\n\n note = -1;\n money_copy -= fiveNotes * 5;\n }\n\n if (note <= money_copy)\n notes = money_copy / note;\n }\n Amount amountWithdrawn = new Amount(money, fiftyNotes, twentyNotes, tenNotes, fiveNotes);\n\n // deducting amount that has been withdrawn\n amountInATM.setTotalAmount(amountInATM.getTotalAmount() - money);\n for (int i = 0; i < users.size(); ++i) {\n if (accNo.equals(users.get(i).getAccNo())) {\n if (users.get(i).getBalance() >= money) {\n users.get(i).setBalance(users.get(i).getBalance() - money);\n }\n else if (users.get(i).getBalance() + users.get(i).getOverdraft() >= money) {\n money -= users.get(i).getBalance();\n users.get(i).setBalance(0);\n users.get(i).setOverdraft(users.get(i).getOverdraft() - money);\n }\n }\n }\n\n readAndWrite.truncateAFile(\"./src/dataLayer/users.csv\");\n readAndWrite.writeHeadersInFile();\n for (User user : users) {\n readAndWrite.writeUserIntoFile(user);\n }\n\n readAndWrite.truncateAFile(\"./src/dataLayer/atm_data.csv\");\n readAndWrite.writeAtmHeadersInFile();\n readAndWrite.writeAtmDataIntoFile(amountInATM);\n\n\n return amountWithdrawn;\n }\n}" }, { "identifier": "Amount", "path": "source-code/src/logicLayer/Amount.java", "snippet": "public class Amount {\n private int totalAmount, fiftyNotes, twentyNotes, tenNotes, fiveNotes;\n\n // constructor\n public Amount() {}\n\n public Amount(int totalAmount, int fiftyNotes, int twentyNotes, int tenNotes, int fiveNotes) {\n this.totalAmount = totalAmount;\n this.fiftyNotes = fiftyNotes;\n this.twentyNotes = twentyNotes;\n this.tenNotes = tenNotes;\n this.fiveNotes = fiveNotes;\n }\n\n // getters\n public int getFiftyNotes() {return fiftyNotes;}\n public int getFiveNotes() {return fiveNotes;}\n public int getTenNotes() {return tenNotes;}\n public int getTotalAmount() {return totalAmount;}\n public int getTwentyNotes() {return twentyNotes;}\n\n // setters\n public void setFiftyNotes(int fiftyNotes) {this.fiftyNotes = fiftyNotes;}\n public void setFiveNotes(int fiveNotes) {this.fiveNotes = fiveNotes;}\n public void setTenNotes(int tenNotes) {this.tenNotes = tenNotes;}\n public void setTotalAmount(int totalAmount) {this.totalAmount = totalAmount;}\n public void setTwentyNotes(int twentyNotes) {this.twentyNotes = twentyNotes;}\n}" } ]
import logicLayer.ATM; import logicLayer.Amount;
2,428
package presentationLayer;/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SA */ public class WithdrawInfo extends javax.swing.JFrame { /** * Creates new form WithdrawInfo */ private String accNo; private int amount; public WithdrawInfo(String accNo, int amount) { initComponents(); this.accNo = accNo; this.amount = amount; displayWithdrawInfo(); } // function to display remaining balance and withdrawn notes private void displayWithdrawInfo() { jTextField1.setText(Integer.toString(amount));
package presentationLayer;/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SA */ public class WithdrawInfo extends javax.swing.JFrame { /** * Creates new form WithdrawInfo */ private String accNo; private int amount; public WithdrawInfo(String accNo, int amount) { initComponents(); this.accNo = accNo; this.amount = amount; displayWithdrawInfo(); } // function to display remaining balance and withdrawn notes private void displayWithdrawInfo() { jTextField1.setText(Integer.toString(amount));
ATM atm = ATM.getInstance();
0
2023-10-25 18:26:41+00:00
4k
Java-Game-Engine-Merger/Libgdx-Processing
framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/registry/internal/AbstractGrammarRegistryManager.java
[ { "identifier": "defaultIfNull", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/internal/utils/NullSafetyHelper.java", "snippet": "public static <T> T defaultIfNull(@Nullable final T object,final T defaultValue) {\n if(object==null) {\n return defaultValue;\n }\n return object;\n}" }, { "identifier": "IGrammar", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/grammar/IGrammar.java", "snippet": "public interface IGrammar{\n @Nullable\n String getName();\n String getScopeName();\n Collection<String> getFileTypes();\n ITokenizeLineResult<IToken[]> tokenizeLine(String lineText);\n ITokenizeLineResult<IToken[]> tokenizeLine(String lineText,@Nullable IStateStack prevState,@Nullable Duration timeLimit);\n ITokenizeLineResult<int[]> tokenizeLine2(String lineText);\n ITokenizeLineResult<int[]> tokenizeLine2(String lineText,@Nullable IStateStack prevState,@Nullable Duration timeLimit);\n}" }, { "identifier": "IGrammarSource", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/registry/IGrammarSource.java", "snippet": "public interface IGrammarSource{\n enum ContentType{\n JSON,\n YAML,\n XML\n }\n private static ContentType guessFileFormat(final String fileName) {\n final String extension=fileName.substring(fileName.lastIndexOf('.')+1).trim().toLowerCase();\n return switch(extension) {\n case \"json\"->ContentType.JSON;\n case \"yaml\",\"yaml-tmlanguage\",\"yml\"->ContentType.YAML;\n case \"plist\",\"tmlanguage\",\"xml\"->ContentType.XML;\n default->throw new IllegalArgumentException(\"Unsupported file type: \"+fileName);\n };\n }\n static IGrammarSource fromFile(final Path file) {\n return fromFile(file,null,null);\n }\n static IGrammarSource fromFile(final Path file,@Nullable final ContentType contentType,@Nullable final Charset charset) {\n final var filePath=file.toString();\n final var contentType1=contentType==null?guessFileFormat(filePath):contentType;\n return new IGrammarSource() {\n @Override\n public Reader getReader() throws IOException {\n return Files.newBufferedReader(file,charset==null?StandardCharsets.UTF_8:charset);\n }\n @Override\n public String getFilePath() {\n return filePath;\n }\n @Override\n public ContentType getContentType() {\n return contentType1;\n }\n };\n }\n static IGrammarSource fromResource(final Class<?> clazz,final String resourceName) {\n return fromResource(clazz,resourceName,null,null);\n }\n static IGrammarSource fromResource(final Class<?> clazz,final String resourceName,@Nullable final ContentType contentType,\n @Nullable final Charset charset) {\n final var contentType1=contentType==null?guessFileFormat(resourceName):contentType;\n return new IGrammarSource() {\n @Override\n public Reader getReader() throws IOException {\n return new BufferedReader(new InputStreamReader(\n clazz.getResourceAsStream(resourceName),\n charset==null?StandardCharsets.UTF_8:charset));\n }\n @Override\n public String getFilePath() {\n return resourceName;\n }\n @Override\n public ContentType getContentType() {\n return contentType1;\n }\n };\n }\n static IGrammarSource fromString(final ContentType contentType,final String content) {\n return new IGrammarSource() {\n @Override\n public Reader getReader() throws IOException {\n return new StringReader(content);\n }\n @Override\n public String getFilePath() {\n return \"string.\"+contentType.name().toLowerCase();\n }\n @Override\n public ContentType getContentType() {\n return contentType;\n }\n };\n }\n default ContentType getContentType() {\n return guessFileFormat(getFilePath());\n }\n String getFilePath();\n Reader getReader() throws IOException;\n}" }, { "identifier": "IRegistryOptions", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/registry/IRegistryOptions.java", "snippet": "public interface IRegistryOptions{\n @Nullable\n default IRawTheme getTheme() {\n return null;\n }\n @Nullable\n default List<String> getColorMap() {\n return null;\n }\n @Nullable\n default IGrammarSource getGrammarSource(@SuppressWarnings(\"unused\") final String scopeName) {\n return null;\n }\n @Nullable\n default Collection<String> getInjections(@SuppressWarnings(\"unused\") final String scopeName) {\n return null;\n }\n}" }, { "identifier": "Registry", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/core/registry/Registry.java", "snippet": "public final class Registry{\n // private static final Logger LOGGER=System.getLogger(Registry.class.getName());\n private final IRegistryOptions _options;\n private final SyncRegistry _syncRegistry;\n private final Map<String,Boolean> _ensureGrammarCache=new HashMap<>();\n public Registry() {\n this(new IRegistryOptions() {});\n }\n public Registry(final IRegistryOptions options) {\n this._options=options;\n this._syncRegistry=new SyncRegistry(TextMateTheme.createFromRawTheme(options.getTheme(),options.getColorMap()));\n }\n public void setTheme(final IThemeSource source) throws TMException {\n try {\n this._syncRegistry.setTheme(TextMateTheme.createFromRawTheme(RawThemeReader.readTheme(source),_options.getColorMap()));\n }catch(final Exception ex) {\n throw new TMException(\"Loading theme from '\"+source.getFilePath()+\"' failed: \"+ex.getMessage(),ex);\n }\n }\n public List<String> getColorMap() {\n return this._syncRegistry.getColorMap();\n }\n @Nullable\n public IGrammar loadGrammarWithEmbeddedLanguages(\n final String initialScopeName,\n final int initialLanguage,\n final Map<String,Integer> embeddedLanguages) {\n return this.loadGrammarWithConfiguration(initialScopeName,initialLanguage,\n new IGrammarConfiguration() {\n @Override\n public @Nullable Map<String,Integer> getEmbeddedLanguages() {\n return embeddedLanguages;\n }\n });\n }\n @Nullable\n public IGrammar loadGrammarWithConfiguration(\n final String initialScopeName,\n final int initialLanguage,\n final IGrammarConfiguration configuration) {\n return this._loadGrammar(\n initialScopeName,\n initialLanguage,\n configuration.getEmbeddedLanguages(),\n configuration.getTokenTypes(),\n new BalancedBracketSelectors(\n nullToEmpty(configuration.getBalancedBracketSelectors()),\n nullToEmpty(configuration.getUnbalancedBracketSelectors())));\n }\n @Nullable\n public IGrammar loadGrammar(final String initialScopeName) {\n return this._loadGrammar(initialScopeName,0,null,null,null);\n }\n @Nullable\n private IGrammar _loadGrammar(\n final String initialScopeName,\n final int initialLanguage,\n @Nullable final Map<String,Integer> embeddedLanguages,\n @Nullable final Map<String,Integer> tokenTypes,\n @Nullable final BalancedBracketSelectors balancedBracketSelectors) {\n final var dependencyProcessor=new ScopeDependencyProcessor(this._syncRegistry,initialScopeName);\n while(!dependencyProcessor.Q.isEmpty()) {\n dependencyProcessor.Q.forEach(request->this._loadSingleGrammar(request.scopeName));\n dependencyProcessor.processQueue();\n }\n return this._grammarForScopeName(\n initialScopeName,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors);\n }\n private void _loadSingleGrammar(final String scopeName) {\n this._ensureGrammarCache.computeIfAbsent(scopeName,this::_doLoadSingleGrammar);\n }\n private boolean _doLoadSingleGrammar(final String scopeName) {\n final var grammarSource=this._options.getGrammarSource(scopeName);\n if(grammarSource==null) {\n // System.out.println(WARNING,\"No grammar source for scope [{0}]\",scopeName);\n System.err.println(\"No grammar source for scope [{0}]\"+\" \"+scopeName);\n return false;\n }\n try {\n final var grammar=RawGrammarReader.readGrammar(grammarSource);\n this._syncRegistry.addGrammar(grammar,this._options.getInjections(scopeName));\n }catch(final Exception ex) {\n // System.out.println(ERROR,\"Loading grammar for scope [{0}] failed: {1}\",scopeName,ex.getMessage(),ex);\n System.err.println(\"Loading grammar for scope [{0}] failed: {1}\"+\" \"+scopeName+\" \"+ex.getMessage()+\" \"+ex);\n return false;\n }\n return true;\n }\n public IGrammar addGrammar(final IGrammarSource source) throws TMException {\n return addGrammar(source,null,null,null);\n }\n public IGrammar addGrammar(\n final IGrammarSource source,\n @Nullable final List<String> injections,\n @Nullable final Integer initialLanguage,\n @Nullable final Map<String,Integer> embeddedLanguages) throws TMException {\n try {\n final var rawGrammar=RawGrammarReader.readGrammar(source);\n this._syncRegistry.addGrammar(rawGrammar,\n injections==null||injections.isEmpty()\n ?this._options.getInjections(rawGrammar.getScopeName())\n :injections);\n return castNonNull(\n this._grammarForScopeName(rawGrammar.getScopeName(),initialLanguage,embeddedLanguages,null,null));\n }catch(final Exception ex) {\n throw new TMException(\"Loading grammar from '\"+source.getFilePath()+\"' failed: \"+ex.getMessage(),ex);\n }\n }\n @Nullable\n public IGrammar grammarForScopeName(final String scopeName) {\n return _grammarForScopeName(scopeName,null,null,null,null);\n }\n @Nullable\n private IGrammar _grammarForScopeName(\n final String scopeName,\n @Nullable final Integer initialLanguage,\n @Nullable final Map<String,Integer> embeddedLanguages,\n @Nullable final Map<String,Integer> tokenTypes,\n @Nullable final BalancedBracketSelectors balancedBracketSelectors) {\n return this._syncRegistry.grammarForScopeName(\n scopeName,\n initialLanguage==null?0:initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors);\n }\n}" }, { "identifier": "IGrammarDefinition", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/registry/IGrammarDefinition.java", "snippet": "public interface IGrammarDefinition extends ITMResource{\n String getScopeName();\n}" }, { "identifier": "IGrammarRegistryManager", "path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/registry/IGrammarRegistryManager.java", "snippet": "public interface IGrammarRegistryManager{\n // --------------- TextMate grammar definitions methods\n IGrammarDefinition[] getDefinitions();\n void registerGrammarDefinition(IGrammarDefinition definition);\n void unregisterGrammarDefinition(IGrammarDefinition definition);\n void save() throws BackingStoreException;\n // --------------- TextMate grammar queries methods.\n @Nullable\n IGrammar getGrammarFor(IContentType @Nullable [] contentTypes);\n @Nullable\n IGrammar getGrammarForScope(String scopeName);\n @Nullable\n IGrammar getGrammarForFileType(String fileType);\n @Nullable\n List<IContentType> getContentTypesForScope(String scopeName);\n @Nullable\n Collection<String> getInjections(String scopeName);\n}" } ]
import static org.eclipse.tm4e.core.internal.utils.NullSafetyHelper.defaultIfNull; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import org.eclipse.core.runtime.content.IContentType; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.tm4e.core.grammar.IGrammar; import org.eclipse.tm4e.core.registry.IGrammarSource; import org.eclipse.tm4e.core.registry.IRegistryOptions; import org.eclipse.tm4e.core.registry.Registry; import org.eclipse.tm4e.registry.IGrammarDefinition; import org.eclipse.tm4e.registry.IGrammarRegistryManager;
2,910
package org.eclipse.tm4e.registry.internal; public abstract class AbstractGrammarRegistryManager implements IGrammarRegistryManager{ private final GrammarCache pluginCache=new GrammarCache(); protected final GrammarCache userCache=new GrammarCache(); private static final class EclipseRegistryOptions implements IRegistryOptions{ @Nullable private AbstractGrammarRegistryManager registryManager; private void setRegistry(final AbstractGrammarRegistryManager registryManager) { this.registryManager=registryManager; } @Nullable @Override public Collection<String> getInjections(final String scopeName) { final var registryManager=this.registryManager; if(registryManager==null) { return null; } return registryManager.getInjections(scopeName); } @Override
package org.eclipse.tm4e.registry.internal; public abstract class AbstractGrammarRegistryManager implements IGrammarRegistryManager{ private final GrammarCache pluginCache=new GrammarCache(); protected final GrammarCache userCache=new GrammarCache(); private static final class EclipseRegistryOptions implements IRegistryOptions{ @Nullable private AbstractGrammarRegistryManager registryManager; private void setRegistry(final AbstractGrammarRegistryManager registryManager) { this.registryManager=registryManager; } @Nullable @Override public Collection<String> getInjections(final String scopeName) { final var registryManager=this.registryManager; if(registryManager==null) { return null; } return registryManager.getInjections(scopeName); } @Override
public @Nullable IGrammarSource getGrammarSource(final String scopeName) {
2
2023-10-27 05:47:39+00:00
4k
llllllxy/tinycloud
tinycloud-common/src/main/java/org/tinycloud/common/config/GlobalExceptionHandler.java
[ { "identifier": "ResultCode", "path": "tinycloud-common/src/main/java/org/tinycloud/common/consts/ResultCode.java", "snippet": "public enum ResultCode {\n SUCCESS(\"0\", \"成功\"),\n PARAM_ERROR(\"400\", \"参数校验失败\"),\n UNAUTHORIZED(\"401\", \"会话不存在或已失效\"),\n NOT_EXIST(\"402\", \"不存在\"),\n FORBIDDEN(\"403\", \"访问受限,无权限\"),\n RESOURCE_NOT_FOUND(\"404\", \"资源未找到\"),\n RESOURCE_METHOD_NOT_SUPPORT(\"405\", \"请求方法不支持\"),\n RESOURCE_CONFLICT(\"409\", \"资源冲突\"),\n DUPLICATE_SUBMISSIONS(\"410\", \"重复提交\"),\n REQUEST_PARAM_ERROR(\"412\", \"参数错误\"),\n PRECONDITION_FAILED(\"428\", \"要求先决条件\"),\n NOT_SUPPORT(\"429\", \"不支持的请求\"),\n ALREADY_EXECUTING(\"410\", \"程序正在执行,请稍后再试\"),\n UNKNOWN_ERROR(\"500\", \"系统未知错误\"),\n NOT_IMPLEMENTED(\"501\", \"接口暂未实现\");\n\n /**\n * 错误码\n */\n private String code;\n\n /**\n * 错误描述\n */\n private String desc;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n ResultCode(String code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n ResultCode() {\n }\n}" }, { "identifier": "BusinessException", "path": "tinycloud-common/src/main/java/org/tinycloud/common/exception/BusinessException.java", "snippet": "public class BusinessException extends RuntimeException {\n\n private final String code;\n\n private final String message;\n\n private final Object errT;\n\n public String getCode() {\n return code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public Object getErrT() {\n return errT;\n }\n\n private BusinessException(String code, String message, Object errT) {\n super(message);\n this.code = code;\n this.message = message;\n this.errT = errT;\n }\n\n private BusinessException(String code, String message) {\n this(code, message, null);\n }\n\n /**\n * 带系统码的异常,用来区分微服务系统\n * @param systemCode 系统编码枚举\n * @param code 错误码\n * @param message 错误信息\n */\n public BusinessException(SystemCode systemCode, String code, String message) {\n this(systemCode.getCode() + code, message, null);\n }\n\n /**\n * 带系统码的异常,用来区分微服务系统\n * @param systemCode 系统编码枚举\n * @param code 错误码\n */\n public BusinessException(SystemCode systemCode, ResultCode code) {\n this(systemCode.getCode() + code.getCode(), code.getDesc());\n }\n\n /**\n * 带系统码的异常,用来区分微服务系统\n * @param systemCode 系统编码枚举\n * @param code 错误码\n * @param errT 错误明细\n */\n public BusinessException(SystemCode systemCode, ResultCode code, Object errT) {\n this(systemCode.getCode() + code.getCode(), code.getDesc(), errT);\n }\n}" }, { "identifier": "ApiResult", "path": "tinycloud-common/src/main/java/org/tinycloud/common/model/ApiResult.java", "snippet": "public class ApiResult<T> implements Serializable {\n private static final long serialVersionUID = -1491499610241557029L;\n\n private String code = ResultCode.SUCCESS.getCode();\n\n private T data;\n\n private String msg = ResultCode.SUCCESS.getDesc();\n\n private String traceId;\n\n private long time;\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n /**\n * 空构造方法\n */\n public ApiResult() {\n this.traceId = MDC.get(\"traceId\");\n this.time = System.currentTimeMillis();\n }\n\n /**\n * 带参构造方法\n *\n * @param code 编码\n * @param data 自定义data\n * @param msg 自定义消息\n */\n public ApiResult(String code, T data, String msg) {\n this.code = code;\n this.data = data;\n this.msg = msg;\n this.traceId = MDC.get(\"traceId\");\n this.time = System.currentTimeMillis();\n }\n\n /**\n * 返回成功\n *\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> success() {\n return success(null);\n }\n\n /**\n * 返回成功\n *\n * @param data 自定义data\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> success(T data) {\n return success(data, ResultCode.SUCCESS.getDesc());\n }\n\n /**\n * 返回成功\n *\n * @param data 自定义data\n * @param msg 自定义消息\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> success(T data, String msg) {\n return new ApiResult<>(ResultCode.SUCCESS.getCode(), data, msg);\n }\n\n /**\n * 返回失败\n *\n * @param msg 自定义消息\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> fail(String msg) {\n return new ApiResult<>(ResultCode.UNKNOWN_ERROR.getCode(), null, msg);\n }\n\n /**\n * 返回失败\n *\n * @param code 自定义错误码\n * @param msg 自定义消息\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> fail(String code, String msg) {\n return new ApiResult<>(code, null, msg);\n }\n\n /**\n * 返回失败(标记系统)\n *\n * @param systemCode 自定义系统码\n * @param code 自定义错误码\n * @param msg 自定义消息\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> fail(SystemCode systemCode, String code, String msg) {\n return new ApiResult<>(systemCode.getCode() + code, null, msg);\n }\n\n /**\n * 返回失败(标记系统)\n *\n * @param systemCode 自定义系统码\n * @param error 自定义错误码\n * @return ApiResult<T>\n */\n public static ApiResult<?> fail(SystemCode systemCode, ResultCode error) {\n return new ApiResult<>(systemCode.getCode() + error.getCode(), null, error.getDesc());\n }\n\n /**\n * 返回失败\n *\n * @param systemCode 自定义系统码\n * @param error 自定义错误码\n * @param data 自定义消息\n * @param <T> 泛型\n * @return ApiResult<T>\n */\n public static <T> ApiResult<T> fail(SystemCode systemCode, ResultCode error, T data) {\n return new ApiResult<>(systemCode.getCode() + error.getCode(), data, error.getDesc());\n }\n\n}" } ]
import org.tinycloud.common.consts.ResultCode; import org.tinycloud.common.exception.BusinessException; import org.tinycloud.common.model.ApiResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import java.util.List;
2,317
package org.tinycloud.common.config; /** * <p> * 全局统一异常处理 * </p> * * @author liuxingyu01 * @since 2023/3/4 14:49 **/ @RestControllerAdvice public class GlobalExceptionHandler { static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 捕获404异常 * * @param e NoHandlerFoundException * @return ApiResult */ @ExceptionHandler(NoHandlerFoundException.class)
package org.tinycloud.common.config; /** * <p> * 全局统一异常处理 * </p> * * @author liuxingyu01 * @since 2023/3/4 14:49 **/ @RestControllerAdvice public class GlobalExceptionHandler { static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 捕获404异常 * * @param e NoHandlerFoundException * @return ApiResult */ @ExceptionHandler(NoHandlerFoundException.class)
public ApiResult<?> handle404Error(Throwable e) {
2
2023-10-28 02:05:15+00:00
4k
AysuCgs/JavaMicroservices
AuthService/src/main/java/com/aysu/service/AuthService.java
[ { "identifier": "DoRegisterRequestDto", "path": "AuthService/src/main/java/com/aysu/dto/request/DoRegisterRequestDto.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\npublic class DoRegisterRequestDto {\n\n @NotBlank(message = \"Kullanici adi bos gecilemez.\")\n private String username;\n\n// @Email(message = \"Email giriniz\")\n private String email;\n\n // TODO password Regex yap\n private String password;\n private String repassword;\n\n}" }, { "identifier": "AuthServiceException", "path": "AuthService/src/main/java/com/aysu/exception/AuthServiceException.java", "snippet": "@Getter\npublic class AuthServiceException extends RuntimeException {\n\n private final ErrorType type;\n\n public AuthServiceException(ErrorType type) {\n super(type.getMessage());\n this.type = type;\n }\n\n public AuthServiceException(ErrorType type, String message) {\n super(message);\n this.type = type;\n }\n\n}" }, { "identifier": "ErrorType", "path": "AuthService/src/main/java/com/aysu/exception/ErrorType.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\npublic enum ErrorType {\n\n MUSTERI_BULUNAMADI(1003,\"Aradığınız müşteri sistemde kayıtlı değil\", NOT_FOUND),\n URUN_EKLEME_HATASI(2001,\"Ürün ekleme başarısız oldu\", INTERNAL_SERVER_ERROR),\n INVALID_PARAMETER(3001,\"Geçersiz parametre girişi yaptınız\", HttpStatus.BAD_REQUEST),\n\n REGISTER_PASSWORD_MISMACTH(4001,\"Girilen parolalar eşleşmedi.\", HttpStatus.BAD_REQUEST),\n REGISTER_USERNAME_EXISTS(4002,\"Geçersiz parametre girişi yaptınız\", HttpStatus.BAD_REQUEST),\n\n LOGIN_USERNAME_OR_PASSWORD_NOT_EXISTS(5001,\"Girilen kullanıcı adı veya parola hatalı.\", HttpStatus.BAD_REQUEST),\n\n INVALID_TOKEN(6001,\"Girilen token gecersiz.\", HttpStatus.BAD_REQUEST);\n\n\n private int code;\n private String message;\n private HttpStatus status;\n}" }, { "identifier": "IUserProfileManager", "path": "AuthService/src/main/java/com/aysu/manager/IUserProfileManager.java", "snippet": "@FeignClient(name = \"user-profile-manager\",url = \"http://localhost:9093/user\",decode404 = true)\npublic interface IUserProfileManager {\n @PostMapping(SAVE)\n ResponseEntity<Boolean> save(@RequestBody UserProfileSaveRequestDto dto);\n}" }, { "identifier": "IAuthMapper", "path": "AuthService/src/main/java/com/aysu/mapper/IAuthMapper.java", "snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface IAuthMapper {\n\n IAuthMapper INSTANCE= Mappers.getMapper(IAuthMapper.class);\n\n Auth toAuth(final DoRegisterRequestDto dto);\n\n @Mapping(target = \"authid\",source = \"id\")\n UserProfileSaveRequestDto fromAuth (final Auth auth);\n\n}" }, { "identifier": "SaveAuthModel", "path": "AuthService/src/main/java/com/aysu/rabbitmq/model/SaveAuthModel.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class SaveAuthModel implements Serializable {\n\n private Long authid;\n private String username;\n private String email;\n}" }, { "identifier": "CreateUserProducer", "path": "AuthService/src/main/java/com/aysu/rabbitmq/producer/CreateUserProducer.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class CreateUserProducer {\n\n public final RabbitTemplate rabbitTemplate;\n\n public void convertAndSend(SaveAuthModel model){\n rabbitTemplate.convertAndSend(\"direct-exchange-auth\",\"save-binding-key\",model);\n }\n}" }, { "identifier": "IAuthRepository", "path": "AuthService/src/main/java/com/aysu/repository/IAuthRepository.java", "snippet": "@Repository\npublic interface IAuthRepository extends JpaRepository<Auth, Long> {\n\n Boolean existsByUsername(String username);\n\n Optional<Auth> findOptionalByUsernameAndPassword(String username, String password);\n\n}" }, { "identifier": "Auth", "path": "AuthService/src/main/java/com/aysu/repository/entity/Auth.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Entity\n@Table(name = \"tbl_auth\")\npublic class Auth {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true)\n private String username;\n private String email;\n private String password;\n\n private Long createAt;\n private boolean state;\n\n}" }, { "identifier": "JwtTokenManager", "path": "AuthService/src/main/java/com/aysu/utility/JwtTokenManager.java", "snippet": "@Component\npublic class JwtTokenManager {\n /* 1.Durum\n String secretKey = \"Ankara_06\";\n String issuer = \"Adana_01\";\n Long exDate = 1000L * 60 * 1; // 1 dakika*/\n\n //2.Durum\n @Value(\"${authservice.secrets.key}\")\n String secretKey;\n @Value(\"${authservice.secrets.issuer}\")\n String issuer;\n @Value(\"${authservice.secrets.exDate}\")\n Long exDate;\n\n\n // Token uretme\n public Optional<String> createToken (Long id){\n String token = \"\";\n try {\n token = JWT.create().withAudience()\n .withClaim(\"id\", id)\n .withClaim(\"info\", \"AuthService\")\n .withClaim(\"lastjoin\", System.currentTimeMillis())\n .withIssuer(issuer)\n .withIssuedAt(new Date())\n .withExpiresAt(new Date(System.currentTimeMillis() + exDate))\n .sign(Algorithm.HMAC512(secretKey));\n\n return Optional.of(token);\n } catch (Exception e) {\n return Optional.empty();\n }\n }\n\n // Token dogulama\n public Boolean verifyToken (String token){\n\n try{\n Algorithm algorithm = Algorithm.HMAC512(secretKey);\n JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();\n DecodedJWT decodedJWT = verifier.verify(token);\n\n if (decodedJWT == null)\n return false;\n\n } catch (Exception e){\n return false;\n }\n return true;\n }\n\n\n // Tokendan bilgi aliyoruz.\n public Optional<Long> getIdFromToken (String token){\n try {\n Algorithm algorithm = Algorithm.HMAC512(secretKey);\n JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build();\n DecodedJWT decodedJWT = verifier.verify(token);\n\n System.out.println(\"Tokendaki decodedJWT : \"+ decodedJWT);\n\n if (decodedJWT == null)\n return Optional.empty();\n\n Long id = decodedJWT.getClaim(\"id\").asLong();\n\n String info = decodedJWT.getClaim(\"info\").asString();\n System.out.println(\"info : \"+ info);\n\n return Optional.of(id);\n\n } catch (Exception e){\n return Optional.empty();\n }\n\n }\n\n\n}" }, { "identifier": "ServiceManager", "path": "AuthService/src/main/java/com/aysu/utility/ServiceManager.java", "snippet": "public class ServiceManager<T,ID> implements IService<T,ID>{\n\n private final JpaRepository<T,ID> repository;\n public ServiceManager(JpaRepository<T, ID> repository) {\n this.repository = repository;\n }\n\n @Override\n public T save(T t) {\n return repository.save(t);\n }\n @Override\n public Iterable<T> saveAll(Iterable<T> t) {\n return repository.saveAll(t);\n }\n\n @Override\n public T update(T t) {\n return repository.save(t);\n }\n\n @Override\n public void delete(T t) {\n repository.delete(t);\n }\n @Override\n public void deleteById(ID id) {\n repository.deleteById(id);\n }\n\n @Override\n public Optional<T> findById(ID id) {\n return repository.findById(id);\n }\n @Override\n public List<T> findAll() {\n return repository.findAll();\n }\n\n}" }, { "identifier": "DoLoginRequestDto", "path": "AuthService/src/main/java/com/aysu/dto/request/DoLoginRequestDto.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\npublic class DoLoginRequestDto {\n\n @NotBlank(message = \"Kullanıcı adi boş gecilemez.\")\n @Size(min = 2, max = 50)\n private String username;\n\n private String password;\n\n}" } ]
import com.aysu.dto.request.DoRegisterRequestDto; import com.aysu.exception.AuthServiceException; import com.aysu.exception.ErrorType; import com.aysu.manager.IUserProfileManager; import com.aysu.mapper.IAuthMapper; import com.aysu.rabbitmq.model.SaveAuthModel; import com.aysu.rabbitmq.producer.CreateUserProducer; import com.aysu.repository.IAuthRepository; import com.aysu.repository.entity.Auth; import com.aysu.utility.JwtTokenManager; import com.aysu.utility.ServiceManager; import com.aysu.dto.request.DoLoginRequestDto; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional;
2,441
package com.aysu.service; @Service public class AuthService extends ServiceManager<Auth, Long> { private final IAuthRepository repository; private final JwtTokenManager jwtTokenManager; private final IUserProfileManager userProfileManager; private final CreateUserProducer createUserProducer; public AuthService(IAuthRepository repository, JwtTokenManager jwtTokenManager, IUserProfileManager userProfileManager, CreateUserProducer createUserProducer) { super(repository); this.repository = repository; this.jwtTokenManager = jwtTokenManager; this.userProfileManager = userProfileManager; this.createUserProducer = createUserProducer; } public String doLogin(DoLoginRequestDto dto) { Optional<Auth> auth = repository.findOptionalByUsernameAndPassword(dto.getUsername(), dto.getPassword()); if (auth.isEmpty())
package com.aysu.service; @Service public class AuthService extends ServiceManager<Auth, Long> { private final IAuthRepository repository; private final JwtTokenManager jwtTokenManager; private final IUserProfileManager userProfileManager; private final CreateUserProducer createUserProducer; public AuthService(IAuthRepository repository, JwtTokenManager jwtTokenManager, IUserProfileManager userProfileManager, CreateUserProducer createUserProducer) { super(repository); this.repository = repository; this.jwtTokenManager = jwtTokenManager; this.userProfileManager = userProfileManager; this.createUserProducer = createUserProducer; } public String doLogin(DoLoginRequestDto dto) { Optional<Auth> auth = repository.findOptionalByUsernameAndPassword(dto.getUsername(), dto.getPassword()); if (auth.isEmpty())
throw new AuthServiceException(ErrorType.LOGIN_USERNAME_OR_PASSWORD_NOT_EXISTS);
2
2023-10-27 19:48:42+00:00
4k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/common/config/auth/realm/AuthClientRealm.java
[ { "identifier": "AuthResultConstant", "path": "src/main/java/com/bluewind/base/common/config/auth/constant/AuthResultConstant.java", "snippet": "public class AuthResultConstant {\n\n // 用户不存在\n public final static int USER_NOT_EXIST = 10000;\n\n // 用户名密码不匹配\n public final static int USERNAME_AND_PASSWORD_NOT_MATCH = 10001;\n\n // 用户失效\n public final static int USER_IS_INVALID = 10002;\n\n // 用户被锁定\n public final static int USER_IS_LOCKED = 10003;\n\n // 超过最大会话数量\n public final static int EXCEED_SESSIONS_MAXNUM = 10004;\n\n // 登录验证成功\n public final static int MATCH_SUCCESS = 10005;\n}" }, { "identifier": "UserInfoUtil", "path": "src/main/java/com/bluewind/base/common/config/auth/util/UserInfoUtil.java", "snippet": "public class UserInfoUtil {\n private static final Logger logger = LoggerFactory.getLogger(UserInfoUtil.class);\n\n\n private static RedisUtils redisUtils;\n\n private static RedisUtils getRedisUtils() {\n if (redisUtils == null) {\n Object bean = SpringContextUtil.getBean(\"redisUtils\");\n if (bean == null) {\n logger.error(\"redisUtils bean is null!\");\n }\n redisUtils = (RedisUtils) bean;\n }\n return redisUtils;\n }\n\n\n private static AuthService authService;\n\n private static AuthService getAuthService() {\n if (authService == null) {\n AuthService bean = SpringContextUtil.getBean(AuthService.class);\n if (bean == null) {\n logger.error(\"FinanceConvertUtilsService bean is null\");\n }\n authService = bean;\n return authService;\n }\n return authService;\n }\n\n\n /**\n * 获取当前登录用户的token会话串\n *\n * @return String\n */\n public static String getToken() {\n HttpServletRequest httpServletRequest = ServletUtils.getRequest();\n if (Objects.isNull(httpServletRequest)) {\n return null;\n }\n String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);\n if (StringUtils.isBlank(token)) {\n token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);\n }\n return token;\n }\n\n\n /**\n * 获取指定HttpServletRequest的token会话串\n *\n * @return String\n */\n public static String getToken(HttpServletRequest httpServletRequest) {\n if (Objects.isNull(httpServletRequest)) {\n return null;\n }\n String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);\n if (StringUtils.isBlank(token)) {\n token = CookieUtils.getCookie(httpServletRequest, AuthConstant.BLUEWIND_COOKIE_KEY);\n }\n return token;\n }\n\n\n /**\n * 获取当前登录用户账户\n *\n * @return String\n */\n public static String getUserName() {\n Subject subject = SecurityUtils.getSubject();\n return (String) subject.getPrincipal();\n }\n\n /**\n * 获取当前用户的userInfo\n *\n * @return UcUserDTO\n */\n public static UserInfo getUserInfo() {\n String username = getUserName();\n // 先从缓存中取,缓存中取不到再去数据库取\n String redisKey = AuthConstant.BLUEWIND_USERINFO_CACHE + \":\" + username;\n UserInfo userInfo = (UserInfo) getRedisUtils().get(redisKey);\n if (Objects.isNull(userInfo)) {\n userInfo = getAuthService().getUserInfo(username);\n getRedisUtils().set(redisKey, userInfo, AuthUtil.getSessionsTime());\n }\n return userInfo;\n }\n\n\n /**\n * 获取用户编码\n *\n * @return String\n */\n public static long getUserId() {\n UserInfo userInfo = getUserInfo();\n return userInfo.getUserId();\n }\n\n}" }, { "identifier": "AuthService", "path": "src/main/java/com/bluewind/base/module/system/auth/service/AuthService.java", "snippet": "public interface AuthService {\n\n int authentication(String username, String password);\n\n void recordFailUserLogin(String username);\n\n UserInfo getUserInfo(String username);\n\n Set<String> listRolePermissionByUserId(Long userId);\n\n Set<String> listUserRoleByUserId(Long userId);\n}" } ]
import com.bluewind.base.common.config.auth.constant.AuthResultConstant; import com.bluewind.base.common.config.auth.util.UserInfoUtil; import com.bluewind.base.module.system.auth.service.AuthService; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired;
1,698
package com.bluewind.base.common.config.auth.realm; /** * @author liuxingyu01 * @date 2022-08-26 14:30 * @description 自定义Realm **/ public class AuthClientRealm extends AuthorizingRealm { final static Logger logger = LoggerFactory.getLogger(AuthClientRealm.class); @Autowired private AuthService authService; /** * 身份认证 * * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); /* * 免密单点登录 */ if (StringUtils.isBlank(password)) { return new SimpleAuthenticationInfo(username, password, getName()); } // 根据用户名查找到用户信息 int resutl = authService.authentication(username, password); // 超过最大尝试次数,锁定一段时间 if (resutl == AuthResultConstant.USER_IS_LOCKED) { throw new LockedAccountException(); } // 超过最大会话数量 if (resutl == AuthResultConstant.EXCEED_SESSIONS_MAXNUM) { throw new ExcessiveAttemptsException(); } // 没找到帐号(用户不存在) if (resutl == AuthResultConstant.USER_NOT_EXIST) { throw new UnknownAccountException(); } // 校验用户状态(用户已失效) if (resutl == AuthResultConstant.USER_IS_INVALID) { throw new DisabledAccountException(); } // 用户名密码不匹配 if (resutl == AuthResultConstant.USERNAME_AND_PASSWORD_NOT_MATCH) { throw new IncorrectCredentialsException(); } return new SimpleAuthenticationInfo(username, password, getName()); } /** * 角色权限认证 * * @param principalCollection * @return AuthorizationInfo */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = (String) principalCollection.getPrimaryPrincipal(); if (StringUtils.isNoneBlank(username)) { // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission) SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
package com.bluewind.base.common.config.auth.realm; /** * @author liuxingyu01 * @date 2022-08-26 14:30 * @description 自定义Realm **/ public class AuthClientRealm extends AuthorizingRealm { final static Logger logger = LoggerFactory.getLogger(AuthClientRealm.class); @Autowired private AuthService authService; /** * 身份认证 * * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); /* * 免密单点登录 */ if (StringUtils.isBlank(password)) { return new SimpleAuthenticationInfo(username, password, getName()); } // 根据用户名查找到用户信息 int resutl = authService.authentication(username, password); // 超过最大尝试次数,锁定一段时间 if (resutl == AuthResultConstant.USER_IS_LOCKED) { throw new LockedAccountException(); } // 超过最大会话数量 if (resutl == AuthResultConstant.EXCEED_SESSIONS_MAXNUM) { throw new ExcessiveAttemptsException(); } // 没找到帐号(用户不存在) if (resutl == AuthResultConstant.USER_NOT_EXIST) { throw new UnknownAccountException(); } // 校验用户状态(用户已失效) if (resutl == AuthResultConstant.USER_IS_INVALID) { throw new DisabledAccountException(); } // 用户名密码不匹配 if (resutl == AuthResultConstant.USERNAME_AND_PASSWORD_NOT_MATCH) { throw new IncorrectCredentialsException(); } return new SimpleAuthenticationInfo(username, password, getName()); } /** * 角色权限认证 * * @param principalCollection * @return AuthorizationInfo */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = (String) principalCollection.getPrimaryPrincipal(); if (StringUtils.isNoneBlank(username)) { // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission) SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
Long userId = UserInfoUtil.getUserId();
1
2023-10-26 10:02:07+00:00
4k
Daudeuf/GLauncher
src/main/java/fr/glauncher/ui/panels/Launch.java
[ { "identifier": "Controller", "path": "src/main/java/fr/glauncher/Controller.java", "snippet": "public class Controller\n{\n\tpublic static final PackInfos pack;\n\n\tstatic {\n\t\ttry {\n\t\t\tpack = PackInfos.create(\"https://raw.githubusercontent.com/Daudeuf/GLauncher/master/modpack_info.json\");\n\t\t} catch (URISyntaxException | IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tprivate static final String NAME = \"glauncher\";\n\tprivate static final String LABEL = \"GLauncher\";\n\n\tprivate final ILogger logger;\n\tprivate final Path launcherDir;\n\tprivate final Launcher launcher;\n\tprivate final Saver saver;\n\tprivate final Auth auth;\n\n\tpublic Controller()\n\t{\n\t\tthis.launcherDir = createGameDir(NAME, true);\n\t\tthis.logger = new Logger(String.format(\"[%s]\", LABEL), this.launcherDir.resolve(\"launcher.log\"));\n\n\t\tif (Files.notExists(this.launcherDir))\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFiles.createDirectory(this.launcherDir);\n\t\t\t}\n\t\t\tcatch (IOException e)\n\t\t\t{\n\t\t\t\tthis.logger.err(\"Unable to create launcher folder\");\n\t\t\t\tthis.logger.printStackTrace(e);\n\t\t\t}\n\t\t}\n\n\t\tthis.saver = new Saver(this.launcherDir.resolve(\"config.properties\"));\n\t\tthis.saver.load();\n\n\t\tthis.auth = new Auth ( this );\n\t\tthis.launcher = new Launcher( this );\n\n\t\tthis.launcher.checkOnline();\n\t}\n\n\tpublic ILogger getLogger() { return this.logger; }\n\tpublic Path getLauncherDir() { return this.launcherDir; }\n\tpublic Saver getSaver() { return this.saver; }\n\tpublic Auth getAuth() { return this.auth; }\n\n\tpublic static Path createGameDir(String serverName, boolean inLinuxLocalShare)\n\t{\n\t\tfinal String os = Objects.requireNonNull(System.getProperty(\"os.name\")).toLowerCase();\n\n\t\tif (os.contains(\"win\"))\n\t\t{\n\t\t\treturn Paths.get(System.getenv(\"APPDATA\"), '.' + serverName);\n\t\t}\n\t\telse if (os.contains(\"mac\"))\n\t\t{\n\t\t\treturn Paths.get(\n\t\t\t\t\tSystem.getProperty(\"user.home\"),\n\t\t\t\t\t\"Library\",\n\t\t\t\t\t\"Application Support\",\n\t\t\t\t\tserverName\n\t\t\t);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (inLinuxLocalShare && os.contains(\"linux\"))\n\t\t\t{\n\t\t\t\treturn Paths.get(\n\t\t\t\t\t\tSystem.getProperty(\"user.home\"),\n\t\t\t\t\t\t\".local\",\n\t\t\t\t\t\t\"share\",\n\t\t\t\t\t\tserverName\n\t\t\t\t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn Paths.get(\n\t\t\t\t\t\tSystem.getProperty(\"user.home\"),\n\t\t\t\t\t\t'.' + serverName\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void switchLogin()\n\t{\n\t\tthis.launcher.switchLogin();\n\t}\n\tpublic void hide() { this.launcher.setVisible( !this.launcher.isVisible() ); }\n\tpublic void refreshHeadImg() { this.launcher.refreshHeadImg(); }\n}" }, { "identifier": "Setup", "path": "src/main/java/fr/glauncher/game/Setup.java", "snippet": "public class Setup\n{\n\tpublic static void setup(Controller ctrl, Launch launch)\n\t{\n\t\tIProgressCallback callback = makeCallback( ctrl, launch );\n\n\t\ttry\n\t\t{\n\t\t\tController.pack.refresh();\n\n\t\t\tfinal VanillaVersion vanillaVersion = new VanillaVersion.VanillaVersionBuilder()\n\t\t\t\t\t.withName(Controller.pack.getVersion().split(\"-\")[0])\n\t\t\t\t\t.build();\n\n\t\t\tString modsString = ctrl.getSaver().get(\"additional_mod_list\", \"\");\n\t\t\tString[] mods = modsString.split(\"\\n\");\n\n\t\t\tfinal AbstractForgeVersion forge = new ForgeVersionBuilder(ForgeVersionType.NEW)\n\t\t\t\t\t.withForgeVersion(Controller.pack.getVersion())\n\t\t\t\t\t.withCurseModPack(new CurseModPackInfo(\n\t\t\t\t\t\t\tController.pack.getProjectId(),\n\t\t\t\t\t\t\tController.pack.getFileId(),\n\t\t\t\t\t\t\ttrue)\n\t\t\t\t\t)\n\t\t\t\t\t.withFileDeleter(new ModFileDeleter(true, mods))\n\t\t\t\t\t.build();\n\n\t\t\tfinal FlowUpdater updater = new FlowUpdater.FlowUpdaterBuilder()\n\t\t\t\t\t.withVanillaVersion(vanillaVersion)\n\t\t\t\t\t.withModLoaderVersion(forge)\n\t\t\t\t\t.withLogger(ctrl.getLogger())\n\t\t\t\t\t.withProgressCallback(callback)\n\t\t\t\t\t.build();\n\n\t\t\tupdater.update(ctrl.getLauncherDir());\n\n\t\t\t// Fix Shaders\n\t\t\tFile modsFolder = new File(ctrl.getLauncherDir().toFile(), \"mods\" );\n\t\t\tFile shadersFolder = new File(ctrl.getLauncherDir().toFile(), \"shaderpacks\");\n\n\t\t\tif (!shadersFolder.exists()) shadersFolder.mkdirs();\n\n\t\t\tif (\n\t\t\t\t\tmodsFolder.exists() &&\n\t\t\t\t\tmodsFolder.isDirectory() &&\n\t\t\t\t\tshadersFolder.exists() &&\n\t\t\t\t\tshadersFolder.isDirectory()\n\t\t\t) {\n\t\t\t\tFile[] shaders = modsFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(\".zip\"));\n\n\t\t\t\tassert shaders != null;\n\t\t\t\tfor (File shader : shaders) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tFiles.copy(shader.toPath(), new File(shadersFolder, shader.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);\n\t\t\t\t\t} catch (IOException exp) {\n\t\t\t\t\t\tctrl.getLogger().printStackTrace(exp);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// End Fixing Shaders\n\n\t\t\tctrl.getLogger().info(\"Launching !\");\n\t\t\tnew Start(ctrl, updater.getVanillaVersion().getName());\n\t\t}\n\t\tcatch (Exception exp)\n\t\t{\n\t\t\tctrl.getLogger().printStackTrace(exp);\n\t\t}\n\t}\n\n\tpublic static IProgressCallback makeCallback(Controller ctrl, Launch launch)\n\t{\n\t\treturn new IProgressCallback()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void step(Step step)\n\t\t\t{\n\t\t\t\tlaunch.setInLoading( true );\n\n\t\t\t\tif (step.name().equals(\"END\"))\n\t\t\t\t{\n\t\t\t\t\tlaunch.setInLoading( false );\n\t\t\t\t\tctrl.hide();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void update(DownloadList.DownloadInfo info)\n\t\t\t{\n\t\t\t\tlaunch.setLoadingProgress( (int) (10000.0 * info.getDownloadedBytes() / info.getTotalToDownloadBytes()) );\n\t\t\t}\n\t\t};\n\t}\n}" }, { "identifier": "AdditionalModList", "path": "src/main/java/fr/glauncher/ui/frames/AdditionalModList.java", "snippet": "public class AdditionalModList extends JFrame implements ActionListener {\n\tprivate final JTextArea txtArea;\n\tprivate final Controller ctrl;\n\n\tpublic AdditionalModList(Controller ctrl)\n\t{\n\t\tthis.ctrl = ctrl;\n\n\t\tthis.setTitle(\"Mods supplémentaires\");\n\t\tthis.setLocationRelativeTo(null);\n\t\tthis.setSize(450, 350);\n\t\tthis.setDefaultCloseOperation(DISPOSE_ON_CLOSE);\n\n\t\tJPanel p = new JPanel( new BorderLayout(20, 20) );\n\n\t\tthis.txtArea = new JTextArea();\n\t\tJButton btn = new JButton(\"Valider\");\n\t\tbtn.addActionListener(this);\n\n\t\tSaver s = this.ctrl.getSaver();\n\n\t\tthis.txtArea.setText( s.get(\"additional_mod_list\", \"\") );\n\n\t\tp.add(btn, BorderLayout.SOUTH );\n\t\tp.add( this.txtArea, BorderLayout.CENTER );\n\n\t\tthis.add(p);\n\n\t\tthis.setVisible(true);\n\t}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent e)\n\t{\n\t\tSaver s = this.ctrl.getSaver();\n\n\t\ts.set(\"additional_mod_list\", this.txtArea.getText());\n\t\ts.save();\n\n\t\tthis.dispose();\n\t}\n}" } ]
import com.sun.management.OperatingSystemMXBean; import fr.glauncher.Controller; import fr.glauncher.game.Setup; import fr.glauncher.ui.frames.AdditionalModList; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.management.ManagementFactory; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException;
2,537
package fr.glauncher.ui.panels; public class Launch extends JPanel implements ActionListener, ChangeListener { private final Controller ctrl; private final JButton btnDisconnect; private final JButton btnPlay; private final JButton btnAdditional; private final JSpinner ramSelector; private final JProgressBar progressBar; private final JLabel lblRamInfo; private final JPanel panelBot; private final Image imgFond; private Image imgHead; public Launch( Controller ctrl ) { this.imgFond = getToolkit().getImage ( getClass().getResource("/background.png") ); this.ctrl = ctrl; this.setLayout( new BorderLayout() ); SpinnerModel ramModel = new SpinnerNumberModel(4096, 1024, 16384, 256); long memorySize = ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalMemorySize(); this.btnDisconnect = new JButton("Déconnexion"); this.btnPlay = new JButton("Jouer"); this.btnAdditional = new JButton("Mods supplémentaires"); this.ramSelector = new JSpinner(ramModel); this.progressBar = new JProgressBar(0, 10000); this.lblRamInfo = new JLabel(String.format(" Mémoire RAM disponible : %,d Mo ", memorySize / ( 1_024 * 1_024 ))); this.progressBar.setStringPainted(true); this.progressBar.setValue(0); this.btnPlay .addActionListener( this ); this.btnDisconnect.addActionListener( this ); this.btnAdditional.addActionListener( this ); this.ramSelector.setEditor(new JSpinner.NumberEditor(this.ramSelector, "# Mo")); this.ramSelector.addChangeListener(this); Border border = BorderFactory.createLineBorder(Color.darkGray, 2); this.lblRamInfo.setBorder(border); this.lblRamInfo.setBackground( Color.lightGray ); this.lblRamInfo.setOpaque(true); String ramValue = ctrl.getSaver().get("ram"); if (ramValue != null && ramValue.matches("\\d+")) this.ramSelector.setValue( Integer.parseInt(ramValue) ); JPanel panelTop = new JPanel(); this.panelBot = new JPanel(); panelTop.setOpaque( false ); this.panelBot.setOpaque( false ); panelTop.add( this.btnAdditional ); panelTop.add( this.btnDisconnect ); panelTop.add( this.btnPlay ); this.panelBot.add(this.ramSelector); this.panelBot.add(this.lblRamInfo); this.add(panelTop, BorderLayout.NORTH ); this.add( this.panelBot, BorderLayout.SOUTH ); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage ( this.imgFond, 0, 0, this ); if (this.imgHead != null) g.drawImage ( this.imgHead, 50, 200, this ); } @Override public void actionPerformed(ActionEvent e) { if ( e.getSource() == this.btnPlay ) { this.ctrl.getLogger().info("Preparing launch !");
package fr.glauncher.ui.panels; public class Launch extends JPanel implements ActionListener, ChangeListener { private final Controller ctrl; private final JButton btnDisconnect; private final JButton btnPlay; private final JButton btnAdditional; private final JSpinner ramSelector; private final JProgressBar progressBar; private final JLabel lblRamInfo; private final JPanel panelBot; private final Image imgFond; private Image imgHead; public Launch( Controller ctrl ) { this.imgFond = getToolkit().getImage ( getClass().getResource("/background.png") ); this.ctrl = ctrl; this.setLayout( new BorderLayout() ); SpinnerModel ramModel = new SpinnerNumberModel(4096, 1024, 16384, 256); long memorySize = ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalMemorySize(); this.btnDisconnect = new JButton("Déconnexion"); this.btnPlay = new JButton("Jouer"); this.btnAdditional = new JButton("Mods supplémentaires"); this.ramSelector = new JSpinner(ramModel); this.progressBar = new JProgressBar(0, 10000); this.lblRamInfo = new JLabel(String.format(" Mémoire RAM disponible : %,d Mo ", memorySize / ( 1_024 * 1_024 ))); this.progressBar.setStringPainted(true); this.progressBar.setValue(0); this.btnPlay .addActionListener( this ); this.btnDisconnect.addActionListener( this ); this.btnAdditional.addActionListener( this ); this.ramSelector.setEditor(new JSpinner.NumberEditor(this.ramSelector, "# Mo")); this.ramSelector.addChangeListener(this); Border border = BorderFactory.createLineBorder(Color.darkGray, 2); this.lblRamInfo.setBorder(border); this.lblRamInfo.setBackground( Color.lightGray ); this.lblRamInfo.setOpaque(true); String ramValue = ctrl.getSaver().get("ram"); if (ramValue != null && ramValue.matches("\\d+")) this.ramSelector.setValue( Integer.parseInt(ramValue) ); JPanel panelTop = new JPanel(); this.panelBot = new JPanel(); panelTop.setOpaque( false ); this.panelBot.setOpaque( false ); panelTop.add( this.btnAdditional ); panelTop.add( this.btnDisconnect ); panelTop.add( this.btnPlay ); this.panelBot.add(this.ramSelector); this.panelBot.add(this.lblRamInfo); this.add(panelTop, BorderLayout.NORTH ); this.add( this.panelBot, BorderLayout.SOUTH ); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage ( this.imgFond, 0, 0, this ); if (this.imgHead != null) g.drawImage ( this.imgHead, 50, 200, this ); } @Override public void actionPerformed(ActionEvent e) { if ( e.getSource() == this.btnPlay ) { this.ctrl.getLogger().info("Preparing launch !");
new Thread(() -> Setup.setup( this.ctrl, this ) ).start();
1
2023-10-28 15:35:30+00:00
4k
oehf/xds-registry-to-fhir
src/main/java/org/openehealth/app/xdstofhir/registry/common/mapper/XdsToFhirDocumentMapper.java
[ { "identifier": "MHD_COMPREHENSIVE_PROFILE", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java", "snippet": "public static final String MHD_COMPREHENSIVE_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.DocumentReference\";" }, { "identifier": "toUrnCoded", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java", "snippet": "public static String toUrnCoded(String value) {\n String adaptedValue = value;\n try {\n URN.create(adaptedValue);\n } catch (URISyntaxException invalidUrn) {\n try {\n new Oid(value);\n adaptedValue = OID_URN + value;\n } catch (GSSException invalidOid) {\n try {\n UUID.fromString(value);\n adaptedValue = OID_URN + value;\n } catch (IllegalArgumentException invalidUuid) {\n adaptedValue = XDS_URN + value;\n }\n }\n }\n return adaptedValue;\n}" }, { "identifier": "MappingSupport", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java", "snippet": "@UtilityClass\npublic class MappingSupport {\n public static final String OID_URN = \"urn:oid:\";\n public static final String UUID_URN = \"urn:uuid:\";\n public static final String XDS_URN = \"urn:ihe:xds:\";\n public static final String URI_URN = \"urn:ietf:rfc:3986\";\n public static final String MHD_COMPREHENSIVE_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.DocumentReference\";\n public static final String MHD_COMPREHENSIVE_SUBMISSIONSET_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.SubmissionSet\";\n public static final String MHD_COMPREHENSIVE_FOLDER_PROFILE = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/IHE.MHD.Comprehensive.Folder\";\n\n public static final Map<Precision, TemporalPrecisionEnum> PRECISION_MAP_FROM_XDS = new EnumMap<>(\n Map.of(Precision.DAY, TemporalPrecisionEnum.DAY,\n Precision.HOUR, TemporalPrecisionEnum.SECOND,\n Precision.MINUTE, TemporalPrecisionEnum.SECOND,\n Precision.MONTH, TemporalPrecisionEnum.MONTH,\n Precision.SECOND, TemporalPrecisionEnum.SECOND,\n Precision.YEAR, TemporalPrecisionEnum.YEAR));\n public static final Map<TemporalPrecisionEnum, Precision> PRECISION_MAP_FROM_FHIR = PRECISION_MAP_FROM_XDS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n public static final Map<AssociationType, DocumentRelationshipType> DOC_DOC_FHIR_ASSOCIATIONS = new EnumMap<>(\n Map.of(AssociationType.APPEND, DocumentRelationshipType.APPENDS,\n AssociationType.REPLACE, DocumentRelationshipType.REPLACES,\n AssociationType.SIGNS, DocumentRelationshipType.SIGNS,\n AssociationType.TRANSFORM, DocumentRelationshipType.TRANSFORMS));\n\n public static final Map<DocumentRelationshipType, AssociationType> DOC_DOC_XDS_ASSOCIATIONS = DOC_DOC_FHIR_ASSOCIATIONS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n\n public static final Map<AvailabilityStatus, DocumentReferenceStatus> STATUS_MAPPING_FROM_XDS = new EnumMap<>(\n Map.of(AvailabilityStatus.APPROVED, DocumentReferenceStatus.CURRENT,\n AvailabilityStatus.DEPRECATED, DocumentReferenceStatus.SUPERSEDED));\n public static final Map<DocumentReferenceStatus, AvailabilityStatus> STATUS_MAPPING_FROM_FHIR = STATUS_MAPPING_FROM_XDS\n .entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey, (x, y) -> y, LinkedHashMap::new));\n\n\n public static String toUrnCoded(String value) {\n String adaptedValue = value;\n try {\n URN.create(adaptedValue);\n } catch (URISyntaxException invalidUrn) {\n try {\n new Oid(value);\n adaptedValue = OID_URN + value;\n } catch (GSSException invalidOid) {\n try {\n UUID.fromString(value);\n adaptedValue = OID_URN + value;\n } catch (IllegalArgumentException invalidUuid) {\n adaptedValue = XDS_URN + value;\n }\n }\n }\n return adaptedValue;\n }\n\n public static String urnDecodedScheme(String urnCodedSystem) {\n return urnCodedSystem\n .replace(OID_URN, \"\")\n .replace(UUID_URN, \"\")\n .replace(XDS_URN, \"\");\n }\n\n}" }, { "identifier": "RegistryConfiguration", "path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/RegistryConfiguration.java", "snippet": "@ConfigurationProperties(prefix = \"xds\")\n@Component\n@Getter\n@Setter\npublic class RegistryConfiguration {\n\n private static final String DOCUMENT_UNIQUE_ID_PLACEHOLDER = \"$documentUniqueId\";\n private Map<String, String> repositoryEndpoint;\n private String unknownRepositoryId;\n private String defaultHash;\n\n /**\n * Take a repositoryUniqueId and document uniqueid to build download URL where a client\n * can retrieve the document from.\n *\n * @param repositoryUniqueId\n * @param uniqueId\n * @return String containing the http download endpoint for the given document.\n */\n public String urlFrom(String repositoryUniqueId, String uniqueId) {\n return repositoryEndpoint.get(repositoryUniqueId).replace(DOCUMENT_UNIQUE_ID_PLACEHOLDER, uniqueId);\n }\n\n /**\n * Take a Input from a attachment URL of a FHIR DocumentReference and lookup\n * the corresponding repositoryUniqueId.\n *\n * @param url - Attachment URL\n * @return The repositoryUniqueId\n */\n public String repositoryFromUrl(String url) {\n return repositoryEndpoint.entrySet().stream()\n .filter(configItem -> url.matches(configItem.getValue().replace(DOCUMENT_UNIQUE_ID_PLACEHOLDER, \".*\")))\n .map(Map.Entry::getKey).findFirst().orElse(unknownRepositoryId);\n }\n\n}" } ]
import static java.util.Collections.singletonList; import static org.openehealth.app.xdstofhir.registry.common.MappingSupport.MHD_COMPREHENSIVE_PROFILE; import static org.openehealth.app.xdstofhir.registry.common.MappingSupport.toUrnCoded; import static org.openehealth.ipf.commons.ihe.xds.core.metadata.AvailabilityStatus.APPROVED; import java.util.Date; import java.util.List; import java.util.function.BiFunction; import lombok.RequiredArgsConstructor; import org.hl7.fhir.r4.model.Address; import org.hl7.fhir.r4.model.Base64BinaryType; import org.hl7.fhir.r4.model.CanonicalType; import org.hl7.fhir.r4.model.DateTimeType; import org.hl7.fhir.r4.model.DateType; import org.hl7.fhir.r4.model.DocumentReference; import org.hl7.fhir.r4.model.DocumentReference.DocumentReferenceRelatesToComponent; import org.hl7.fhir.r4.model.Enumerations.AdministrativeGender; import org.hl7.fhir.r4.model.Enumerations.DocumentReferenceStatus; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Period; import org.hl7.fhir.r4.model.Practitioner; import org.hl7.fhir.r4.model.Reference; import org.openehealth.app.xdstofhir.registry.common.MappingSupport; import org.openehealth.app.xdstofhir.registry.common.RegistryConfiguration; import org.openehealth.ipf.commons.ihe.xds.core.metadata.DocumentEntry; import org.openehealth.ipf.commons.ihe.xds.core.metadata.PatientInfo; import org.openehealth.ipf.commons.ihe.xds.core.metadata.Person; import org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId; import org.openehealth.ipf.commons.map.BidiMappingService; import org.springframework.stereotype.Component;
2,098
package org.openehealth.app.xdstofhir.registry.common.mapper; @Component @RequiredArgsConstructor public class XdsToFhirDocumentMapper extends AbstractXdsToFhirMapper implements BiFunction<DocumentEntry, List<DocumentReferenceRelatesToComponent>, DocumentReference> { private static final String HL7V2FHIR_PATIENT_ADMINISTRATIVE_GENDER = "hl7v2fhir-patient-administrativeGender"; private final RegistryConfiguration registryConfig; private final BidiMappingService hl7v2FhirMapping; @Override public DocumentReference apply(final DocumentEntry xdsDoc, List<DocumentReferenceRelatesToComponent> documentReferences) { var fhirDoc = new DocumentReference(); fhirDoc.setId(xdsDoc.getEntryUuid()); fhirDoc.getMeta().setProfile(singletonList(new CanonicalType(MHD_COMPREHENSIVE_PROFILE))); fhirDoc.setStatus(xdsDoc.getAvailabilityStatus() == APPROVED ? DocumentReferenceStatus.CURRENT : DocumentReferenceStatus.SUPERSEDED); fhirDoc.addIdentifier(fromIdentifier(xdsDoc.getEntryUuid(), Identifier.IdentifierUse.OFFICIAL));
package org.openehealth.app.xdstofhir.registry.common.mapper; @Component @RequiredArgsConstructor public class XdsToFhirDocumentMapper extends AbstractXdsToFhirMapper implements BiFunction<DocumentEntry, List<DocumentReferenceRelatesToComponent>, DocumentReference> { private static final String HL7V2FHIR_PATIENT_ADMINISTRATIVE_GENDER = "hl7v2fhir-patient-administrativeGender"; private final RegistryConfiguration registryConfig; private final BidiMappingService hl7v2FhirMapping; @Override public DocumentReference apply(final DocumentEntry xdsDoc, List<DocumentReferenceRelatesToComponent> documentReferences) { var fhirDoc = new DocumentReference(); fhirDoc.setId(xdsDoc.getEntryUuid()); fhirDoc.getMeta().setProfile(singletonList(new CanonicalType(MHD_COMPREHENSIVE_PROFILE))); fhirDoc.setStatus(xdsDoc.getAvailabilityStatus() == APPROVED ? DocumentReferenceStatus.CURRENT : DocumentReferenceStatus.SUPERSEDED); fhirDoc.addIdentifier(fromIdentifier(xdsDoc.getEntryUuid(), Identifier.IdentifierUse.OFFICIAL));
fhirDoc.setMasterIdentifier(fromIdentifier(toUrnCoded(xdsDoc.getUniqueId()), Identifier.IdentifierUse.USUAL));
1
2023-10-30 18:58:31+00:00
4k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/MainSite.java
[ { "identifier": "ChoosedPalette", "path": "src/com/context/ChoosedPalette.java", "snippet": "public class ChoosedPalette {\r\n private static final Palette DARK_PALETTE = new Palette(Color.decode(\"#0B0D16\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#4562FF\"),\r\n Color.decode(\"#8F8F8F\"),\r\n Color.decode(\"#4562FF\"),\r\n Color.decode(\"#16D685\"),\r\n Color.decode(\"#9665FF\"),\r\n Color.decode(\"#505050\"),\r\n Color.decode(\"#272727\"),\r\n Color.decode(\"#1E1E1E\"),\r\n Color.decode(\"#272727\"),\r\n Color.decode(\"#191516\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#FFFFFF\"));\r\n private static final Palette WHITE_PALETTE = new Palette(Color.decode(\"#0B0D16\"),\r\n Color.decode(\"#2F4590\"),\r\n Color.decode(\"#4562FF\"),\r\n Color.decode(\"#8F8F8F\"),\r\n Color.decode(\"#E1ECFF\"),\r\n Color.decode(\"#CFFFEB\"),\r\n Color.decode(\"#E6DBFD\"),\r\n Color.decode(\"#E1ECFF\"),\r\n Color.decode(\"#F4F6FF\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#9665FF\"));\r\n private static Color lightHover = WHITE_PALETTE.getLightHover();\r\n private static Color darkestColor = WHITE_PALETTE.getDarkestColor();\r\n private static Color darkColor = WHITE_PALETTE.getDarkColor();\r\n private static Color midColor = WHITE_PALETTE.getMidColor();\r\n private static Color textColor = WHITE_PALETTE.getTextColor();\r\n private static Color primaryLightColor = WHITE_PALETTE.getPrimaryLightColor();\r\n private static Color secondaryLightColor = WHITE_PALETTE.getSecondaryLightColor();\r\n private static Color terciaryLightColor = WHITE_PALETTE.getTerciaryLightColor();\r\n private static Color gray = WHITE_PALETTE.getGray();\r\n private static Color primaryBackground = WHITE_PALETTE.getPrimaryBackground();\r\n private static Color secondaryBackground = WHITE_PALETTE.getSecondaryBackground();\r\n private static Color terciaryBackground = WHITE_PALETTE.getTerciaryBackground();\r\n private static Color white = WHITE_PALETTE.getWhite();\r\n private static Color terciaryTextColor = WHITE_PALETTE.getTerciaryTextColor();\r\n \r\n public static void changePalette(Palette palette) {\r\n darkestColor = palette.getDarkestColor();\r\n darkColor = palette.getDarkColor();\r\n midColor = palette.getMidColor();\r\n textColor = palette.getTextColor();\r\n primaryLightColor = palette.getPrimaryLightColor();\r\n secondaryLightColor = palette.getSecondaryLightColor();\r\n terciaryLightColor = palette.getTerciaryLightColor();\r\n gray = palette.getGray();\r\n lightHover = palette.getLightHover();\r\n primaryBackground = palette.getPrimaryBackground();\r\n secondaryBackground = palette.getSecondaryBackground();\r\n terciaryBackground = palette.getTerciaryBackground();\r\n white = palette.getWhite();\r\n terciaryTextColor = palette.getTerciaryTextColor();\r\n }\r\n\r\n public static Color getTerciaryBackground() {\r\n return terciaryBackground;\r\n }\r\n\r\n public static void setTerciaryBackground(Color terciaryBackground) {\r\n ChoosedPalette.terciaryBackground = terciaryBackground;\r\n }\r\n \r\n public static Color getLightHover() {\r\n return lightHover;\r\n }\r\n\r\n public static void setLightHover(Color lightHover) {\r\n ChoosedPalette.lightHover = lightHover;\r\n }\r\n\r\n public static Color getDarkestColor() {\r\n return darkestColor;\r\n }\r\n\r\n public static void setDarkestColor(Color darkestColor) {\r\n ChoosedPalette.darkestColor = darkestColor;\r\n }\r\n\r\n public static Color getDarkColor() {\r\n return darkColor;\r\n }\r\n\r\n public static void setDarkColor(Color darkColor) {\r\n ChoosedPalette.darkColor = darkColor;\r\n }\r\n\r\n public static Color getMidColor() {\r\n return midColor;\r\n }\r\n\r\n public static void setMidColor(Color midColor) {\r\n ChoosedPalette.midColor = midColor;\r\n }\r\n\r\n public static Color getTextColor() {\r\n return textColor;\r\n }\r\n\r\n public static void setTextColor(Color textColor) {\r\n ChoosedPalette.textColor = textColor;\r\n }\r\n\r\n public static Color getPrimaryLightColor() {\r\n return primaryLightColor;\r\n }\r\n\r\n public static void setPrimaryLightColor(Color primaryLightColor) {\r\n ChoosedPalette.primaryLightColor = primaryLightColor;\r\n }\r\n\r\n public static Color getSecondaryLightColor() {\r\n return secondaryLightColor;\r\n }\r\n\r\n public static void setSecondaryLightColor(Color secondaryLightColor) {\r\n ChoosedPalette.secondaryLightColor = secondaryLightColor;\r\n }\r\n\r\n public static Color getTerciaryLightColor() {\r\n return terciaryLightColor;\r\n }\r\n\r\n public static void setTerciaryLightColor(Color terciaryLightColor) {\r\n ChoosedPalette.terciaryLightColor = terciaryLightColor;\r\n }\r\n\r\n public static Color getGray() {\r\n return gray;\r\n }\r\n\r\n public static void setGray(Color gray) {\r\n ChoosedPalette.gray = gray;\r\n }\r\n\r\n public static Palette getDARK_PALETTE() {\r\n return DARK_PALETTE;\r\n }\r\n\r\n public static Palette getWHITE_PALETTE() {\r\n return WHITE_PALETTE;\r\n }\r\n\r\n public static Color getWhite() {\r\n return white;\r\n }\r\n\r\n public static void setWhite(Color white) {\r\n ChoosedPalette.white = white;\r\n }\r\n\r\n public static Color getPrimaryBackground() {\r\n return primaryBackground;\r\n }\r\n\r\n public static void setPrimaryBackground(Color primaryBackground) {\r\n ChoosedPalette.primaryBackground = primaryBackground;\r\n }\r\n\r\n public static Color getSecondaryBackground() {\r\n return secondaryBackground;\r\n }\r\n\r\n public static void setSecondaryBackground(Color secondaryBackground) {\r\n ChoosedPalette.secondaryBackground = secondaryBackground;\r\n }\r\n\r\n public static Color getTerciaryTextColor() {\r\n return terciaryTextColor;\r\n }\r\n\r\n public static void setTerciaryTextColor(Color terciaryTextColor) {\r\n ChoosedPalette.terciaryTextColor = terciaryTextColor;\r\n }\r\n}\r" }, { "identifier": "Tools", "path": "src/com/utils/Tools.java", "snippet": "public class Tools {\r\n \r\n /** \r\n * Este metodo se encargara de desplegar un panel donde sea indicado\r\n * \r\n * @param container el panel contenedor donde vamos a agregar nuestro nuevo panel\r\n * @param content el panel de contenido que vamos a agregar\r\n * @param width ancho para el panel de contenido\r\n * @param height alto para el panel de contenido\r\n */\r\n public static void showPanel(JPanel container,JPanel content, int width, int height) {\r\n content.setSize(width, height);\r\n content.setLocation(0, 0);\r\n container.removeAll();\r\n container.add(content, new org.netbeans.lib.awtextra.AbsoluteConstraints(0,0,-1,-1));\r\n container.revalidate();\r\n container.repaint();\r\n \r\n SwingUtilities.updateComponentTreeUI(container);\r\n }\r\n \r\n /** \r\n * Este metodo ajusta la barra de scroll y su movimiento\r\n * \r\n * @param scrollPanel el panel que se vera afectado\r\n */\r\n public static void setScroll(JScrollPane scrollPanel) {\r\n CustomScrollBar csb = new CustomScrollBar();\r\n csb.setOrientation(JScrollBar.VERTICAL);\r\n scrollPanel.setVerticalScrollBar(csb);\r\n scrollPanel.getVerticalScrollBar().setUnitIncrement(35);\r\n }\r\n \r\n /** \r\n * Este metodo coloca una imagen dentro de un label, se utiliza en su mayoria para los iconos de la interfaz\r\n * \r\n * @param label JLabel que se vera afectado\r\n * @param root ruta de la imagen que colocaremos\r\n * @param minWidth es para recortar el ancho de la imagen\r\n * @param minHeight\r\n * @param color\r\n */\r\n public static void setImageLabel(JLabel label, String root, int minWidth, int minHeight, Color color) {\r\n File img;\r\n BufferedImage bufferedImage;\r\n ImageIcon imageIcon;\r\n Icon icon;\r\n \r\n try {\r\n img = new File(root);\r\n bufferedImage = colorImage(ImageIO.read(img), color.getRed(), color.getGreen(), color.getBlue());\r\n imageIcon = new ImageIcon(bufferedImage);\r\n icon = new ImageIcon(\r\n imageIcon.getImage().getScaledInstance(label.getWidth() - minWidth, label.getHeight() - minHeight, Image.SCALE_DEFAULT)\r\n );\r\n \r\n label.setIcon(icon);\r\n label.removeAll();\r\n label.repaint();\r\n } catch (IOException e) {\r\n System.out.println(e);\r\n }\r\n }\r\n \r\n public static void setImage(JLabel label, String root, int minWidth, int minHeight) {\r\n ImageIcon imageIcon;\r\n Icon icon;\r\n \r\n// try {\r\n imageIcon = new ImageIcon(root);\r\n icon = new ImageIcon(\r\n imageIcon.getImage().getScaledInstance(label.getWidth() - minWidth, label.getHeight() - minHeight, Image.SCALE_SMOOTH)\r\n );\r\n \r\n label.setIcon(icon);\r\n label.removeAll();\r\n label.repaint();\r\n// } catch (Exception e) {\r\n// System.out.println(e + \"aca\");\r\n// }\r\n }\r\n \r\n public static void deleteText(JTextField JTextField) {\r\n String text = JTextField.getText();\r\n \r\n if (text.contains(\"Ingresa\") || text.contains(\"$\") || text.contains(\"dd\") || text.contains(\"mm\") || text.contains(\"aaaa\") || text.contains(\"[email protected]\") || text.contains(\"password\")) {\r\n JTextField.setText(\"\");\r\n }\r\n }\r\n \r\n public static void deleteIngresaText(JTextField jTextField) {\r\n String text = jTextField.getText();\r\n \r\n if (text.contains(\"Ingresa\")) {\r\n jTextField.setText(\"\");\r\n }\r\n }\r\n \r\n public static void deleteDateType(JTextField jTextField) {\r\n String text = jTextField.getText();\r\n \r\n if (text.contains(\"dd\") || text.contains(\"mm\") || text.contains(\"aaaa\")) {\r\n jTextField.setText(\"\");\r\n }\r\n }\r\n \r\n public static void addMouseListenerIngresa(ArrayList<JTextField> deleteIngresa) {\r\n deleteIngresa.forEach(item -> {\r\n item.addMouseListener(new MouseAdapter() {\r\n public void mouseClicked(MouseEvent evt) {\r\n deleteIngresaText(item);\r\n }\r\n });\r\n });\r\n }\r\n \r\n public static void addMouseListenerDate(ArrayList<JTextField> deleteDate) {\r\n deleteDate.forEach(item -> {\r\n item.addMouseListener(new MouseAdapter() {\r\n public void mouseClicked(MouseEvent evt) {\r\n deleteDateType(item);\r\n }\r\n });\r\n });\r\n }\r\n \r\n public static void addKeyTypedListener(ArrayList<JTextField> dateArray, int length) {\r\n dateArray.forEach(item -> {\r\n item.addKeyListener(new KeyAdapter() {\r\n public void keyTyped(KeyEvent evt) {\r\n numbersForDate(item, evt, length);\r\n }\r\n });\r\n });\r\n }\r\n \r\n public static boolean esAnnioBisiesto(int annio) {\r\n GregorianCalendar calendar = new GregorianCalendar();\r\n \r\n boolean esBisiesto = false;\r\n \r\n if (calendar.isLeapYear(annio)) {\r\n esBisiesto = true;\r\n }\r\n \r\n return esBisiesto;\r\n }\r\n \r\n public static void numbersForDate(JTextField jTextField, KeyEvent evt, int length) {\r\n if (!Character.isDigit(evt.getKeyChar()) || jTextField.getText().length() == length) {\r\n evt.consume();\r\n }\r\n }\r\n \r\n public static void onlyNumbers(JTextField JTextField,KeyEvent evt, int length) {\r\n if (!Character.isDigit(evt.getKeyChar()) && evt.getKeyChar() != '.') {\r\n evt.consume();\r\n } else if (evt.getKeyChar() == '.' && JTextField.getText().contains(\".\") || JTextField.getText().length() == length) {\r\n evt.consume();\r\n }\r\n }\r\n \r\n /** \r\n * Este metodo se encargara de colorear la imagen segun los argumentos indicados\r\n * \r\n * @param image imagen buffer a la que cambiaremos el color\r\n * @param red numero del 0 a 255 para el rojo en el sistema rbg\r\n * @param green numero del 0 a 255 para el verde en el sistema rgb\r\n * @param blue numero del 0 a 255 para el azul en el sistema rgb\r\n * \r\n * @return image se retorna la imagen con el color modificado\r\n */\r\n private static BufferedImage colorImage(BufferedImage image, int red, int green, int blue) {\r\n int width = image.getWidth();\r\n int height = image.getHeight();\r\n WritableRaster raster = image.getRaster();\r\n\r\n for (int i = 0; i < width; i++) {\r\n for (int j = 0; j < height; j++) {\r\n int[] pixels = raster.getPixel(i, j, (int[]) null);\r\n pixels[0] = red;\r\n pixels[1] = green;\r\n pixels[2] = blue;\r\n raster.setPixel(i, j, pixels);\r\n }\r\n }\r\n \r\n return image;\r\n }\r\n \r\n public static void setTimeout(Runnable runnable, int delay) {\r\n new Thread(() -> {\r\n try {\r\n Thread.sleep(delay);\r\n runnable.run();\r\n }\r\n catch (InterruptedException e){\r\n System.err.println(e);\r\n }\r\n }).start();\r\n }\r\n}\r" } ]
import com.context.ChoosedPalette; import com.utils.Tools; import java.awt.Color; import java.awt.Dimension; import java.awt.Insets; import java.awt.Toolkit; import javax.swing.JPanel; import javax.swing.SwingUtilities;
3,454
package com.view; /** * <h1>Application</h1> * * @author Daniel Batres * @version 1.0.0 * @since 11/09/22 */ public class MainSite extends javax.swing.JFrame { private int y; private int x; private Toolkit toolkit = Toolkit.getDefaultToolkit(); private Dimension dimension = toolkit.getScreenSize(); private Insets taskBar = toolkit.getScreenInsets(getGraphicsConfiguration()); private int userScreenWidth = (int) dimension.getWidth(); private int userScreenHeight = (int) dimension.getHeight() - taskBar.bottom; /** * Creacion de nueva aplicacion */ public MainSite() { initComponents(); setSize(userScreenWidth, userScreenHeight); setLocationRelativeTo(null); windowControls.setBackground(ChoosedPalette.getDarkestColor()); controllers.setBackground(ChoosedPalette.getDarkestColor()); minButton.setBackground(ChoosedPalette.getDarkestColor()); maxButton.setBackground(ChoosedPalette.getDarkestColor()); cross.setBackground(ChoosedPalette.getDarkestColor()); try {
package com.view; /** * <h1>Application</h1> * * @author Daniel Batres * @version 1.0.0 * @since 11/09/22 */ public class MainSite extends javax.swing.JFrame { private int y; private int x; private Toolkit toolkit = Toolkit.getDefaultToolkit(); private Dimension dimension = toolkit.getScreenSize(); private Insets taskBar = toolkit.getScreenInsets(getGraphicsConfiguration()); private int userScreenWidth = (int) dimension.getWidth(); private int userScreenHeight = (int) dimension.getHeight() - taskBar.bottom; /** * Creacion de nueva aplicacion */ public MainSite() { initComponents(); setSize(userScreenWidth, userScreenHeight); setLocationRelativeTo(null); windowControls.setBackground(ChoosedPalette.getDarkestColor()); controllers.setBackground(ChoosedPalette.getDarkestColor()); minButton.setBackground(ChoosedPalette.getDarkestColor()); maxButton.setBackground(ChoosedPalette.getDarkestColor()); cross.setBackground(ChoosedPalette.getDarkestColor()); try {
Tools.setImageLabel(cross, "src/com/assets/cruz.png", 15, 10, ChoosedPalette.getWhite());
1
2023-10-26 19:35:40+00:00
4k
SUFIAG/Issue-Tracking-Application-Java
source-code/src/main/java/presentationLayer/DeleteIssue.java
[ { "identifier": "ITS", "path": "source-code/src/main/java/logicLayer/ITS.java", "snippet": "public class ITS {\n private writerAndReader readAndWrite;\n private Vector<Issue> issues;\n private static ITS instance;\n\n //constructor\n private ITS() {\n //initializing data members\n readAndWrite = new writerAndReader();\n issues = new Vector<>();\n\n //initializing issues from file\n try {\n File myObj = new File(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n if (!myObj.createNewFile()) { //if file has already created\n readAndWrite.readIssuesFromFile(issues);\n } else {\n readAndWrite.writeHeadersInFile();\n }\n } catch (Exception e) {\n System.err.println(\"Error: \" + e.getMessage());\n }\n }\n\n //getters\n public writerAndReader getReadAndWrite() {\n return readAndWrite;\n }\n public Vector<Issue> getIssues() {return issues;}\n\n //setters\n public void setReadAndWrite(writerAndReader readAndWrite) {\n this.readAndWrite = readAndWrite;\n }\n public void setIssues(Vector<Issue> issues) {this.issues = issues;}\n\n //function to get instance of this class\n public static ITS getInstance(){\n if (instance == null) {\n instance = new ITS();\n }\n return instance;\n }\n\n //function to check if the issue exists or not\n public boolean validateIssueID(String ID) {\n for (Issue issue : issues) {\n if (Integer.parseInt(ID) == issue.getID()) {\n return true;\n }\n }\n return false;\n }\n\n //function for adding issue\n public void addIssue(String desc, String assignee, String status, String creationDate) {\n int ID = 0;\n\n //getting maximum ID\n for (Issue issue : issues) {\n if (issue.getID() > ID) {\n ID = issue.getID();\n }\n }\n ID++;\n\n //adding issue\n Issue i = new Issue(ID, desc, assignee, status, creationDate);\n issues.add(i);\n readAndWrite.writeIssueIntoFile(i);\n }\n\n //function for editing Issue\n public void editIssue(String ID, String desc, String assignee, String status, String creationDate){\n for (int i = 0; i < issues.size(); ++i) {\n if (Integer.parseInt(ID) == issues.get(i).getID()) {\n issues.set(i, new Issue(issues.get(i).getID(), desc, assignee, status, creationDate));\n }\n }\n readAndWrite.truncateAFile(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n readAndWrite.writeHeadersInFile();\n for (Issue issue : issues) {\n readAndWrite.writeIssueIntoFile(issue);\n }\n }\n\n //function for deleting issue\n public void deleteIssue(String ID) {\n int index = -1;\n for(int i = 0; i < issues.size(); ++i){\n //Replacing IDs and Also Finding Index to Delete\n if (Integer.parseInt(ID) == issues.get(i).getID()){\n index = i;\n if (i == 0) {\n issues.get(i).setID(0);\n } else if (i == issues.size() - 1) {\n break;\n } else {\n issues.get(i).setID(issues.get(i).getID() - 1);\n }\n } else if(index != -1){\n issues.get(i).setID(issues.get(i - 1).getID() + 1);\n }\n }\n issues.remove(index); //Removing issue From Vector\n readAndWrite.truncateAFile(\"./IssuesTrackingSystem/src/main/java/dataLayer/issues.csv\");\n readAndWrite.writeHeadersInFile();\n for (Issue issue : issues) {\n readAndWrite.writeIssueIntoFile(issue);\n }\n }\n\n // function for searching issue\n public Issue searchIssue(String ID){\n for (Issue issue : issues) {\n if (Integer.parseInt(ID) == issue.getID()) {\n return issue;\n }\n }\n return null;\n }\n}" }, { "identifier": "Issue", "path": "source-code/src/main/java/logicLayer/Issue.java", "snippet": "public class Issue {\n private String desc, assignee, status, creationDate;\n private int ID;\n\n //constructors\n public Issue(){}\n public Issue(int ID, String desc, String assignee, String status, String creationDate) {\n this.ID = ID;\n this.desc = desc;\n this.assignee = assignee;\n this.status = status;\n this.creationDate = creationDate;\n }\n\n //getters\n public int getID() {return ID;}\n public String getAssignee() {return assignee;}\n public String getCreationDate() {return creationDate;}\n public String getDesc() {return desc;}\n public String getStatus() {return status;}\n\n //setters\n public void setAssignee(String assignee) {this.assignee = assignee;}\n public void setCreationDate(String creationDate) {this.creationDate = creationDate;}\n public void setDesc(String desc) {this.desc = desc;}\n public void setID(int ID) {this.ID = ID;}\n public void setStatus(String status) {this.status = status;}\n}" } ]
import logicLayer.Issue; import javax.swing.table.DefaultTableModel; import java.util.Vector; import logicLayer.ITS;
2,819
boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(jTable1); if (jTable1.getColumnModel().getColumnCount() > 0) { jTable1.getColumnModel().getColumn(0).setResizable(false); jTable1.getColumnModel().getColumn(1).setResizable(false); jTable1.getColumnModel().getColumn(2).setResizable(false); jTable1.getColumnModel().getColumn(3).setResizable(false); jTable1.getColumnModel().getColumn(4).setResizable(false); } jLabel2.setText("Issue No"); jTextField1.setForeground(new java.awt.Color(204, 204, 204)); jTextField1.setText("Enter Issue No Here"); jTextField1.setToolTipText(""); jTextField1.setMaximumSize(new java.awt.Dimension(129, 25)); jTextField1.setMinimumSize(new java.awt.Dimension(129, 25)); jTextField1.setPreferredSize(new java.awt.Dimension(129, 25)); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField1FocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextField1FocusLost(evt); } }); jButton2.setText("Submit"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 204, 51)); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1) .addGroup(layout.createSequentialGroup() .addGap(113, 113, 113) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addGap(36, 36, 36) .addComponent(jLabel6)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(41, 41, 41) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(169, 169, 169) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(91, 175, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2))) .addComponent(jButton2) .addGap(1, 1, 1) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addContainerGap(40, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents // function to clear all the issues displayed in the table private void clearIssues() { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); int rowCount = model.getRowCount(); for (int i = rowCount - 1; i >= 0; i--) { model.removeRow(i); } } // function to display all the issues in the table private void displayIssues() { DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package presentationLayer; /** * * @author SA */ public class DeleteIssue extends javax.swing.JFrame { /** * Creates new form DeleteIssue */ public DeleteIssue() { initComponents(); displayIssues(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMinimumSize(new java.awt.Dimension(434, 343)); setSize(new java.awt.Dimension(0, 0)); jButton1.setText("Back"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Leelawadee", 1, 18)); // NOI18N jLabel1.setText("DELETE ISSUE"); jLabel1.setToolTipText(""); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Issue No", "Description", "Assignee", "Status", "Creation Date" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(jTable1); if (jTable1.getColumnModel().getColumnCount() > 0) { jTable1.getColumnModel().getColumn(0).setResizable(false); jTable1.getColumnModel().getColumn(1).setResizable(false); jTable1.getColumnModel().getColumn(2).setResizable(false); jTable1.getColumnModel().getColumn(3).setResizable(false); jTable1.getColumnModel().getColumn(4).setResizable(false); } jLabel2.setText("Issue No"); jTextField1.setForeground(new java.awt.Color(204, 204, 204)); jTextField1.setText("Enter Issue No Here"); jTextField1.setToolTipText(""); jTextField1.setMaximumSize(new java.awt.Dimension(129, 25)); jTextField1.setMinimumSize(new java.awt.Dimension(129, 25)); jTextField1.setPreferredSize(new java.awt.Dimension(129, 25)); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField1FocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextField1FocusLost(evt); } }); jButton2.setText("Submit"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 204, 51)); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1) .addGroup(layout.createSequentialGroup() .addGap(113, 113, 113) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addGap(36, 36, 36) .addComponent(jLabel6)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(41, 41, 41) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(169, 169, 169) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(91, 175, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2))) .addComponent(jButton2) .addGap(1, 1, 1) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addContainerGap(40, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents // function to clear all the issues displayed in the table private void clearIssues() { DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); int rowCount = model.getRowCount(); for (int i = rowCount - 1; i >= 0; i--) { model.removeRow(i); } } // function to display all the issues in the table private void displayIssues() { DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
ITS its = ITS.getInstance();
0
2023-10-25 19:14:47+00:00
4k
ddoubest/mini-spring
src/com/minis/context/AnnotationClassPathXmlApplicationContext.java
[ { "identifier": "ConfigurableListableBeanFactory", "path": "src/com/minis/beans/factory/ConfigurableListableBeanFactory.java", "snippet": "public interface ConfigurableListableBeanFactory extends ConfigurableBeanFactory, ListableBeanFactory, AutowireCapableBeanFactory {\n}" }, { "identifier": "FactoryAwareBeanPostProcessor", "path": "src/com/minis/beans/factory/FactoryAwareBeanPostProcessor.java", "snippet": "public class FactoryAwareBeanPostProcessor implements BeanPostProcessor {\n private BeanFactory beanFactory;\n\n public FactoryAwareBeanPostProcessor(BeanFactory beanFactory) {\n this.beanFactory = beanFactory;\n }\n\n @Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {\n if (bean instanceof BeanFactoryAware) {\n BeanFactoryAware beanFactoryAware = (BeanFactoryAware) bean;\n beanFactoryAware.setBeanFactory(beanFactory);\n }\n return bean;\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n this.beanFactory = beanFactory;\n }\n\n @Override\n public BeanFactory getBeanFactory() {\n return beanFactory;\n }\n}" }, { "identifier": "AutowiredAnnotationBeanPostProcessor", "path": "src/com/minis/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java", "snippet": "public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor {\n private BeanFactory beanFactory;\n\n public AutowiredAnnotationBeanPostProcessor(BeanFactory beanFactory) {\n this.beanFactory = beanFactory;\n }\n\n @Override\n public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {\n Class<?> clazz = bean.getClass();\n for (Field field : clazz.getDeclaredFields()) {\n if (field.isAnnotationPresent(Autowired.class)) {\n String fieldName = field.getName();\n Object autowiredBean = beanFactory.getBean(fieldName);\n try {\n field.setAccessible(true);\n field.set(bean, autowiredBean);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return bean;\n }\n\n @Override\n public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {\n return bean;\n }\n\n @Override\n public void setBeanFactory(BeanFactory beanFactory) {\n this.beanFactory = beanFactory;\n }\n\n @Override\n public BeanFactory getBeanFactory() {\n return beanFactory;\n }\n}" }, { "identifier": "DefaultListableBeanFactory", "path": "src/com/minis/beans/factory/support/DefaultListableBeanFactory.java", "snippet": "public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory {\n private ConfigurableListableBeanFactory parentBeanFactory;\n\n @Override\n public void registerDependentBean(String beanName, String dependentBeanName) {\n BeanDefinition beanDefinition = getBeanDefinition(beanName);\n List<String> currentDependentBeans = Arrays.stream(beanDefinition.getDependsOn()).collect(Collectors.toList());\n currentDependentBeans.add(dependentBeanName);\n beanDefinition.setDependsOn(currentDependentBeans.toArray(new String[0]));\n }\n\n @Override\n public String[] getDependentBeans(String beanName) {\n return getBeanDefinition(beanName).getDependsOn();\n }\n\n @Override\n public int getBeanDefinitionCount() {\n return beanDefinitions.size();\n }\n\n @Override\n public String[] getBeanDefinitionNames() {\n return beanDefinitions.keySet().toArray(new String[0]);\n }\n\n @Override\n public String[] getBeanNamesForType(Class<?> clazz) {\n List<String> beanNames = new ArrayList<>();\n beanDefinitions.forEach((name, beanDefinition) -> {\n if (clazz.isAssignableFrom(beanDefinition.getBeanClass())) {\n beanNames.add(name);\n }\n });\n return beanNames.toArray(new String[0]);\n }\n\n @Override\n public <T> Map<String, T> getBeansOfTypes(Class<T> clazz) {\n Map<String, T> beans = new HashMap<>();\n beanDefinitions.forEach((name, beanDefinition) -> {\n if (clazz.isAssignableFrom(beanDefinition.getBeanClass())) {\n try {\n Object bean = getBean(name);\n beans.put(name, clazz.cast(bean));\n } catch (BeansException e) {\n throw new RuntimeException(e);\n }\n }\n });\n return beans;\n }\n\n public void setParentBeanFactory(ConfigurableListableBeanFactory parentBeanFactory) {\n this.parentBeanFactory = parentBeanFactory;\n }\n\n public ConfigurableListableBeanFactory getParentBeanFactory() {\n return parentBeanFactory;\n }\n\n @Override\n protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {\n return object;\n }\n}" }, { "identifier": "XmlBeanDefinitionReader", "path": "src/com/minis/beans/factory/xml/XmlBeanDefinitionReader.java", "snippet": "public class XmlBeanDefinitionReader {\n private final AbstractBeanFactory beanFactory;\n\n public XmlBeanDefinitionReader(AbstractBeanFactory beanFactory) {\n this.beanFactory = beanFactory;\n }\n\n public void loadBeanDefinitions(Resource resource) {\n while (resource.hasNext()) {\n Element element = (Element) resource.next();\n String beanName = element.attributeValue(\"id\");\n String beanClass = element.attributeValue(\"class\");\n BeanDefinition beanDefinition = new BeanDefinition(beanName, beanClass);\n\n // setBeanClass\n try {\n beanDefinition.setBeanClass(Class.forName(beanClass));\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n\n // 构造器\n List<Element> argumentElements = element.elements(\"constructor-arg\");\n ConstructorArgumentValues AVS = new ConstructorArgumentValues();\n for (Element argumentElement : argumentElements) {\n String type = argumentElement.attributeValue(\"type\");\n String name = argumentElement.attributeValue(\"name\");\n String value = argumentElement.attributeValue(\"value\");\n AVS.addArgumentValue(new ConstructorArgumentValue(type, name, value));\n }\n beanDefinition.setConstructorArgumentValues(AVS);\n\n // 属性\n List<Element> propertyElements = element.elements(\"property\");\n PropertyValues PVS = new PropertyValues();\n List<String> refs = new ArrayList<>();\n for (Element propertyElement : propertyElements) {\n String type = propertyElement.attributeValue(\"type\");\n String name = propertyElement.attributeValue(\"name\");\n String value = propertyElement.attributeValue(\"value\");\n String ref = propertyElement.attributeValue(\"ref\");\n boolean isRef = false;\n if (ref != null && !ref.equals(\"\")) {\n value = ref;\n isRef = true;\n refs.add(ref);\n }\n PVS.addPropertyValue(new PropertyValue(type, name, value, isRef));\n }\n beanDefinition.setPropertyValues(PVS);\n\n // 依赖引用\n beanDefinition.setDependsOn(refs.toArray(new String[0]));\n\n beanFactory.registerBeanDefinition(beanName, beanDefinition);\n }\n }\n}" }, { "identifier": "ApplicationListener", "path": "src/com/minis/event/ApplicationListener.java", "snippet": "public class ApplicationListener implements EventListener {\n void onApplicationEvent(ApplicationEvent event) {\n System.out.println(event.toString());\n }\n}" }, { "identifier": "ContextRefreshEvent", "path": "src/com/minis/event/ContextRefreshEvent.java", "snippet": "public class ContextRefreshEvent extends ApplicationEvent {\n /**\n * Constructs a prototypical Event.\n *\n * @param source The object on which the Event initially occurred.\n * @throws IllegalArgumentException if source is null.\n */\n public ContextRefreshEvent(Object source) {\n super(source);\n }\n}" }, { "identifier": "SimpleApplicationEventPublisher", "path": "src/com/minis/event/SimpleApplicationEventPublisher.java", "snippet": "public class SimpleApplicationEventPublisher implements ApplicationEventPublisher {\n private final List<ApplicationListener> listeners = new ArrayList<>();\n\n @Override\n public void publishEvent(ApplicationEvent event) {\n for (ApplicationListener listener : listeners) {\n listener.onApplicationEvent(event);\n }\n }\n\n @Override\n public void addApplicationListener(ApplicationListener listener) {\n listeners.add(listener);\n }\n}" }, { "identifier": "ClassPathXmlResource", "path": "src/com/minis/resources/ClassPathXmlResource.java", "snippet": "public class ClassPathXmlResource implements Resource {\n private final Document document;\n private final Element rootElement;\n private final Iterator<Element> elementIterator;\n\n public Document getDocument() {\n return document;\n }\n\n public Element getRootElement() {\n return rootElement;\n }\n\n @SuppressWarnings(\"unchecked\")\n public ClassPathXmlResource(String fileName) {\n SAXReader reader = new SAXReader();\n try {\n URL xmlPath = ClassPathXmlResource.class.getClassLoader().getResource(fileName);\n this.document = reader.read(xmlPath);\n this.rootElement = document.getRootElement();\n this.elementIterator = rootElement.elementIterator();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public boolean hasNext() {\n return elementIterator.hasNext();\n }\n\n @Override\n public Object next() {\n return elementIterator.next();\n }\n}" }, { "identifier": "Resource", "path": "src/com/minis/resources/Resource.java", "snippet": "public interface Resource extends Iterator<Object> {\n\n}" }, { "identifier": "ScanComponentHelper", "path": "src/com/minis/utils/ScanComponentHelper.java", "snippet": "public class ScanComponentHelper {\n public static List<String> scanPackages(List<String> packageNames) {\n List<String> result = new ArrayList<>();\n for (String packageName : packageNames) {\n result.addAll(Objects.requireNonNull(scanPackage(packageName)));\n }\n return result;\n }\n\n public static void loadBeanDefinitions(AbstractBeanFactory beanFactory, List<String> names) {\n for (String name : names) {\n String[] decomposedNames = name.split(\"\\\\.\");\n String id = StringUtils.lowerFirstCase(decomposedNames[decomposedNames.length - 1]);\n BeanDefinition beanDefinition = new BeanDefinition(id, name);\n beanFactory.registerBeanDefinition(id, beanDefinition);\n }\n }\n\n private static List<String> scanPackage(String packageName) {\n List<String> result = new ArrayList<>();\n\n String relativePath = packageName.replace(\".\", \"/\");\n URI packagePath;\n try {\n packagePath = ScanComponentHelper.class.getResource(\"/\" + relativePath).toURI();\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n File dir = new File(packagePath);\n for (File file : Objects.requireNonNull(dir.listFiles())) {\n if (file.isDirectory()) {\n result.addAll(scanPackage(packageName + \".\" + file.getName()));\n } else {\n String controllerName = packageName + \".\" + file.getName().replace(\".class\", \"\");\n Class<?> clazz = null;\n try {\n clazz = Class.forName(controllerName);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n // 只要Component注解的类\n if (!clazz.isAnnotationPresent(Component.class) && !clazz.isAnnotationPresent(Controller.class)) {\n continue;\n }\n result.add(controllerName);\n }\n }\n\n return result;\n }\n}" } ]
import com.minis.beans.factory.ConfigurableListableBeanFactory; import com.minis.beans.factory.FactoryAwareBeanPostProcessor; import com.minis.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import com.minis.beans.factory.support.DefaultListableBeanFactory; import com.minis.beans.factory.xml.XmlBeanDefinitionReader; import com.minis.event.ApplicationListener; import com.minis.event.ContextRefreshEvent; import com.minis.event.SimpleApplicationEventPublisher; import com.minis.resources.ClassPathXmlResource; import com.minis.resources.Resource; import com.minis.utils.ScanComponentHelper; import java.util.List;
2,966
package com.minis.context; public class AnnotationClassPathXmlApplicationContext extends AbstractApplicationContext { private final DefaultListableBeanFactory beanFactory; public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames) { this(fileName, packageNames, true); } public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames, boolean isRefresh) { Resource resource = new ClassPathXmlResource(fileName); beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); reader.loadBeanDefinitions(resource); List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames); ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames); if (isRefresh) { refresh(); } } @Override protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(this));
package com.minis.context; public class AnnotationClassPathXmlApplicationContext extends AbstractApplicationContext { private final DefaultListableBeanFactory beanFactory; public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames) { this(fileName, packageNames, true); } public AnnotationClassPathXmlApplicationContext(String fileName, List<String> packageNames, boolean isRefresh) { Resource resource = new ClassPathXmlResource(fileName); beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); reader.loadBeanDefinitions(resource); List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames); ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames); if (isRefresh) { refresh(); } } @Override protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(this));
beanFactory.addBeanPostProcessor(new FactoryAwareBeanPostProcessor(this));
1
2023-10-30 12:36:32+00:00
4k
xingduansuzhao-MC/ModTest
src/main/java/com/xdsz/test/fluids/TestFluids.java
[ { "identifier": "RegistryHandler", "path": "src/main/java/com/xdsz/test/util/RegistryHandler.java", "snippet": "public class RegistryHandler {\n\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Test.MOD_ID);\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Test.MOD_ID);\n public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);\n public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Test.MOD_ID);\n public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, Test.MOD_ID);\n\n public static void init(){\n ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());\n TestFluids.register(FMLJavaModLoadingContext.get().getModEventBus());\n SOUND_EVENTS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ENTITY_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n\n //物品\n public static final RegistryObject<Item> SAPPHIRE = ITEMS.register(\"sapphire\",ItemBase::new);\n\n\n\n //方块(手持)\n public static final RegistryObject<Block> SAPPHIRE_BLOCK = BLOCKS.register(\"sapphire_block\",SapphireBlock::new);\n public static final RegistryObject<Block> SAPPHIRE_ORE = BLOCKS.register(\"sapphire_ore\", SapphireOre::new);\n\n\n\n //方块(着地)\n public static final RegistryObject<Item> SAPPHIRE_BLOCK_ITEM = ITEMS.register(\"sapphire_block\",\n () -> new BlockItemBase(SAPPHIRE_BLOCK.get()));\n\n public static final RegistryObject<Item> SAPPHIRE_ORE_ITEM = ITEMS.register(\"sapphire_ore\",\n () -> new BlockItemBase(SAPPHIRE_ORE.get()));\n\n\n\n\n //工具\n public static final RegistryObject<SwordItem> SAPPHIRE_SWORD = ITEMS.register(\"sapphire_sword\",\n () -> new SwordItem(ModItemTier.SAPPHIRE, 50, 20.0F, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<AxeItem> SAPPHIRE_AXE = ITEMS.register(\"sapphire_axe\",\n () -> new AxeItem(ModItemTier.SAPPHIRE, 100,20.0F, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<ShovelItem> SAPPHIRE_SHOVEL = ITEMS.register(\"sapphire_shovel\",\n () -> new ShovelItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<HoeItem> SAPPHIRE_HOE = ITEMS.register(\"sapphire_hoe\",\n () -> new HoeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<PickaxeItem> SAPPHIRE_PICKAXE = ITEMS.register(\"sapphire_pickaxe\",\n () -> new PickaxeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));\n\n\n\n //盔甲\n public static final RegistryObject<ArmorItem> SAPPHIRE_HELMET = ITEMS.register(\"sapphire_helmet\",\n () -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.HEAD, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<ArmorItem> SAPPHIRE_CHESTPLATE = ITEMS.register(\"sapphire_chestplate\",\n () -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.CHEST, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<ArmorItem> SAPPHIRE_LEGS = ITEMS.register(\"sapphire_leggings\",\n () -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.LEGS, new Item.Properties().group(Test.TAB)));\n\n public static final RegistryObject<ArmorItem> SAPPHIRE_BOOTS = ITEMS.register(\"sapphire_boots\",\n () -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.FEET, new Item.Properties().group(Test.TAB)));\n\n\n //毒苹果\n public static final RegistryObject<PoisonApple> POISON_APPLE = ITEMS.register(\"poison_apple\", PoisonApple::new);\n\n //流体(桶)\n public static final RegistryObject<Item> HONEYTEST_BUCKET = ITEMS.register(\"honeytest_bucket\",\n ()->new BucketItem(()->TestFluids.HONEYTEST_FLUID.get(), new Item.Properties().maxStackSize(1).group(Test.TAB)));\n\n //音乐\n public static final RegistryObject<SoundEvent> CAI_XUKUN = SOUND_EVENTS.register(\"cai_xukun\",\n ()->new SoundEvent(new ResourceLocation(Test.MOD_ID, \"cai_xukun\")));\n\n public static final RegistryObject<Item> KUN_DISC = ITEMS.register(\"kun_disc\",\n ()->new MusicDiscItem(1, () -> CAI_XUKUN.get(), new Item.Properties().maxStackSize(16).group(Test.TAB)));\n\n //实体\n public static final RegistryObject<EntityType<TestBearEntity>> TEST_BEAR = ENTITY_TYPES.register(\"test_bear\",\n () -> EntityType.Builder.create(TestBearEntity::new, EntityClassification.CREATURE)\n .build(new ResourceLocation(Test.MOD_ID, \"test_bear\").toString()));\n\n //刷怪蛋\n public static final RegistryObject<TestSpawnEgg> TEST_SPAWN_EGG = ITEMS.register(\"test_spawn_egg\",\n () -> new TestSpawnEgg(RegistryHandler.TEST_BEAR, 0x2a2a2a, 0xa299e7, new Item.Properties().group(Test.TAB)));\n}" }, { "identifier": "FLUIDS", "path": "src/main/java/com/xdsz/test/util/RegistryHandler.java", "snippet": "public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);" } ]
import com.xdsz.test.util.RegistryHandler; import net.minecraft.block.AbstractBlock; import net.minecraft.block.FlowingFluidBlock; import net.minecraft.block.material.Material; import net.minecraft.fluid.FlowingFluid; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvents; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fluids.FluidAttributes; import net.minecraftforge.fluids.ForgeFlowingFluid; import net.minecraftforge.fml.RegistryObject; import static com.xdsz.test.util.RegistryHandler.FLUIDS;
1,854
package com.xdsz.test.fluids; public class TestFluids { public static final ResourceLocation WATER_STILL_RL = new ResourceLocation("block/water_still"); public static final ResourceLocation WATER_FLOWING_RL = new ResourceLocation("block/water_flow"); public static final ResourceLocation WATER_OVERLAY_RL = new ResourceLocation("block/water_overlay"); public static final RegistryObject<FlowingFluid> HONEYTEST_FLUID = FLUIDS.register("honeytest_fluid", () -> new ForgeFlowingFluid.Source(TestFluids.HONEYTEST_PROPERTIES)); public static final RegistryObject<FlowingFluid> HONEYTEST_FLOWING = FLUIDS.register("honeytest_flowing", () -> new ForgeFlowingFluid.Flowing(TestFluids.HONEYTEST_PROPERTIES)); public static final ForgeFlowingFluid.Properties HONEYTEST_PROPERTIES = new ForgeFlowingFluid.Properties( () -> HONEYTEST_FLUID.get(), () -> HONEYTEST_FLOWING.get(), FluidAttributes.builder(WATER_STILL_RL, WATER_FLOWING_RL) .sound(SoundEvents.ITEM_HONEY_BOTTLE_DRINK).overlay(WATER_OVERLAY_RL) .color(0xffffd247)).slopeFindDistance(9).levelDecreasePerBlock(2)
package com.xdsz.test.fluids; public class TestFluids { public static final ResourceLocation WATER_STILL_RL = new ResourceLocation("block/water_still"); public static final ResourceLocation WATER_FLOWING_RL = new ResourceLocation("block/water_flow"); public static final ResourceLocation WATER_OVERLAY_RL = new ResourceLocation("block/water_overlay"); public static final RegistryObject<FlowingFluid> HONEYTEST_FLUID = FLUIDS.register("honeytest_fluid", () -> new ForgeFlowingFluid.Source(TestFluids.HONEYTEST_PROPERTIES)); public static final RegistryObject<FlowingFluid> HONEYTEST_FLOWING = FLUIDS.register("honeytest_flowing", () -> new ForgeFlowingFluid.Flowing(TestFluids.HONEYTEST_PROPERTIES)); public static final ForgeFlowingFluid.Properties HONEYTEST_PROPERTIES = new ForgeFlowingFluid.Properties( () -> HONEYTEST_FLUID.get(), () -> HONEYTEST_FLOWING.get(), FluidAttributes.builder(WATER_STILL_RL, WATER_FLOWING_RL) .sound(SoundEvents.ITEM_HONEY_BOTTLE_DRINK).overlay(WATER_OVERLAY_RL) .color(0xffffd247)).slopeFindDistance(9).levelDecreasePerBlock(2)
.block(()->TestFluids.HONEYTEST_BLOCK.get()).bucket(()-> RegistryHandler.HONEYTEST_BUCKET.get());
0
2023-10-28 05:14:07+00:00
4k
frc2052/2024-JumpstartSwerveDemo
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DriveCommand", "path": "src/main/java/frc/robot/commands/drive/DriveCommand.java", "snippet": "public class DriveCommand extends CommandBase {\n protected final DrivetrainSubsystem drivetrain;\n\n private final DoubleSupplier xSupplier;\n private final DoubleSupplier ySupplier;\n private final DoubleSupplier rotationSupplier;\n \n private final SlewRateLimiter xLimiter;\n private final SlewRateLimiter yLimiter;\n private final SlewRateLimiter rotationLimiter;\n\n /**\n * @param xSupplier supplier for forward velocity.\n * @param ySupplier supplier for sideways velocity.\n * @param rotationSupplier supplier for angular velocity.\n */\n public DriveCommand(\n DoubleSupplier xSupplier, \n DoubleSupplier ySupplier, \n DoubleSupplier rotationSupplier,\n DrivetrainSubsystem drivetrain\n ) {\n this.drivetrain = drivetrain;\n this.xSupplier = xSupplier;\n this.ySupplier = ySupplier;\n this.rotationSupplier = rotationSupplier;\n\n xLimiter = new SlewRateLimiter(2);\n yLimiter = new SlewRateLimiter(2);\n rotationLimiter = new SlewRateLimiter(3);\n\n addRequirements(drivetrain);\n }\n\n protected double getX() {\n return slewAxis(xLimiter, deadBand(-xSupplier.getAsDouble()));\n }\n\n protected double getY() {\n return slewAxis(yLimiter, deadBand(-ySupplier.getAsDouble()));\n }\n\n protected double getRotation() {\n return slewAxis(rotationLimiter, deadBand(-rotationSupplier.getAsDouble())) / 2;\n }\n\n @Override\n public void execute() {\n drivetrain.drive(-getX(), -getY(), -getRotation());\n }\n\n @Override\n public void end(boolean interrupted) {\n drivetrain.stop();\n }\n\n protected double slewAxis(SlewRateLimiter limiter, double value) {\n return limiter.calculate(Math.copySign(Math.pow(value, 4), value));\n }\n\n protected double deadBand(double value) {\n if (Math.abs(value) <= 0.15) {\n return 0.0;\n }\n // Limit the value to always be in the range of [-1.0, 1.0]\n return Math.copySign(Math.min(1.0, Math.abs(value)), value);\n }\n}" }, { "identifier": "DrivetrainSubsystem", "path": "src/main/java/frc/robot/subsystems/DrivetrainSubsystem.java", "snippet": "public class DrivetrainSubsystem extends SubsystemBase {\n private final SwerveModule frontLeftWheel;\n private final SwerveModule frontRightWheel;\n private final SwerveModule backLeftWheel;\n private final SwerveModule backRightWheel;\n\n public double xMetersPerSecond;\n public double yMetersPerSecond;\n public double radiansPersecond;\n\n private static final SwerveDriveKinematics kinematics = new SwerveDriveKinematics(\n // Front left\n new Translation2d(Constants.Drivetrain.DRIVETRAIN_TRACKWIDTH_METERS / 2.0, -Constants.Drivetrain.DRIVETRAIN_WHEELBASE_METERS / 2.0),\n // Front right\n new Translation2d(Constants.Drivetrain.DRIVETRAIN_TRACKWIDTH_METERS / 2.0, Constants.Drivetrain.DRIVETRAIN_WHEELBASE_METERS / 2.0),\n // Back left\n new Translation2d(-Constants.Drivetrain.DRIVETRAIN_TRACKWIDTH_METERS / 2.0, -Constants.Drivetrain.DRIVETRAIN_WHEELBASE_METERS / 2.0),\n // Back right\n new Translation2d(-Constants.Drivetrain.DRIVETRAIN_TRACKWIDTH_METERS / 2.0, Constants.Drivetrain.DRIVETRAIN_WHEELBASE_METERS / 2.0)\n );\n\n /** Creates a new DrivetrainSubsystem. */\n public DrivetrainSubsystem() {\n\n frontLeftWheel = new SwerveModule(\n \"frontLeftModule\",\n Constants.Drivetrain.FRONT_LEFT_MODULE_DRIVE_MOTOR, \n Constants.Drivetrain.FRONT_LEFT_MODULE_STEER_MOTOR,\n Constants.Drivetrain.FRONT_LEFT_MODULE_ENCODER,\n new Rotation2d(Constants.Drivetrain.FRONT_LEFT_MODULE_STEER_OFFSET_RADIANS)\n );\n frontRightWheel = new SwerveModule(\n \"frontRightModule\",\n Constants.Drivetrain.FRONT_RIGHT_MODULE_DRIVE_MOTOR,\n Constants.Drivetrain.FRONT_RIGHT_MODULE_STEER_MOTOR,\n Constants.Drivetrain.FRONT_RIGHT_MODULE_ENCODER,\n new Rotation2d(Constants.Drivetrain.FRONT_RIGHT_MODULE_STEER_OFFSET_RADIANS)\n );\n backLeftWheel = new SwerveModule(\n \"backLeftModule\",\n Constants.Drivetrain.BACK_LEFT_MODULE_DRIVE_MOTOR, \n Constants.Drivetrain.BACK_LEFT_MODULE_STEER_MOTOR,\n Constants.Drivetrain.BACK_LEFT_MODULE_ENCODER,\n new Rotation2d(Constants.Drivetrain.BACK_LEFT_MODULE_STEER_OFFSET_RADIANS)\n\n );\n backRightWheel = new SwerveModule(\n \"backRightModule\",\n Constants.Drivetrain.BACK_RIGHT_MODULE_DRIVE_MOTOR, \n Constants.Drivetrain.BACK_RIGHT_MODULE_STEER_MOTOR,\n Constants.Drivetrain.BACK_RIGHT_MODULE_ENCODER,\n new Rotation2d(Constants.Drivetrain.BACK_RIGHT_MODULE_STEER_OFFSET_RADIANS)\n );\n }\n\n public void drive(ChassisSpeeds chassisSpeeds) {\n SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(chassisSpeeds);\n setModuleStates(swerveModuleStates);\n }\n\n /**\n * All parameters are taken in normalized terms of [-1.0 to 1.0].\n */\n public void drive(double normalizedXVelocity, double normalizedYVelocity, double normalizedRotationVelocity){\n \n normalizedXVelocity = Math.copySign(\n Math.min(Math.abs(normalizedXVelocity), 1.0),\n normalizedXVelocity\n );\n normalizedYVelocity = Math.copySign(\n Math.min(Math.abs(normalizedYVelocity), 1.0),\n normalizedYVelocity\n );\n normalizedRotationVelocity = Math.copySign(\n Math.min(Math.abs(normalizedRotationVelocity), 1.0),\n normalizedRotationVelocity\n );\n\n ChassisSpeeds chassisSpeeds = new ChassisSpeeds(\n normalizedXVelocity * SwerveModule.getMaxVelocityMetersPerSecond(), \n normalizedYVelocity * SwerveModule.getMaxVelocityMetersPerSecond(), \n normalizedRotationVelocity * SwerveModule.getMaxAngularVelocityRadiansPerSecond()\n );\n\n drive(chassisSpeeds);\n }\n\n // Stop wheels from snapping to 0 when they have no velocity\n public void setModuleStates(SwerveModuleState[] swerveModuleStates) {\n // Check if the wheels don't have a drive velocity to maintain the current wheel orientation.\n boolean hasVelocity = swerveModuleStates[0].speedMetersPerSecond != 0\n || swerveModuleStates[1].speedMetersPerSecond != 0 \n || swerveModuleStates[2].speedMetersPerSecond != 0\n || swerveModuleStates[3].speedMetersPerSecond != 0;\n\n frontLeftWheel.setState(\n swerveModuleStates[1].speedMetersPerSecond, \n hasVelocity ? swerveModuleStates[1].angle : frontRightWheel.getState().angle\n );\n frontRightWheel.setState(\n swerveModuleStates[0].speedMetersPerSecond, \n hasVelocity ? swerveModuleStates[0].angle : frontLeftWheel.getState().angle\n );\n backLeftWheel.setState(\n swerveModuleStates[3].speedMetersPerSecond, \n hasVelocity ? swerveModuleStates[3].angle : backRightWheel.getState().angle\n );\n backRightWheel.setState(\n swerveModuleStates[2].speedMetersPerSecond, \n hasVelocity ? swerveModuleStates[2].angle : backLeftWheel.getState().angle\n );\n }\n\n public void stop() {\n drive(0, 0, 0);\n }\n\n @Override\n public void periodic() {\n //debug();\n }\n\n public void debug() {\n backLeftWheel.debug(\"Back Left\");\n backRightWheel.debug(\"Back Right\");\n frontLeftWheel.debug(\"Front Left\");\n frontRightWheel.debug(\"Front Right\");\n }\n}" } ]
import frc.robot.commands.drive.DriveCommand; import frc.robot.subsystems.DrivetrainSubsystem; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj2.command.Command;
2,284
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { // The robot's subsystems and commands are defined here... public final DrivetrainSubsystem drivetrain; // Replace with CommandPS4Controller or CommandJoystick if needed private final Joystick joystick = new Joystick(0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { drivetrain = new DrivetrainSubsystem(); drivetrain.setDefaultCommand(
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { // The robot's subsystems and commands are defined here... public final DrivetrainSubsystem drivetrain; // Replace with CommandPS4Controller or CommandJoystick if needed private final Joystick joystick = new Joystick(0); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { drivetrain = new DrivetrainSubsystem(); drivetrain.setDefaultCommand(
new DriveCommand(
0
2023-10-25 02:54:34+00:00
4k
SUFIAG/Weather-Application-Android
app/src/main/java/com/aniketjain/weatherapp/HomeActivity.java
[ { "identifier": "getCityNameUsingNetwork", "path": "app/src/main/java/com/aniketjain/weatherapp/location/CityFinder.java", "snippet": "public static String getCityNameUsingNetwork(Context context, Location location) {\n String city = \"\";\n try {\n Geocoder geocoder = new Geocoder(context, Locale.getDefault());\n List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);\n city = addresses.get(0).getLocality();\n Log.d(\"city\", city);\n } catch (Exception e) {\n Log.d(\"city\", \"Error to find the city.\");\n }\n return city;\n}" }, { "identifier": "setLongitudeLatitude", "path": "app/src/main/java/com/aniketjain/weatherapp/location/CityFinder.java", "snippet": "public static void setLongitudeLatitude(Location location) {\n try {\n LocationCord.lat = String.valueOf(location.getLatitude());\n LocationCord.lon = String.valueOf(location.getLongitude());\n Log.d(\"location_lat\", LocationCord.lat);\n Log.d(\"location_lon\", LocationCord.lon);\n } catch (NullPointerException e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "isInternetConnected", "path": "app/src/main/java/com/aniketjain/weatherapp/network/InternetConnectivity.java", "snippet": "public static boolean isInternetConnected(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||\n connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;\n}" }, { "identifier": "DaysAdapter", "path": "app/src/main/java/com/aniketjain/weatherapp/adapter/DaysAdapter.java", "snippet": "public class DaysAdapter extends RecyclerView.Adapter<DaysAdapter.DayViewHolder> {\n private final Context context;\n\n public DaysAdapter(Context context) {\n this.context = context;\n }\n\n private String updated_at, min, max, pressure, wind_speed, humidity;\n private int condition;\n private long update_time, sunset, sunrise;\n\n @NonNull\n @Override\n public DayViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(context).inflate(R.layout.day_item_layout, parent, false);\n return new DayViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull DayViewHolder holder, int position) {\n getDailyWeatherInfo(position + 1, holder);\n }\n\n @Override\n public int getItemCount() {\n return 6;\n }\n\n @SuppressLint(\"DefaultLocale\")\n private void getDailyWeatherInfo(int i, DayViewHolder holder) {\n URL url = new URL();\n RequestQueue requestQueue = Volley.newRequestQueue(context);\n JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url.getLink(), null, response -> {\n try {\n update_time = response.getJSONObject(\"current\").getLong(\"dt\");\n updated_at = new SimpleDateFormat(\"EEEE\", Locale.ENGLISH).format(new Date((update_time * 1000) + (i * 864_000_00L))); // i=0\n\n condition = response.getJSONArray(\"daily\").getJSONObject(i).getJSONArray(\"weather\").getJSONObject(0).getInt(\"id\");\n sunrise = response.getJSONArray(\"daily\").getJSONObject(i).getLong(\"sunrise\");\n sunset = response.getJSONArray(\"daily\").getJSONObject(i).getLong(\"sunset\");\n\n min = String.format(\"%.0f\", response.getJSONArray(\"daily\").getJSONObject(i).getJSONObject(\"temp\").getDouble(\"min\") - 273.15);\n max = String.format(\"%.0f\", response.getJSONArray(\"daily\").getJSONObject(i).getJSONObject(\"temp\").getDouble(\"max\") - 273.15);\n pressure = response.getJSONArray(\"daily\").getJSONObject(i).getString(\"pressure\");\n wind_speed = response.getJSONArray(\"daily\").getJSONObject(i).getString(\"wind_speed\");\n humidity = response.getJSONArray(\"daily\").getJSONObject(i).getString(\"humidity\");\n\n updateUI(holder);\n hideProgressBar(holder);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }, null);\n requestQueue.add(jsonObjectRequest);\n Log.i(\"json_req\", \"Day \" + i);\n }\n\n @SuppressLint(\"SetTextI18n\")\n private void updateUI(DayViewHolder holder) {\n String day = UpdateUI.TranslateDay(updated_at, context);\n holder.dTime.setText(day);\n holder.temp_min.setText(min + \"°C\");\n holder.temp_max.setText(max + \"°C\");\n holder.pressure.setText(pressure + \" mb\");\n holder.wind.setText(wind_speed + \" km/h\");\n holder.humidity.setText(humidity + \"%\");\n holder.icon.setImageResource(\n context.getResources().getIdentifier(\n UpdateUI.getIconID(condition, update_time, sunrise, sunset),\n \"drawable\",\n context.getPackageName()\n ));\n }\n\n private void hideProgressBar(DayViewHolder holder) {\n holder.progress.setVisibility(View.GONE);\n holder.layout.setVisibility(View.VISIBLE);\n }\n\n static class DayViewHolder extends RecyclerView.ViewHolder {\n SpinKitView progress;\n RelativeLayout layout;\n TextView dTime, temp_min, temp_max, pressure, wind, humidity;\n ImageView icon;\n\n public DayViewHolder(@NonNull View itemView) {\n super(itemView);\n progress = itemView.findViewById(R.id.day_progress_bar);\n layout = itemView.findViewById(R.id.day_relative_layout);\n dTime = itemView.findViewById(R.id.day_time);\n temp_min = itemView.findViewById(R.id.day_min_temp);\n temp_max = itemView.findViewById(R.id.day_max_temp);\n pressure = itemView.findViewById(R.id.day_pressure);\n wind = itemView.findViewById(R.id.day_wind);\n humidity = itemView.findViewById(R.id.day_humidity);\n icon = itemView.findViewById(R.id.day_icon);\n }\n }\n}" }, { "identifier": "LocationCord", "path": "app/src/main/java/com/aniketjain/weatherapp/location/LocationCord.java", "snippet": "public class LocationCord {\n public static String lat = \"\";\n public static String lon = \"\";\n public final static String API_KEY = \"0bc14881636d2234e8c17736a470535f\";\n// public final static String API_KEY = \"eeb8b40367eee691683e5a079e2fa695\";\n}" }, { "identifier": "Toaster", "path": "app/src/main/java/com/aniketjain/weatherapp/toast/Toaster.java", "snippet": "public class Toaster {\n public static void successToast(Context context, String msg) {\n Toasty.custom(\n context,\n msg,\n R.drawable.ic_baseline_check_24,\n \"#454B54\",\n 14,\n \"#EEEEEE\");\n }\n\n public static void errorToast(Context context, String msg) {\n Toasty.custom(\n context,\n msg,\n R.drawable.ic_baseline_error_outline_24,\n \"#454B54\",\n 14,\n \"#EEEEEE\");\n }\n}" }, { "identifier": "UpdateUI", "path": "app/src/main/java/com/aniketjain/weatherapp/update/UpdateUI.java", "snippet": "public class UpdateUI {\n\n public static String getIconID(int condition, long update_time, long sunrise, long sunset) {\n if (condition >= 200 && condition <= 232)\n return \"thunderstorm\";\n else if (condition >= 300 && condition <= 321)\n return \"drizzle\";\n else if (condition >= 500 && condition <= 531)\n return \"rain\";\n else if (condition >= 600 && condition <= 622)\n return \"snow\";\n else if (condition >= 701 && condition <= 781)\n return \"wind\";\n else if (condition == 800) {\n if (update_time >= sunrise && update_time <= sunset)\n return \"clear_day\";\n else\n return \"clear_night\";\n } else if (condition == 801) {\n if (update_time >= sunrise && update_time <= sunset)\n return \"few_clouds_day\";\n else\n return \"few_clouds_night\";\n } else if (condition == 802)\n return \"scattered_clouds\";\n else if (condition == 803 || condition == 804)\n return \"broken_clouds\";\n return null;\n }\n\n public static String TranslateDay(String dayToBeTranslated, Context context) {\n switch (dayToBeTranslated.trim()) {\n case \"Monday\":\n return context.getResources().getString(R.string.monday);\n case \"Tuesday\":\n return context.getResources().getString(R.string.tuesday);\n case \"Wednesday\":\n return context.getResources().getString(R.string.wednesday);\n case \"Thursday\":\n return context.getResources().getString(R.string.thursday);\n case \"Friday\":\n return context.getResources().getString(R.string.friday);\n case \"Saturday\":\n return context.getResources().getString(R.string.saturday);\n case \"Sunday\":\n return context.getResources().getString(R.string.sunday);\n }\n return dayToBeTranslated;\n }\n}" }, { "identifier": "URL", "path": "app/src/main/java/com/aniketjain/weatherapp/url/URL.java", "snippet": "public class URL {\n private String link;\n private static String city_url;\n\n public URL() {\n link = \"https://api.openweathermap.org/data/2.5/onecall?exclude=minutely&lat=\"\n + LocationCord.lat + \"&lon=\" + LocationCord.lon + \"&appid=\" + LocationCord.API_KEY;\n }\n\n public String getLink() {\n return link;\n }\n\n\n public static void setCity_url(String cityName) {\n city_url = \"https://api.openweathermap.org/data/2.5/weather?&q=\" + cityName + \"&appid=\" + LocationCord.API_KEY;\n }\n\n public static String getCity_url() {\n return city_url;\n }\n\n}" } ]
import static com.aniketjain.weatherapp.location.CityFinder.getCityNameUsingNetwork; import static com.aniketjain.weatherapp.location.CityFinder.setLongitudeLatitude; import static com.aniketjain.weatherapp.network.InternetConnectivity.isInternetConnected; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; import android.util.Log; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.LinearLayoutManager; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.aniketjain.weatherapp.adapter.DaysAdapter; import com.aniketjain.weatherapp.databinding.ActivityHomeBinding; import com.aniketjain.weatherapp.location.LocationCord; import com.aniketjain.weatherapp.toast.Toaster; import com.aniketjain.weatherapp.update.UpdateUI; import com.aniketjain.weatherapp.url.URL; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.play.core.appupdate.AppUpdateInfo; import com.google.android.play.core.appupdate.AppUpdateManager; import com.google.android.play.core.appupdate.AppUpdateManagerFactory; import com.google.android.play.core.install.model.AppUpdateType; import com.google.android.play.core.install.model.UpdateAvailability; import com.google.android.play.core.tasks.Task; import org.json.JSONException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.Objects;
3,500
package com.aniketjain.weatherapp; public class HomeActivity extends AppCompatActivity { private final int WEATHER_FORECAST_APP_UPDATE_REQ_CODE = 101; // for app update private static final int PERMISSION_CODE = 1; // for user location permission private String name, updated_at, description, temperature, min_temperature, max_temperature, pressure, wind_speed, humidity; private int condition; private long update_time, sunset, sunrise; private String city = ""; private final int REQUEST_CODE_EXTRA_INPUT = 101; private ActivityHomeBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // binding binding = ActivityHomeBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); // set navigation bar color setNavigationBarColor(); //check for new app update checkUpdate(); // set refresh color schemes setRefreshLayoutColor(); // when user do search and refresh listeners(); // getting data using internet connection getDataUsingNetwork(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_EXTRA_INPUT) { if (resultCode == RESULT_OK && data != null) { ArrayList<String> arrayList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); binding.layout.cityEt.setText(Objects.requireNonNull(arrayList).get(0).toUpperCase()); searchCity(binding.layout.cityEt.getText().toString()); } } } private void setNavigationBarColor() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setNavigationBarColor(getResources().getColor(R.color.navBarColor)); } } private void setUpDaysRecyclerView() { DaysAdapter daysAdapter = new DaysAdapter(this); binding.dayRv.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) ); binding.dayRv.setAdapter(daysAdapter); } @SuppressLint("ClickableViewAccessibility") private void listeners() { binding.layout.mainLayout.setOnTouchListener((view, motionEvent) -> { hideKeyboard(view); return false; }); binding.layout.searchBarIv.setOnClickListener(view -> searchCity(binding.layout.cityEt.getText().toString())); binding.layout.searchBarIv.setOnTouchListener((view, motionEvent) -> { hideKeyboard(view); return false; }); binding.layout.cityEt.setOnEditorActionListener((textView, i, keyEvent) -> { if (i == EditorInfo.IME_ACTION_GO) { searchCity(binding.layout.cityEt.getText().toString()); hideKeyboard(textView); return true; } return false; }); binding.layout.cityEt.setOnFocusChangeListener((view, b) -> { if (!b) { hideKeyboard(view); } }); binding.mainRefreshLayout.setOnRefreshListener(() -> { checkConnection(); Log.i("refresh", "Refresh Done."); binding.mainRefreshLayout.setRefreshing(false); //for the next time }); //Mic Search binding.layout.micSearchId.setOnClickListener(view -> { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, REQUEST_CODE_EXTRA_INPUT); try { //it was deprecated but still work startActivityForResult(intent, REQUEST_CODE_EXTRA_INPUT); } catch (Exception e) { Log.d("Error Voice", "Mic Error: " + e); } }); } private void setRefreshLayoutColor() { binding.mainRefreshLayout.setProgressBackgroundColorSchemeColor( getResources().getColor(R.color.textColor) ); binding.mainRefreshLayout.setColorSchemeColors( getResources().getColor(R.color.navBarColor) ); } private void searchCity(String cityName) { if (cityName == null || cityName.isEmpty()) {
package com.aniketjain.weatherapp; public class HomeActivity extends AppCompatActivity { private final int WEATHER_FORECAST_APP_UPDATE_REQ_CODE = 101; // for app update private static final int PERMISSION_CODE = 1; // for user location permission private String name, updated_at, description, temperature, min_temperature, max_temperature, pressure, wind_speed, humidity; private int condition; private long update_time, sunset, sunrise; private String city = ""; private final int REQUEST_CODE_EXTRA_INPUT = 101; private ActivityHomeBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // binding binding = ActivityHomeBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); // set navigation bar color setNavigationBarColor(); //check for new app update checkUpdate(); // set refresh color schemes setRefreshLayoutColor(); // when user do search and refresh listeners(); // getting data using internet connection getDataUsingNetwork(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_EXTRA_INPUT) { if (resultCode == RESULT_OK && data != null) { ArrayList<String> arrayList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); binding.layout.cityEt.setText(Objects.requireNonNull(arrayList).get(0).toUpperCase()); searchCity(binding.layout.cityEt.getText().toString()); } } } private void setNavigationBarColor() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setNavigationBarColor(getResources().getColor(R.color.navBarColor)); } } private void setUpDaysRecyclerView() { DaysAdapter daysAdapter = new DaysAdapter(this); binding.dayRv.setLayoutManager( new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) ); binding.dayRv.setAdapter(daysAdapter); } @SuppressLint("ClickableViewAccessibility") private void listeners() { binding.layout.mainLayout.setOnTouchListener((view, motionEvent) -> { hideKeyboard(view); return false; }); binding.layout.searchBarIv.setOnClickListener(view -> searchCity(binding.layout.cityEt.getText().toString())); binding.layout.searchBarIv.setOnTouchListener((view, motionEvent) -> { hideKeyboard(view); return false; }); binding.layout.cityEt.setOnEditorActionListener((textView, i, keyEvent) -> { if (i == EditorInfo.IME_ACTION_GO) { searchCity(binding.layout.cityEt.getText().toString()); hideKeyboard(textView); return true; } return false; }); binding.layout.cityEt.setOnFocusChangeListener((view, b) -> { if (!b) { hideKeyboard(view); } }); binding.mainRefreshLayout.setOnRefreshListener(() -> { checkConnection(); Log.i("refresh", "Refresh Done."); binding.mainRefreshLayout.setRefreshing(false); //for the next time }); //Mic Search binding.layout.micSearchId.setOnClickListener(view -> { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, REQUEST_CODE_EXTRA_INPUT); try { //it was deprecated but still work startActivityForResult(intent, REQUEST_CODE_EXTRA_INPUT); } catch (Exception e) { Log.d("Error Voice", "Mic Error: " + e); } }); } private void setRefreshLayoutColor() { binding.mainRefreshLayout.setProgressBackgroundColorSchemeColor( getResources().getColor(R.color.textColor) ); binding.mainRefreshLayout.setColorSchemeColors( getResources().getColor(R.color.navBarColor) ); } private void searchCity(String cityName) { if (cityName == null || cityName.isEmpty()) {
Toaster.errorToast(this, "Please enter the city name");
5
2023-10-25 21:15:57+00:00
4k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/v2210/AbstractVerifiableCredentialTest.java
[ { "identifier": "ProofGenerator", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/ProofGenerator.java", "snippet": "public class ProofGenerator {\n\n\t/**\n\t * Generate the proof of the serialized JSON-LD document, using the provided JSON Web Key\n\t */\n\tpublic static Proof generateProof(String jsonLd, String verificationMethod, JWK jwk) {\n\t\tfinal String signature = JsonWebSignatureUtils.generateSignature(jsonLd, jwk);\n\t\treturn toProof(signature, verificationMethod);\n\t}\n\n\tprivate static Proof toProof(String signature, String verificationMethod) {\n\t\treturn Proof.builder()\n\t\t\t\t.type(\"JsonWebSignature2020\")\n\t\t\t\t.created(ZonedDateTime.now(ZoneOffset.UTC))\n\t\t\t\t.proofPurpose(\"assertionMethod\")\n\t\t\t\t.verificationMethod(verificationMethod)\n\t\t\t\t.jws(signature)\n\t\t\t\t.build();\n\t}\n\n\tprivate ProofGenerator() {\n\t\t// no instance allowed\n\t}\n}" }, { "identifier": "JwkSetUtils", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jose/JwkSetUtils.java", "snippet": "public class JwkSetUtils {\n\n\t/**\n\t * JWT are signed with RS256 algorithm, that is an RSA signature with SHA-256.\n\t * It's a popular algorithm, and the default one in NimbusReactiveJwtDecoder (used by the resources servers).\n\t * The minimum recommended size for RSA key is 2048 bits.\n\t */\n\tprivate static final int RSA_KEY_SIZE = 2048;\n\n\tprivate static final String SIGNATURE_ALGORITHM = \"SHA256withRSA\";\n\n\tprivate JwkSetUtils() {\n\t\t// no instance allowed\n\t}\n\n\t/**\n\t * Parses the specified JSON object representing a JSON Web Key (JWK) set.\n\t *\n\t * @throws KeyParsingException If the data map couldn't be parsed to a valid JSON Web Key (JWK) set.\n\t */\n\tpublic static JWKSet parseJwkSet(Map<String, Object> data) {\n\t\ttry {\n\t\t\treturn JWKSet.parse(data);\n\t\t} catch (ParseException e) {\n\t\t\tthrow new KeyParsingException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a new Jwk Set, and generate a self-signed X.509 certificate.\n\t *\n\t * @param certBaseUrl X509 certificate URL, formatted with the keyId (%s will be replaced by the keyId if present); can be null\n\t * @param certIssuerCommonName Common name that appears in the X509 certificate\n\t * @param certValidityInMonths validity of the generated X509 certificate, in months\n\t * @throws KeyCreationException If the keys cannot be created\n\t */\n\tpublic static CreatedKeys createKeysWithSelfSignedCertificate(String certBaseUrl, String certIssuerCommonName,\n\t\t\tint certValidityInMonths) {\n\t\ttry {\n\t\t\tfinal KeyPair keyPair = generateRsaKey();\n\t\t\tfinal X509Certificate cert = getSelfSignedX509Certificate(keyPair, certIssuerCommonName, certValidityInMonths);\n\t\t\tfinal RSAKey rsaKey = buildRsaKey(certBaseUrl, cert, (RSAPrivateKey) keyPair.getPrivate());\n\t\t\treturn new CreatedKeys(new JWKSet(rsaKey), List.of(X509CertUtils.toPEMString(cert)));\n\n\t\t} catch (OperatorCreationException | CertificateException | JOSEException e) {\n\t\t\tthrow new KeyCreationException(\"The key pair and/or the X.509 certificate cannot be created\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Create a JWK Set from the private key contained in the pem file, and generate a self-signed X.509 certificate.\n\t *\n\t * @param privateKeyInputStream private key in PEM format\n\t */\n\tpublic static CreatedKeys importKeysWithSelfSignedCertificate(InputStream privateKeyInputStream, String certBaseUrl,\n\t\t\tString certIssuerCommonName, int certValidityInMonths) {\n\t\ttry (InputStreamReader pemReader = new InputStreamReader(privateKeyInputStream)) {\n\t\t\tfinal KeyPair keyPair = parseRsaPrivateKey(pemReader);\n\t\t\tfinal X509Certificate cert = getSelfSignedX509Certificate(keyPair, certIssuerCommonName, certValidityInMonths);\n\t\t\tfinal RSAKey rsaKey = buildRsaKey(certBaseUrl, cert, (RSAPrivateKey) keyPair.getPrivate());\n\t\t\treturn new CreatedKeys(new JWKSet(rsaKey), List.of(X509CertUtils.toPEMString(cert)));\n\n\t\t} catch (JOSEException | IOException | OperatorCreationException | GeneralSecurityException e) {\n\t\t\tthrow new KeyCreationException(\"The key pair cannot be imported and/or the X.509 certificate cannot be created\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Create a JWK Set from the private key contained in the pem file, and the provided X.509 certificate.\n\t * Certificate must be valid, et match the provided private key.\n\t *\n\t * @param privateKeyInputStream private key in PEM format\n\t * @param certificateInputStream certificate in PEM format\n\t */\n\tpublic static CreatedKeys importKeysAndCertificate(InputStream privateKeyInputStream, InputStream certificateInputStream,\n\t\t\tString certBaseUrl) {\n\t\ttry (InputStreamReader pemReader = new InputStreamReader(privateKeyInputStream)) {\n\t\t\tfinal KeyPair keyPair = parseRsaPrivateKey(pemReader);\n\t\t\tfinal List<X509Certificate> certificates = getX509Certificates(certificateInputStream);\n\t\t\tfinal RSAKey rsaKey = buildRsaKey(certBaseUrl, certificates.get(0), (RSAPrivateKey) keyPair.getPrivate());\n\t\t\treturn new CreatedKeys(new JWKSet(rsaKey), certificates.stream().map(X509CertUtils::toPEMString).toList());\n\n\t\t} catch (GeneralSecurityException | JOSEException | IOException | MissingCertificateException e) {\n\t\t\tthrow new KeyCreationException(\"The key pair and/or the X.509 certificate cannot be imported\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Generate a self-signed certificate from the specified keyPair\n\t */\n\tprivate static X509Certificate getSelfSignedX509Certificate(KeyPair keyPair, String commonName, int validityInMonths)\n\t\t\tthrows OperatorCreationException, CertificateException {\n\t\t// arbitrary X500Name\n\t\tfinal X500Name name = new X500Name(\"CN=%s\".formatted(commonName));\n\t\t// certificate serial number https://www.rfc-editor.org/rfc/rfc3280#section-4.1.2.2\n\t\tfinal BigInteger serial = BigInteger.valueOf(new SecureRandom().nextLong(0, Long.MAX_VALUE));\n\t\t// certificate validity arbitrary set to 1 year\n\t\tfinal OffsetDateTime now = LocalDate.now().atStartOfDay().atOffset(ZoneOffset.UTC);\n\t\tfinal Date notBefore = Date.from(now.toInstant());\n\t\tfinal Date notAfter = Date.from(now.plusMonths(validityInMonths).toInstant());\n\n\t\tfinal X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(\n\t\t\t\tname, serial, notBefore, notAfter, name, keyPair.getPublic());\n\t\tfinal ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(keyPair.getPrivate());\n\t\tfinal JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider());\n\n\t\treturn converter.getCertificate(certBuilder.build(contentSigner));\n\t}\n\n\t/**\n\t * Parse X.509 certificates from the InputStream\n\t */\n\tprivate static List<X509Certificate> getX509Certificates(InputStream certificateInputStream)\n\t\t\tthrows IOException, CertificateException, MissingCertificateException {\n\t\tfinal String pemEncodedCert = IOUtils.readInputStreamToString(certificateInputStream);\n\t\tfinal List<X509Certificate> certificates = X509CertChainUtils.parse(pemEncodedCert);\n\t\tif (certificates.isEmpty()) {\n\t\t\tthrow new MissingCertificateException();\n\t\t}\n\t\tfor (X509Certificate certificate : certificates) {\n\t\t\tcertificate.checkValidity();\n\t\t}\n\t\treturn certificates;\n\t}\n\n\tprivate static KeyPair generateRsaKey() {\n\t\tfinal KeyPair keyPair;\n\t\ttry {\n\t\t\tfinal KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n\t\t\tkeyPairGenerator.initialize(RSA_KEY_SIZE);\n\t\t\tkeyPair = keyPairGenerator.generateKeyPair();\n\t\t} catch (InvalidParameterException | NoSuchAlgorithmException e) {\n\t\t\tthrow new KeyCreationException(\"The RSA key pair cannot be generated\", e);\n\t\t}\n\t\treturn keyPair;\n\t}\n\n\tprivate static KeyPair parseRsaPrivateKey(Reader pemReader) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {\n\t\tfinal Object readObject;\n\t\ttry (final PEMParser pemParser = new PEMParser(pemReader)) {\n\t\t\treadObject = pemParser.readObject();\n\t\t}\n\n\t\t// get private key\n\t\tfinal PrivateKeyInfo privateKeyInfo;\n\t\tif (readObject instanceof PEMKeyPair pemKeyPair) {\n\t\t\tprivateKeyInfo = pemKeyPair.getPrivateKeyInfo();\n\t\t} else {\n\t\t\tprivateKeyInfo = PrivateKeyInfo.getInstance(readObject);\n\t\t}\n\t\tfinal RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);\n\n\t\t// generate public key from private key\n\t\tfinal RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent());\n\t\tfinal KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n\t\tfinal PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);\n\n\t\treturn new KeyPair(publicKey, privateKey);\n\t}\n\n\tprivate static RSAKey buildRsaKey(String certBaseUrl, X509Certificate cert, RSAPrivateKey privateKey) throws JOSEException {\n\t\tfinal String kid = UUID.randomUUID().toString();\n\t\treturn new RSAKey.Builder(RSAKey.parse(cert))\n\t\t\t\t.keyID(kid)\n\t\t\t\t.privateKey(privateKey)\n\t\t\t\t// The \"alg\" (algorithm) parameter identifies the algorithm intended for use with the key.\n\t\t\t\t.algorithm(JsonWebSignatureUtils.JWS_ALGORITHM)\n\t\t\t\t.x509CertURL(Optional.ofNullable(certBaseUrl).map(u -> URI.create(u.formatted(kid))).orElse(null))\n\t\t\t\t.build();\n\t}\n\n\tpublic record CreatedKeys(JWKSet jwkSet, List<String> certificates) {\n\t}\n}" }, { "identifier": "ProofSignatureExpectationsHelper", "path": "trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/utils/ProofSignatureExpectationsHelper.java", "snippet": "public class ProofSignatureExpectationsHelper {\n\n\tprivate final JWKSet jwkSet;\n\n\tprivate final List<String> certificates;\n\n\tpublic ProofSignatureExpectationsHelper(JWKSet jwkSet, List<String> certificates) {\n\t\tthis.jwkSet = jwkSet;\n\t\tthis.certificates = certificates;\n\t}\n\n\tpublic void assertSignatureIsValid(String content) {\n\t\tfinal DocumentContext documentContext = JsonPath.parse(content);\n\t\tfinal String jws = documentContext.read(\"$['proof']['jws']\", String.class);\n\t\t// get JSON-LD without the proof\n\t\tdocumentContext.delete(\"$['proof']\");\n\t\tfinal String jsonLd = documentContext.jsonString();\n\n\t\tassertThat(jwkSet.getKeys())\n\t\t\t\t.isNotEmpty().first()\n\t\t\t\t.matches(jwk -> JsonWebSignatureUtils.isSignatureValid(jws, jsonLd, jwk),\n\t\t\t\t\t\t\"proof signature is valid (JWK)\");\n\n\t\tassertThat(certificates)\n\t\t\t\t.isNotEmpty().first()\n\t\t\t\t.extracting(X509CertUtils::parse)\n\t\t\t\t.matches(certificate -> JsonWebSignatureUtils.isSignatureValid(jws, jsonLd, certificate),\n\t\t\t\t\t\t\"proof signature is valid (X.509 certificate\");\n\t}\n}" }, { "identifier": "assertThatJsonStringValue", "path": "trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/utils/TestUtils.java", "snippet": "public static AbstractStringAssert<?> assertThatJsonStringValue(String jsonPath, String json) {\n\treturn assertThat((String) JsonPath.compile(jsonPath).read(json));\n}" } ]
import com.dawex.sigourney.trustframework.vc.core.ProofGenerator; import com.dawex.sigourney.trustframework.vc.core.SignedObject; import com.dawex.sigourney.trustframework.vc.core.jose.JwkSetUtils; import com.dawex.sigourney.trustframework.vc.model.utils.ProofSignatureExpectationsHelper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import static com.dawex.sigourney.trustframework.vc.model.utils.TestUtils.assertThatJsonStringValue; import static org.assertj.core.api.Assertions.assertThat;
3,074
package com.dawex.sigourney.trustframework.vc.model.v2210; public abstract class AbstractVerifiableCredentialTest { private static final JwkSetUtils.CreatedKeys CREATED_KEYS = JwkSetUtils.createKeysWithSelfSignedCertificate(null, "Test", 12); private final static com.nimbusds.jose.jwk.JWK JWK = CREATED_KEYS.jwkSet().getKeys().stream().findFirst().orElseThrow(); private static final String PROOF_VERIFICATION_METHOD = "did:web:dawex.com:api:credentials#ded0da80-ef24-41ea-8824-34d082fb5dfb"; private final ObjectMapper objectMapper = getObjectMapper(); protected abstract ObjectMapper getObjectMapper(); protected String serializeVc(Object verifiableCredential) throws JsonProcessingException {
package com.dawex.sigourney.trustframework.vc.model.v2210; public abstract class AbstractVerifiableCredentialTest { private static final JwkSetUtils.CreatedKeys CREATED_KEYS = JwkSetUtils.createKeysWithSelfSignedCertificate(null, "Test", 12); private final static com.nimbusds.jose.jwk.JWK JWK = CREATED_KEYS.jwkSet().getKeys().stream().findFirst().orElseThrow(); private static final String PROOF_VERIFICATION_METHOD = "did:web:dawex.com:api:credentials#ded0da80-ef24-41ea-8824-34d082fb5dfb"; private final ObjectMapper objectMapper = getObjectMapper(); protected abstract ObjectMapper getObjectMapper(); protected String serializeVc(Object verifiableCredential) throws JsonProcessingException {
final var proof = ProofGenerator.generateProof(
0
2023-10-25 16:10:40+00:00
4k
AysuCgs/JavaMonolithic
src/main/java/com/aysu/service/SatisService.java
[ { "identifier": "ISatisRepository", "path": "src/main/java/com/aysu/repository/ISatisRepository.java", "snippet": "@Repository\npublic interface ISatisRepository extends JpaRepository<Satis,Long> {\n /**\n * 1. Kime ne satıldı? Liste olarak görelim.\n * findAll bu işi görür.\n */\n\n /**\n * 2. A kişisine ne satıldı? liste olarak göster.\n */\n List<Satis> findAllByMusteriid(Long musteriid);\n /**\n * 3. En çok alışveriş yapan müşteri\n * select musteriid from tblsatis group by musteriid order by count(musteriid) limit 1\n */\n//jpql\n @Query(value = \"select s.musteriid from tblsatis s group by s.musteriid order by count(s.musteriid) desc limit 1\",nativeQuery = true)\n List<Long> findByMaxSatisMusteriId();\n\n /**\n * 4. En çok satılan 3 ürünü\n * select s.urunid from Satis s group by s.urunid order by sum(s.adet) desc limit 3\n */\n @Query(value=\"select s.urunid from tblsatis s group by s.urunid order by sum(s.adet) desc limit 3\",nativeQuery = true)\n List<Long> findTop3Product();\n}" }, { "identifier": "Musteri", "path": "src/main/java/com/aysu/repository/entity/Musteri.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Entity\n@Table(name = \"tblmusteri\")\npublic class Musteri {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n Long id;\n\n String ad;\n String adres;\n String tel;\n\n String il;\n String username;\n String password;\n String email;\n String img;\n}" }, { "identifier": "Satis", "path": "src/main/java/com/aysu/repository/entity/Satis.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Entity\n@Table(name = \"tblsatis\")\npublic class Satis {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n Long id;\n Long musteriid;\n Long urunid;\n Long tarih;\n Integer adet;\n Double birimfiyat;\n Double toplamfiyat;\n}" }, { "identifier": "Urun", "path": "src/main/java/com/aysu/repository/entity/Urun.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\n@ToString\n@Entity\n@Table(name = \"tblurun\")\npublic class Urun {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n Long id;\n String ad;\n String marka;\n String model;\n Double fiyat;\n Double kdv;\n String img;\n String aciklama;\n String birim;\n}" }, { "identifier": "ServiceManager", "path": "src/main/java/com/aysu/utility/ServiceManager.java", "snippet": "public class ServiceManager<T,ID> implements IService<T,ID>{\n\n private final JpaRepository<T,ID> repository;\n public ServiceManager(JpaRepository<T, ID> repository) {\n this.repository = repository;\n }\n\n @Override\n public T save(T t) {\n return repository.save(t);\n }\n @Override\n public Iterable<T> saveAll(Iterable<T> t) {\n return repository.saveAll(t);\n }\n @Override\n public T update(T t) {\n return repository.save(t);\n }\n @Override\n public void delete(T t) {\n repository.delete(t);\n }\n @Override\n public void deleteById(ID id) {\n repository.deleteById(id);\n }\n @Override\n public Optional<T> findById(ID id) {\n return repository.findById(id);\n }\n @Override\n public List<T> findAll() {\n return repository.findAll();\n }\n\n}" }, { "identifier": "VwSatis", "path": "src/main/java/com/aysu/view/VwSatis.java", "snippet": "@Builder // bir sınıftan nesne türetmeyi sağlar.\n@Data //get set metodlarını otomatik tanımlar.\n@NoArgsConstructor //boş constructor oluşturur.\n@AllArgsConstructor //dolu constructor oluşturur.\npublic class VwSatis {\n Long satisid;\n Long musteriid;\n String musteriad;\n Long urunid;\n String urunad;\n Integer adet;\n Double birimfiyat;\n Double toplamfiyat;\n}" } ]
import com.aysu.repository.ISatisRepository; import com.aysu.repository.entity.Musteri; import com.aysu.repository.entity.Satis; import com.aysu.repository.entity.Urun; import com.aysu.utility.ServiceManager; import com.aysu.view.VwSatis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
1,697
package com.aysu.service; @Service public class SatisService extends ServiceManager<Satis, Long> { private final ISatisRepository repository; @Autowired private MusteriService musteriService; @Autowired private UrunService urunService; public SatisService(ISatisRepository repository) { super(repository); this.repository = repository; } /** * 1. Kime ne satıldı? Liste olarak görelim. * findAll bu işi görür. */ public List<Satis> findAll() { return repository.findAll(); } /** * 2. A kişisine ne satıldı? liste olarak göster. */ public List<Satis> findAllByMusteriid(Long musteriid) { return repository.findAllByMusteriid(musteriid); } /** * 3. En çok alışveriş yapan müşteri * select musteriid from tblmusteri group by musteriid order by count(musteriid) limit 1 */ public String findByMaxSatisMusteriId() { return musteriService.findById(repository.findByMaxSatisMusteriId().get(0)).get().getAd() ; } /** * 4. En çok satılan 3 ürünü * select s.urunid from Satis s group by s.urunid order by sum(s.adet) desc limit 3 */ public List<String> findTop3ProductName() { return urunService.findByIdIn(repository.findTop3Product()); }
package com.aysu.service; @Service public class SatisService extends ServiceManager<Satis, Long> { private final ISatisRepository repository; @Autowired private MusteriService musteriService; @Autowired private UrunService urunService; public SatisService(ISatisRepository repository) { super(repository); this.repository = repository; } /** * 1. Kime ne satıldı? Liste olarak görelim. * findAll bu işi görür. */ public List<Satis> findAll() { return repository.findAll(); } /** * 2. A kişisine ne satıldı? liste olarak göster. */ public List<Satis> findAllByMusteriid(Long musteriid) { return repository.findAllByMusteriid(musteriid); } /** * 3. En çok alışveriş yapan müşteri * select musteriid from tblmusteri group by musteriid order by count(musteriid) limit 1 */ public String findByMaxSatisMusteriId() { return musteriService.findById(repository.findByMaxSatisMusteriId().get(0)).get().getAd() ; } /** * 4. En çok satılan 3 ürünü * select s.urunid from Satis s group by s.urunid order by sum(s.adet) desc limit 3 */ public List<String> findTop3ProductName() { return urunService.findByIdIn(repository.findTop3Product()); }
public List<VwSatis> findAllSatisList(){
5
2023-10-27 19:47:03+00:00
4k
SkEditorTeam/SkAnalyzer
MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/MockSkriptBridgeImpl.java
[ { "identifier": "AnalyzerFlag", "path": "api/src/main/java/me/glicz/skanalyzer/AnalyzerFlag.java", "snippet": "@AllArgsConstructor\npublic enum AnalyzerFlag {\n FORCE_VAULT_HOOK(\"--forceVaultHook\"),\n FORCE_REGIONS_HOOK(\"--forceRegionsHook\"),\n ENABLE_PLAIN_LOGGER(\"--enablePlainLogger\");\n\n private static final Map<String, AnalyzerFlag> ARG_TO_FLAG = new HashMap<>();\n\n static {\n for (AnalyzerFlag flag : values())\n ARG_TO_FLAG.put(flag.arg, flag);\n }\n\n private final String arg;\n\n public static AnalyzerFlag getByArg(String arg) {\n return ARG_TO_FLAG.get(arg);\n }\n}" }, { "identifier": "SkAnalyzer", "path": "api/src/main/java/me/glicz/skanalyzer/SkAnalyzer.java", "snippet": "@Getter\npublic class SkAnalyzer {\n public static final String WORKING_DIR_PROPERTY = \"skanalyzer.workingDir\";\n private final EnumSet<AnalyzerFlag> flags;\n private final File workingDirectory;\n private final Logger logger;\n private final AnalyzerServer server;\n private final AddonsLoader addonsLoader;\n\n private SkAnalyzer(AnalyzerFlag[] flags, File workingDirectory) {\n this.flags = EnumSet.noneOf(AnalyzerFlag.class);\n this.flags.addAll(List.of(flags));\n this.workingDirectory = Objects.requireNonNullElse(workingDirectory, AddonsLoader.ADDONS);\n this.logger = LogManager.getLogger(getFlags().contains(AnalyzerFlag.ENABLE_PLAIN_LOGGER) ? \"PlainLogger\" : \"SkAnalyzer\");\n\n logger.info(\"Enabling...\");\n\n this.server = MockBukkit.mock(new AnalyzerServer());\n\n extractEmbeddedAddons();\n\n this.addonsLoader = new AddonsLoader(this);\n this.addonsLoader.loadAddons();\n\n server.startTicking();\n logger.info(\"Successfully enabled. Have fun!\");\n }\n\n @Contract(\" -> new\")\n public static @NotNull Builder builder() {\n return new Builder();\n }\n\n @Unmodifiable\n public EnumSet<AnalyzerFlag> getFlags() {\n return EnumSet.copyOf(flags);\n }\n\n public CompletableFuture<ScriptAnalyzeResult> parseScript(String path) {\n return addonsLoader.getMockSkriptBridge().parseScript(path);\n }\n\n private void extractEmbeddedAddons() {\n logger.info(\"Extracting embedded addons...\");\n\n extractEmbeddedAddon(AddonsLoader.MOCK_SKRIPT);\n extractEmbeddedAddon(AddonsLoader.MOCK_SKRIPT_BRIDGE);\n\n logger.info(\"Successfully extracted embedded addons!\");\n }\n\n private void extractEmbeddedAddon(String name) {\n try (InputStream embeddedJar = getClass().getClassLoader().getResourceAsStream(name + \".embedded\")) {\n Preconditions.checkArgument(embeddedJar != null, \"Couldn't find embedded %s\", name);\n FileUtils.copyInputStreamToFile(embeddedJar, new File(workingDirectory, name));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Data\n @Accessors(fluent = true, chain = true)\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Builder {\n private AnalyzerFlag[] flags = {};\n private File workingDirectory = Optional.ofNullable(System.getProperty(WORKING_DIR_PROPERTY))\n .map(File::new)\n .orElse(null);\n\n public AnalyzerFlag[] flags() {\n return flags;\n }\n\n public Builder flags(@NotNull AnalyzerFlag @NotNull ... flags) {\n this.flags = flags;\n return this;\n }\n\n public SkAnalyzer build() {\n return new SkAnalyzer(flags, workingDirectory);\n }\n }\n}" }, { "identifier": "ReflectionUtil", "path": "MockSkriptBridge/src/main/java/me/glicz/skanalyzer/bridge/util/ReflectionUtil.java", "snippet": "@UtilityClass\npublic class ReflectionUtil {\n private static final Field scriptCommandField, commandPermissionField, commandDescriptionField,\n commandUsageField, argumentTypeField, exprField, skriptEventInfoField, structureField;\n\n static {\n Field tempScriptCommandField = null;\n try {\n tempScriptCommandField = StructCommand.class.getDeclaredField(\"scriptCommand\");\n tempScriptCommandField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n scriptCommandField = tempScriptCommandField;\n\n Field tempCommandPermissionField = null;\n try {\n tempCommandPermissionField = ScriptCommand.class.getDeclaredField(\"permission\");\n tempCommandPermissionField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n commandPermissionField = tempCommandPermissionField;\n\n Field tempCommandDescriptionField = null;\n try {\n tempCommandDescriptionField = ScriptCommand.class.getDeclaredField(\"description\");\n tempCommandDescriptionField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n commandDescriptionField = tempCommandDescriptionField;\n\n Field tempCommandUsageField = null;\n try {\n tempCommandUsageField = ScriptCommand.class.getDeclaredField(\"usage\");\n tempCommandUsageField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n commandUsageField = tempCommandUsageField;\n\n\n Field tempArgumentTypeField = null;\n try {\n tempArgumentTypeField = Argument.class.getDeclaredField(\"type\");\n tempArgumentTypeField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n argumentTypeField = tempArgumentTypeField;\n\n Field tempExprField = null;\n try {\n tempExprField = SkriptEvent.class.getDeclaredField(\"expr\");\n tempExprField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n exprField = tempExprField;\n\n Field tempSkriptEventInfo = null;\n try {\n tempSkriptEventInfo = SkriptEvent.class.getDeclaredField(\"skriptEventInfo\");\n tempSkriptEventInfo.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n skriptEventInfoField = tempSkriptEventInfo;\n\n Field tempStructureField = null;\n try {\n tempStructureField = StructFunction.class.getDeclaredField(\"signature\");\n tempStructureField.setAccessible(true);\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n structureField = tempStructureField;\n }\n\n public static ScriptCommand getScriptCommand(StructCommand command) {\n try {\n return (ScriptCommand) scriptCommandField.get(command);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static String getCommandPermission(ScriptCommand command) {\n try {\n return (String) commandPermissionField.get(command);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static String getCommandDescription(ScriptCommand command) {\n try {\n return (String) commandDescriptionField.get(command);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static String getCommandUsage(ScriptCommand command) {\n try {\n return (String) commandUsageField.get(command);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static ClassInfo<?> getArgumentType(Argument<?> argument) {\n try {\n return (ClassInfo<?>) argumentTypeField.get(argument);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static String getEventExpression(SkriptEvent event) {\n try {\n return (String) exprField.get(event);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static SkriptEventInfo<?> getEventInfo(SkriptEvent event) {\n try {\n return (SkriptEventInfo<?>) skriptEventInfoField.get(event);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n\n public static Signature<?> getFunctionSignature(StructFunction function) {\n try {\n return (Signature<?>) structureField.get(function);\n } catch (Throwable e) {\n e.printStackTrace(System.out);\n return null;\n }\n }\n}" }, { "identifier": "CommandData", "path": "api/src/main/java/me/glicz/skanalyzer/structure/data/CommandData.java", "snippet": "public final class CommandData extends StructureData {\n private final List<String> aliases;\n private final String permission;\n private final String description;\n private final String prefix;\n private final String usage;\n private final List<String> arguments;\n\n public CommandData(int line, String value, List<String> aliases, String permission,\n String description, String prefix, String usage, List<String> arguments) {\n super(line, value);\n this.aliases = aliases;\n this.permission = permission;\n this.description = description;\n this.prefix = prefix;\n this.usage = usage;\n this.arguments = arguments;\n }\n}" }, { "identifier": "EventData", "path": "api/src/main/java/me/glicz/skanalyzer/structure/data/EventData.java", "snippet": "public final class EventData extends StructureData {\n private final String id;\n private final EventPriority eventPriority;\n\n public EventData(int line, String value, String id, EventPriority eventPriority) {\n super(line, value);\n this.id = id;\n this.eventPriority = eventPriority;\n }\n}" }, { "identifier": "FunctionData", "path": "api/src/main/java/me/glicz/skanalyzer/structure/data/FunctionData.java", "snippet": "public final class FunctionData extends StructureData {\n private final boolean local;\n private final Map<String, String> parameters;\n private final String returnType;\n\n public FunctionData(int line, String value, boolean local, Map<String, String> parameters, String returnType) {\n super(line, value);\n this.local = local;\n this.parameters = parameters;\n this.returnType = returnType;\n }\n}" } ]
import ch.njol.skript.ScriptLoader; import ch.njol.skript.Skript; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.command.ScriptCommand; import ch.njol.skript.hooks.VaultHook; import ch.njol.skript.hooks.regions.RegionsPlugin; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptEventInfo; import ch.njol.skript.lang.function.Signature; import ch.njol.skript.log.RedirectingLogHandler; import ch.njol.skript.structures.StructCommand; import ch.njol.skript.structures.StructFunction; import me.glicz.skanalyzer.AnalyzerFlag; import me.glicz.skanalyzer.ScriptAnalyzeResult; import me.glicz.skanalyzer.SkAnalyzer; import me.glicz.skanalyzer.bridge.util.ReflectionUtil; import me.glicz.skanalyzer.structure.ScriptStructure; import me.glicz.skanalyzer.structure.data.CommandData; import me.glicz.skanalyzer.structure.data.EventData; import me.glicz.skanalyzer.structure.data.FunctionData; import org.apache.commons.lang3.StringUtils; import org.skriptlang.skript.lang.script.Script; import java.io.File; import java.io.IOException; import java.nio.file.InvalidPathException; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors;
3,309
package me.glicz.skanalyzer.bridge; public class MockSkriptBridgeImpl extends MockSkriptBridge { public MockSkriptBridgeImpl(SkAnalyzer skAnalyzer) { super(skAnalyzer); parseFlags(); } public void parseFlags() { if (skAnalyzer.getFlags().contains(AnalyzerFlag.FORCE_VAULT_HOOK)) { try { String basePackage = VaultHook.class.getPackage().getName(); Skript.getAddonInstance().loadClasses(basePackage + ".economy"); Skript.getAddonInstance().loadClasses(basePackage + ".chat"); Skript.getAddonInstance().loadClasses(basePackage + ".permission"); skAnalyzer.getLogger().info("Force loaded Vault hook"); } catch (IOException e) { skAnalyzer.getLogger().error("Something went wrong while trying to force load Vault hook", e); } } if (skAnalyzer.getFlags().contains(AnalyzerFlag.FORCE_REGIONS_HOOK)) { try { String basePackage = RegionsPlugin.class.getPackage().getName(); Skript.getAddonInstance().loadClasses(basePackage); skAnalyzer.getLogger().info("Force loaded regions hook"); } catch (IOException e) { skAnalyzer.getLogger().error("Something went wrong while trying to force load regions hook", e); } } } @Override public CompletableFuture<ScriptAnalyzeResult> parseScript(String path) { File file = new File(path); if (!file.exists() || !file.getName().endsWith(".sk")) { skAnalyzer.getLogger().error("Invalid file path"); return CompletableFuture.failedFuture(new InvalidPathException(path, "Provided file doesn't end with '.sk'")); } AnalyzerCommandSender sender = new AnalyzerCommandSender(skAnalyzer); RedirectingLogHandler logHandler = new RedirectingLogHandler(sender, null).start(); return ScriptLoader.loadScripts(file, logHandler, false) .handle((info, throwable) -> { if (throwable != null) { skAnalyzer.getLogger().error("Something went wrong while trying to parse '%s'".formatted(path), throwable); return CompletableFuture.failedFuture(new RuntimeException(throwable)); } return CompletableFuture.completedFuture(info); }) .thenApply(info -> sender.finish(file, handleParsedScript(file))); } private ScriptStructure handleParsedScript(File file) { List<CommandData> commandDataList = new ArrayList<>(); List<EventData> eventDataList = new ArrayList<>(); List<FunctionData> functionDataList = new ArrayList<>(); Script script = ScriptLoader.getScript(file); if (script != null) { script.getStructures().forEach(structure -> { if (structure instanceof StructCommand command) {
package me.glicz.skanalyzer.bridge; public class MockSkriptBridgeImpl extends MockSkriptBridge { public MockSkriptBridgeImpl(SkAnalyzer skAnalyzer) { super(skAnalyzer); parseFlags(); } public void parseFlags() { if (skAnalyzer.getFlags().contains(AnalyzerFlag.FORCE_VAULT_HOOK)) { try { String basePackage = VaultHook.class.getPackage().getName(); Skript.getAddonInstance().loadClasses(basePackage + ".economy"); Skript.getAddonInstance().loadClasses(basePackage + ".chat"); Skript.getAddonInstance().loadClasses(basePackage + ".permission"); skAnalyzer.getLogger().info("Force loaded Vault hook"); } catch (IOException e) { skAnalyzer.getLogger().error("Something went wrong while trying to force load Vault hook", e); } } if (skAnalyzer.getFlags().contains(AnalyzerFlag.FORCE_REGIONS_HOOK)) { try { String basePackage = RegionsPlugin.class.getPackage().getName(); Skript.getAddonInstance().loadClasses(basePackage); skAnalyzer.getLogger().info("Force loaded regions hook"); } catch (IOException e) { skAnalyzer.getLogger().error("Something went wrong while trying to force load regions hook", e); } } } @Override public CompletableFuture<ScriptAnalyzeResult> parseScript(String path) { File file = new File(path); if (!file.exists() || !file.getName().endsWith(".sk")) { skAnalyzer.getLogger().error("Invalid file path"); return CompletableFuture.failedFuture(new InvalidPathException(path, "Provided file doesn't end with '.sk'")); } AnalyzerCommandSender sender = new AnalyzerCommandSender(skAnalyzer); RedirectingLogHandler logHandler = new RedirectingLogHandler(sender, null).start(); return ScriptLoader.loadScripts(file, logHandler, false) .handle((info, throwable) -> { if (throwable != null) { skAnalyzer.getLogger().error("Something went wrong while trying to parse '%s'".formatted(path), throwable); return CompletableFuture.failedFuture(new RuntimeException(throwable)); } return CompletableFuture.completedFuture(info); }) .thenApply(info -> sender.finish(file, handleParsedScript(file))); } private ScriptStructure handleParsedScript(File file) { List<CommandData> commandDataList = new ArrayList<>(); List<EventData> eventDataList = new ArrayList<>(); List<FunctionData> functionDataList = new ArrayList<>(); Script script = ScriptLoader.getScript(file); if (script != null) { script.getStructures().forEach(structure -> { if (structure instanceof StructCommand command) {
ScriptCommand scriptCommand = ReflectionUtil.getScriptCommand(command);
2
2023-10-25 20:04:09+00:00
4k
mcxiaoxiao/library-back
src/main/java/com/main/book/BookResolver.java
[ { "identifier": "BookEntity", "path": "src/main/java/com/main/schema/BookEntity.java", "snippet": "@Entity\n@Table(name = \"book\", schema = \"public\", catalog = \"library\")\npublic class BookEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"bookid\")\n private int bookid;\n @Basic\n @Column(name = \"author\")\n private String author;\n @Basic\n @Column(name = \"level\")\n private Integer level;\n @Basic\n @Column(name = \"type\")\n private String type;\n @Basic\n @Column(name = \"borrowed\")\n private Boolean borrowed;\n @Basic\n @Column(name = \"isbn\")\n private String isbn;\n @Basic\n @Column(name = \"libid\")\n private Integer libid;\n @Basic\n @Column(name = \"name\")\n private String name;\n @Basic\n @Column(name = \"price\")\n private Double price;\n @Basic\n @Column(name = \"publisher\")\n private String publisher;\n @Basic\n @Column(name = \"libname\")\n private String libname;\n @Basic\n @Column(name = \"content\")\n private String content;\n\n public int getBookid() {\n return bookid;\n }\n\n public void setBookid(int bookid) {\n this.bookid = bookid;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public Integer getLevel() {\n return level;\n }\n\n public void setLevel(Integer level) {\n this.level = level;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Boolean getBorrowed() {\n return borrowed;\n }\n\n public void setBorrowed(Boolean borrowed) {\n this.borrowed = borrowed;\n }\n\n public String getIsbn() {\n return isbn;\n }\n\n public void setIsbn(String isbn) {\n this.isbn = isbn;\n }\n\n public Integer getLibid() {\n return libid;\n }\n\n public void setLibid(Integer libid) {\n this.libid = libid;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\n }\n\n public String getPublisher() {\n return publisher;\n }\n\n public void setPublisher(String publisher) {\n this.publisher = publisher;\n }\n\n public String getLibname() {\n return libname;\n }\n\n public void setLibname(String libname) {\n this.libname = libname;\n }\n\n public String getContent() { return content; }\n\n public void setContent(String content) { this.content = content;}\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n BookEntity that = (BookEntity) o;\n\n if (bookid != that.bookid) return false;\n if (author != null ? !author.equals(that.author) : that.author != null) return false;\n if (level != null ? !level.equals(that.level) : that.level != null) return false;\n if (type != null ? !type.equals(that.type) : that.type != null) return false;\n if (borrowed != null ? !borrowed.equals(that.borrowed) : that.borrowed != null) return false;\n if (isbn != null ? !isbn.equals(that.isbn) : that.isbn != null) return false;\n if (libid != null ? !libid.equals(that.libid) : that.libid != null) return false;\n if (name != null ? !name.equals(that.name) : that.name != null) return false;\n if (price != null ? !price.equals(that.price) : that.price != null) return false;\n if (publisher != null ? !publisher.equals(that.publisher) : that.publisher != null) return false;\n if (libname != null ? !libname.equals(that.libname) : that.libname != null) return false;\n if (content != null ? !content.equals(that.content) : that.content != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = bookid;\n result = 31 * result + (author != null ? author.hashCode() : 0);\n result = 31 * result + (level != null ? level.hashCode() : 0);\n result = 31 * result + (type != null ? type.hashCode() : 0);\n result = 31 * result + (borrowed != null ? borrowed.hashCode() : 0);\n result = 31 * result + (isbn != null ? isbn.hashCode() : 0);\n result = 31 * result + (libid != null ? libid.hashCode() : 0);\n result = 31 * result + (name != null ? name.hashCode() : 0);\n result = 31 * result + (price != null ? price.hashCode() : 0);\n result = 31 * result + (publisher != null ? publisher.hashCode() : 0);\n result = 31 * result + (libname != null ? libname.hashCode() : 0);\n result = 31 * result + (content != null ? content.hashCode() : 0);\n return result;\n }\n\n\n}" }, { "identifier": "PagesBookEntity", "path": "src/main/java/com/main/schema/PagesBookEntity.java", "snippet": "public class PagesBookEntity {\n public List<BookEntity> list;\n public int totalCount;\n}" } ]
import com.main.schema.BookEntity; import com.main.schema.PagesBookEntity; import com.netflix.graphql.dgs.DgsComponent; import com.netflix.graphql.dgs.DgsMutation; import com.netflix.graphql.dgs.DgsQuery; import com.netflix.graphql.dgs.InputArgument; import javax.annotation.Resource;
1,631
package com.main.book; @DgsComponent public class BookResolver { @Resource private BookService bookService; @DgsQuery public PagesBookEntity findBookAll(@InputArgument Integer pageNumber, @InputArgument Integer pageSize) { PagesBookEntity p = new PagesBookEntity(); p.list = bookService.findBookPaginated(pageNumber,pageSize).getContent(); p.totalCount = bookService.findBookAll().size(); return p; } @DgsQuery
package com.main.book; @DgsComponent public class BookResolver { @Resource private BookService bookService; @DgsQuery public PagesBookEntity findBookAll(@InputArgument Integer pageNumber, @InputArgument Integer pageSize) { PagesBookEntity p = new PagesBookEntity(); p.list = bookService.findBookPaginated(pageNumber,pageSize).getContent(); p.totalCount = bookService.findBookAll().size(); return p; } @DgsQuery
public BookEntity findBookById(@InputArgument Integer id) {
0
2023-10-30 14:38:00+00:00
4k
kdetard/koki
app/src/main/java/io/github/kdetard/koki/di/NetworkModule.java
[ { "identifier": "AqicnService", "path": "app/src/main/java/io/github/kdetard/koki/aqicn/AqicnService.java", "snippet": "public interface AqicnService {\n @GET(\"https://api.waqi.info/feed/{cityOrStationId}/\")\n Single<AqicnResponse> fromCityOrStationId(@Path(\"cityOrStationId\") String cityOrStationId, @Query(\"token\") String token);\n}" }, { "identifier": "KeycloakApiService", "path": "app/src/main/java/io/github/kdetard/koki/keycloak/KeycloakApiService.java", "snippet": "public interface KeycloakApiService {\n @GET\n Single<ResponseBody> stepOnSignInPage(\n @Url String url,\n @Query(\"client_id\") String clientId,\n @Query(\"redirect_uri\") String username,\n @Query(\"response_type\") String responseType // only supports \"code\" for now\n );\n\n @GET\n Single<ResponseBody> stepOnSignUpPage(@Url String url);\n\n @POST\n @FormUrlEncoded\n Single<KeycloakToken> newSession(\n @Url String url,\n @Field(\"client_id\") String clientId,\n @Field(\"username\") String username,\n @Field(\"password\") String password,\n @Field(\"grant_type\") String grantType // only supports \"password\" for now\n );\n\n @POST\n @FormUrlEncoded\n Single<Response<ResponseBody>> createUser(\n @Url String url,\n @Field(\"username\") String username,\n @Field(\"email\") String email,\n @Field(\"password\") String password,\n @Field(\"password-confirm\") String confirmPassword,\n @Field(\"register\") String register // default is empty\n );\n\n @POST\n @FormUrlEncoded\n Single<Response<ResponseBody>> resetPassword(\n @Url String url,\n @Field(\"username\") String usernameOrEmail,\n @Field(\"login\") String login // default is empty\n );\n\n @POST\n @FormUrlEncoded\n Completable endSession(\n @Url String url,\n @Field(\"client_id\") String clientId,\n @Field(\"refresh_token\") String refreshToken\n );\n\n @POST\n @FormUrlEncoded\n Single<KeycloakToken> refreshSession(\n @Url String url,\n @Field(\"client_id\") String clientId,\n @Field(\"refresh_token\") String refreshToken,\n @Field(\"grant_type\") String grantType // must be \"refresh_token\"\n );\n}" }, { "identifier": "MMKVCookieJar", "path": "app/src/main/java/io/github/kdetard/koki/network/MMKVCookieJar.java", "snippet": "public class MMKVCookieJar implements CookieJar {\n private final MMKV store;\n private final JsonAdapter<Cookie> cookieJsonAdapter;\n\n public MMKVCookieJar(String name) {\n super();\n store = MMKV.mmkvWithID(name, MMKV.MULTI_PROCESS_MODE);\n final var moshi = new Moshi.Builder()\n .add(new CookieJsonAdapter())\n .build();\n cookieJsonAdapter = moshi.adapter(Cookie.class).nullSafe();\n }\n\n private Cookie tryParse(final String cookieJsonString) {\n try {\n return cookieJsonAdapter.fromJson(cookieJsonString);\n } catch (IOException e) {\n return null;\n }\n }\n\n @Override\n public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {\n final var url = httpUrl.host();\n final var cookies = new HashSet<>(store.getStringSet(url, new HashSet<>()));\n\n cookies.addAll(\n list.stream()\n .map(cookieJsonAdapter::toJson)\n .collect(Collectors.toList()));\n\n store.encode(url, cookies);\n }\n\n @NonNull\n @Override\n public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {\n final var url = httpUrl.host();\n final var cookies = new HashSet<>(store.getStringSet(url, new HashSet<>()));\n\n return cookies.stream()\n .map(c -> {\n final var cookie = tryParse(c);\n if (cookie == null || cookie.expiresAt() < System.currentTimeMillis()) {\n return null;\n }\n return cookie;\n })\n .filter(Objects::nonNull)\n .collect(Collectors.toList());\n }\n}" }, { "identifier": "NetworkUtils", "path": "app/src/main/java/io/github/kdetard/koki/network/NetworkUtils.java", "snippet": "public class NetworkUtils {\n public static boolean hasNetwork(@NonNull Context context) {\n var isConnected = false; // Initial Value\n var connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivityManager == null) return false;\n var activeNetwork = connectivityManager.getActiveNetworkInfo();\n if (activeNetwork != null && activeNetwork.isConnected())\n isConnected = true;\n return isConnected;\n }\n\n @Nullable\n public static Request commonAuthenticator(\n @NonNull JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter,\n @NonNull RxDataStore<Settings> settings,\n @Nullable String host,\n @NonNull Request request,\n @Nullable Response response\n ) throws IOException {\n if (host == null || !host.equals(\"uiot.ixxc.dev\") || request.header(\"Authorization\") != null)\n return request;\n\n if (responseCount(response) >= 3) {\n return null; // If we've failed 3 times, give up. - in real life, never give up!!\n }\n\n final var keycloakTokenJson = settings.data()\n .map(Settings::getKeycloakTokenJson)\n .map(json -> json.isEmpty() ? \"{}\" : json)\n .blockingFirst();\n\n final var keycloakToken = keycloakTokenJsonAdapter.fromJson(keycloakTokenJson);\n\n if (keycloakToken != null) {\n Timber.d(\"Authenticator called with accessToken: %s\", keycloakToken.accessToken());\n // Add new header to rejected request and retry it\n return request.newBuilder()\n .header(\"Authorization\", String.format(\"%s %s\", keycloakToken.tokenType(), keycloakToken.accessToken()))\n .build();\n }\n\n return request;\n }\n\n private static int responseCount(Response response) {\n if (response == null) return 0;\n int result = 1;\n while ((response = response.priorResponse()) != null) {\n result++;\n }\n return result;\n }\n\n public static void handleError(@NonNull Context context, @NonNull Throwable throwable) {\n Timber.e(throwable, \"Network Error\");\n if (throwable instanceof IOException) {\n if (!hasNetwork(context)) {\n // No Internet Connection\n Timber.e(\"No Internet Connection\");\n } else {\n // Other IOException\n Timber.e(\"Other IOException\");\n }\n } else {\n // Other Throwable\n Timber.e(\"Other Throwable\");\n }\n }\n}" }, { "identifier": "OpenMeteoService", "path": "app/src/main/java/io/github/kdetard/koki/openmeteo/OpenMeteoService.java", "snippet": "public interface OpenMeteoService {\n @GET(\"https://api.open-meteo.com/v1/forecast?latitude=10.82&longitude=106.62&current=temperature_2m,relative_humidity_2m,apparent_temperature,rain&timezone=auto&forecast_days=1\")\n Single<OpenMeteoResponse> getWeather();\n}" }, { "identifier": "OpenRemoteService", "path": "app/src/main/java/io/github/kdetard/koki/openremote/OpenRemoteService.java", "snippet": "public interface OpenRemoteService {\n @GET(\"/api/master/user/user\")\n Single<User> getUser();\n\n @GET(\"/api/master/asset/{assetId}\")\n Single<Asset<AssetAttribute>> getAsset(@Path(\"assetId\") String assetId);\n\n @POST(\"/api/master/asset/query\")\n @Headers({\n \"accept: application/json\",\n \"Content-Type: application/json\"\n })\n Single<List<Asset<AssetAttribute>>> getAssets();\n\n @GET(\"/api/master/dashboard/all/master\")\n Single<List<Dashboard>> getDashboards();\n\n @GET(\"/realm/accessible\")\n Single<List<Realm>> getRealms();\n\n @POST(\"/api/master/asset/datapoint/{assetId}/attribute/{attributeName}\")\n Single<List<Datapoint>> getDatapoint(\n @Path(\"assetId\") String assetId,\n @Path(\"attributeName\") String attributeName,\n @Body DatapointQuery body\n );\n}" } ]
import android.content.Context; import androidx.datastore.rxjava3.RxDataStore; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import java.io.File; import java.util.Objects; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import dagger.hilt.InstallIn; import dagger.hilt.android.qualifiers.ApplicationContext; import dagger.hilt.components.SingletonComponent; import io.github.kdetard.koki.BuildConfig; import io.github.kdetard.koki.Settings; import io.github.kdetard.koki.aqicn.AqicnService; import io.github.kdetard.koki.keycloak.KeycloakApiService; import io.github.kdetard.koki.keycloak.models.KeycloakToken; import io.github.kdetard.koki.network.CacheInterceptor; import io.github.kdetard.koki.network.MMKVCookieJar; import io.github.kdetard.koki.network.NetworkUtils; import io.github.kdetard.koki.network.StrictAuthenticator; import io.github.kdetard.koki.openmeteo.OpenMeteoService; import io.github.kdetard.koki.openremote.OpenRemoteService; import io.reactivex.rxjava3.schedulers.Schedulers; import okhttp3.Authenticator; import okhttp3.Cache; import okhttp3.CookieJar; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory;
2,377
package io.github.kdetard.koki.di; @Module @InstallIn(SingletonComponent.class) public abstract class NetworkModule { public static final String BASE_URL = "https://uiot.ixxc.dev"; public static final String COOKIE_STORE_NAME = "kookies"; // get it? ;D @Provides @Singleton public static CookieJar provideCookieJar() {
package io.github.kdetard.koki.di; @Module @InstallIn(SingletonComponent.class) public abstract class NetworkModule { public static final String BASE_URL = "https://uiot.ixxc.dev"; public static final String COOKIE_STORE_NAME = "kookies"; // get it? ;D @Provides @Singleton public static CookieJar provideCookieJar() {
return new MMKVCookieJar(COOKIE_STORE_NAME);
2
2023-10-30 00:44:59+00:00
4k
HiNinoJay/easyUsePoi
src/main/java/top/nino/easyUsePoi/word/NinoWordUtil.java
[ { "identifier": "DocumentTool", "path": "src/main/java/top/nino/easyUsePoi/word/module/DocumentTool.java", "snippet": "@Component\n@Slf4j\npublic class DocumentTool {\n\n /**\n * A4纸张 的 宽\n */\n private final static long A4_WIDTH = 12242L;\n\n /**\n * A4纸张 的 高\n */\n private final static long A4_HEIGHT = 15842L;\n\n\n @Autowired\n private ParagraphTool paragraphTool;\n\n @Autowired\n private TableTool tableTool;\n\n @Autowired\n private BarChartTool barChartTool;\n\n @Autowired\n private PiChartTool piChartTool;\n\n\n /**\n * 创建一个 word 自定义 宽 和 高\n * @param width\n * @param height\n * @return\n */\n public XWPFDocument createNewWord(Long width, Long height) {\n XWPFDocument docxDocument = new XWPFDocument();\n CTSectPr sectPr = docxDocument.getDocument().getBody().addNewSectPr();\n// CTPageSz pgsz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz();\n// pgsz.setW(BigInteger.valueOf(width));\n// pgsz.setH(BigInteger.valueOf(height));\n return docxDocument;\n }\n\n /**\n * 创建一个word, 设置该word 的整体默认参数\n * sd\n * 比如:页面大小\n *\n * @return\n */\n public XWPFDocument createA4Word() {\n return createNewWord(A4_WIDTH, A4_HEIGHT);\n }\n\n\n /**\n * 生成一个默认首页\n * @param xwpfDocument\n * @param preData\n */\n private void constructDefaultIndexPage(XWPFDocument xwpfDocument, HashMap<String, String> preData) {\n\n String companyName = preData.get(\"companyName\");\n String productName = preData.get(\"productName\");\n String sampleNum = preData.get(\"collectedSampleCount\");\n String url = preData.get(\"surfacePicture\");\n\n String text2 = productName + \"数据分析结题报告\";\n String text3 = \"easy Use Poi\";\n String text4 = sampleNum + \"例数据分析\";\n String text5 = \"Nino | \" + LocalDateTime.now().getYear() + \"年\" + LocalDateTime.now().getMonthValue() + \"月\";\n\n XWPFParagraph paragraph = drawDefaultAnnouncementParagraph(xwpfDocument);\n drawDefaultPngPicture(paragraph, url);\n drawDefaultAnnouncementText(paragraph, companyName);\n drawAnnouncementTextColorAndSize(paragraph, text2, ColorEnum.CUSTOM_COLOR.getHexCode(), FontSizeEnum.TWO.getSizeInPoints(), true);\n drawDefaultMainBodyText(paragraph, text3);\n drawDefaultMainBodyText(paragraph, text4);\n drawNewBreak(xwpfDocument, 5);\n drawDefaultMainBodyText(paragraph, text5);\n\n drawNewPage(xwpfDocument);\n }\n\n\n /**\n * 新开一页\n * @param docxDocument\n */\n public void drawNewPage(XWPFDocument docxDocument) {\n docxDocument.createParagraph().createRun().addBreak(BreakType.PAGE);\n }\n\n\n /**\n * 添加回车\n * @param docxDocument\n * @param breakNum\n */\n public void drawNewBreak(XWPFDocument docxDocument, Integer breakNum) {\n XWPFRun run = docxDocument.createParagraph().createRun();\n for(int i = 0; i < breakNum; i++) {\n run.addBreak();\n }\n }\n\n\n /**\n * 根据 wordModule 生成 一个段落\n * @param xwpfDocument\n * @param wordModule\n * @return\n */\n public XWPFParagraph drawParagraph(XWPFDocument xwpfDocument, WordModule wordModule) {\n return paragraphTool.drawParagraph(xwpfDocument, wordModule);\n }\n\n /**\n * 在 段落 中 添加多段文字\n * @param paragraph\n * @param textList\n * @param preData\n */\n public void drawText(XWPFParagraph paragraph, List<WordText> textList, HashMap<String, String> preData) {\n textList.forEach(textPo -> {\n paragraphTool.drawText(paragraph, textPo, preData);\n });\n }\n\n /**\n * 根据 wordModule 生成一个表格\n * @param xwpfDocument\n * @param wordModule\n */\n public void drawTable(XWPFDocument xwpfDocument, WordModule wordModule) {\n tableTool.drawTable(xwpfDocument, wordModule);\n }\n\n /**\n * 根据 wordModule 生成 一个 柱状图\n * @param xwpfDocument\n * @param wordModule\n */\n public void drawBarChart(XWPFDocument xwpfDocument, WordModule wordModule) {\n barChartTool.drawBarChart(xwpfDocument, wordModule);\n }\n\n /**\n * 根据 wordModule 生成 一个 饼状图\n * @param xwpfDocument\n * @param wordModule\n */\n public void drawPiChart(XWPFDocument xwpfDocument, WordModule wordModule) {\n piChartTool.drawPieChart(xwpfDocument, wordModule);\n }\n\n\n /**\n * 提供一个默认的正文段落:靠左,首行缩进为 0, 行间距为1.5\n * @param xwpfDocument\n * @return\n */\n public XWPFParagraph drawDefaultMainBodyParagraph(XWPFDocument xwpfDocument) {\n return paragraphTool.drawDefaultMainBodyParagraph(xwpfDocument);\n }\n\n /**\n * 提供一个默认的公告文字段落:居中,首行缩进为 0, 行间距为1.5\n * @param xwpfDocument\n * @return\n */\n public XWPFParagraph drawDefaultAnnouncementParagraph(XWPFDocument xwpfDocument) {\n return paragraphTool.drawDefaultAnnouncementParagraph(xwpfDocument);\n }\n\n /**\n * 在 段落中 新增一段 默认正文格式的文字:宋体,四号字体大小,黑色,不加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultMainBodyText(XWPFParagraph paragraph, String text) {\n paragraphTool.drawDefaultMainBodyText(paragraph, text);\n }\n\n\n /**\n * 默认 小标题 文本格式: 黑体,三号字体大小,黑色,加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultTitleText(XWPFParagraph paragraph, String text) {\n paragraphTool.drawDefaultTitleText(paragraph, text);\n }\n\n /**\n * 默认 居中公告标题 文本格式: 黑体,三号字体大小,黑色,加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultAnnouncementText(XWPFParagraph paragraph, String text) {\n paragraphTool.drawDefaultAnnouncementText(paragraph, text);\n }\n\n /**\n * 可变化 公告文字 的颜色 和 字体大小\n * @param paragraph\n * @param text\n * @param colorHex\n * @param fontSize\n * @param boldFlag\n */\n public void drawAnnouncementTextColorAndSize(XWPFParagraph paragraph, String text, String colorHex, Integer fontSize, boolean boldFlag) {\n paragraphTool.drawAnnouncementTextColorAndSize(paragraph, text, colorHex, fontSize, boldFlag);\n }\n\n /**\n * 给段落 增加一张图片\n *\n * @param paragraph\n * @param pictureUrl\n */\n public void drawDefaultPngPicture(XWPFParagraph paragraph, String pictureUrl) {\n paragraphTool.drawDefaultPngPicture(paragraph, pictureUrl);\n }\n\n\n /**\n * 绘画一个表格\n * @param xwpfDocument\n * @param rows\n * @param cols\n * @param text\n */\n public void drawTable(XWPFDocument xwpfDocument, int rows, int cols, List<List<String>> text) {\n tableTool.drawTable(xwpfDocument, rows, cols, text);\n }\n\n /**\n * 绘画一个饼状图\n * @param docxDocument\n * @param charTitle\n * @param xAxisData\n * @param yAxisData\n */\n public void drawPieChart(XWPFDocument docxDocument, String charTitle, String[] xAxisData, Integer[] yAxisData) {\n piChartTool.drawPieChart(docxDocument, charTitle, xAxisData, yAxisData);\n }\n\n /**\n * 绘画一个 默认样式 柱状图\n * @param docxDocument\n * @param chartTile\n * @param xAxisName\n * @param xAxisData\n * @param yAxisName\n * @param yAxisData\n * @param titleName\n * @param color\n */\n public void drawDefaultBarChart(XWPFDocument docxDocument, String chartTile, String xAxisName, String[] xAxisData, String yAxisName, Integer[] yAxisData, String titleName, PresetColor color) {\n barChartTool.drawDefaultBarChart(docxDocument, chartTile, xAxisName, xAxisData, yAxisName, yAxisData, titleName, color);\n }\n\n\n\n\n /**\n * 通过 json 识别后的 vo 自动生成 word\n * @param wordJsonVo\n * @return\n */\n public XWPFDocument constructWordByVo(WordJsonVo wordJsonVo) {\n\n HashMap<String, String> preData = wordJsonVo.getPreData();\n if(CollectionUtils.isEmpty(wordJsonVo.getWordBody())) {\n return null;\n }\n\n XWPFDocument xwpfDocument = createA4Word();\n\n constructDefaultIndexPage(xwpfDocument, preData);\n\n wordJsonVo.getWordBody().forEach(wordModule -> {\n\n if(wordModule.getType().equals(ModuleTypeEnum.PARAGRAPH.getName())) {\n XWPFParagraph paragraph = drawParagraph(xwpfDocument, wordModule);\n // todo 画图\n drawText(paragraph, wordModule.getTextList(), preData);\n }\n\n if(wordModule.getType().equals(ModuleTypeEnum.TABLE.getName())) {\n drawTable(xwpfDocument, wordModule);\n }\n\n if(wordModule.getType().equals(ModuleTypeEnum.BAR_CHART.getName())) {\n drawBarChart(xwpfDocument, wordModule);\n }\n\n if(wordModule.getType().equals(ModuleTypeEnum.Pi_CHART.getName())) {\n drawPiChart(xwpfDocument, wordModule);\n }\n\n if(ObjectUtils.isNotEmpty(wordModule.getPageBreak()) && wordModule.getPageBreak()) {\n drawNewPage(xwpfDocument);\n }\n });\n return xwpfDocument;\n }\n\n\n /**\n * 根据传入的文件名生成word\n * @param xwpfDocument\n * @param fileName\n */\n public void exportWord(XWPFDocument xwpfDocument, String fileName) {\n String path = fileName + \".docx\";\n File file = new File(path);\n FileOutputStream stream = null;\n try {\n stream = new FileOutputStream(file);\n xwpfDocument.write(stream);\n } catch (IOException e) {\n throw new RuntimeException(e);\n } finally {\n try {\n stream.close();\n } catch (IOException e) {\n log.error(\"请检查你是否已经打开该word文件!如果已经打开,请关闭!\");\n }\n }\n log.info(\"word生成完成!\");\n }\n\n /**\n * 生成该word\n *\n * @param docxDocument\n */\n public void exportWord(XWPFDocument docxDocument) {\n exportWord(docxDocument, \"json生成word\");\n }\n}" }, { "identifier": "WordJsonVo", "path": "src/main/java/top/nino/easyUsePoi/word/module/data/WordJsonVo.java", "snippet": "@Data\npublic class WordJsonVo {\n\n /**\n * 一些提前准备的数据\n */\n private HashMap<String, String> preData;\n\n\n /**\n * 该word的组成\n */\n private List<WordModule> wordBody;\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import top.nino.easyUsePoi.word.module.DocumentTool; import top.nino.easyUsePoi.word.module.data.WordJsonVo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection;
3,407
package top.nino.easyUsePoi.word; /** * 初步成果:手动传入参数,绘制出我们要的word样式 * 最终成功:只需传入定义好的json,即可自动绘制出我们要的word样式 * * @author zengzhongjie */ @Slf4j @Component public class NinoWordUtil { @Autowired
package top.nino.easyUsePoi.word; /** * 初步成果:手动传入参数,绘制出我们要的word样式 * 最终成功:只需传入定义好的json,即可自动绘制出我们要的word样式 * * @author zengzhongjie */ @Slf4j @Component public class NinoWordUtil { @Autowired
private DocumentTool documentTool;
0
2023-10-31 19:43:22+00:00
4k
Verionn/MoneyMinder
src/main/java/com/minder/MoneyMinder/controllers/item/ItemController.java
[ { "identifier": "ItemServiceImpl", "path": "src/main/java/com/minder/MoneyMinder/services/implementations/ItemServiceImpl.java", "snippet": "@Service\npublic class ItemServiceImpl implements ItemService {\n private final ItemRepository itemRepository;\n private final ListRepository listRepository;\n private final PurchasedItemMapper purchasedItemMapper = PurchasedItemMapper.INSTANCE;\n private final PurchasedItemRepository purchasedItemRepository;\n\n @Autowired\n public ItemServiceImpl(ItemRepository itemRepository, ListRepository listRepository, PurchasedItemRepository purchasedItemRepository) {\n this.itemRepository = itemRepository;\n this.listRepository = listRepository;\n this.purchasedItemRepository = purchasedItemRepository;\n }\n\n @Override\n public ItemEntity addItem(ItemEntity itemEntity, Long listId) {\n itemEntity.setListId(listId);\n itemEntity.setTimeCreated(LocalDateTime.now());\n return itemRepository.save(itemEntity);\n }\n\n @Override\n public Optional<ItemEntity> getItem(Long itemId) {\n return itemRepository.findById(itemId);\n }\n\n @Override\n public List<ItemEntity> getItemsByListId(Long listId) {\n return itemRepository.findByListId(listId);\n }\n\n @Override\n public void deleteItem(Long itemID) {\n itemRepository.deleteById(itemID);\n }\n\n @Override\n public Optional<ItemEntity> updateItem(Long itemId, UpdateItemRequestBody updateItemRequestBody) {\n return itemRepository.findById(itemId)\n .map(itemEntity -> updateItemEntity(itemEntity, updateItemRequestBody))\n .map(itemRepository::save);\n }\n\n @Override\n public boolean existsById(Long itemId) {\n return itemRepository.existsById(itemId);\n }\n\n @Override\n @Transactional\n public void deleteItemsByListId(Long listId) {\n itemRepository.deleteAllByListId(listId);\n }\n\n @Override\n public PurchasedItemResponse markItemAsPurchased(PurchasedItemRecord purchasedItemRecord) {\n return purchasedItemMapper.purchasedItemRecordToPurchasedItemResponse(\n purchasedItemRepository.save(purchasedItemMapper.purchasedItemRecordToPurchasedItemEntity(purchasedItemRecord)));\n }\n\n @Override\n public boolean checkIfItemIsOnTheList(Long itemId, Long listId) {\n return itemRepository.getReferenceById(itemId).getListId().equals(listId);\n }\n\n private ItemEntity updateItemEntity(ItemEntity itemEntity, UpdateItemRequestBody updateItemRequestBody) {\n itemEntity.setName(updateItemRequestBody.name());\n itemEntity.setCategoryId(updateItemRequestBody.categoryId());\n itemEntity.setPrice(updateItemRequestBody.price());\n itemEntity.setAmount(updateItemRequestBody.amount());\n itemEntity.setWeight(updateItemRequestBody.weight());\n itemEntity.setListId(updateItemRequestBody.listId());\n return itemEntity;\n }\n}" }, { "identifier": "ListServiceImpl", "path": "src/main/java/com/minder/MoneyMinder/services/implementations/ListServiceImpl.java", "snippet": "@Service\npublic class ListServiceImpl implements ListService {\n\n private final ListRepository listRepository;\n\n @Autowired\n public ListServiceImpl(ListRepository listRepository) {\n this.listRepository = listRepository;\n }\n\n public Optional<ListEntity> getList(Long listId) {\n return listRepository.findById(listId);\n }\n\n public List<ListEntity> getLists() {\n return listRepository.findAll();\n }\n\n public ListEntity addList(ListEntity listEntity) {\n return listRepository.save(updateListEntity(listEntity));\n }\n\n public void deleteList(Long listId) {\n listRepository.deleteById(listId);\n }\n\n public Optional<ListEntity> updateList(Long listId, UpdateListRequestBody updateListRequestBody) {\n return listRepository.findById(listId)\n .map(listEntity -> updateListEntity(listEntity, updateListRequestBody))\n .map(listRepository::save);\n }\n\n public double getFullPrice(Long listId) {\n return listRepository.findTotalAmountByListId(listId);\n }\n\n public boolean existsById(Long listId) {\n return listRepository.existsById(listId);\n }\n\n private ListEntity updateListEntity(ListEntity listEntity, UpdateListRequestBody updateListRequestBody) {\n listEntity.setName(updateListRequestBody.name());\n if (updateListRequestBody.description() == null) {\n listEntity.setDescription(\"\");\n } else {\n listEntity.setDescription(updateListRequestBody.description());\n }\n return listEntity;\n }\n\n private ListEntity updateListEntity(ListEntity listEntity) {\n if (listEntity.getDescription() == null) {\n listEntity.setDescription(\"\");\n }\n listEntity.setDescription(listEntity.getDescription());\n return listEntity;\n }\n}" }, { "identifier": "ItemMapper", "path": "src/main/java/com/minder/MoneyMinder/services/mappers/ItemMapper.java", "snippet": "@Mapper\npublic interface ItemMapper {\n ItemMapper INSTANCE = Mappers.getMapper(ItemMapper.class);\n\n ItemEntity createItemRequestBodyToItem(CreateItemRequestBody createItemRequestBody);\n\n ItemEntity updateItemRequestBodyToItem(UpdateItemRequestBody updateItemRequestBody);\n\n ItemResponse itemToItemResponse(ItemEntity itemEntity);\n\n List<ItemResponse> itemsToItemResponses(List<ItemEntity> items);\n}" }, { "identifier": "PurchasedItemMapper", "path": "src/main/java/com/minder/MoneyMinder/services/mappers/PurchasedItemMapper.java", "snippet": "@Mapper\npublic interface PurchasedItemMapper {\n PurchasedItemMapper INSTANCE = Mappers.getMapper(PurchasedItemMapper.class);\n\n PurchasedItemRecord itemEntityToPurchasedItemRecord(ItemEntity itemEntity, LocalDateTime timeBought);\n\n PurchasedItemEntity purchasedItemRecordToPurchasedItemEntity(PurchasedItemRecord purchasedItemRecord);\n\n PurchasedItemResponse purchasedItemRecordToPurchasedItemResponse(PurchasedItemEntity purchasedItemEntity);\n\n List<PurchasedItemResponse> purchasedItemListEntityToPurchasedItemListResponse(List<PurchasedItemEntity> purchasedItemsByCategoryId);\n List<PurchasedItemNameResponse> purchasedItemListEntityToPurchasedItemNameListResponse (List<PurchasedItemEntity> purchasedItemEntities);\n}" } ]
import com.minder.MoneyMinder.controllers.item.dto.*; import com.minder.MoneyMinder.controllers.purchasedItem.dto.PurchasedItemResponse; import com.minder.MoneyMinder.services.*; import com.minder.MoneyMinder.services.implementations.ItemServiceImpl; import com.minder.MoneyMinder.services.implementations.ListServiceImpl; import com.minder.MoneyMinder.services.mappers.ItemMapper; import com.minder.MoneyMinder.services.mappers.PurchasedItemMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime;
1,623
package com.minder.MoneyMinder.controllers.item; @RestController @RequestMapping(path = "/lists") public class ItemController { private final ItemService itemService; private final ListService listService; private final PurchasedItemService purchasedItemService; private final ItemMapper itemMapper = ItemMapper.INSTANCE; private final PurchasedItemMapper purchasedItemMapper = PurchasedItemMapper.INSTANCE; @Autowired
package com.minder.MoneyMinder.controllers.item; @RestController @RequestMapping(path = "/lists") public class ItemController { private final ItemService itemService; private final ListService listService; private final PurchasedItemService purchasedItemService; private final ItemMapper itemMapper = ItemMapper.INSTANCE; private final PurchasedItemMapper purchasedItemMapper = PurchasedItemMapper.INSTANCE; @Autowired
public ItemController(ItemServiceImpl itemService, ListServiceImpl listService, PurchasedItemService purchasedItemService) {
0
2023-10-25 12:45:10+00:00
4k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/HttpBridge.java
[ { "identifier": "DataRetrievalError", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalError.java", "snippet": "public class DataRetrievalError extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalError.class);\n\n public DataRetrievalError(String message) {\n super(message);\n }\n\n public DataRetrievalError(String message, Throwable cause) {\n super(message, cause);\n }\n\n public DataRetrievalError(Throwable cause) {\n super(cause);\n }\n \n \n}" }, { "identifier": "DataRetrievalRuntimeException", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalRuntimeException.java", "snippet": "public class DataRetrievalRuntimeException extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogger(DataRetrievalRuntimeException.class);\n\n public DataRetrievalRuntimeException(String message) {\n super(message);\n }\n\n public DataRetrievalRuntimeException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public DataRetrievalRuntimeException(Throwable cause) {\n super(cause);\n }\n\n public DataRetrievalRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n \n \n}" }, { "identifier": "AcknowledgementMarketDocument", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/AcknowledgementMarketDocument.java", "snippet": "@XmlRootElement(name = \"Acknowledgement_MarketDocument\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class AcknowledgementMarketDocument {\n\n @XmlElement(name = \"mRID\", required = true)\n private String mRID;\n\n @XmlElement(name = \"createdDateTime\")\n protected XMLGregorianCalendar createdDateTime;\n\n @XmlElement(name = \"sender_MarketParticipant.mRID\")\n private PartyIDString senderMarketParticipant;\n\n @XmlElement(name = \"receiver_MarketParticipant.mRID\")\n private PartyIDString receiverMarketParticipant;\n\n @XmlElement(name = \"received_MarketDocument.createdDateTime\")\n private XMLGregorianCalendar receivedMarketDocumentCreatedDateTime;\n\n @XmlElement(name = \"Reason\")\n private Reason reason;\n\n public String getmRID() {\n return mRID;\n }\n\n public void setmRID(String mRID) {\n this.mRID = mRID;\n }\n\n public XMLGregorianCalendar getCreatedDateTime() {\n return createdDateTime;\n }\n\n public void setCreatedDateTime(XMLGregorianCalendar createdDateTime) {\n this.createdDateTime = createdDateTime;\n }\n\n public PartyIDString getSenderMarketParticipant() {\n return senderMarketParticipant;\n }\n\n public void setSenderMarketParticipant(PartyIDString senderMarketParticipant) {\n this.senderMarketParticipant = senderMarketParticipant;\n }\n\n public PartyIDString getReceiverMarketParticipant() {\n return receiverMarketParticipant;\n }\n\n public void setReceiverMarketParticipant(PartyIDString receiverMarketParticipant) {\n this.receiverMarketParticipant = receiverMarketParticipant;\n }\n\n public XMLGregorianCalendar getReceivedMarketDocumentCreatedDateTime() {\n return receivedMarketDocumentCreatedDateTime;\n }\n\n public void setReceivedMarketDocumentCreatedDateTime(XMLGregorianCalendar receivedMarketDocumentCreatedDateTime) {\n this.receivedMarketDocumentCreatedDateTime = receivedMarketDocumentCreatedDateTime;\n }\n\n public Reason getReason() {\n return reason;\n }\n\n public void setReason(Reason reason) {\n this.reason = reason;\n }\n\n \n \n}" }, { "identifier": "JAXBDeserializerHelper", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/custom/JAXBDeserializerHelper.java", "snippet": "public class JAXBDeserializerHelper {\n\n private static final Logger LOGGER = LogManager.getLogger(JAXBDeserializerHelper.class);\n\n private JAXBDeserializerHelper() {\n // API Class\n }\n\n public static <T> T doJAXBUnmarshall(InputStream source, Class<T> clazz) throws JAXBException {\n return doJAXBUnmarshall(source, clazz, false);\n }\n \n\n public static <T> T doJAXBUnmarshall(InputStream source, Class<T> clazz, boolean verbose) throws JAXBException{\n try {\n SAXParserFactory spf = SAXParserFactory.newInstance();\n spf.setNamespaceAware(true);\n\n // Apply the filter\n XMLFilter filter = new NamespaceFilter(\"urn:iec62325.351:tc57wg16:451-6:generationloaddocument:3:0\", true);\n SAXParser saxParser = spf.newSAXParser();\n XMLReader xr = saxParser.getXMLReader();\n filter.setParent(xr);\n\n // Do the unmarshalling\n JAXBContext context = JAXBContext.newInstance(clazz);\n Unmarshaller unmarshaller = context.createUnmarshaller();\n if (verbose) {\n unmarshaller.setEventHandler(new ValidationEventHandler() {\n public boolean handleEvent(ValidationEvent event) {\n System.out.println(\"Event: \" + event.getMessage());\n System.out.println(\"Severity: \" + event.getSeverity());\n return true; // Continue processing.\n }\n });\n }\n Source src = new SAXSource(filter, new InputSource(source));\n return (T) unmarshaller.unmarshal(src);\n } catch (ParserConfigurationException | SAXException ex) {\n throw new JAXBException(ex);\n }\n }\n\n}" } ]
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Scanner; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.XmlStreamReader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalError; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.AcknowledgementMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.custom.JAXBDeserializerHelper;
1,929
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * This class builds the request with the provided parameters, performs it and returns the expected result, or throws * exceptions when things do not behave as expected. Errors should be logged, but simple * {@link DataRetrievalRuntimeException} should be throw when it is impossible to retrieve data. * * @author Andres Bel Alonso */ public class HttpBridge { private static final Logger LOGGER = LogManager.getLogger(HttpBridge.class); // TODO : make request configurable private final static LeakyBucket throttler = new LeakyBucket(1); // 2 request per second, 120 per minute approx is under the 400 of ENTSOE platform private static RequestCache REQUEST_CACHE = new RequestCache(); public static void setRequestCache(RequestCache cache) { REQUEST_CACHE = cache; } private final boolean useCache; public HttpBridge(boolean useCache) { this.useCache = useCache; } /** * Send request via GET method. * * @param <T> * @param params - map including all URL params * @param urlName - base URL * @param jaxbContext * @throws DataRetrievalRuntimeException When there is an error parsing or making the http request. * @return - plain XML content */
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * This class builds the request with the provided parameters, performs it and returns the expected result, or throws * exceptions when things do not behave as expected. Errors should be logged, but simple * {@link DataRetrievalRuntimeException} should be throw when it is impossible to retrieve data. * * @author Andres Bel Alonso */ public class HttpBridge { private static final Logger LOGGER = LogManager.getLogger(HttpBridge.class); // TODO : make request configurable private final static LeakyBucket throttler = new LeakyBucket(1); // 2 request per second, 120 per minute approx is under the 400 of ENTSOE platform private static RequestCache REQUEST_CACHE = new RequestCache(); public static void setRequestCache(RequestCache cache) { REQUEST_CACHE = cache; } private final boolean useCache; public HttpBridge(boolean useCache) { this.useCache = useCache; } /** * Send request via GET method. * * @param <T> * @param params - map including all URL params * @param urlName - base URL * @param jaxbContext * @throws DataRetrievalRuntimeException When there is an error parsing or making the http request. * @return - plain XML content */
public <T> T doGetOperation(Map<String, String> params, String urlName, Class<T> projectClass) throws DataRetrievalRuntimeException {
1
2023-10-30 09:09:53+00:00
4k
EricFan2002/SC2002
src/app/controller/deserializer/UserDeserializer.java
[ { "identifier": "Student", "path": "src/app/entity/user/Student.java", "snippet": "public class Student extends User {\n\n /**\n * The number of points accumulated by the student.\n */\n protected int points;\n\n /**\n * The list of camps attended by the student.\n */\n private ArrayList<Camp> attendedCampList;\n\n /**\n * The list of camps where the student participated as a committee member.\n */\n private ArrayList<Camp> committeeCampList;\n\n /**\n * The list of enquiries submitted by the student.\n */\n private ArrayList<Enquiry> enquiryList;\n\n /**\n * The list of suggestions submitted by the student.\n */\n private ArrayList<Suggestion> suggestionList;\n\n /**\n * Constructs a Student object with the specified ID, name, and faculty.\n *\n * @param ID The ID of the student.\n * @param name The name of the student.\n * @param faculty The faculty of the student.\n */\n public Student(String ID, String name, String faculty) {\n super(ID, name, faculty);\n points = 0;\n attendedCampList = new ArrayList<Camp>();\n committeeCampList = new ArrayList<Camp>();\n enquiryList = new ArrayList<Enquiry>();\n suggestionList = new ArrayList<Suggestion>();\n }\n\n /**\n * Constructs a Student object with default values.\n */\n public Student() {\n super();\n attendedCampList = new ArrayList<Camp>();\n committeeCampList = new ArrayList<Camp>();\n enquiryList = new ArrayList<Enquiry>();\n suggestionList = new ArrayList<Suggestion>();\n }\n\n /**\n * Gets the number of points accumulated by the student.\n *\n * @return The number of points.\n */\n public int getPoints() {\n return points;\n }\n\n /**\n * Adds points to the total points accumulated by the student.\n *\n * @param points The points to be added.\n */\n public void addPoints(int points) {\n this.points += points;\n }\n\n /**\n * Sets the total points accumulated by the student.\n *\n * @param points The total points to be set.\n */\n public void setPoints(int points) {\n this.points = points;\n }\n\n /**\n * Adds a camp to the list of camps where the student participated as a committee member.\n *\n * @param camp The camp to be added.\n */\n public void addCommitteeCamp(Camp camp) {\n committeeCampList.add(camp);\n }\n\n /**\n * Adds a camp to the list of camps attended by the student.\n *\n * @param camp The camp to be added.\n */\n public void addAttendedCamp(Camp camp) {\n attendedCampList.add(camp);\n }\n\n /**\n * Removes a camp from the list of camps where the student participated as a committee member.\n *\n * @param camp The camp to be removed.\n */\n public void removeCommitteeCamp(Camp camp) {\n committeeCampList.remove(camp);\n }\n\n /**\n * Removes a camp from the list of camps attended by the student.\n *\n * @param camp The camp to be removed.\n */\n public void removeAttendedCamp(Camp camp) {\n attendedCampList.remove(camp);\n }\n\n /**\n * Gets the list of camps attended by the student.\n *\n * @return An {@code ArrayList} representing the attended camps.\n */\n public ArrayList<Camp> getAttendedCampList() {\n return attendedCampList;\n }\n\n /**\n * Gets the list of camps where the student participated as a committee member.\n *\n * @return An {@code ArrayList} representing the committee camps.\n */\n public ArrayList<Camp> getCommitteeCampList() {\n return committeeCampList;\n }\n\n /**\n * Adds an enquiry to the list of enquiries submitted by the student.\n *\n * @param enquiry The enquiry to be added.\n */\n public void addEnquiry(Enquiry enquiry) {\n enquiryList.add(enquiry);\n }\n\n /**\n * Removes an enquiry from the list of enquiries submitted by the student.\n *\n * @param enquiry The enquiry to be removed.\n */\n public void removeEnquiry(Enquiry enquiry) {\n enquiryList.remove(enquiry);\n }\n\n /**\n * Gets the list of enquiries submitted by the student.\n *\n * @return An {@code ArrayList} representing the enquiries.\n */\n public ArrayList<Enquiry> getEnquiryList() {\n return enquiryList;\n }\n\n /**\n * Adds a suggestion to the list of suggestions submitted by the student.\n *\n * @param suggestion The suggestion to be added.\n */\n public void addSuggestion(Suggestion suggestion) {\n suggestionList.add(suggestion);\n }\n\n /**\n * Removes a suggestion from the list of suggestions submitted by the student.\n *\n * @param suggestion The suggestion to be removed.\n */\n public void removeSuggestion(Suggestion suggestion) {\n suggestionList.remove(suggestion);\n }\n\n /**\n * Gets the list of suggestions submitted by the student.\n *\n * @return An {@code ArrayList} representing the suggestions.\n */\n public ArrayList<Suggestion> getSuggestionList() {\n return suggestionList;\n }\n}" }, { "identifier": "User", "path": "src/app/entity/user/User.java", "snippet": "public abstract class User implements ITaggedItem {\n\n /**\n * The user's ID.\n */\n protected String ID;\n\n /**\n * The user's name.\n */\n protected String name;\n\n /**\n * The user's password (default set to 'password').\n */\n protected String password;\n\n /**\n * The user's faculty.\n */\n protected String school;\n\n /**\n * Constructs a User object with default values.\n */\n public User() {\n this.ID = \"\";\n this.name = \"\";\n this.password = \"password\";\n this.school = \"\";\n }\n\n /**\n * Constructs a User object with the specified ID, name, and faculty.\n *\n * @param ID The ID of the user.\n * @param name The name of the user.\n * @param faculty The faculty of the user.\n */\n public User(String ID, String name, String faculty) {\n this.ID = ID;\n this.name = name;\n this.password = \"password\";\n this.school = faculty;\n }\n\n /**\n * Gets the name of the user.\n *\n * @return The name of the user.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets the ID of the user.\n *\n * @return The ID of the user.\n */\n public String getID() {\n return ID;\n }\n\n /**\n * Sets the ID of the user.\n *\n * @param ID The ID to be set.\n */\n public void setID(String ID) {\n this.ID = ID;\n }\n\n /**\n * Sets the faculty of the user.\n *\n * @param school The faculty to be set.\n */\n public void setSchool(String school) {\n this.school = school;\n }\n\n /**\n * Gets the faculty of the user.\n *\n * @return The faculty of the user.\n */\n public String getSchool() {\n return school;\n }\n\n /**\n * Gets the password of the user.\n *\n * @return The password of the user.\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Gets the email of the user.\n *\n * @return The email of the user.\n */\n public String getEmail() {\n return ID + \"@e.ntu.edu.sg\";\n }\n\n /**\n * Sets the name of the user.\n *\n * @param name The name to be set.\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Sets the password of the user.\n *\n * @param password The password to be set.\n */\n public void setPassword(String password) {\n this.password = password;\n }\n}" }, { "identifier": "UserFactory", "path": "src/app/entity/user/UserFactory.java", "snippet": "public class UserFactory {\n\n /**\n * Creates and returns a user object based on the specified user type.\n *\n * @param userType The type of the user (e.g., \"student\" or \"staff\").\n * @param ID The ID of the user.\n * @param name The name of the user.\n * @param faculty The faculty of the user.\n * @return A user object of the specified type, or {@code null} if the user type is unknown.\n */\n public static User getUser(String userType, String ID, String name, String faculty) {\n if (userType.equalsIgnoreCase(\"student\")) {\n return new Student(ID, name, faculty);\n } else if (userType.equalsIgnoreCase(\"staff\")) {\n return new Staff(ID, name, faculty);\n } else {\n return null;\n }\n }\n}" }, { "identifier": "UserList", "path": "src/app/entity/user/UserList.java", "snippet": "public class UserList extends RepositoryList<User> implements IFilterableByID<User>, IFilterableBySchool<User> {\n\n /**\n * Constructs a UserList object with the specified list of users.\n *\n * @param all The list of users to be included in the user list.\n */\n public UserList(List<User> all) {\n super(all);\n }\n\n /**\n * Constructs an empty UserList object.\n */\n public UserList() {\n super();\n }\n\n /**\n * Filters the user list by the specified user ID.\n *\n * @param id The user ID to filter by.\n * @return A UserList containing users with the specified ID.\n */\n public UserList filterByID(String id) {\n UserList result = new UserList();\n for (User user : super.all) {\n if (user.getID().equals(id)) {\n result.add(user);\n }\n }\n return result;\n }\n\n public UserList filterBySchool(String school){\n UserList result = new UserList();\n for(User user: super.all){\n if(Objects.equals(user.getSchool(), school)){\n result.add(user);\n }\n }\n return result;\n }\n\n /**\n * Converts the user list to an array of users.\n *\n * @return An array of users.\n */\n public User[] toArray() {\n return super.all.toArray(new User[super.all.size()]);\n }\n\n /**\n * Checks if the user list is empty.\n *\n * @return {@code true} if the user list is empty, {@code false} otherwise.\n */\n public boolean isEmpty() {\n return super.all.isEmpty();\n }\n\n /**\n * Serializes the user list and represents its data as an ArrayList of ArrayList of Strings.\n *\n * @return An {@code ArrayList<ArrayList<String>>} representing the serialized data of the user list.\n */\n public ArrayList<ArrayList<String>> serialize() {\n ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();\n all.forEach(userRaw -> {\n User user = userRaw;\n ArrayList<String> record = new ArrayList<String>();\n String userType = (user instanceof Staff) ? \"1\" : \"0\";\n String pointString = (user instanceof Student) ? Integer.toString(((Student) user).getPoints()) : \"0\";\n record.add(user.getID());\n record.add(user.getName());\n record.add(user.getPassword());\n record.add(user.getSchool());\n record.add(userType);\n record.add(pointString);\n\n result.add(record);\n });\n\n return result;\n }\n}" } ]
import java.util.ArrayList; import app.entity.user.Student; import app.entity.user.User; import app.entity.user.UserFactory; import app.entity.user.UserList;
3,173
package app.controller.deserializer; /** * The UserDeserializer class contains methods to deserialize user data into a * UserList object. */ public class UserDeserializer { /** * Private constructor to prevent instantiation. */ private UserDeserializer() { } /** * Deserializes the provided data into a UserList object containing User * entities. * * @param data The data to deserialize, represented as an ArrayList of * ArrayLists of Strings. * @return A UserList object populated with deserialized user data. */ public static UserList deserialize(ArrayList<ArrayList<String>> data) { UserList cur = new UserList(); data.forEach(record -> { // Extracting data from the record to create a User object // id, name, password, faculty, type, points String id = record.get(0); String name = record.get(1); String password = record.get(2); String faculty = record.get(3); int type = Integer.parseInt(record.get(4));
package app.controller.deserializer; /** * The UserDeserializer class contains methods to deserialize user data into a * UserList object. */ public class UserDeserializer { /** * Private constructor to prevent instantiation. */ private UserDeserializer() { } /** * Deserializes the provided data into a UserList object containing User * entities. * * @param data The data to deserialize, represented as an ArrayList of * ArrayLists of Strings. * @return A UserList object populated with deserialized user data. */ public static UserList deserialize(ArrayList<ArrayList<String>> data) { UserList cur = new UserList(); data.forEach(record -> { // Extracting data from the record to create a User object // id, name, password, faculty, type, points String id = record.get(0); String name = record.get(1); String password = record.get(2); String faculty = record.get(3); int type = Integer.parseInt(record.get(4));
String typeName = (type == 1) ? "Staff" : "Student";
0
2023-11-01 05:18:29+00:00
4k
LLNL/response
src/main/java/gov/llnl/gnem/response/ChannelMatchPolicyHolder.java
[ { "identifier": "ChannelMatchPolicy", "path": "src/main/java/com/isti/jevalresp/ChannelMatchPolicy.java", "snippet": "public class ChannelMatchPolicy implements Serializable {\r\n\r\n private static final long serialVersionUID = 6639216586376908870L;\r\n\r\n public static enum Policy {\r\n NO_MATCH_REQUIRED, FULL_MATCH, STA_CHAN_EPOCH_MATCH, NET_STA_CHAN_EPOCH_MATCH, AGENCY_NET_STA_CHAN_LOCID_EPOCH_MATCH, NET_STA_CHAN_LOCID_EPOCH_MATCH, NET_STA_CHAN_MATCH\r\n }\r\n\r\n private final boolean matchAgency;\r\n private final boolean matchNet;\r\n private final boolean matchNetJdate;\r\n private final boolean matchSta;\r\n private final boolean matchChannel;\r\n private final boolean matchLocationCode;\r\n private final boolean matchEpoch;\r\n private final Policy policy;\r\n\r\n public static String getPolicyListString() {\r\n Policy[] all = Policy.values();\r\n StringBuilder sb = new StringBuilder(\"Available policies are: (\");\r\n for (int j = 0; j < all.length - 1; ++j) {\r\n sb.append(all[j].toString()).append(\", \");\r\n }\r\n sb.append(all[all.length - 1].toString()).append(\").\");\r\n return sb.toString();\r\n }\r\n\r\n public boolean isParsedFieldsMatchRequest(String station, String staNameStr, String channel, String chaNameStr, String network, String netNameStr, String locid, String siteNameStr,\r\n Date requestedEndDate, Date requestedBeginDate, Date parsedStartDateObj, Date parsedEndDateObj) {\r\n if (matchNet && !network.equals(netNameStr)) {\r\n return false;\r\n }\r\n if (matchSta && !station.equals(staNameStr)) {\r\n return false;\r\n }\r\n if (matchChannel && !channel.equals(chaNameStr)) {\r\n return false;\r\n }\r\n\r\n if (matchEpoch && !requestedEpochIsValid(requestedEndDate, requestedBeginDate, parsedStartDateObj, parsedEndDateObj)) {\r\n return false;\r\n }\r\n if (matchLocationCode && !locationCodesMatch(locid, siteNameStr)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n private boolean locationCodesMatch(String locid, String siteNameStr) {\r\n if (locid == null || locid.equals(\"--\") | locid.equals(\"\") | locid.equals(\"??\") | locid.equals(\"*\") | locid.equals(\"**\")) {\r\n locid = \"--\";\r\n }\r\n if (siteNameStr == null || siteNameStr.equals(\"--\") | siteNameStr.equals(\"\") | siteNameStr.equals(\"??\") | siteNameStr.equals(\"*\") | siteNameStr.equals(\"**\")) {\r\n siteNameStr = \"--\";\r\n }\r\n\r\n return locid.equals(siteNameStr);\r\n }\r\n\r\n public ChannelMatchPolicy(Policy policy) {\r\n this.policy = policy;\r\n switch (policy) {\r\n case NO_MATCH_REQUIRED: {\r\n matchAgency = false;\r\n matchNet = false;\r\n matchNetJdate = false;\r\n matchSta = false;\r\n matchChannel = false;\r\n matchLocationCode = false;\r\n matchEpoch = false;\r\n break;\r\n }\r\n case AGENCY_NET_STA_CHAN_LOCID_EPOCH_MATCH: {\r\n matchAgency = true;\r\n matchNet = true;\r\n matchNetJdate = false;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = true;\r\n matchEpoch = true;\r\n break;\r\n }\r\n case FULL_MATCH: {\r\n matchAgency = true;\r\n matchNet = true;\r\n matchNetJdate = true;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = true;\r\n matchEpoch = true;\r\n break;\r\n }\r\n case STA_CHAN_EPOCH_MATCH: {\r\n matchAgency = false;\r\n matchNet = false;\r\n matchNetJdate = false;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = false;\r\n matchEpoch = true;\r\n break;\r\n }\r\n case NET_STA_CHAN_EPOCH_MATCH: {\r\n matchAgency = false;\r\n matchNet = true;\r\n matchNetJdate = false;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = false;\r\n matchEpoch = true;\r\n break;\r\n }\r\n case NET_STA_CHAN_LOCID_EPOCH_MATCH:\r\n matchAgency = false;\r\n matchNet = true;\r\n matchNetJdate = false;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = true;\r\n matchEpoch = true;\r\n break;\r\n case NET_STA_CHAN_MATCH:\r\n matchAgency = false;\r\n matchNet = true;\r\n matchNetJdate = false;\r\n matchSta = true;\r\n matchChannel = true;\r\n matchLocationCode = false;\r\n matchEpoch = false;\r\n break;\r\n\r\n default:\r\n throw new IllegalArgumentException(\"Unrecognized policy: \" + policy);\r\n\r\n }\r\n\r\n }\r\n\r\n private static boolean requestedEpochIsValid(Date requestedEndDate, Date requestedBeginDate, Date parsedStartDateObj, Date parsedEndDateObj) {\r\n if (requestedBeginDate != null) {\r\n return (requestedBeginDate.compareTo(parsedStartDateObj) >= 0 && requestedBeginDate.compareTo(parsedEndDateObj) <= 0);\r\n } else if (requestedEndDate != null) {\r\n return (requestedEndDate.compareTo(parsedStartDateObj) >= 0 && requestedEndDate.compareTo(parsedEndDateObj) <= 0);\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n public boolean isMatchNet() {\r\n return matchNet;\r\n }\r\n\r\n public boolean isMatchSta() {\r\n return matchSta;\r\n }\r\n\r\n public boolean isMatchChannel() {\r\n return matchChannel;\r\n }\r\n\r\n public boolean isMatchLocationCode() {\r\n return matchLocationCode;\r\n }\r\n\r\n public boolean isMatchEpoch() {\r\n return matchEpoch;\r\n }\r\n\r\n public Policy getPolicy() {\r\n return policy;\r\n }\r\n\r\n public boolean isMatchAgency() {\r\n return matchAgency;\r\n }\r\n\r\n public boolean isMatchNetJdate() {\r\n return matchNetJdate;\r\n }\r\n\r\n public static String getHelpMessageString() {\r\n return \"The ChannelMatchPolicy controls how much of the channel metadata is used in \"\r\n + \"finding and parsing responses. Up to 7 fields can be required to match for \"\r\n + \"selection of response metadata and up to 5 may be used for matching blocks \"\r\n + \"in RESP-type responses. (Note: In the old LLNL schema only sta,chan, and \"\r\n + \"time can be used and more restrictive key combinations are not supported. \\n\"\r\n + getPolicyListString();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"ChannelMatchPolicy{\"\r\n + \"matchAgency=\"\r\n + matchAgency\r\n + \", matchNet=\"\r\n + matchNet\r\n + \", matchNetJdate=\"\r\n + matchNetJdate\r\n + \", matchSta=\"\r\n + matchSta\r\n + \", matchChannel=\"\r\n + matchChannel\r\n + \", matchLocationCode=\"\r\n + matchLocationCode\r\n + \", matchEpoch=\"\r\n + matchEpoch\r\n + \", policy=\"\r\n + policy\r\n + '}';\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n int hash = 5;\r\n hash = 89 * hash + (this.matchAgency ? 1 : 0);\r\n hash = 89 * hash + (this.matchNet ? 1 : 0);\r\n hash = 89 * hash + (this.matchNetJdate ? 1 : 0);\r\n hash = 89 * hash + (this.matchSta ? 1 : 0);\r\n hash = 89 * hash + (this.matchChannel ? 1 : 0);\r\n hash = 89 * hash + (this.matchLocationCode ? 1 : 0);\r\n hash = 89 * hash + (this.matchEpoch ? 1 : 0);\r\n hash = 89 * hash + Objects.hashCode(this.policy);\r\n return hash;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (obj == null) {\r\n return false;\r\n }\r\n if (getClass() != obj.getClass()) {\r\n return false;\r\n }\r\n final ChannelMatchPolicy other = (ChannelMatchPolicy) obj;\r\n if (this.matchAgency != other.matchAgency) {\r\n return false;\r\n }\r\n if (this.matchNet != other.matchNet) {\r\n return false;\r\n }\r\n if (this.matchNetJdate != other.matchNetJdate) {\r\n return false;\r\n }\r\n if (this.matchSta != other.matchSta) {\r\n return false;\r\n }\r\n if (this.matchChannel != other.matchChannel) {\r\n return false;\r\n }\r\n if (this.matchLocationCode != other.matchLocationCode) {\r\n return false;\r\n }\r\n if (this.matchEpoch != other.matchEpoch) {\r\n return false;\r\n }\r\n if (this.policy != other.policy) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n}\r" }, { "identifier": "Policy", "path": "src/main/java/com/isti/jevalresp/ChannelMatchPolicy.java", "snippet": "public static enum Policy {\r\n NO_MATCH_REQUIRED, FULL_MATCH, STA_CHAN_EPOCH_MATCH, NET_STA_CHAN_EPOCH_MATCH, AGENCY_NET_STA_CHAN_LOCID_EPOCH_MATCH, NET_STA_CHAN_LOCID_EPOCH_MATCH, NET_STA_CHAN_MATCH\r\n}\r" } ]
import com.isti.jevalresp.ChannelMatchPolicy; import com.isti.jevalresp.ChannelMatchPolicy.Policy;
2,564
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * 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% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class ChannelMatchPolicyHolder { ChannelMatchPolicy policy; private ChannelMatchPolicyHolder() {
/*- * #%L * Seismic Response Processing Module * LLNL-CODE-856351 * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. * %% * Copyright (C) 2023 Lawrence Livermore National Laboratory * %% * 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% */ package gov.llnl.gnem.response; /** * * @author dodge1 */ public class ChannelMatchPolicyHolder { ChannelMatchPolicy policy; private ChannelMatchPolicyHolder() {
policy = new ChannelMatchPolicy(Policy.FULL_MATCH);
1
2023-10-30 21:06:43+00:00
4k
NUMS-half/OnlineOA
src/main/java/cn/edu/neu/onlineoa/service/ApprovalFlowService.java
[ { "identifier": "ApprovalFlow", "path": "src/main/java/cn/edu/neu/onlineoa/bean/ApprovalFlow.java", "snippet": "public class ApprovalFlow {\n private String cid;\n private String firstTeacherId;\n private String secondTeacherId;\n\n public ApprovalFlow() {}\n\n public ApprovalFlow(String cid, String firstTeacherId, String secondTeacherId) {\n this.cid = cid;\n this.firstTeacherId = firstTeacherId;\n this.secondTeacherId = secondTeacherId;\n }\n\n public String getCid() {\n return cid;\n }\n\n public void setCid(String cid) {\n this.cid = cid;\n }\n\n public String getFirstTeacherId() {\n return firstTeacherId;\n }\n\n public void setFirstTeacherId(String firstTeacherId) {\n this.firstTeacherId = firstTeacherId;\n }\n\n public String getSecondTeacherId() {\n return secondTeacherId;\n }\n\n public void setSecondTeacherId(String secondTeacherId) {\n this.secondTeacherId = secondTeacherId;\n }\n}" }, { "identifier": "ApplyDao", "path": "src/main/java/cn/edu/neu/onlineoa/mapper/ApplyDao.java", "snippet": "public interface ApplyDao {\n\n /**\n * 用于管理员查看所有的申请结果与记录\n * @return apply list\n */\n @Select(\"select a.aid, status, studentId, studentName, courseId, courseName, applyReason, firstApproveTeaId, secondApproveTeaId, rejectReason, confirm \" +\n \"from apply a join apply_log al on a.aid = al.aid\")\n List<Apply> findAllApply();\n\n /**\n * 用于查找某学生所有已经确认的申请\n * @param studentId 学生ID\n * @return apply list\n */\n @Select(\"select a.aid, status, studentId, studentName, courseId, courseName, applyReason, firstApproveTeaId, secondApproveTeaId, rejectReason, confirm \" +\n \"from apply a join apply_log al on a.aid = al.aid \" +\n \"where studentId = #{studentId} and confirm = 1\")\n List<Apply> findAllConfirmedApply(@Param(\"studentId\") String studentId);\n\n /**\n * 用于查找所有的申请结果与记录,进行记录导出\n * @return apply list\n */\n @Select(\"select a.aid, status, studentId, studentName, courseId, courseName, applyReason, applyTime, firstApproveTeaId, firstApproveTime, secondApproveTeaId, secondApproveTime, rejectReason, confirm \" +\n \"from apply a join apply_log al on a.aid = al.aid \" +\n \"where status = 3\")\n List<Apply> findAllPassedApply();\n\n /**\n * 按照申请编号在apply表中查找申请\n * @param aid 申请编号\n * @return apply\n */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, rejectReason, confirm \" +\n \"from apply where aid = #{aid}\")\n Apply findApplyByAid(int aid);\n\n /**\n * 按照学生ID在apply表中查找申请\n * @param studentId 学生ID\n * @return apply list\n */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, rejectReason, confirm \" +\n \"from apply where studentId = #{studentId}\")\n List<Apply> findApplyByStuId(String studentId);\n\n /* no use now */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, firstTeacherId, secondTeacherId, rejectReason, confirm \" +\n \"from apply join approval_flow on (courseId = cid) \" +\n \"where firstTeacherId = #{teacherId}\")\n List<Apply> findApplyByTea1Id(String teacherId);\n\n /* no use now */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, firstTeacherId, secondTeacherId, rejectReason, confirm \" +\n \"from apply join approval_flow on (courseId = cid) \" +\n \"where secondTeacherId = #{teacherId}\")\n List<Apply> findApplyByTea2Id(String teacherId);\n\n /**\n * 按照审批流查找第一审批人需要进行审批的申请\n * @param teacherId 第一审批人ID\n * @return apply list\n */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, firstTeacherId, secondTeacherId, rejectReason, confirm \" +\n \"from apply join approval_flow on (courseId = cid) \" +\n \"where firstTeacherId = #{teacherId} and status = 1\")\n List<Apply> findApplyToApproveByTea1Id(String teacherId);\n\n /**\n * 按照审批流查找第二审批人需要进行审批的申请\n * @param teacherId 第二审批人ID\n * @return apply list\n */\n @Select(\"select aid, status, studentId, studentName, courseId, courseName, applyReason, firstTeacherId, secondTeacherId, rejectReason, confirm \" +\n \"from apply join approval_flow on (courseId = cid) \" +\n \"where secondTeacherId = #{teacherId} and status = 2\")\n List<Apply> findApplyToApproveByTea2Id(String teacherId);\n\n /**\n * 删除指定申请编号的申请\n * @param aid 指定的申请编号\n * @return 是否删除成功\n * @throws Exception 违反数据库约束等异常\n */\n @Delete(\"delete from apply where aid = #{aid}\")\n int deleteApplyByAid(int aid) throws Exception;\n\n /**\n * 新建申请插入apply表\n * @param apply 新建的申请信息\n * @return 是否插入成功\n * @throws Exception 违反数据库约束等异常\n */\n @Insert(\"insert into apply (aid, status, studentId, studentName, courseId, courseName, applyReason, rejectReason, confirm) \" +\n \"values (#{aid}, #{status}, #{studentId}, #{studentName}, #{courseId}, #{courseName}, #{applyReason}, #{rejectReason}, #{confirm})\")\n @Options(useGeneratedKeys = true, keyProperty = \"aid\")\n int addApply(Apply apply) throws Exception;\n\n /**\n * 更新apply表中的申请信息\n * @param apply 更新后的申请信息\n * @return 是否更新成功\n * @throws Exception 违反数据库约束等异常\n */\n @Update(\"update apply set status=#{status}, studentId=#{studentId}, studentName=#{studentName}, \" +\n \"courseId=#{courseId}, courseName=#{courseName}, applyReason=#{applyReason}, \" +\n \"rejectReason=#{rejectReason}, confirm=#{confirm} \" +\n \"where aid=#{aid}\")\n int updateApply(Apply apply) throws Exception;\n\n /**\n * 根据多条件查询指定学生的已经确认的申请\n * @param apply 多条件信息\n * @param studentId 指定的学生ID\n * @return apply list\n */\n List<Apply> findConfirmedApplyWithMultiCondition(@Param(\"apply\") Apply apply, @Param(\"studentId\") String studentId);\n\n /**\n * 根据多条件查询符合条件的申请,可设置第一或第二审批人ID\n * @param apply 多条件信息\n * @param teacherId1 可指定的第一审批人ID\n * @param teacherId2 可指定的第二审批人ID\n * @return apply list\n */\n List<Apply> findApplyWithMultiCondition(@Param(\"apply\") Apply apply, @Param(\"teacherId1\") String teacherId1, @Param(\"teacherId2\") String teacherId2);\n\n /**\n * 按照身份不同多条件查找审批老师的审批记录\n * @param uid\n * @param identity\n * @param apply\n * @return\n */\n List<Apply> findApplyHistory(@Param(\"uid\") String uid, @Param(\"identity\") int identity , @Param(\"apply\") Apply apply);\n}" }, { "identifier": "ApprovalFlowDao", "path": "src/main/java/cn/edu/neu/onlineoa/mapper/ApprovalFlowDao.java", "snippet": "public interface ApprovalFlowDao {\n\n @Select(\"select * from approval_flow\")\n List<ApprovalFlow> findAllApprovalFlow();\n\n @Delete(\"delete from approval_flow where cid = #{cid}\")\n int deleteApprovalFlow(String cid) throws Exception;\n\n @Insert(\"insert into approval_flow (cid, firstTeacherId, secondTeacherId) \" +\n \"values (#{cid}, #{firstTeacherId}, #{secondTeacherId})\")\n int addApprovalFlow(ApprovalFlow approvalFlow) throws Exception;\n\n @Update(\"update approval_flow set firstTeacherId=#{firstTeacherId}, secondTeacherId=#{secondTeacherId} \" +\n \"where cid=#{cid}\")\n int updateApprovalFlow(ApprovalFlow approvalFlow) throws Exception;\n}" }, { "identifier": "MybatisUtils", "path": "src/main/java/cn/edu/neu/onlineoa/utils/MybatisUtils.java", "snippet": "public class MybatisUtils {\n private static SqlSessionFactory sessionFactory = null;\n static {\n String resource = \"mybatis-config.xml\";\n InputStream inputStream = null;\n try {\n inputStream = Resources.getResourceAsStream(resource);\n } catch ( IOException e) {\n e.printStackTrace();\n }\n sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);\n }\n public static SqlSessionFactory getSessionFactoryInstance(){\n return sessionFactory;\n }\n}" } ]
import cn.edu.neu.onlineoa.bean.ApprovalFlow; import cn.edu.neu.onlineoa.mapper.ApplyDao; import cn.edu.neu.onlineoa.mapper.ApprovalFlowDao; import cn.edu.neu.onlineoa.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import java.util.List;
2,585
package cn.edu.neu.onlineoa.service; public class ApprovalFlowService { SqlSessionFactory sqlSessionFactory = MybatisUtils.getSessionFactoryInstance(); public List<ApprovalFlow> findAllApprovalFlow() { try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {
package cn.edu.neu.onlineoa.service; public class ApprovalFlowService { SqlSessionFactory sqlSessionFactory = MybatisUtils.getSessionFactoryInstance(); public List<ApprovalFlow> findAllApprovalFlow() { try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {
ApprovalFlowDao approvalFlowDao = sqlSession.getMapper(ApprovalFlowDao.class);
2
2023-10-31 04:50:21+00:00
4k
TNO/PPS
plugins/nl.esi.pps.tmsc.metric.edit/src-gen/nl/esi/pps/tmsc/metric/provider/MetricEditPlugin.java
[ { "identifier": "PropertiesEditPlugin", "path": "plugins/nl.esi.emf.properties.edit/src-gen/nl/esi/emf/properties/provider/PropertiesEditPlugin.java", "snippet": "public final class PropertiesEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic static final PropertiesEditPlugin INSTANCE = new PropertiesEditPlugin();\n\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tprivate static Implementation plugin;\n\n\t/**\n\t * Create the instance.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic PropertiesEditPlugin() {\n\t\tsuper(new ResourceLocator[] {});\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\t@Override\n\tpublic ResourceLocator getPluginResourceLocator() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\tpublic static Implementation getPlugin() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The actual implementation of the Eclipse <b>Plugin</b>.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic static class Implementation extends EclipsePlugin {\n\t\t/**\n\t\t * Creates an instance.\n\t\t * <!-- begin-user-doc -->\n\t\t * <!-- end-user-doc -->\n\t\t * @generated\n\t\t */\n\t\tpublic Implementation() {\n\t\t\tsuper();\n\n\t\t\t// Remember the static instance.\n\t\t\t//\n\t\t\tplugin = this;\n\t\t}\n\t}\n\n}" }, { "identifier": "ArchitectureEditPlugin", "path": "plugins/nl.esi.pps.architecture.edit/src-gen/nl/esi/pps/architecture/provider/ArchitectureEditPlugin.java", "snippet": "public final class ArchitectureEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic static final ArchitectureEditPlugin INSTANCE = new ArchitectureEditPlugin();\n\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tprivate static Implementation plugin;\n\n\t/**\n\t * Create the instance.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic ArchitectureEditPlugin() {\n\t\tsuper(new ResourceLocator[] { PropertiesEditPlugin.INSTANCE, });\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\t@Override\n\tpublic ResourceLocator getPluginResourceLocator() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\tpublic static Implementation getPlugin() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The actual implementation of the Eclipse <b>Plugin</b>.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated NOT\n\t */\n\tpublic static class Implementation extends PngEclipsePlugin {\n\t\t/**\n\t\t * Creates an instance.\n\t\t * <!-- begin-user-doc -->\n\t\t * <!-- end-user-doc -->\n\t\t * @generated\n\t\t */\n\t\tpublic Implementation() {\n\t\t\tsuper();\n\n\t\t\t// Remember the static instance.\n\t\t\t//\n\t\t\tplugin = this;\n\t\t}\n\t}\n\n}" }, { "identifier": "TmscEditPlugin", "path": "plugins/nl.esi.pps.tmsc.edit/src-gen/nl/esi/pps/tmsc/provider/TmscEditPlugin.java", "snippet": "public final class TmscEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic static final TmscEditPlugin INSTANCE = new TmscEditPlugin();\n\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tprivate static Implementation plugin;\n\n\t/**\n\t * Create the instance.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */\n\tpublic TmscEditPlugin() {\n\t\tsuper(new ResourceLocator[] { ArchitectureEditPlugin.INSTANCE, PropertiesEditPlugin.INSTANCE, });\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\t@Override\n\tpublic ResourceLocator getPluginResourceLocator() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * Returns the singleton instance of the Eclipse plugin.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the singleton instance.\n\t * @generated\n\t */\n\tpublic static Implementation getPlugin() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * Creates a {@link ResourceSet} with edit support.\n\t * \n\t * @see #createItemProviderAdapterFactory()\n\t * @see ResourceSet#getAdapterFactories()\n\t */\n\tpublic static ResourceSet createResourceSet() {\n\t\tResourceSetImpl resourceSet = new ResourceSetImpl();\n\t\tresourceSet.getAdapterFactories().add(createItemProviderAdapterFactory());\n\t\treturn resourceSet;\n\t}\n\n\t/**\n\t * Creates a {@link ComposedAdapterFactory} for all dependent languages, incl. reflective support.\n\t */\n\tpublic static ComposedAdapterFactory createItemProviderAdapterFactory() {\n\t\tComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(\n\t\t\t\tComposedAdapterFactory.Descriptor.Registry.INSTANCE) {\n\t\t\t// Avoiding multi-threading issues by making this method synchronized\n\t\t\t@Override\n\t\t\tpublic synchronized AdapterFactory getFactoryForTypes(Collection<?> types) {\n\t\t\t\treturn super.getFactoryForTypes(types);\n\t\t\t}\n\t\t};\n\t\tadapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new TmscItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new ArchitectureItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new SpecifiedItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new ImplementedItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new DeployedItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new InstantiatedItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new PropertiesItemProviderAdapterFactory());\n\t\tadapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());\n\n\t\treturn adapterFactory;\n\t}\n\n\t/**\n\t * The actual implementation of the Eclipse <b>Plugin</b>.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated NOT\n\t */\n\tpublic static class Implementation extends PngEclipsePlugin {\n\t\tprivate DataAnalysisItemContentProviderRegistryReader dataAnalysisRegistryReader = null;\n\n\t\t/**\n\t\t * Creates an instance.\n\t\t * <!-- begin-user-doc -->\n\t\t * <!-- end-user-doc -->\n\t\t * @generated\n\t\t */\n\t\tpublic Implementation() {\n\t\t\tsuper();\n\n\t\t\t// Remember the static instance.\n\t\t\t//\n\t\t\tplugin = this;\n\t\t}\n\n\t\t@Override\n\t\tpublic void start(BundleContext context) throws Exception {\n\t\t\tsuper.start(context);\n\t\t}\n\n\t\t@Override\n\t\tpublic void stop(BundleContext context) throws Exception {\n\t\t\tsuper.stop(context);\n\t\t\tif (dataAnalysisRegistryReader != null) {\n\t\t\t\tdataAnalysisRegistryReader.dispose();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Returns an unmodifiable {@link Map} containing all registered\n\t\t * {@link IDataAnalysisItemContentProvider data-analysis content providers},\n\t\t * mapped by their\n\t\t * {@link IDataAnalysisItemContentProvider#getConfigurations(Object)\n\t\t * configuration}.\n\t\t * \n\t\t * @return a {@link Map} containing all registered data-analysis content\n\t\t * providers, mapped by their configuration.\n\t\t */\n\t\tpublic Iterable<IDataAnalysisItemContentProvider> getRegisteredDataAnalysisItemContentProviders(EClass eClass) {\n\t\t\tif (dataAnalysisRegistryReader == null) {\n\t\t\t\tdataAnalysisRegistryReader = new DataAnalysisItemContentProviderRegistryReader(this);\n\t\t\t\tdataAnalysisRegistryReader.readRegistry();\n\t\t\t}\n\t\t\treturn dataAnalysisRegistryReader.getDataAnalysisItemContentProviders(eClass);\n\t\t}\n\t}\n}" } ]
import nl.esi.emf.properties.provider.PropertiesEditPlugin; import nl.esi.pps.architecture.provider.ArchitectureEditPlugin; import nl.esi.pps.tmsc.provider.TmscEditPlugin; import org.eclipse.emf.common.EMFPlugin; import org.eclipse.emf.common.util.ResourceLocator;
2,391
/** */ package nl.esi.pps.tmsc.metric.provider; /** * This is the central singleton for the Metric edit plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class MetricEditPlugin extends EMFPlugin { /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final MetricEditPlugin INSTANCE = new MetricEditPlugin(); /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static Implementation plugin; /** * Create the instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MetricEditPlugin() {
/** */ package nl.esi.pps.tmsc.metric.provider; /** * This is the central singleton for the Metric edit plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class MetricEditPlugin extends EMFPlugin { /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final MetricEditPlugin INSTANCE = new MetricEditPlugin(); /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static Implementation plugin; /** * Create the instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MetricEditPlugin() {
super(new ResourceLocator[] { ArchitectureEditPlugin.INSTANCE, PropertiesEditPlugin.INSTANCE,
0
2023-10-30 16:00:25+00:00
4k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/entity/custom/gauntlet/GauntletMovement.java
[ { "identifier": "ValidatedTargetSelector", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/ValidatedTargetSelector.java", "snippet": "public class ValidatedTargetSelector implements ITargetSelector {\n private final IEntity entity;\n private final IValidDirection validator;\n private Vec3 previousDirection;\n\n public ValidatedTargetSelector(IEntity entity, IValidDirection validator) {\n this.entity = entity;\n this.validator = validator;\n this.previousDirection = RandomUtils.randVec();\n }\n\n @Override\n public Vec3 getTarget() {\n Vec3 pos = entity.getPos();\n for (int i = 5; i < 200; i += 20) {\n Vec3 newDirection = VecUtils.rotateVector(previousDirection, RandomUtils.randVec(), RandomUtils.randDouble() * i);\n\n if (validator.isValidDirection(newDirection.normalize())) {\n previousDirection = newDirection;\n return pos.add(newDirection);\n }\n }\n\n previousDirection = VecUtils.negateServer(previousDirection);\n return pos.add(previousDirection);\n }\n}" }, { "identifier": "VelocitySteering", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/VelocitySteering.java", "snippet": "public class VelocitySteering implements ISteering {\n private final IEntity entity;\n private final double maxVelocity;\n private final double inverseMass;\n\n public VelocitySteering(IEntity entity, double maxVelocity, double mass) {\n if (mass == 0.0) throw new IllegalArgumentException(\"Mass cannot be zero\");\n this.entity = entity;\n this.maxVelocity = maxVelocity;\n this.inverseMass = 1 / mass;\n }\n\n @Override\n public Vec3 accelerateTo(Vec3 target) {\n return target.subtract(entity.getPos())\n .normalize()\n .scale(maxVelocity)\n .subtract(entity.getDeltaMovement())\n .scale(inverseMass);\n }\n}" }, { "identifier": "VelocityGoal", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/goals/VelocityGoal.java", "snippet": "public class VelocityGoal extends Goal {\n private final Consumer<Vec3> onTargetSelected;\n private final ISteering steering;\n private final ITargetSelector targetSelector;\n\n public VelocityGoal(Consumer<Vec3> onTargetSelected, ISteering steering, ITargetSelector targetSelector) {\n this.onTargetSelected = onTargetSelected;\n this.steering = steering;\n this.targetSelector = targetSelector;\n setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK));\n }\n\n @Override\n public boolean canUse() {\n return true;\n }\n\n @Override\n public void tick() {\n Vec3 target = targetSelector.getTarget();\n Vec3 velocity = steering.accelerateTo(target);\n onTargetSelected.accept(velocity);\n super.tick();\n }\n}" }, { "identifier": "CanMoveThrough", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/valid_direction/CanMoveThrough.java", "snippet": "public class CanMoveThrough implements IValidDirection {\n private final Entity entity;\n private final double reactionDistance;\n\n public CanMoveThrough(Entity entity, double reactionDistance) {\n this.entity = entity;\n this.reactionDistance = reactionDistance;\n }\n\n @Override\n public boolean isValidDirection(Vec3 normedDirection) {\n Vec3 reactionDirection = normedDirection.scale(reactionDistance).add(entity.getDeltaMovement());\n Vec3 target = entity.position().add(reactionDirection);\n boolean noBlockCollisions = MathUtils.willAABBFit(entity.getBoundingBox(), reactionDirection, box -> !entity.level().noCollision(entity, box));\n ClipContext context = new ClipContext(\n entity.position().add(normedDirection.scale(1.0)),\n target,\n ClipContext.Block.COLLIDER,\n ClipContext.Fluid.ANY,\n entity\n );\n HitResult blockCollision = entity.level().clip(context);\n boolean noFluidCollisions = blockCollision.getType() == HitResult.Type.MISS;\n\n return noFluidCollisions && noBlockCollisions;\n }\n}" }, { "identifier": "InDesiredRange", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/valid_direction/InDesiredRange.java", "snippet": "public class InDesiredRange implements IValidDirection {\n private final Function<Vec3, Boolean> tooClose;\n private final Function<Vec3, Boolean> tooFar;\n private final Function<Vec3, Boolean> movingCloser;\n\n public InDesiredRange(Function<Vec3, Boolean> tooClose, Function<Vec3, Boolean> tooFar, Function<Vec3, Boolean> movingCloser) {\n this.tooClose = tooClose;\n this.tooFar = tooFar;\n this.movingCloser = movingCloser;\n }\n\n @Override\n public boolean isValidDirection(Vec3 normedDirection) {\n boolean isTooClose = tooClose.apply(normedDirection);\n boolean isMovingCloser = movingCloser.apply(normedDirection);\n boolean isTooFar = tooFar.apply(normedDirection);\n\n return (isTooClose && !isMovingCloser) ||\n (isTooFar && isMovingCloser) ||\n (!isTooFar && !isTooClose);\n }\n}" }, { "identifier": "ValidDirectionAnd", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/ai/valid_direction/ValidDirectionAnd.java", "snippet": "public class ValidDirectionAnd implements IValidDirection {\n private final List<IValidDirection> validators;\n\n public ValidDirectionAnd(List<IValidDirection> validators) {\n this.validators = validators;\n }\n\n @Override\n public boolean isValidDirection(Vec3 normedDirection) {\n return validators.stream().allMatch(validator -> validator.isValidDirection(normedDirection));\n }\n}" }, { "identifier": "EntityAdapter", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/util/EntityAdapter.java", "snippet": "public class EntityAdapter implements IEntity {\n private final LivingEntity entity;\n\n public EntityAdapter(LivingEntity entity) {\n this.entity = entity;\n }\n\n @Override\n public Vec3 getDeltaMovement() {\n return entity.getDeltaMovement();\n }\n\n @Override\n public Vec3 getPos() {\n return entity.position();\n }\n\n @Override\n public Vec3 getEyePos() {\n return MobUtils.eyePos(entity);\n }\n\n @Override\n public Vec3 getLookAngle() {\n return entity.getLookAngle();\n }\n\n @Override\n public int getTickCount() {\n return entity.tickCount;\n }\n\n @Override\n public boolean isAlive() {\n return entity.isAlive();\n }\n\n @Override\n public IEntity target() {\n if(entity instanceof Mob) {\n LivingEntity target = ((Mob) entity).getTarget();\n if(target != null)\n return new EntityAdapter(target);\n }\n return null;\n }\n}" } ]
import com.cerbon.bosses_of_mass_destruction.entity.ai.ValidatedTargetSelector; import com.cerbon.bosses_of_mass_destruction.entity.ai.VelocitySteering; import com.cerbon.bosses_of_mass_destruction.entity.ai.goals.VelocityGoal; import com.cerbon.bosses_of_mass_destruction.entity.ai.valid_direction.CanMoveThrough; import com.cerbon.bosses_of_mass_destruction.entity.ai.valid_direction.InDesiredRange; import com.cerbon.bosses_of_mass_destruction.entity.ai.valid_direction.ValidDirectionAnd; import com.cerbon.bosses_of_mass_destruction.entity.util.EntityAdapter; import com.cerbon.cerbons_api.api.static_utilities.MathUtils; import com.cerbon.cerbons_api.api.static_utilities.MobUtils; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.function.Function; import java.util.function.Supplier;
2,233
package com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet; public class GauntletMovement { private final GauntletEntity entity; private final double reactionDistance = 4.0; private final EntityAdapter iEntity; private final double tooFarFromTargetDistance = 25.0; private final double tooCloseToTargetDistance = 5.0; public GauntletMovement(GauntletEntity entity) { this.entity = entity; this.iEntity = new EntityAdapter(entity); } public VelocityGoal buildAttackMovement(){ Supplier<Vec3> targetPos = entity::safeGetTargetPos; ValidDirectionAnd canMoveTowardsPositionValidator = getValidDirectionAnd(targetPos); ValidatedTargetSelector targetSelector = new ValidatedTargetSelector( iEntity, canMoveTowardsPositionValidator ); return new VelocityGoal( this::moveAndLookAtTarget, new VelocitySteering(iEntity, entity.getAttributeValue(Attributes.FLYING_SPEED), 120.0), targetSelector ); } @NotNull private ValidDirectionAnd getValidDirectionAnd(Supplier<Vec3> targetPos) { Function<Vec3, Boolean> tooCloseToTarget = vec3 -> getWithinDistancePredicate(tooCloseToTargetDistance, targetPos).apply(vec3); Function<Vec3, Boolean> tooFarFromTarget = vec3 -> !getWithinDistancePredicate(tooFarFromTargetDistance, targetPos).apply(vec3); Function<Vec3, Boolean> movingToTarget = vec3 -> MathUtils.movingTowards(entity.safeGetTargetPos(), entity.position(), vec3); return new ValidDirectionAnd( Arrays.asList( new CanMoveThrough(entity, reactionDistance),
package com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet; public class GauntletMovement { private final GauntletEntity entity; private final double reactionDistance = 4.0; private final EntityAdapter iEntity; private final double tooFarFromTargetDistance = 25.0; private final double tooCloseToTargetDistance = 5.0; public GauntletMovement(GauntletEntity entity) { this.entity = entity; this.iEntity = new EntityAdapter(entity); } public VelocityGoal buildAttackMovement(){ Supplier<Vec3> targetPos = entity::safeGetTargetPos; ValidDirectionAnd canMoveTowardsPositionValidator = getValidDirectionAnd(targetPos); ValidatedTargetSelector targetSelector = new ValidatedTargetSelector( iEntity, canMoveTowardsPositionValidator ); return new VelocityGoal( this::moveAndLookAtTarget, new VelocitySteering(iEntity, entity.getAttributeValue(Attributes.FLYING_SPEED), 120.0), targetSelector ); } @NotNull private ValidDirectionAnd getValidDirectionAnd(Supplier<Vec3> targetPos) { Function<Vec3, Boolean> tooCloseToTarget = vec3 -> getWithinDistancePredicate(tooCloseToTargetDistance, targetPos).apply(vec3); Function<Vec3, Boolean> tooFarFromTarget = vec3 -> !getWithinDistancePredicate(tooFarFromTargetDistance, targetPos).apply(vec3); Function<Vec3, Boolean> movingToTarget = vec3 -> MathUtils.movingTowards(entity.safeGetTargetPos(), entity.position(), vec3); return new ValidDirectionAnd( Arrays.asList( new CanMoveThrough(entity, reactionDistance),
new InDesiredRange(tooCloseToTarget, tooFarFromTarget, movingToTarget)
4
2023-10-25 16:28:17+00:00
4k
SmartGecko44/Spigot-Admin-Toys
src/main/java/org/gecko/wauh/listeners/BedrockListener.java
[ { "identifier": "Main", "path": "src/main/java/org/gecko/wauh/Main.java", "snippet": "public final class Main extends JavaPlugin {\n\n ConfigurationManager configManager;\n FileConfiguration config;\n private int playerRadiusLimit;\n private int tntRadiusLimit;\n private int creeperRadiusLimit;\n private boolean showRemoval = true;\n private BucketListener bucketListener;\n private BarrierListener barrierListener;\n private BedrockListener bedrockListener;\n private WaterBucketListener waterBucketListener;\n private TNTListener tntListener;\n private CreeperListener creeperListener;\n private static final Logger logger = Logger.getLogger(Main.class.getName());\n private final EnchantmentHandler enchantmentHandler = new EnchantmentHandler();\n\n // Enchantments\n public static final Enchantment disarm = new Disarm();\n public static final Enchantment aim = new Aim();\n public static final Enchantment multishot = new Multishot();\n public static final Enchantment drill = new Drill();\n public static final Enchantment smelt = new Smelt();\n\n\n @Override\n public void onEnable() {\n // Plugin startup logic\n Bukkit.getConsoleSender().sendMessage(\"\");\n Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + \"Yay\");\n\n // Create instances of the listeners\n bucketListener = new BucketListener();\n barrierListener = new BarrierListener();\n bedrockListener = new BedrockListener();\n waterBucketListener = new WaterBucketListener();\n tntListener = new TNTListener();\n creeperListener = new CreeperListener();\n configManager = new ConfigurationManager(this);\n config = configManager.getConfig();\n ConfigGUI configGUI = new ConfigGUI(this);\n Mirror mirror = new Mirror(this);\n\n // Register the listeners\n getServer().getPluginManager().registerEvents(bucketListener, this);\n getServer().getPluginManager().registerEvents(barrierListener, this);\n getServer().getPluginManager().registerEvents(bedrockListener, this);\n getServer().getPluginManager().registerEvents(waterBucketListener, this);\n getServer().getPluginManager().registerEvents(tntListener, this);\n getServer().getPluginManager().registerEvents(creeperListener, this);\n getServer().getPluginManager().registerEvents(configGUI, this);\n getServer().getPluginManager().registerEvents(mirror, this);\n\n // Create enchant instances\n Disarm disarmListener = new Disarm();\n BowListener bowListener = new BowListener();\n Drill drillListener = new Drill();\n Smelt smeltListener = new Smelt();\n\n // Enchantment listeners\n getServer().getPluginManager().registerEvents(disarmListener, this);\n getServer().getPluginManager().registerEvents(bowListener, this);\n getServer().getPluginManager().registerEvents(drillListener, this);\n getServer().getPluginManager().registerEvents(smeltListener, this);\n\n // Register Enchantments\n try {\n registerEnchantment(disarm);\n registerEnchantment(aim);\n registerEnchantment(multishot);\n registerEnchantment(drill);\n registerEnchantment(smelt);\n } catch (IllegalArgumentException ignored) {\n // Ignore any exceptions during enchantment registration\n }\n\n // Register commands\n this.getCommand(\"stopwauh\").setExecutor(new StopWauh(bucketListener, barrierListener, bedrockListener, waterBucketListener));\n this.getCommand(\"setradiuslimit\").setExecutor(new SetRadiusLimitCommand(this));\n this.getCommand(\"setradiuslimit\").setTabCompleter(new SetRadiusLimitCommand(this));\n this.getCommand(\"toggleremovalview\").setExecutor(new ToggleRemovalView(this));\n this.getCommand(\"test\").setExecutor(new test(configGUI));\n this.getCommand(\"givecustomitems\").setExecutor(new GiveCustomItems());\n this.getCommand(\"givecustomitems\").setTabCompleter(new SetRadiusLimitCommand(this));\n this.getCommand(\"ench\").setExecutor(new Ench());\n }\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n Enchantment.stopAcceptingRegistrations();\n }\n\n public int getRadiusLimit() {\n playerRadiusLimit = config.getInt(\"playerRadiusLimit\", playerRadiusLimit);\n return playerRadiusLimit + 2;\n }\n\n public void setRadiusLimit(int newLimit) {\n playerRadiusLimit = newLimit;\n config.set(\"playerRadiusLimit\", playerRadiusLimit);\n configManager.saveConfig();\n }\n\n public int getTntRadiusLimit() {\n tntRadiusLimit = config.getInt(\"tntRadiusLimit\", tntRadiusLimit);\n return tntRadiusLimit + 2;\n }\n\n public void setTntRadiusLimit(int newLimit) {\n tntRadiusLimit = newLimit;\n config.set(\"tntRadiusLimit\", tntRadiusLimit);\n configManager.saveConfig();\n }\n\n public int getCreeperRadiusLimit() {\n creeperRadiusLimit = config.getInt(\"creeperRadiusLimit\", creeperRadiusLimit);\n return creeperRadiusLimit + 2;\n }\n\n public void setCreeperLimit(int newLimit) {\n creeperRadiusLimit = newLimit;\n config.set(\"creeperRadiusLimit\", creeperRadiusLimit);\n configManager.saveConfig();\n }\n\n public boolean getShowRemoval() {\n return showRemoval;\n }\n\n public void setRemovalView(boolean newShowRemoval) {\n showRemoval = newShowRemoval;\n }\n\n public BucketListener getBucketListener() {\n return bucketListener;\n }\n\n public BarrierListener getBarrierListener() {\n return barrierListener;\n }\n\n public BedrockListener getBedrockListener() {\n return bedrockListener;\n }\n\n public WaterBucketListener getWaterBucketListener() {\n return waterBucketListener;\n }\n\n public TNTListener getTntListener() {\n return tntListener;\n }\n\n public CreeperListener getCreeperListener() {\n return creeperListener;\n }\n\n public EnchantmentHandler getEnchantmentHandler() {\n return enchantmentHandler;\n }\n\n public static void registerEnchantment(Enchantment enchantment) {\n boolean registered = true;\n try {\n Field f = Enchantment.class.getDeclaredField(\"acceptingNew\");\n f.setAccessible(true);\n f.set(null, true); // Allow enchantment registration temporarily\n Enchantment.registerEnchantment(enchantment);\n } catch (Exception e) {\n registered = false;\n logger.log(Level.SEVERE, \"Error while registering enchantment \" + enchantment + \" Error:\" + e);\n } finally {\n try {\n // Set acceptingNew back to false to avoid potential issues\n Field f = Enchantment.class.getDeclaredField(\"acceptingNew\");\n f.setAccessible(true);\n f.set(null, false);\n } catch (Exception ignored) {\n // Ignore any exceptions during cleanup\n }\n }\n\n if (registered) {\n // It's been registered!\n Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + enchantment.getName() + \" Registered\");\n }\n }\n}" }, { "identifier": "ConfigurationManager", "path": "src/main/java/org/gecko/wauh/data/ConfigurationManager.java", "snippet": "public class ConfigurationManager {\n private final File configFile;\n private FileConfiguration config;\n private final Logger logger = Logger.getLogger(ConfigurationManager.class.getName());\n public ConfigurationManager(Main plugin) {\n File dir = new File(\"plugins/Wauh\");\n\n if (!dir.exists()) {\n boolean dirCreated = dir.mkdirs();\n\n if (!dirCreated) {\n plugin.getLogger().log(Level.SEVERE, \"Config folder could not be created\");\n } else {\n Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + \"Config folder created!\");\n }\n }\n\n this.configFile = new File(dir, \"data.yml\");\n\n try {\n // Create the data.yml file if it doesn't exist\n if (!configFile.exists()) {\n boolean fileCreated = configFile.createNewFile();\n if (!fileCreated) {\n logger.log(Level.SEVERE, \"Config file could not be created\");\n } else {\n Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + \"Config file created!\");\n FileWriter writer = getFileWriter();\n writer.close();\n }\n }\n\n this.config = YamlConfiguration.loadConfiguration(configFile);\n } catch (IOException ex) {\n plugin.getLogger().log(Level.SEVERE, \"Could not load config file\", ex);\n }\n }\n\n private FileWriter getFileWriter() throws IOException {\n try (FileWriter writer = new FileWriter(configFile)) {\n writer.write(\"playerRadiusLimit: 20\\n\");\n writer.write(\"tntRadiusLimit: 5\\n\");\n writer.write(\"creeperRadiusLimit: 5\\n\");\n writer.write(\"Bucket enabled: 1\\n\");\n writer.write(\"Barrier enabled: 1\\n\");\n writer.write(\"Bedrock enabled: 1\\n\");\n writer.write(\"Tsunami enabled: 1\\n\");\n writer.write(\"Creeper enabled: 0\\n\");\n writer.write(\"TNT enabled: 1\\n\");\n return writer;\n } catch (IOException e) {\n throw new IOException(\"Unable to create FileWriter\", e);\n }\n }\n\n public FileConfiguration getConfig() {\n return config;\n }\n\n public void saveConfig() {\n try {\n config.save(configFile);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Unable to save config\", e);\n }\n }\n\n}" }, { "identifier": "Scale", "path": "src/main/java/org/gecko/wauh/logic/Scale.java", "snippet": "public class Scale {\n\n public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) {\n Main mainPlugin = Main.getPlugin(Main.class);\n\n BucketListener bucketListener = mainPlugin.getBucketListener();\n BarrierListener barrierListener = mainPlugin.getBarrierListener();\n BedrockListener bedrockListener = mainPlugin.getBedrockListener();\n WaterBucketListener waterBucketListener = mainPlugin.getWaterBucketListener();\n\n // Set BLOCKS_PER_ITERATION dynamically based on the total count\n int sqrtTotalBlocks = (int) (Math.sqrt(totalRemovedCount) * (Math.sqrt(radiusLimit) * 1.25));\n int scaledBlocksPerIteration = Math.max(1, sqrtTotalBlocks);\n // Update BLOCKS_PER_ITERATION based on the scaled value\n\n Iterator<Block> iterator = markedBlocks.iterator();\n\n if (source.equalsIgnoreCase(\"bedrock\")) {\n bedrockListener.CleanRemove(scaledBlocksPerIteration, iterator);\n } else if (source.equalsIgnoreCase(\"bucket\")) {\n bucketListener.CleanRemove(scaledBlocksPerIteration, iterator);\n } else if (source.equalsIgnoreCase(\"barrier\")) {\n barrierListener.CleanRemove(scaledBlocksPerIteration, iterator);\n } else if (source.equalsIgnoreCase(\"wauh\")) {\n waterBucketListener.CleanRemove(scaledBlocksPerIteration, iterator);\n }\n\n }\n}" } ]
import de.tr7zw.changeme.nbtapi.NBTItem; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.gecko.wauh.Main; import org.gecko.wauh.data.ConfigurationManager; import org.gecko.wauh.logic.Scale; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger;
3,449
package org.gecko.wauh.listeners; public class BedrockListener implements Listener { private static final Set<Material> IMMUTABLE_MATERIALS = EnumSet.of(Material.BEDROCK, Material.STATIONARY_WATER, Material.WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.TNT); private final Set<Block> markedBlocks = new HashSet<>(); private final Set<Block> processedBlocks = new HashSet<>(); private final Set<Block> removedBlocks = new HashSet<>(); private final Main mainPlugin = Main.getPlugin(Main.class); public Player currentRemovingPlayer; public boolean stopAllRemoval = false; public boolean allRemovalActive = false; private int allRemovedCount; private Set<Block> blocksToProcess = new HashSet<>(); private Location clickedLocation; private boolean limitReached = false; private int highestDist = 0; private int dist; private int radiusLimit; private int realRadiusLimit; private int repetitions = 3; private boolean repeated = false; private boolean explosionTrigger = false; private String realSource = null; private final java.util.logging.Logger logger = Logger.getLogger(Main.class.getName()); private void addIfValid(Block block, Set<Block> nextSet) { if (realSource.equalsIgnoreCase("TNT") || realSource.equalsIgnoreCase("creeper")) { if (!IMMUTABLE_MATERIALS.contains(block.getType())) { nextSet.add(block); } else if (block.getType() == Material.TNT) { Location location = block.getLocation(); block.setType(Material.AIR); TNTPrimed tntPrimed = (TNTPrimed) location.getWorld().spawnEntity(location.add(0.5, 0.5, 0.5), EntityType.PRIMED_TNT); tntPrimed.setFuseTicks(20); nextSet.add(block); } } else if (!IMMUTABLE_MATERIALS.contains(block.getType()) && !(block.getType() == Material.AIR)) { nextSet.add(block); } else if (block.getType() == Material.TNT) { Location location = block.getLocation(); block.setType(Material.AIR); TNTPrimed tntPrimed = (TNTPrimed) location.getWorld().spawnEntity(location.add(0.5, 0.5, 0.5), EntityType.PRIMED_TNT); tntPrimed.setFuseTicks(20); nextSet.add(block); } } @EventHandler public void bedrockBreakEventHandler(BlockBreakEvent event) { bedrockValueAssignHandler(event, "player"); } public void bedrockValueAssignHandler(BlockBreakEvent event, String source) { realSource = source; TNTListener tntListener = mainPlugin.getTntListener(); if (tntListener == null) { return; } if (event == null && source.equalsIgnoreCase("TNT")) { if (tntListener.tntPlayer != null) { if (!tntListener.tntPlayer.isOp()) { return; } } } if (event != null) { if (!event.getPlayer().isOp()) { return; } }
package org.gecko.wauh.listeners; public class BedrockListener implements Listener { private static final Set<Material> IMMUTABLE_MATERIALS = EnumSet.of(Material.BEDROCK, Material.STATIONARY_WATER, Material.WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.TNT); private final Set<Block> markedBlocks = new HashSet<>(); private final Set<Block> processedBlocks = new HashSet<>(); private final Set<Block> removedBlocks = new HashSet<>(); private final Main mainPlugin = Main.getPlugin(Main.class); public Player currentRemovingPlayer; public boolean stopAllRemoval = false; public boolean allRemovalActive = false; private int allRemovedCount; private Set<Block> blocksToProcess = new HashSet<>(); private Location clickedLocation; private boolean limitReached = false; private int highestDist = 0; private int dist; private int radiusLimit; private int realRadiusLimit; private int repetitions = 3; private boolean repeated = false; private boolean explosionTrigger = false; private String realSource = null; private final java.util.logging.Logger logger = Logger.getLogger(Main.class.getName()); private void addIfValid(Block block, Set<Block> nextSet) { if (realSource.equalsIgnoreCase("TNT") || realSource.equalsIgnoreCase("creeper")) { if (!IMMUTABLE_MATERIALS.contains(block.getType())) { nextSet.add(block); } else if (block.getType() == Material.TNT) { Location location = block.getLocation(); block.setType(Material.AIR); TNTPrimed tntPrimed = (TNTPrimed) location.getWorld().spawnEntity(location.add(0.5, 0.5, 0.5), EntityType.PRIMED_TNT); tntPrimed.setFuseTicks(20); nextSet.add(block); } } else if (!IMMUTABLE_MATERIALS.contains(block.getType()) && !(block.getType() == Material.AIR)) { nextSet.add(block); } else if (block.getType() == Material.TNT) { Location location = block.getLocation(); block.setType(Material.AIR); TNTPrimed tntPrimed = (TNTPrimed) location.getWorld().spawnEntity(location.add(0.5, 0.5, 0.5), EntityType.PRIMED_TNT); tntPrimed.setFuseTicks(20); nextSet.add(block); } } @EventHandler public void bedrockBreakEventHandler(BlockBreakEvent event) { bedrockValueAssignHandler(event, "player"); } public void bedrockValueAssignHandler(BlockBreakEvent event, String source) { realSource = source; TNTListener tntListener = mainPlugin.getTntListener(); if (tntListener == null) { return; } if (event == null && source.equalsIgnoreCase("TNT")) { if (tntListener.tntPlayer != null) { if (!tntListener.tntPlayer.isOp()) { return; } } } if (event != null) { if (!event.getPlayer().isOp()) { return; } }
ConfigurationManager configManager;
1
2023-10-28 11:26:45+00:00
4k
King-BR/Mindustry-Discord-Chat
src/discordchat/Discord/Listeners/MsgCreate.java
[ { "identifier": "GameInfo", "path": "src/discordchat/Discord/Commands/GameInfo.java", "snippet": "public class GameInfo {\n public GameInfo(DiscordApi bot, JSONObject config, MessageCreateEvent event, String[] args) {\n if (!event.getServerTextChannel().isPresent()) return;\n ServerTextChannel channel = event.getServerTextChannel().get();\n\n if (!worldLoad.started || !state.isPlaying()) {\n new MessageBuilder()\n .append(\"The server is offline!\")\n .send(channel)\n .join();\n return;\n }\n\n Teams.TeamData data = !Groups.player.isEmpty() ? Groups.player.first().team().data() : state.teams.get(Team.sharded);\n CoreBlock.CoreBuild core = data.cores.first();\n ItemModule items = core.items;\n\n String waves = \"Wave: \" + state.wave +\n \"\\nNext wave in: \" + Utils.msToDuration((state.wavetime / 60) * 1000, true) +\n \"\\nEnemies alive: \" + state.enemies;\n\n StringBuilder res = new StringBuilder();\n items.each((arg1, arg2) -> res.append(Strings.stripColors(arg1.name))\n .append(\": \")\n .append(items.get(arg1.id))\n .append(\"\\n\"));\n\n String map = \"Name: \" + state.map.name() +\n \"\\nAuthor: \" + state.map.author() +\n \"\\nSize: \" + state.map.width + \"x\" + state.map.height +\n \"\\nDescription: \" + state.map.description();\n\n StringBuilder players = new StringBuilder();\n for (Player p : Groups.player) {\n players.append(Strings.stripColors(p.name())).append(\", \");\n }\n\n StringBuilder modsStr = new StringBuilder();\n for (Mods.LoadedMod lmod : mods.list()) {\n modsStr.append(lmod.meta.displayName).append(\", \");\n }\n\n EmbedBuilder embed = new EmbedBuilder()\n .setColor(Color.ORANGE)\n .setTimestampToNow()\n .setTitle(\"Game info\")\n .setDescription(waves)\n .addField(\"Mods\", mods.list().size == 0 ? \"No mods\" : modsStr.substring(0, modsStr.length()-2))\n .addField(\"Map\", map)\n .addField(\"Players\", Groups.player.isEmpty() ? \"No players online\" : players.substring(0, players.length()-2));\n\n EmbedBuilder resEmbed = new EmbedBuilder()\n .setColor(Color.ORANGE)\n .setTimestampToNow()\n .setTitle(\"Resources\")\n .setDescription(res.toString());\n\n if (state.map.previewFile().exists()) embed.setImage(state.map.previewFile().file());\n\n new MessageBuilder()\n .setEmbeds(embed, resEmbed)\n .send(channel)\n .join();\n }\n}" }, { "identifier": "InfoPlayer", "path": "src/discordchat/Discord/Commands/InfoPlayer.java", "snippet": "public class InfoPlayer {\n public InfoPlayer(DiscordApi bot, JSONObject config, MessageCreateEvent event, String[] args) throws IOException {\n if (!event.getServerTextChannel().isPresent()) return;\n ServerTextChannel channel = event.getServerTextChannel().get();\n\n if (args.length < 2) {\n new MessageBuilder()\n .append(\"You forgot to say the player name!\")\n .send(channel)\n .join();\n return;\n }\n\n if (netServer.admins.findByName(args[1]).size > 0 || netServer.admins.searchNames(args[1]).size > 0) {\n ObjectSet<Administration.PlayerInfo> players = netServer.admins.findByName(args[1]);\n\n if (players.size <= 1) players = netServer.admins.searchNames(args[1]);\n\n EmbedBuilder embed = new EmbedBuilder()\n .setTimestampToNow()\n .setColor(Color.GREEN)\n .setTitle(\"Player information\")\n .setDescription(players.size + \" players found\");\n\n int i = 0;\n for (Administration.PlayerInfo info : players) {\n if (i < 21) {\n embed.addInlineField((i + 1) + \" - \" + info.lastName, \"UUID: `\" + info.id + \"`\\n\" +\n \"Names used: `\" + info.names.toString(\", \") + \"`\\n\" +\n \"Joined \" + info.timesJoined + \" time\" + (info.timesJoined > 1 ? \"s\": \"\") + \"\\n\" +\n \"Kicked \" + info.timesKicked + \" time\" + (info.timesKicked > 1 ? \"s\": \"\") + \"\\n\");\n }\n\n i++;\n }\n\n new MessageBuilder()\n .setEmbed(embed)\n .send(channel)\n .join();\n } else {\n new MessageBuilder()\n .append(\"Couldn't find any player with this name!\")\n .send(channel)\n .join();\n }\n }\n}" }, { "identifier": "Ip", "path": "src/discordchat/Discord/Commands/Ip.java", "snippet": "public class Ip {\n public Ip(DiscordApi bot, JSONObject config, MessageCreateEvent event, String[] args) {\n if (!event.getServerTextChannel().isPresent()) return;\n ServerTextChannel channel = event.getServerTextChannel().get();\n\n if (!config.has(\"server_ip\") || config.getString(\"server_ip\").isEmpty()) {\n new MessageBuilder()\n .append(\"Server ip is not configured! Please ask the server owner to configure it!\")\n .send(channel)\n .join();\n return;\n }\n\n EmbedBuilder embed = new EmbedBuilder()\n .setTimestampToNow()\n .setTitle(\"Server IP\")\n .setDescription(\"```\\n\" + config.getString(\"server_ip\") + \"\\n```\")\n .setColor(Color.green);\n\n new MessageBuilder()\n .setEmbed(embed)\n .send(channel)\n .join();\n }\n}" }, { "identifier": "sendMsgToGame", "path": "src/discordchat/Discord/internal/sendMsgToGame.java", "snippet": "public class sendMsgToGame {\n public sendMsgToGame(DiscordApi bot, MessageCreateEvent event, JSONObject config) {\n if (event.getServerTextChannel().isPresent()) {\n String name = Strings.stripColors(event.getMessageAuthor().getDisplayName());\n String msg = event.getMessage().getReadableContent().replace(\"\\n\", \" \");\n msg = msg.replaceAll(\"_\", \"\\\\_\").replaceAll(\"\\\\*\", \"\\\\*\").replaceAll(\"~\", \"\\\\~\");\n\n Call.sendMessage(\"[blue]\\uE80D[] [orange][[[]\" + name + \"[orange]]:[] \" + msg);\n Log.info(\"DISCORD > [\" + name + \"]: \" + msg);\n }\n }\n\n public sendMsgToGame(DiscordApi bot, MessageAuthor author, String msg, JSONObject config) {\n String name = author.getDisplayName();\n msg = msg.replaceAll(\"_\", \"\\\\_\").replaceAll(\"\\\\*\", \"\\\\*\").replaceAll(\"~\", \"\\\\~\");\n\n Call.sendMessage(\"[blue]\\uE80D[] [orange][[[]\" + name + \"[orange]]:[] \" + msg);\n Log.info(\"DISCORD > [\" + name + \"]: \" + msg);\n }\n\n public sendMsgToGame(DiscordApi bot, String author, String msg, JSONObject config) {\n String name = Strings.stripColors(author);\n name = name.replaceAll(\"_\", \"\").replaceAll(\"\\\\*\", \"\").replaceAll(\"~\", \"\");\n msg = msg.replaceAll(\"_\", \"\").replaceAll(\"\\\\*\", \"\").replaceAll(\"~\", \"\");\n\n Call.sendMessage(\"[blue]\\uE80D[] [orange][[[]\" + name + \"[orange]]:[] \" + msg);\n Log.info(\"DISCORD > [\" + name + \"]: \" + msg);\n }\n}" }, { "identifier": "config", "path": "src/discordchat/DiscordChat.java", "snippet": "public static JSONObject config;" } ]
import arc.util.Log; import discordchat.Discord.Commands.GameInfo; import discordchat.Discord.Commands.InfoPlayer; import discordchat.Discord.Commands.Ip; import discordchat.Discord.internal.sendMsgToGame; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.ServerTextChannel; import org.javacord.api.event.message.MessageCreateEvent; import org.javacord.api.listener.message.MessageCreateListener; import java.io.IOException; import java.util.stream.Stream; import static discordchat.DiscordChat.config;
2,158
package discordchat.Discord.Listeners; public class MsgCreate implements MessageCreateListener { private final DiscordApi bot; public MsgCreate(DiscordApi _bot) { this.bot = _bot; } @Override public void onMessageCreate(MessageCreateEvent event) { String prefix = config.getString("prefix"); if (event.getServerTextChannel().isPresent() && event.getMessageAuthor().isRegularUser()) { ServerTextChannel channel = event.getServerTextChannel().get(); if (!event.getMessageContent().startsWith(prefix)) { if (channel.getIdAsString().equals(config.getString("channel_chat"))) { new sendMsgToGame(bot, event, config); } } else if (channel.getIdAsString().equals(config.getString("channel_chat")) || channel.getIdAsString().equals(config.getString("channel_log")) || channel.getIdAsString().equals(config.getString("channel_announcement"))) { String[] args = Stream.of(event.getMessageContent().split(" ")).filter(str -> !str.isEmpty()).toArray(String[]::new); switch (args[0].replaceFirst(prefix, "")) { case "ip" -> new Ip(bot, config, event, args);
package discordchat.Discord.Listeners; public class MsgCreate implements MessageCreateListener { private final DiscordApi bot; public MsgCreate(DiscordApi _bot) { this.bot = _bot; } @Override public void onMessageCreate(MessageCreateEvent event) { String prefix = config.getString("prefix"); if (event.getServerTextChannel().isPresent() && event.getMessageAuthor().isRegularUser()) { ServerTextChannel channel = event.getServerTextChannel().get(); if (!event.getMessageContent().startsWith(prefix)) { if (channel.getIdAsString().equals(config.getString("channel_chat"))) { new sendMsgToGame(bot, event, config); } } else if (channel.getIdAsString().equals(config.getString("channel_chat")) || channel.getIdAsString().equals(config.getString("channel_log")) || channel.getIdAsString().equals(config.getString("channel_announcement"))) { String[] args = Stream.of(event.getMessageContent().split(" ")).filter(str -> !str.isEmpty()).toArray(String[]::new); switch (args[0].replaceFirst(prefix, "")) { case "ip" -> new Ip(bot, config, event, args);
case "gameinfo", "gi" -> new GameInfo(bot, config, event, args);
0
2023-10-25 20:15:57+00:00
4k
RelativityMC/FlowSched
src/main/java/com/ishland/flowsched/executor/test/TestThroughput.java
[ { "identifier": "LockToken", "path": "src/main/java/com/ishland/flowsched/executor/LockToken.java", "snippet": "public interface LockToken {\n}" }, { "identifier": "ExecutorManager", "path": "src/main/java/com/ishland/flowsched/executor/ExecutorManager.java", "snippet": "public class ExecutorManager {\n\n private final DynamicPriorityQueue<Task> globalWorkQueue = new DynamicPriorityQueue<>(256);\n private final Object2ReferenceOpenHashMap<LockToken, Set<Task>> lockListeners = new Object2ReferenceOpenHashMap<>();\n private final SimpleObjectPool<Set<Task>> lockListenersPool = new SimpleObjectPool<>(\n pool -> new ReferenceArraySet<>(32),\n Set::clear,\n Set::clear,\n 4096\n );\n private final Object schedulingMutex = new Object();\n final Object workerMonitor = new Object();\n private final WorkerThread[] workerThreads;\n\n /**\n * Creates a new executor manager.\n *\n * @param workerThreadCount the number of worker threads.\n */\n public ExecutorManager(int workerThreadCount) {\n this(workerThreadCount, thread -> {});\n }\n\n /**\n * Creates a new executor manager.\n *\n * @param workerThreadCount the number of worker threads.\n * @param threadInitializer the thread initializer.\n */\n public ExecutorManager(int workerThreadCount, Consumer<Thread> threadInitializer) {\n workerThreads = new WorkerThread[workerThreadCount];\n for (int i = 0; i < workerThreadCount; i++) {\n final WorkerThread thread = new WorkerThread(this);\n threadInitializer.accept(thread);\n thread.start();\n workerThreads[i] = thread;\n }\n }\n\n /**\n * Attempt to lock the given tokens.\n * The caller should discard the task if this method returns false, as it reschedules the task.\n *\n * @return {@code true} if the lock is acquired, {@code false} otherwise.\n */\n boolean tryLock(Task task) {\n synchronized (this.schedulingMutex) {\n for (LockToken token : task.lockTokens()) {\n final Set<Task> listeners = this.lockListeners.get(token);\n if (listeners != null) {\n listeners.add(task);\n return false;\n }\n }\n for (LockToken token : task.lockTokens()) {\n assert !this.lockListeners.containsKey(token);\n this.lockListeners.put(token, this.lockListenersPool.alloc());\n }\n return true;\n }\n }\n\n /**\n * Release the locks held by the given task.\n * @param task the task.\n */\n void releaseLocks(Task task) {\n synchronized (this.schedulingMutex) {\n for (LockToken token : task.lockTokens()) {\n final Set<Task> listeners = this.lockListeners.remove(token);\n if (listeners != null) {\n for (Task listener : listeners) {\n this.schedule(listener);\n }\n this.lockListenersPool.release(listeners);\n } else {\n throw new IllegalStateException(\"Lock token \" + token + \" is not locked\");\n }\n }\n }\n }\n\n /**\n * Polls an executable task from the global work queue.\n * @return the task, or {@code null} if no task is executable.\n */\n Task pollExecutableTask() {\n synchronized (this.schedulingMutex) {\n Task task;\n while ((task = this.globalWorkQueue.dequeue()) != null) {\n if (this.tryLock(task)) {\n return task;\n }\n }\n }\n return null;\n }\n\n /**\n * Shuts down the executor manager.\n */\n public void shutdown() {\n for (WorkerThread workerThread : workerThreads) {\n workerThread.shutdown();\n }\n }\n\n /**\n * Schedules a task.\n * @param task the task.\n */\n public void schedule(Task task) {\n synchronized (this.schedulingMutex) {\n this.globalWorkQueue.enqueue(task, task.priority());\n }\n synchronized (this.workerMonitor) {\n this.workerMonitor.notify();\n }\n }\n\n /**\n * Schedules a runnable for execution with the given priority.\n *\n * @param runnable the runnable.\n * @param priority the priority.\n */\n public void schedule(Runnable runnable, int priority) {\n this.schedule(new SimpleTask(runnable, priority));\n }\n\n /**\n * Creates an executor that schedules runnables with the given priority.\n *\n * @param priority the priority.\n * @return the executor.\n */\n public Executor executor(int priority) {\n return runnable -> this.schedule(runnable, priority);\n }\n\n /**\n * Notifies the executor manager that the priority of the given task has changed.\n *\n * @param task the task.\n */\n public void notifyPriorityChange(Task task) {\n synchronized (this.schedulingMutex) {\n this.globalWorkQueue.changePriority(task, task.priority());\n }\n }\n\n}" }, { "identifier": "Task", "path": "src/main/java/com/ishland/flowsched/executor/Task.java", "snippet": "public interface Task {\n\n void run(Runnable releaseLocks);\n\n void propagateException(Throwable t);\n\n LockToken[] lockTokens();\n\n int priority();\n\n}" } ]
import com.ishland.flowsched.executor.LockToken; import com.ishland.flowsched.executor.ExecutorManager; import com.ishland.flowsched.executor.Task; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger;
1,723
package com.ishland.flowsched.executor.test; public class TestThroughput { private static final Semaphore semaphore = new Semaphore(1 << 7); public static volatile double accumulation = 0; public static volatile long[] latency = new long[1 << 20]; public static AtomicInteger counter = new AtomicInteger(); public static void main(String[] args) { final ExecutorManager manager = new ExecutorManager(4); long last = System.nanoTime(); int schedules = 0; final ExecutorService pool = Executors.newFixedThreadPool(4); while (true) { if (schedules >= 1 << 20) { final long now = System.nanoTime(); System.out.println(String.format("Throughput: %.2f rps, latency: %.2fns, acc: %e", schedules * 1e9 / (now - last), Arrays.stream(latency).average().getAsDouble(), accumulation)); last = now; schedules = 0; } semaphore.acquireUninterruptibly(); schedules ++; // manager.schedule(new DummyTask()); pool.execute(new DummyTask()); } } static class DummyTask implements Task, Runnable { public static final Runnable EMPTY_RUNNABLE = () -> {}; private final long start = System.nanoTime(); @Override public void run() { run(EMPTY_RUNNABLE); } @Override public void run(Runnable releaseLocks) { // for (int i = 0; i < 1 << 8; i ++) accumulation += Math.random(); final long end = System.nanoTime(); latency[counter.getAndIncrement() & (latency.length - 1)] = end - start; semaphore.release(); releaseLocks.run(); } @Override public void propagateException(Throwable t) { } @Override
package com.ishland.flowsched.executor.test; public class TestThroughput { private static final Semaphore semaphore = new Semaphore(1 << 7); public static volatile double accumulation = 0; public static volatile long[] latency = new long[1 << 20]; public static AtomicInteger counter = new AtomicInteger(); public static void main(String[] args) { final ExecutorManager manager = new ExecutorManager(4); long last = System.nanoTime(); int schedules = 0; final ExecutorService pool = Executors.newFixedThreadPool(4); while (true) { if (schedules >= 1 << 20) { final long now = System.nanoTime(); System.out.println(String.format("Throughput: %.2f rps, latency: %.2fns, acc: %e", schedules * 1e9 / (now - last), Arrays.stream(latency).average().getAsDouble(), accumulation)); last = now; schedules = 0; } semaphore.acquireUninterruptibly(); schedules ++; // manager.schedule(new DummyTask()); pool.execute(new DummyTask()); } } static class DummyTask implements Task, Runnable { public static final Runnable EMPTY_RUNNABLE = () -> {}; private final long start = System.nanoTime(); @Override public void run() { run(EMPTY_RUNNABLE); } @Override public void run(Runnable releaseLocks) { // for (int i = 0; i < 1 << 8; i ++) accumulation += Math.random(); final long end = System.nanoTime(); latency[counter.getAndIncrement() & (latency.length - 1)] = end - start; semaphore.release(); releaseLocks.run(); } @Override public void propagateException(Throwable t) { } @Override
public LockToken[] lockTokens() {
0
2023-10-25 10:07:17+00:00
4k
sinch/sinch-sdk-java
client/src/test/java/com/sinch/sdk/domains/verification/models/webhooks/VerificationResultEventTest.java
[ { "identifier": "NumberIdentity", "path": "client/src/main/com/sinch/sdk/domains/verification/models/NumberIdentity.java", "snippet": "public class NumberIdentity extends Identity {\n\n private final String endpoint;\n\n public String getEndpoint() {\n return endpoint;\n }\n\n /**\n * @param endpoint An E.164-compatible phone number.\n */\n public NumberIdentity(String endpoint) {\n super(\"number\");\n this.endpoint = endpoint;\n }\n\n @Override\n public String toString() {\n return \"NumberIdentity{\" + \"endpoint='\" + endpoint + '\\'' + \"} \" + super.toString();\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n\n String endpoint;\n\n private Builder() {}\n\n public Builder setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n return this;\n }\n\n public NumberIdentity build() {\n return new NumberIdentity(endpoint);\n }\n }\n}" }, { "identifier": "VerificationId", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationId.java", "snippet": "public class VerificationId {\n\n public final String id;\n\n public VerificationId(String id) {\n this.id = id;\n }\n\n @Override\n public String toString() {\n return \"VerificationId{\" + \"id='\" + id + '\\'' + '}';\n }\n\n public String getId() {\n return id;\n }\n\n public static VerificationId valueOf(String id) {\n return new VerificationId(id);\n }\n}" }, { "identifier": "VerificationMethodType", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationMethodType.java", "snippet": "public class VerificationMethodType extends EnumDynamic<String, VerificationMethodType> {\n\n /** Verification by SMS message with a PIN code */\n public static final VerificationMethodType SMS = new VerificationMethodType(\"sms\");\n\n /**\n * Verification by placing a flashcall (missed call) and detecting the incoming calling number\n * (CLI).\n */\n public static final VerificationMethodType FLASH_CALL = new VerificationMethodType(\"flashcall\");\n\n /**\n * Verification by placing a PSTN call to the user's phone and playing an announcement, asking the\n * user to press a particular digit to verify the phone number.\n */\n public static final VerificationMethodType CALLOUT = new VerificationMethodType(\"callout\");\n\n /**\n * Data verification. Verification by accessing internal infrastructure of mobile carriers to\n * verify if given verification attempt was originated from device with matching phone number.\n */\n public static final VerificationMethodType SEAMLESS = new VerificationMethodType(\"seamless\");\n\n /** */\n private static final EnumSupportDynamic<String, VerificationMethodType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n VerificationMethodType.class,\n VerificationMethodType::new,\n Arrays.asList(SMS, FLASH_CALL, CALLOUT, SEAMLESS));\n\n private VerificationMethodType(String value) {\n super(value);\n }\n\n public static Stream<VerificationMethodType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static VerificationMethodType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(VerificationMethodType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}" }, { "identifier": "VerificationReference", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationReference.java", "snippet": "public class VerificationReference {\n\n public final String reference;\n\n public VerificationReference(String reference) {\n this.reference = reference;\n }\n\n @Override\n public String toString() {\n return \"VerificationReference{\" + \"reference='\" + reference + '\\'' + '}';\n }\n\n public String getReference() {\n return reference;\n }\n\n public static VerificationReference valueOf(String reference) {\n return new VerificationReference(reference);\n }\n}" }, { "identifier": "VerificationReportReasonType", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationReportReasonType.java", "snippet": "public class VerificationReportReasonType\n extends EnumDynamic<String, VerificationReportReasonType> {\n\n public static final VerificationReportReasonType FRAUD =\n new VerificationReportReasonType(\"Fraud\");\n public static final VerificationReportReasonType NOT_ENOUGH_CREDIT =\n new VerificationReportReasonType(\"Not enough credit\");\n public static final VerificationReportReasonType BLOCKED =\n new VerificationReportReasonType(\"Blocked\");\n public static final VerificationReportReasonType DENIED_BY_CALLBACK =\n new VerificationReportReasonType(\"Denied by callback\");\n public static final VerificationReportReasonType INVALID_CALLBACK =\n new VerificationReportReasonType(\"Invalid callback\");\n public static final VerificationReportReasonType INTERNAL_ERROR =\n new VerificationReportReasonType(\"Internal error\");\n public static final VerificationReportReasonType DESTINATION_DENIED =\n new VerificationReportReasonType(\"Destination denied\");\n public static final VerificationReportReasonType NETWORK_ERROR_OR_NUMBER_UNREACHABLE =\n new VerificationReportReasonType(\"Network error or number unreachable\");\n public static final VerificationReportReasonType FAILED_PENDING =\n new VerificationReportReasonType(\"Failed pending\");\n public static final VerificationReportReasonType SMS_DELIVERY_FAILURE =\n new VerificationReportReasonType(\"SMS delivery failure\");\n public static final VerificationReportReasonType INVALID_CLI =\n new VerificationReportReasonType(\"Invalid CLI\");\n public static final VerificationReportReasonType INVALID_CODE =\n new VerificationReportReasonType(\"Invalid code\");\n public static final VerificationReportReasonType EXPIRED =\n new VerificationReportReasonType(\"Expired\");\n public static final VerificationReportReasonType HUNG_UP_WITHOUT_ENTERING_VALID_CODE =\n new VerificationReportReasonType(\"Hung up without entering valid code\");\n\n private static final EnumSupportDynamic<String, VerificationReportReasonType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n VerificationReportReasonType.class,\n VerificationReportReasonType::new,\n Arrays.asList(\n FRAUD,\n NOT_ENOUGH_CREDIT,\n BLOCKED,\n DENIED_BY_CALLBACK,\n INVALID_CALLBACK,\n INTERNAL_ERROR,\n DESTINATION_DENIED,\n NETWORK_ERROR_OR_NUMBER_UNREACHABLE,\n FAILED_PENDING,\n SMS_DELIVERY_FAILURE,\n INVALID_CLI,\n INVALID_CODE,\n EXPIRED,\n HUNG_UP_WITHOUT_ENTERING_VALID_CODE));\n\n private VerificationReportReasonType(String value) {\n super(value);\n }\n\n public static Stream<VerificationReportReasonType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static VerificationReportReasonType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(VerificationReportReasonType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}" }, { "identifier": "VerificationReportStatusType", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationReportStatusType.java", "snippet": "public class VerificationReportStatusType\n extends EnumDynamic<String, VerificationReportStatusType> {\n\n /** The verification is ongoing */\n public static final VerificationReportStatusType PENDING =\n new VerificationReportStatusType(\"PENDING\");\n\n /** The verification was successful */\n public static final VerificationReportStatusType SUCCESSFUL =\n new VerificationReportStatusType(\"SUCCESSFUL\");\n\n /** The verification attempt was made, but the number wasn't verified */\n public static final VerificationReportStatusType FAIL = new VerificationReportStatusType(\"FAIL\");\n\n /** The verification attempt was denied by Sinch or your backend */\n public static final VerificationReportStatusType DENIED =\n new VerificationReportStatusType(\"DENIED\");\n\n /** The verification attempt was aborted by requesting a new verification */\n public static final VerificationReportStatusType ABORTED =\n new VerificationReportStatusType(\"ABORTED\");\n\n /**\n * The verification couldn't be completed due to a network error or the number being unreachable\n */\n public static final VerificationReportStatusType ERROR =\n new VerificationReportStatusType(\"ERROR\");\n\n private static final EnumSupportDynamic<String, VerificationReportStatusType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n VerificationReportStatusType.class,\n VerificationReportStatusType::new,\n Arrays.asList(PENDING, SUCCESSFUL, FAIL, DENIED, ABORTED, ERROR));\n\n private VerificationReportStatusType(String value) {\n super(value);\n }\n\n public static Stream<VerificationReportStatusType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static VerificationReportStatusType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(VerificationReportStatusType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}" }, { "identifier": "VerificationSourceType", "path": "client/src/main/com/sinch/sdk/domains/verification/models/VerificationSourceType.java", "snippet": "public class VerificationSourceType extends EnumDynamic<String, VerificationSourceType> {\n\n public static final VerificationSourceType INTERCEPTED =\n new VerificationSourceType(\"intercepted\");\n\n public static final VerificationSourceType MANUAL = new VerificationSourceType(\"manual\");\n\n /** */\n private static final EnumSupportDynamic<String, VerificationSourceType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n VerificationSourceType.class,\n VerificationSourceType::new,\n Arrays.asList(INTERCEPTED, MANUAL));\n\n private VerificationSourceType(String value) {\n super(value);\n }\n\n public static Stream<VerificationSourceType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static VerificationSourceType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(VerificationSourceType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}" } ]
import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.domains.verification.models.NumberIdentity; import com.sinch.sdk.domains.verification.models.VerificationId; import com.sinch.sdk.domains.verification.models.VerificationMethodType; import com.sinch.sdk.domains.verification.models.VerificationReference; import com.sinch.sdk.domains.verification.models.VerificationReportReasonType; import com.sinch.sdk.domains.verification.models.VerificationReportStatusType; import com.sinch.sdk.domains.verification.models.VerificationSourceType; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test;
2,565
package com.sinch.sdk.domains.verification.models.webhooks; @TestWithResources class VerificationResultEventTest { @GivenJsonResource( "/client/sinch/sdk/domains/verification/models/webhooks/VerificationResultEvent.json") static VerificationResultEvent dto; @Test void getId() { Assertions.assertThat(dto.getId()) .usingRecursiveComparison() .isEqualTo(VerificationId.valueOf("1234567890")); } @Test void getEvent() { Assertions.assertThat(dto.getEvent()).isEqualTo("VerificationResultEvent"); } @Test void getMethod() { Assertions.assertThat(dto.getMethod()).isEqualTo(VerificationMethodType.from("sms")); } @Test void getIdentity() { Assertions.assertThat(dto.getIdentity()) .usingRecursiveComparison()
package com.sinch.sdk.domains.verification.models.webhooks; @TestWithResources class VerificationResultEventTest { @GivenJsonResource( "/client/sinch/sdk/domains/verification/models/webhooks/VerificationResultEvent.json") static VerificationResultEvent dto; @Test void getId() { Assertions.assertThat(dto.getId()) .usingRecursiveComparison() .isEqualTo(VerificationId.valueOf("1234567890")); } @Test void getEvent() { Assertions.assertThat(dto.getEvent()).isEqualTo("VerificationResultEvent"); } @Test void getMethod() { Assertions.assertThat(dto.getMethod()).isEqualTo(VerificationMethodType.from("sms")); } @Test void getIdentity() { Assertions.assertThat(dto.getIdentity()) .usingRecursiveComparison()
.isEqualTo(NumberIdentity.builder().setEndpoint("+11235551234").build());
0
2023-10-31 08:32:59+00:00
4k
SpCoGov/SpCoBot
src/main/java/top/spco/core/event/impl/base/event/ArrayBackedEvent.java
[ { "identifier": "ResourceIdentifier", "path": "src/main/java/top/spco/core/resource/ResourceIdentifier.java", "snippet": "public class ResourceIdentifier implements Comparable<ResourceIdentifier> {\n private final String namespace;\n private final String path;\n\n protected ResourceIdentifier(String namespace, String path, @Nullable ResourceIdentifier.Dummy ignoredDummy) {\n this.namespace = namespace;\n this.path = path;\n }\n\n public ResourceIdentifier(String namespace, String path) {\n this(assertValidNamespace(namespace, path), assertValidPath(namespace, path), null);\n }\n\n private static String assertValidNamespace(String namespace, String path) {\n if (!isValidNamespace(namespace)) {\n throw new ResourceIdentifierException(\"Non [a-z0-9_.-] character in namespace of identifier: \" + namespace + \":\" + path);\n } else {\n return namespace;\n }\n }\n\n private static String assertValidPath(String namespace, String path) {\n if (!isValidPath(path)) {\n throw new ResourceIdentifierException(\"Non [a-z0-9/._-] character in path of identifier: \" + namespace + \":\" + path);\n } else {\n return path;\n }\n }\n\n private static boolean isValidPath(String path) {\n for(int i = 0; i < path.length(); ++i) {\n if (!validPathChar(path.charAt(i))) {\n return false;\n }\n }\n\n return true;\n }\n\n public static boolean validPathChar(char character) {\n return character == '_' || character == '-' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '/' || character == '.';\n }\n \n private static boolean isValidNamespace(String namespace) {\n for(int i = 0; i < namespace.length(); ++i) {\n if (!validNamespaceChar(namespace.charAt(i))) {\n return false;\n }\n }\n\n return true;\n }\n\n private static boolean validNamespaceChar(char character) {\n return character == '_' || character == '-' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '.';\n }\n\n @Override\n public int compareTo(@NotNull ResourceIdentifier id) {\n int i = this.path.compareTo(id.path);\n if (i == 0) {\n i = this.namespace.compareTo(id.namespace);\n }\n\n return i;\n }\n\n protected interface Dummy {\n }\n}" }, { "identifier": "Event", "path": "src/main/java/top/spco/core/event/Event.java", "snippet": "@ApiStatus.NonExtendable\npublic abstract class Event<T> {\n /**\n * The invoker field. This should be updated by the implementation to\n * always refer to an instance containing all code that should be\n * executed upon event emission.\n */\n protected volatile T invoker;\n\n /**\n * Returns the invoker instance.\n *\n * <p>An \"invoker\" is an object which hides multiple registered\n * listeners of type T under one instance of type T, executing\n * them and leaving early as necessary.\n *\n * @return The invoker instance.\n */\n public final T invoker() {\n return invoker;\n }\n\n /**\n * Register a listener to the event, in the default phase.\n * Have a look at {@link #addPhaseOrdering} for an explanation of event phases.\n *\n * @param listener The desired listener.\n */\n public abstract void register(T listener);\n\n /**\n * The identifier of the default phase.\n * Have a look at {@link EventFactory#createWithPhases} for an explanation of event phases.\n */\n public static final ResourceIdentifier DEFAULT_PHASE = new ResourceIdentifier(\"spco_bot\", \"default\");\n\n /**\n * Register a listener to the event for the specified phase.\n * Have a look at {@link EventFactory#createWithPhases} for an explanation of event phases.\n *\n * @param phase Identifier of the phase this listener should be registered for. It will be created if it didn't exist yet.\n * @param listener The desired listener.\n */\n public void register(ResourceIdentifier phase, T listener) {\n // This is done to keep compatibility with existing Event subclasses, but they should really not be subclassing Event.\n register(listener);\n }\n\n /**\n * Request that listeners registered for one phase be executed before listeners registered for another phase.\n * Relying on the default phases supplied to {@link EventFactory#createWithPhases} should be preferred over manually\n * registering phase ordering dependencies.\n *\n * <p>Incompatible ordering constraints such as cycles will lead to inconsistent behavior:\n * some constraints will be respected and some will be ignored. If this happens, a warning will be logged.\n *\n * @param firstPhase The identifier of the phase that should run before the other. It will be created if it didn't exist yet.\n * @param secondPhase The identifier of the phase that should run after the other. It will be created if it didn't exist yet.\n */\n public void addPhaseOrdering(ResourceIdentifier firstPhase, ResourceIdentifier secondPhase) {\n // This is not abstract to avoid breaking existing Event subclasses, but they should really not be subclassing Event.\n }\n}" }, { "identifier": "NodeSorting", "path": "src/main/java/top/spco/core/event/impl/base/toposort/NodeSorting.java", "snippet": "public class NodeSorting {\n private static final Logger LOGGER = SpCoBot.logger;\n\n @VisibleForTesting\n public static boolean ENABLE_CYCLE_WARNING = true;\n\n /**\n * Sort a list of nodes.\n *\n * @param sortedNodes The list of nodes to sort. Will be modified in-place.\n * @param elementDescription A description of the elements, used for logging in the presence of cycles.\n * @param comparator The comparator to break ties and to order elements within a cycle.\n * @return {@code true} if all the constraints were satisfied, {@code false} if there was at least one cycle.\n */\n public static <N extends SortableNode<N>> boolean sort(List<N> sortedNodes, String elementDescription, Comparator<N> comparator) {\n // FIRST KOSARAJU SCC VISIT\n List<N> toposort = new ArrayList<>(sortedNodes.size());\n\n for (N node : sortedNodes) {\n forwardVisit(node, null, toposort);\n }\n\n clearStatus(toposort);\n Collections.reverse(toposort);\n\n // SECOND KOSARAJU SCC VISIT\n Map<N, NodeScc<N>> nodeToScc = new IdentityHashMap<>();\n\n for (N node : toposort) {\n if (!node.visited) {\n List<N> sccNodes = new ArrayList<>();\n // Collect nodes in SCC.\n backwardVisit(node, sccNodes);\n // Sort nodes by id.\n sccNodes.sort(comparator);\n // Mark nodes as belonging to this SCC.\n NodeScc<N> scc = new NodeScc<>(sccNodes);\n\n for (N nodeInScc : sccNodes) {\n nodeToScc.put(nodeInScc, scc);\n }\n }\n }\n\n clearStatus(toposort);\n\n // Build SCC graph\n for (NodeScc<N> scc : nodeToScc.values()) {\n for (N node : scc.nodes) {\n for (N subsequentNode : node.subsequentNodes) {\n NodeScc<N> subsequentScc = nodeToScc.get(subsequentNode);\n\n if (subsequentScc != scc) {\n scc.subsequentSccs.add(subsequentScc);\n subsequentScc.inDegree++;\n }\n }\n }\n }\n\n // Order SCCs according to priorities. When there is a choice, use the SCC with the lowest id.\n // The priority queue contains all SCCs that currently have 0 in-degree.\n PriorityQueue<NodeScc<N>> pq = new PriorityQueue<>(Comparator.comparing(scc -> scc.nodes.get(0), comparator));\n sortedNodes.clear();\n\n for (NodeScc<N> scc : nodeToScc.values()) {\n if (scc.inDegree == 0) {\n pq.add(scc);\n // Prevent adding the same SCC multiple times, as nodeToScc may contain the same value multiple times.\n scc.inDegree = -1;\n }\n }\n\n boolean noCycle = true;\n\n while (!pq.isEmpty()) {\n NodeScc<N> scc = pq.poll();\n sortedNodes.addAll(scc.nodes);\n\n if (scc.nodes.size() > 1) {\n noCycle = false;\n\n if (ENABLE_CYCLE_WARNING) {\n // Print cycle warning\n StringBuilder builder = new StringBuilder();\n builder.append(\"Found cycle while sorting \").append(elementDescription).append(\":\\n\");\n\n for (N node : scc.nodes) {\n builder.append(\"\\t\").append(node.getDescription()).append(\"\\n\");\n }\n\n LOGGER.warn(builder.toString());\n }\n }\n\n for (NodeScc<N> subsequentScc : scc.subsequentSccs) {\n subsequentScc.inDegree--;\n\n if (subsequentScc.inDegree == 0) {\n pq.add(subsequentScc);\n }\n }\n }\n\n return noCycle;\n }\n\n private static <N extends SortableNode<N>> void forwardVisit(N node, N parent, List<N> toposort) {\n if (!node.visited) {\n // Not yet visited.\n node.visited = true;\n\n for (N data : node.subsequentNodes) {\n forwardVisit(data, node, toposort);\n }\n\n toposort.add(node);\n }\n }\n\n private static <N extends SortableNode<N>> void clearStatus(List<N> nodes) {\n for (N node : nodes) {\n node.visited = false;\n }\n }\n\n private static <N extends SortableNode<N>> void backwardVisit(N node, List<N> sccNodes) {\n if (!node.visited) {\n node.visited = true;\n sccNodes.add(node);\n\n for (N data : node.previousNodes) {\n backwardVisit(data, sccNodes);\n }\n }\n }\n\n private static class NodeScc<N extends SortableNode<N>> {\n final List<N> nodes;\n final List<NodeScc<N>> subsequentSccs = new ArrayList<>();\n int inDegree = 0;\n\n private NodeScc(List<N> nodes) {\n this.nodes = nodes;\n }\n }\n}" } ]
import top.spco.core.resource.ResourceIdentifier; import top.spco.core.event.Event; import top.spco.core.event.impl.base.toposort.NodeSorting; import java.lang.reflect.Array; import java.util.*; import java.util.function.Function;
2,860
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * 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 top.spco.core.event.impl.base.event; /** * 用于管理事件及其阶段的类,可以注册和处理事件监听器 * * @author Fabric * @version 0.1.0 * @since 0.1.0 */ class ArrayBackedEvent<T> extends Event<T> { private final Function<T[], T> invokerFactory; private final Object lock = new Object(); private T[] handlers; /** * Registered event phases. */
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * 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 top.spco.core.event.impl.base.event; /** * 用于管理事件及其阶段的类,可以注册和处理事件监听器 * * @author Fabric * @version 0.1.0 * @since 0.1.0 */ class ArrayBackedEvent<T> extends Event<T> { private final Function<T[], T> invokerFactory; private final Object lock = new Object(); private T[] handlers; /** * Registered event phases. */
private final Map<ResourceIdentifier, EventPhaseData<T>> phases = new LinkedHashMap<>();
0
2023-10-26 10:27:47+00:00
4k
upe-garanhuns/pweb-2023.2
src/main/java/br/upe/garanhus/esw/pweb/controle/Exec02Servlet.java
[ { "identifier": "PersonagemTO", "path": "src/main/java/br/upe/garanhus/esw/pweb/modelo/PersonagemTO.java", "snippet": "public class PersonagemTO {\n\n private int id;\n\n @JsonbProperty(\"name\")\n private String nome;\n\n private String status;\n\n @JsonbProperty(\"species\")\n private String especie;\n\n @JsonbProperty(\"gender\")\n private String genero;\n\n @JsonbProperty(\"image\")\n private String imagem;\n\n @JsonbProperty(\"episode\")\n private List<String> episodios;\n\n @JsonbProperty(\"created\")\n private String criacao;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getNome() {\n return nome;\n }\n\n public void setNome(String nome) {\n this.nome = nome;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getEspecie() {\n return especie;\n }\n\n public void setEspecie(String especie) {\n this.especie = especie;\n }\n\n public String getGenero() {\n return genero;\n }\n\n public void setGenero(String genero) {\n this.genero = genero;\n }\n\n public String getImagem() {\n return imagem;\n }\n\n public void setImagem(String imagem) {\n this.imagem = imagem;\n }\n\n public List<String> getEpisodios() {\n return episodios;\n }\n\n public void setEpisodios(List<String> episodios) {\n this.episodios = episodios;\n }\n\n public String getCriacao() {\n return criacao;\n }\n\n public void setCriacao(String criacao) {\n this.criacao = criacao;\n }\n\n\n}" }, { "identifier": "RickMortyException", "path": "src/main/java/br/upe/garanhus/esw/pweb/modelo/RickMortyException.java", "snippet": "public class RickMortyException extends RuntimeException {\n\n private static final long serialVersionUID = 8674906927966954109L;\n\n public RickMortyException(String mensagem) {\n super(mensagem);\n }\n\n public RickMortyException(String mensagem, Exception origem) {\n super(mensagem, origem);\n }\n\n}" }, { "identifier": "RickMortyService", "path": "src/main/java/br/upe/garanhus/esw/pweb/modelo/RickMortyService.java", "snippet": "public final class RickMortyService {\n\n private static final Logger logger = Logger.getLogger(RickMortyService.class.getName());\n private static final Jsonb jsonb = JsonbBuilder.create();\n private static final String URL_API = \"https://rickandmortyapi.com/api/\";\n\n private static final String MSG_ERRO_MONTAR_DADOS =\n \"Ocorreu um erro montar os dados da requisição para a API Web Externa\";\n private static final String MSG_ERRO_CONSUMIR_DADOS =\n \"Ocorreu um erro ao executar o cliente HTTP para consumir a API Web Externa\";\n private static final String MSG_ERRO_GERAL = \"Ocorreu um erro inesperado ao consumir a API Web Externa\";\n private static final String MSG_ERRO_ID_NAO_INFORMADO =\n \"É necessário informar o identificador do personagem para consumir a API Web Externa\";\n private static final String MSG_ERRO_INESPERADO = \"Não foi possível obter os dados da API Web: Rick and Morty\";\n\n private final HttpClient cliente;\n\n public RickMortyService() {\n this.cliente = HttpClient.newBuilder().proxy(ProxySelector.getDefault()).build();\n }\n\n public List<PersonagemTO> listar() {\n List<PersonagemTO> personagens = null;\n HttpResponse<String> response = null;\n\n try {\n final HttpRequest request = HttpRequest.newBuilder().uri(new URI(URL_API + \"character\")).GET().build();\n response = this.cliente.send(request, BodyHandlers.ofString());\n\n if (HttpServletResponse.SC_OK != response.statusCode()) {\n this.tratarErroRetornoAPI(response.statusCode());\n }\n\n logger.log(Level.INFO, response.body());\n\n RespostaListaPersonagensTO respostaAPI = jsonb.fromJson(response.body(), RespostaListaPersonagensTO.class);\n personagens = respostaAPI.getPersonagens();\n\n } catch (Exception e) {\n this.tratarErros(e);\n }\n\n return personagens;\n }\n\n public PersonagemTO recuperar(String id) {\n PersonagemTO personagem = null;\n HttpResponse<String> response = null;\n\n if (id == null || id.isEmpty()) {\n logger.log(Level.SEVERE, MSG_ERRO_ID_NAO_INFORMADO);\n throw new RickMortyException(MSG_ERRO_ID_NAO_INFORMADO);\n }\n\n try {\n final HttpRequest request = HttpRequest.newBuilder().uri(new URI(URL_API + \"character/\" + id)).GET().build();\n response = cliente.send(request, BodyHandlers.ofString());\n\n if (HttpServletResponse.SC_OK != response.statusCode()\n && HttpServletResponse.SC_NOT_FOUND != response.statusCode()) {\n this.tratarErroRetornoAPI(response.statusCode());\n }\n\n personagem = jsonb.fromJson(response.body(), PersonagemTO.class);\n logger.log(Level.INFO, response.body());\n\n } catch (Exception e) {\n this.tratarErros(e);\n }\n\n return personagem;\n }\n\n private void tratarErros(Exception e) {\n if (e instanceof URISyntaxException) {\n logger.log(Level.SEVERE, MSG_ERRO_MONTAR_DADOS, e);\n throw new RickMortyException(MSG_ERRO_MONTAR_DADOS);\n }\n if (e instanceof InterruptedException) {\n logger.log(Level.SEVERE, MSG_ERRO_CONSUMIR_DADOS, e);\n throw new RickMortyException(MSG_ERRO_CONSUMIR_DADOS);\n } else {\n if (e instanceof RickMortyException) {\n throw (RickMortyException) e;\n } else {\n logger.log(Level.SEVERE, MSG_ERRO_GERAL, e);\n throw new RickMortyException(MSG_ERRO_GERAL, e);\n }\n }\n }\n\n private void tratarErroRetornoAPI(int statusCode) {\n logger.log(Level.SEVERE, MSG_ERRO_INESPERADO + \"Status Code\" + statusCode);\n throw new RickMortyException(MSG_ERRO_INESPERADO);\n }\n}" } ]
import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import br.upe.garanhus.esw.pweb.modelo.PersonagemTO; import br.upe.garanhus.esw.pweb.modelo.RickMortyException; import br.upe.garanhus.esw.pweb.modelo.RickMortyService; import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
1,909
package br.upe.garanhus.esw.pweb.controle; @SuppressWarnings("serial") @WebServlet(urlPatterns = "/processa-imagem", name = "processa-imagem") public class Exec02Servlet extends HttpServlet { private static final String UTF_8 = "UTF-8"; private static final String APPLICATION_JSON = "application/json"; private static final Logger logger = Logger.getLogger(Exec02Servlet.class.getName()); private static final Jsonb jsonb = JsonbBuilder.create(); private static final String MSG_ERRO_INESPERADO = "Ocorreu um erro inesperado ao processar sua solicitação";
package br.upe.garanhus.esw.pweb.controle; @SuppressWarnings("serial") @WebServlet(urlPatterns = "/processa-imagem", name = "processa-imagem") public class Exec02Servlet extends HttpServlet { private static final String UTF_8 = "UTF-8"; private static final String APPLICATION_JSON = "application/json"; private static final Logger logger = Logger.getLogger(Exec02Servlet.class.getName()); private static final Jsonb jsonb = JsonbBuilder.create(); private static final String MSG_ERRO_INESPERADO = "Ocorreu um erro inesperado ao processar sua solicitação";
private final RickMortyService rickMortyService = new RickMortyService();
2
2023-10-26 00:14:04+00:00
4k
cty1928/GreenTravel
src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/dao/DaoSession.java
[ { "identifier": "BJCamera", "path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/beans/BJCamera.java", "snippet": "public class BJCamera {\n\n private Long id;\n /** Not-null value. */\n private String name;\n private String address;\n private Double latitude;\n private Double longtitude;\n private String direction;\n\n public BJCamera() {\n }\n\n public BJCamera(Long id) {\n this.id = id;\n }\n\n public BJCamera(Long id, String name, String address, Double latitude, Double longtitude, String direction) {\n this.id = id;\n this.name = name;\n this.address = address;\n this.latitude = latitude;\n this.longtitude = longtitude;\n this.direction = direction;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n /** Not-null value. */\n public String getName() {\n return name;\n }\n\n /** Not-null value; ensure this value is available before it is saved to the database. */\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public Double getLatitude() {\n return latitude;\n }\n\n public void setLatitude(Double latitude) {\n this.latitude = latitude;\n }\n\n public Double getLongtitude() {\n return longtitude;\n }\n\n public void setLongtitude(Double longtitude) {\n this.longtitude = longtitude;\n }\n\n public String getDirection() {\n return direction;\n }\n\n public void setDirection(String direction) {\n this.direction = direction;\n }\n\n}" }, { "identifier": "PoiSearchTip", "path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/beans/PoiSearchTip.java", "snippet": "public class PoiSearchTip {\n\n private String name;\n private String district;\n private String adcode;\n\n public PoiSearchTip() {\n }\n\n public PoiSearchTip(String name, String district, String adcode) {\n this.name = name;\n this.district = district;\n this.adcode = adcode;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDistrict() {\n return district;\n }\n\n public void setDistrict(String district) {\n this.district = district;\n }\n\n public String getAdcode() {\n return adcode;\n }\n\n public void setAdcode(String adcode) {\n this.adcode = adcode;\n }\n\n}" }, { "identifier": "BJCameraDao", "path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/dao/BJCameraDao.java", "snippet": "public class BJCameraDao extends AbstractDao<BJCamera, Long> {\n\n public static final String TABLENAME = \"BJCAMERA\";\n\n /**\n * Properties of entity BJCamera.<br/>\n * Can be used for QueryBuilder and for referencing column names.\n */\n public static class Properties {\n public final static Property Id = new Property(0, Long.class, \"id\", true, \"_id\");\n public final static Property Name = new Property(1, String.class, \"name\", false, \"NAME\");\n public final static Property Address = new Property(2, String.class, \"address\", false, \"ADDRESS\");\n public final static Property Latitude = new Property(3, Double.class, \"latitude\", false, \"LATITUDE\");\n public final static Property Longtitude = new Property(4, Double.class, \"longtitude\", false, \"LONGTITUDE\");\n public final static Property Direction = new Property(5, String.class, \"direction\", false, \"DIRECTION\");\n };\n\n\n public BJCameraDao(DaoConfig config) {\n super(config);\n }\n \n public BJCameraDao(DaoConfig config, DaoSession daoSession) {\n super(config, daoSession);\n }\n\n /** Creates the underlying database table. */\n public static void createTable(SQLiteDatabase db, boolean ifNotExists) {\n String constraint = ifNotExists? \"IF NOT EXISTS \": \"\";\n db.execSQL(\"CREATE TABLE \" + constraint + \"\\\"BJCAMERA\\\" (\" + //\n \"\\\"_id\\\" INTEGER PRIMARY KEY AUTOINCREMENT ,\" + // 0: id\n \"\\\"NAME\\\" TEXT NOT NULL ,\" + // 1: name\n \"\\\"ADDRESS\\\" TEXT,\" + // 2: address\n \"\\\"LATITUDE\\\" REAL,\" + // 3: latitude\n \"\\\"LONGTITUDE\\\" REAL,\" + // 4: longtitude\n \"\\\"DIRECTION\\\" TEXT);\"); // 5: direction\n }\n\n /** Drops the underlying database table. */\n public static void dropTable(SQLiteDatabase db, boolean ifExists) {\n String sql = \"DROP TABLE \" + (ifExists ? \"IF EXISTS \" : \"\") + \"\\\"BJCAMERA\\\"\";\n db.execSQL(sql);\n }\n\n /** @inheritdoc */\n @Override\n protected void bindValues(SQLiteStatement stmt, BJCamera entity) {\n stmt.clearBindings();\n \n Long id = entity.getId();\n if (id != null) {\n stmt.bindLong(1, id);\n }\n stmt.bindString(2, entity.getName());\n \n String address = entity.getAddress();\n if (address != null) {\n stmt.bindString(3, address);\n }\n \n Double latitude = entity.getLatitude();\n if (latitude != null) {\n stmt.bindDouble(4, latitude);\n }\n \n Double longtitude = entity.getLongtitude();\n if (longtitude != null) {\n stmt.bindDouble(5, longtitude);\n }\n \n String direction = entity.getDirection();\n if (direction != null) {\n stmt.bindString(6, direction);\n }\n }\n\n /** @inheritdoc */\n @Override\n public Long readKey(Cursor cursor, int offset) {\n return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);\n } \n\n /** @inheritdoc */\n @Override\n public BJCamera readEntity(Cursor cursor, int offset) {\n BJCamera entity = new BJCamera( //\n cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id\n cursor.getString(offset + 1), // name\n cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // address\n cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3), // latitude\n cursor.isNull(offset + 4) ? null : cursor.getDouble(offset + 4), // longtitude\n cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5) // direction\n );\n return entity;\n }\n \n /** @inheritdoc */\n @Override\n public void readEntity(Cursor cursor, BJCamera entity, int offset) {\n entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));\n entity.setName(cursor.getString(offset + 1));\n entity.setAddress(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));\n entity.setLatitude(cursor.isNull(offset + 3) ? null : cursor.getDouble(offset + 3));\n entity.setLongtitude(cursor.isNull(offset + 4) ? null : cursor.getDouble(offset + 4));\n entity.setDirection(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));\n }\n \n /** @inheritdoc */\n @Override\n protected Long updateKeyAfterInsert(BJCamera entity, long rowId) {\n entity.setId(rowId);\n return rowId;\n }\n \n /** @inheritdoc */\n @Override\n public Long getKey(BJCamera entity) {\n if(entity != null) {\n return entity.getId();\n } else {\n return null;\n }\n }\n\n /** @inheritdoc */\n @Override \n protected boolean isEntityUpdateable() {\n return true;\n }\n \n}" }, { "identifier": "PoiSearchTipDao", "path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/dao/PoiSearchTipDao.java", "snippet": "public class PoiSearchTipDao extends AbstractDao<PoiSearchTip, Void> {\n\n public static final String TABLENAME = \"POI_SEARCH_TIP\";\n\n /**\n * Properties of entity PoiSearchTip.<br/>\n * Can be used for QueryBuilder and for referencing column names.\n */\n public static class Properties {\n public final static Property Name = new Property(0, String.class, \"name\", false, \"NAME\");\n public final static Property District = new Property(1, String.class, \"district\", false, \"DISTRICT\");\n public final static Property Adcode = new Property(2, String.class, \"adcode\", false, \"ADCODE\");\n };\n\n\n public PoiSearchTipDao(DaoConfig config) {\n super(config);\n }\n \n public PoiSearchTipDao(DaoConfig config, DaoSession daoSession) {\n super(config, daoSession);\n }\n\n /** Creates the underlying database table. */\n public static void createTable(SQLiteDatabase db, boolean ifNotExists) {\n String constraint = ifNotExists? \"IF NOT EXISTS \": \"\";\n db.execSQL(\"CREATE TABLE \" + constraint + \"\\\"POI_SEARCH_TIP\\\" (\" + //\n \"\\\"NAME\\\" TEXT,\" + // 0: name\n \"\\\"DISTRICT\\\" TEXT,\" + // 1: district\n \"\\\"ADCODE\\\" TEXT);\"); // 2: adcode\n }\n\n /** Drops the underlying database table. */\n public static void dropTable(SQLiteDatabase db, boolean ifExists) {\n String sql = \"DROP TABLE \" + (ifExists ? \"IF EXISTS \" : \"\") + \"\\\"POI_SEARCH_TIP\\\"\";\n db.execSQL(sql);\n }\n\n /** @inheritdoc */\n @Override\n protected void bindValues(SQLiteStatement stmt, PoiSearchTip entity) {\n stmt.clearBindings();\n \n String name = entity.getName();\n if (name != null) {\n stmt.bindString(1, name);\n }\n \n String district = entity.getDistrict();\n if (district != null) {\n stmt.bindString(2, district);\n }\n \n String adcode = entity.getAdcode();\n if (adcode != null) {\n stmt.bindString(3, adcode);\n }\n }\n\n /** @inheritdoc */\n @Override\n public Void readKey(Cursor cursor, int offset) {\n return null;\n } \n\n /** @inheritdoc */\n @Override\n public PoiSearchTip readEntity(Cursor cursor, int offset) {\n PoiSearchTip entity = new PoiSearchTip( //\n cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // name\n cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // district\n cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2) // adcode\n );\n return entity;\n }\n \n /** @inheritdoc */\n @Override\n public void readEntity(Cursor cursor, PoiSearchTip entity, int offset) {\n entity.setName(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0));\n entity.setDistrict(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));\n entity.setAdcode(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));\n }\n \n /** @inheritdoc */\n @Override\n protected Void updateKeyAfterInsert(PoiSearchTip entity, long rowId) {\n // Unsupported or missing PK type\n return null;\n }\n \n /** @inheritdoc */\n @Override\n public Void getKey(PoiSearchTip entity) {\n return null;\n }\n\n /** @inheritdoc */\n @Override \n protected boolean isEntityUpdateable() {\n return true;\n }\n \n}" } ]
import android.database.sqlite.SQLiteDatabase; import java.util.Map; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.AbstractDaoSession; import de.greenrobot.dao.identityscope.IdentityScopeType; import de.greenrobot.dao.internal.DaoConfig; import org.zarroboogs.maps.beans.BJCamera; import org.zarroboogs.maps.beans.PoiSearchTip; import org.zarroboogs.maps.dao.BJCameraDao; import org.zarroboogs.maps.dao.PoiSearchTipDao;
3,304
package org.zarroboogs.maps.dao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * {@inheritDoc} * * @see de.greenrobot.dao.AbstractDaoSession */ public class DaoSession extends AbstractDaoSession { private final DaoConfig bJCameraDaoConfig; private final DaoConfig poiSearchTipDaoConfig; private final BJCameraDao bJCameraDao; private final PoiSearchTipDao poiSearchTipDao; public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) { super(db); bJCameraDaoConfig = daoConfigMap.get(BJCameraDao.class).clone(); bJCameraDaoConfig.initIdentityScope(type); poiSearchTipDaoConfig = daoConfigMap.get(PoiSearchTipDao.class).clone(); poiSearchTipDaoConfig.initIdentityScope(type); bJCameraDao = new BJCameraDao(bJCameraDaoConfig, this); poiSearchTipDao = new PoiSearchTipDao(poiSearchTipDaoConfig, this); registerDao(BJCamera.class, bJCameraDao);
package org.zarroboogs.maps.dao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * {@inheritDoc} * * @see de.greenrobot.dao.AbstractDaoSession */ public class DaoSession extends AbstractDaoSession { private final DaoConfig bJCameraDaoConfig; private final DaoConfig poiSearchTipDaoConfig; private final BJCameraDao bJCameraDao; private final PoiSearchTipDao poiSearchTipDao; public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) { super(db); bJCameraDaoConfig = daoConfigMap.get(BJCameraDao.class).clone(); bJCameraDaoConfig.initIdentityScope(type); poiSearchTipDaoConfig = daoConfigMap.get(PoiSearchTipDao.class).clone(); poiSearchTipDaoConfig.initIdentityScope(type); bJCameraDao = new BJCameraDao(bJCameraDaoConfig, this); poiSearchTipDao = new PoiSearchTipDao(poiSearchTipDaoConfig, this); registerDao(BJCamera.class, bJCameraDao);
registerDao(PoiSearchTip.class, poiSearchTipDao);
1
2023-10-31 01:21:54+00:00
4k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/service/infra/sms/SmsLogService.java
[ { "identifier": "SmsLogExportReqVO", "path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/sms/log/SmsLogExportReqVO.java", "snippet": "@Schema(description = \"管理后台 - 短信日志 Excel 导出 Request VO,参数和 SmsLogPageReqVO 是一致的\")\n@Data\npublic class SmsLogExportReqVO {\n\n @Schema(description = \"短信渠道编号\", example = \"10\")\n private Long channelId;\n\n @Schema(description = \"模板编号\", example = \"20\")\n private Long templateId;\n\n @Schema(description = \"手机号\", example = \"15601691300\")\n private String mobile;\n\n @Schema(description = \"发送状态\", example = \"1\")\n private Integer sendStatus;\n\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n @Schema(description = \"开始发送时间\")\n private LocalDateTime[] sendTime;\n\n @Schema(description = \"接收状态\", example = \"0\")\n private Integer receiveStatus;\n\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n @Schema(description = \"开始接收时间\")\n private LocalDateTime[] receiveTime;\n\n}" }, { "identifier": "SmsLogPageReqVO", "path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/sms/log/SmsLogPageReqVO.java", "snippet": "@Schema(description = \"管理后台 - 短信日志分页 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class SmsLogPageReqVO extends PageParam {\n\n @Schema(description = \"短信渠道编号\", example = \"10\")\n private Long channelId;\n\n @Schema(description = \"模板编号\", example = \"20\")\n private Long templateId;\n\n @Schema(description = \"手机号\", example = \"15601691300\")\n private String mobile;\n\n @Schema(description = \"发送状态,参见 SmsSendStatusEnum 枚举类\", example = \"1\")\n private Integer sendStatus;\n\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n @Schema(description = \"发送时间\")\n private LocalDateTime[] sendTime;\n\n @Schema(description = \"接收状态,参见 SmsReceiveStatusEnum 枚举类\", example = \"0\")\n private Integer receiveStatus;\n\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n @Schema(description = \"接收时间\")\n private LocalDateTime[] receiveTime;\n\n}" }, { "identifier": "SmsLogRespVO", "path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/sms/log/SmsLogRespVO.java", "snippet": "@Schema(description = \"管理后台 - 短信日志 Response VO\")\n@Data\npublic class SmsLogRespVO {\n\n @Schema(description = \"编号\", required = true, example = \"1024\")\n private Long id;\n\n @Schema(description = \"短信渠道编号\", required = true, example = \"10\")\n private Long channelId;\n\n @Schema(description = \"短信渠道编码\", required = true, example = \"ALIYUN\")\n private String channelCode;\n\n @Schema(description = \"模板编号\", required = true, example = \"20\")\n private Long templateId;\n\n @Schema(description = \"模板编码\", required = true, example = \"test-01\")\n private String templateCode;\n\n @Schema(description = \"短信类型\", required = true, example = \"1\")\n private Integer templateType;\n\n @Schema(description = \"短信内容\", required = true, example = \"你好,你的验证码是 1024\")\n private String templateContent;\n\n @Schema(description = \"短信参数\", required = true, example = \"name,code\")\n private Map<String, Object> templateParams;\n\n @Schema(description = \"短信 API 的模板编号\", required = true, example = \"SMS_207945135\")\n private String apiTemplateId;\n\n @Schema(description = \"手机号\", required = true, example = \"15601691300\")\n private String mobile;\n\n @Schema(description = \"用户编号\", example = \"10\")\n private Long userId;\n\n @Schema(description = \"用户类型\", example = \"1\")\n private Integer userType;\n\n @Schema(description = \"发送状态\", required = true, example = \"1\")\n private Integer sendStatus;\n\n @Schema(description = \"发送时间\")\n private LocalDateTime sendTime;\n\n @Schema(description = \"发送结果的编码\", example = \"0\")\n private Integer sendCode;\n\n @Schema(description = \"发送结果的提示\", example = \"成功\")\n private String sendMsg;\n\n @Schema(description = \"短信 API 发送结果的编码\", example = \"SUCCESS\")\n private String apiSendCode;\n\n @Schema(description = \"短信 API 发送失败的提示\", example = \"成功\")\n private String apiSendMsg;\n\n @Schema(description = \"短信 API 发送返回的唯一请求 ID\", example = \"3837C6D3-B96F-428C-BBB2-86135D4B5B99\")\n private String apiRequestId;\n\n @Schema(description = \"短信 API 发送返回的序号\", example = \"62923244790\")\n private String apiSerialNo;\n\n @Schema(description = \"接收状态\", required = true, example = \"0\")\n private Integer receiveStatus;\n\n @Schema(description = \"接收时间\")\n private LocalDateTime receiveTime;\n\n @Schema(description = \"API 接收结果的编码\", example = \"DELIVRD\")\n private String apiReceiveCode;\n\n @Schema(description = \"API 接收结果的说明\", example = \"用户接收成功\")\n private String apiReceiveMsg;\n\n @Schema(description = \"创建时间\", required = true)\n private LocalDateTime createTime;\n\n}" }, { "identifier": "PageResult", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/PageResult.java", "snippet": "@Schema(description = \"分页结果\")\n@Data\npublic final class PageResult<T> implements Serializable {\n\n @Schema(description = \"数据\", required = true)\n private List<T> list;\n\n @Schema(description = \"总量\", required = true)\n private Long total;\n\n public PageResult() {\n }\n\n public PageResult(List<T> list, Long total) {\n this.list = list;\n this.total = total;\n }\n\n public PageResult(Long total) {\n this.list = new ArrayList<>();\n this.total = total;\n }\n\n public static <T> PageResult<T> empty() {\n return new PageResult<>(0L);\n }\n\n public static <T> PageResult<T> empty(Long total) {\n return new PageResult<>(total);\n }\n\n}" }, { "identifier": "SystemSmsLog", "path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/model/infra/sms/SystemSmsLog.java", "snippet": "@Entity\npublic interface SystemSmsLog extends BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n long id();\n\n long channelId();\n\n String channelCode();\n\n long templateId();\n\n String templateCode();\n\n int templateType();\n\n String templateContent();\n\n @Serialized\n Map<String, Object> templateParams();\n\n String apiTemplateId();\n\n String mobile();\n\n long userId();\n\n int userType();\n\n int sendStatus();\n\n @Nullable\n LocalDateTime sendTime();\n\n int sendCode();\n\n String sendMsg();\n\n String apiSendCode();\n\n String apiSendMsg();\n\n String apiRequestId();\n\n String apiSerialNo();\n\n int receiveStatus();\n\n @Nullable\n LocalDateTime receiveTime();\n\n String apiReceiveCode();\n\n String apiReceiveMsg();\n\n}" }, { "identifier": "SystemSmsTemplate", "path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/model/infra/sms/SystemSmsTemplate.java", "snippet": "@Entity\npublic interface SystemSmsTemplate extends BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n long id();\n\n int type();\n\n int status();\n\n String code();\n\n String name();\n\n String content();\n\n @Serialized\n List<String> params();\n\n String remark();\n\n String apiTemplateId();\n\n long channelId();\n\n String channelCode();\n\n}" } ]
import cn.iocoder.yudao.service.vo.infra.sms.log.SmsLogExportReqVO; import cn.iocoder.yudao.service.vo.infra.sms.log.SmsLogPageReqVO; import cn.iocoder.yudao.service.vo.infra.sms.log.SmsLogRespVO; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.service.model.infra.sms.SystemSmsLog; import cn.iocoder.yudao.service.model.infra.sms.SystemSmsTemplate; import java.time.LocalDateTime; import java.util.List; import java.util.Map;
2,805
package cn.iocoder.yudao.service.service.infra.sms; /** * 短信日志 Service 接口 * * @author zzf * @date 13:48 2021/3/2 */ public interface SmsLogService { /** * 创建短信日志 * * @param mobile 手机号 * @param userId 用户编号 * @param userType 用户类型 * @param isSend 是否发送 * @param template 短信模板 * @param templateContent 短信内容 * @param templateParams 短信参数 * @return 发送日志编号 */ Long createSmsLog(String mobile, Long userId, Integer userType, Boolean isSend, SystemSmsTemplate template, String templateContent, Map<String, Object> templateParams); /** * 更新日志的发送结果 * * @param id 日志编号 * @param sendCode 发送结果的编码 * @param sendMsg 发送结果的提示 * @param apiSendCode 短信 API 发送结果的编码 * @param apiSendMsg 短信 API 发送失败的提示 * @param apiRequestId 短信 API 发送返回的唯一请求 ID * @param apiSerialNo 短信 API 发送返回的序号 */ void updateSmsSendResult(Long id, Integer sendCode, String sendMsg, String apiSendCode, String apiSendMsg, String apiRequestId, String apiSerialNo); /** * 更新日志的接收结果 * * @param id 日志编号 * @param success 是否接收成功 * @param receiveTime 用户接收时间 * @param apiReceiveCode API 接收结果的编码 * @param apiReceiveMsg API 接收结果的说明 */ void updateSmsReceiveResult(Long id, Boolean success, LocalDateTime receiveTime, String apiReceiveCode, String apiReceiveMsg); /** * 获得短信日志分页 * * @param pageReqVO 分页查询 * @return 短信日志分页 */
package cn.iocoder.yudao.service.service.infra.sms; /** * 短信日志 Service 接口 * * @author zzf * @date 13:48 2021/3/2 */ public interface SmsLogService { /** * 创建短信日志 * * @param mobile 手机号 * @param userId 用户编号 * @param userType 用户类型 * @param isSend 是否发送 * @param template 短信模板 * @param templateContent 短信内容 * @param templateParams 短信参数 * @return 发送日志编号 */ Long createSmsLog(String mobile, Long userId, Integer userType, Boolean isSend, SystemSmsTemplate template, String templateContent, Map<String, Object> templateParams); /** * 更新日志的发送结果 * * @param id 日志编号 * @param sendCode 发送结果的编码 * @param sendMsg 发送结果的提示 * @param apiSendCode 短信 API 发送结果的编码 * @param apiSendMsg 短信 API 发送失败的提示 * @param apiRequestId 短信 API 发送返回的唯一请求 ID * @param apiSerialNo 短信 API 发送返回的序号 */ void updateSmsSendResult(Long id, Integer sendCode, String sendMsg, String apiSendCode, String apiSendMsg, String apiRequestId, String apiSerialNo); /** * 更新日志的接收结果 * * @param id 日志编号 * @param success 是否接收成功 * @param receiveTime 用户接收时间 * @param apiReceiveCode API 接收结果的编码 * @param apiReceiveMsg API 接收结果的说明 */ void updateSmsReceiveResult(Long id, Boolean success, LocalDateTime receiveTime, String apiReceiveCode, String apiReceiveMsg); /** * 获得短信日志分页 * * @param pageReqVO 分页查询 * @return 短信日志分页 */
PageResult<SmsLogRespVO> getSmsLogPage(SmsLogPageReqVO pageReqVO);
2
2023-10-27 06:35:24+00:00
4k
matheusmisumoto/workout-logger-api
src/main/java/dev/matheusmisumoto/workoutloggerapi/util/WorkoutUtil.java
[ { "identifier": "Workout", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/model/Workout.java", "snippet": "@Entity\r\n@Table(name=\"workouts\")\r\npublic class Workout implements Serializable {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t@Id\r\n\t@GeneratedValue(strategy=GenerationType.AUTO)\r\n\tprivate UUID id;\r\n\r\n\t@JsonFormat(pattern = \"dd/MM/yyyy HH:mm:ss\")\r\n\tprivate OffsetDateTime date;\r\n\tprivate String name;\r\n\tprivate String comment;\r\n\tprivate int duration;\r\n\t\r\n\t@ManyToOne(fetch = FetchType.EAGER)\r\n\t@JoinColumn\r\n\tprivate User user;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate WorkoutStatusType status;\r\n\t\r\n\t@OneToMany(mappedBy=\"workout\", cascade=CascadeType.ALL, orphanRemoval=true)\r\n\tprivate List<WorkoutSet> sets;\r\n\t\r\n\tpublic UUID getId() {\r\n\t\treturn id;\r\n\t}\r\n\tpublic void setId(UUID id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\tpublic OffsetDateTime getDate() {\r\n\t\treturn date;\r\n\t}\r\n\tpublic void setDate(OffsetDateTime date) {\r\n\t\tthis.date = date;\r\n\t}\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\tpublic String getComment() {\r\n\t\treturn comment;\r\n\t}\r\n\tpublic void setComment(String comment) {\r\n\t\tthis.comment = comment;\r\n\t}\r\n\tpublic int getDuration() {\r\n\t\treturn duration;\r\n\t}\r\n\tpublic void setDuration(int duration) {\r\n\t\tthis.duration = duration;\r\n\t}\r\n\tpublic WorkoutStatusType getStatus() {\r\n\t\treturn status;\r\n\t}\r\n\tpublic void setStatus(WorkoutStatusType status) {\r\n\t\tthis.status = status;\r\n\t}\r\n\t\r\n\t@JsonIgnore\r\n\tpublic User getUser() {\r\n\t\treturn user;\r\n\t}\r\n\tpublic void setUser(User user) {\r\n\t\tthis.user = user;\r\n\t}\r\n\t\t\r\n\r\n}\r" }, { "identifier": "WorkoutSet", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/model/WorkoutSet.java", "snippet": "@Entity\r\n@Table(name = \"workouts_sets\")\r\npublic class WorkoutSet implements Serializable {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.AUTO)\r\n\tprivate UUID id;\r\n\t\r\n\t@ManyToOne(fetch = FetchType.EAGER)\r\n\t@JoinColumn\r\n\tprivate Workout workout;\r\n\t\r\n\t@ManyToOne(fetch = FetchType.EAGER)\r\n\t@JoinColumn\r\n\tprivate Exercise exercise;\r\n\t\r\n\t@Min(1)\r\n\tprivate int exerciseOrder;\r\n\t\r\n\t@Min(1)\r\n\t@Max(10)\r\n\tprivate int setOrder;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate WorkoutSetType type;\r\n\t\r\n\t@Max(1000)\r\n\tprivate double weight;\r\n\t\r\n\t@Min(1)\r\n\t@Max(100)\r\n\tprivate int reps;\r\n\r\n\tpublic UUID getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(UUID id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic Workout getWorkout() {\r\n\t\treturn workout;\r\n\t}\r\n\r\n\tpublic void setWorkout(Workout workout) {\r\n\t\tthis.workout = workout;\r\n\t}\r\n\r\n\tpublic Exercise getExercise() {\r\n\t\treturn exercise;\r\n\t}\r\n\r\n\tpublic void setExercise(Exercise exercise) {\r\n\t\tthis.exercise = exercise;\r\n\t}\r\n\r\n\tpublic int getExerciseOrder() {\r\n\t\treturn exerciseOrder;\r\n\t}\r\n\r\n\tpublic void setExerciseOrder(int exerciseOrder) {\r\n\t\tthis.exerciseOrder = exerciseOrder;\r\n\t}\r\n\r\n\tpublic int getSetOrder() {\r\n\t\treturn setOrder;\r\n\t}\r\n\r\n\tpublic void setSetOrder(int setOrder) {\r\n\t\tthis.setOrder = setOrder;\r\n\t}\r\n\r\n\tpublic String getType() {\r\n\t\treturn type.toString();\r\n\t}\r\n\r\n\tpublic void setType(WorkoutSetType type) {\r\n\t\tthis.type = type;\r\n\t}\r\n\r\n\tpublic double getWeight() {\r\n\t\treturn weight;\r\n\t}\r\n\r\n\tpublic void setWeight(double weight) {\r\n\t\tthis.weight = weight;\r\n\t}\r\n\r\n\tpublic int getReps() {\r\n\t\treturn reps;\r\n\t}\r\n\r\n\tpublic void setReps(int reps) {\r\n\t\tthis.reps = reps;\r\n\t}\r\n\t\r\n\r\n\t\r\n}\r" }, { "identifier": "ExerciseRepository", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/repository/ExerciseRepository.java", "snippet": "@Repository\r\npublic interface ExerciseRepository extends JpaRepository<Exercise, UUID> {\r\n\r\n\tList<Exercise> findByTarget(ExerciseTargetType target);\r\n\tList<Exercise> findAllByOrderByNameAsc();\r\n\tList<Exercise> findByEquipment(ExerciseEquipmentType equipment);\r\n\r\n}\r" }, { "identifier": "WorkoutSetRepository", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/repository/WorkoutSetRepository.java", "snippet": "@Repository\r\npublic interface WorkoutSetRepository extends JpaRepository<WorkoutSet, UUID> {\r\n\t\r\n\t@Query(\"SELECT DISTINCT s.exercise FROM WorkoutSet s WHERE s.workout = ?1 ORDER BY s.exerciseOrder ASC\")\r\n\tList<Exercise> findExercisesFromWorkout(Workout workout);\r\n\t\r\n\tList<WorkoutSet> findByWorkoutAndExerciseOrderBySetOrderAsc(Workout workout, Exercise exercise);\r\n\t\r\n\t@Query(\"SELECT SUM(s.weight * s.reps) FROM WorkoutSet s WHERE s.workout = ?1\")\r\n\tDouble calculateTotalWeightLifted(Workout workout);\r\n\t\r\n\t@Query(\"SELECT COUNT(DISTINCT s.exercise) FROM WorkoutSet s WHERE s.workout = ?1\")\r\n\tint calculateTotalExercises(Workout workout);\r\n\t\r\n\t@Query(value = \"SELECT DISTINCT e.target FROM exercises e INNER JOIN workouts_sets s ON s.exercise_id = e.id AND s.workout_id = ?1\", nativeQuery = true)\r\n\tList<ExerciseTargetType> listTargetMuscles(UUID workoutId);\r\n\t\r\n\t@Transactional\r\n\tvoid deleteByWorkout(Workout workout);\r\n\r\n}\r" }, { "identifier": "WorkoutSetType", "path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/type/WorkoutSetType.java", "snippet": "public enum WorkoutSetType {\r\n\tSTANDARD,\r\n\tDROP,\r\n\tNEGATIVE,\r\n\tREST_PAUSE;\r\n\t\r\n\tpublic static WorkoutSetType valueOfDescription(String description) {\r\n\t\tfor (WorkoutSetType setType : WorkoutSetType.values()) {\r\n\t\t\tif (setType.toString().equalsIgnoreCase(description)) {\r\n\t\t\t\treturn setType;\r\n\t }\r\n\t }\r\n\t throw new IllegalArgumentException(\"No matching WorkoutSetType for description: \" + description);\r\n\t}\r\n\r\n}\r" } ]
import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.BeanUtils; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutExerciseRecordDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutExerciseShowDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutRecordDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutSetRecordDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutSetShowDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutShortShowDTO; import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutShowDTO; import dev.matheusmisumoto.workoutloggerapi.model.Workout; import dev.matheusmisumoto.workoutloggerapi.model.WorkoutSet; import dev.matheusmisumoto.workoutloggerapi.repository.ExerciseRepository; import dev.matheusmisumoto.workoutloggerapi.repository.WorkoutSetRepository; import dev.matheusmisumoto.workoutloggerapi.type.WorkoutSetType;
1,925
package dev.matheusmisumoto.workoutloggerapi.util; public class WorkoutUtil { public void recordSets(ExerciseRepository exerciseRepository, WorkoutSetRepository workoutSetRepository,
package dev.matheusmisumoto.workoutloggerapi.util; public class WorkoutUtil { public void recordSets(ExerciseRepository exerciseRepository, WorkoutSetRepository workoutSetRepository,
Workout workout,
0
2023-10-29 23:18:38+00:00
4k
jaszlo/Playerautoma
src/main/java/net/jasper/mod/automation/PlayerRecorder.java
[ { "identifier": "PlayerAutomaClient", "path": "src/main/java/net/jasper/mod/PlayerAutomaClient.java", "snippet": "public class PlayerAutomaClient implements ClientModInitializer {\n\n public static final Logger LOGGER = LoggerFactory.getLogger(\"playerautoma::client\");\n\tpublic static final String RECORDING_FOLDER_NAME = \"Recordings\";\n\tpublic static final String RECORDING_PATH = Path.of(MinecraftClient.getInstance().runDirectory.getAbsolutePath(), RECORDING_FOLDER_NAME).toString();\n\n\n\t@Override\n\tpublic void onInitializeClient() {\n\t\t// Create folder for recordings if not exists\n\t\tFile recordingFolder = new File(RECORDING_PATH);\n\t\tif (!recordingFolder.exists()) {\n\t\t\tboolean failed = !recordingFolder.mkdir();\n\t\t\t// Do not initialize mod if failed to create folder (should not happen)\n\t\t\tif (failed) {\n\t\t\t\tLOGGER.error(\"Failed to create recording folder - PlayerAutoma will not be initialized\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Initialize New Keybinds\n\t\tPlayerAutomaKeyBinds.register();\n\n\t\t// Register Inventory-Automations (Re-Stacking of Blocks)\n\t\tInventoryAutomation.registerInventoryAutomation();\n\n\t\t// Register Player-Recorder (Recording & Replaying)\n\t\tPlayerRecorder.registerInputRecorder();\n\n\t\t// Register Quick slots for Player-Recorder\n\t\tQuickSlots.register();\n\t}\n}" }, { "identifier": "PlayerController", "path": "src/main/java/net/jasper/mod/util/PlayerController.java", "snippet": "public class PlayerController {\n public static void centerPlayer() {\n // Center Camera\n PlayerEntity player= MinecraftClient.getInstance().player;\n assert player != null;\n player.setPitch(0);\n player.setYaw(90);\n\n // Center player on current block\n Vec3d playerPos = player.getPos();\n BlockPos blockPos = new BlockPos((int) Math.floor(playerPos.x), (int) Math.floor(playerPos.y) - 1, (int) Math.floor(playerPos.z));\n player.setPosition(blockPos.getX() + 0.5, blockPos.getY() + 1.0, blockPos.getZ() + 0.5);\n }\n\n public static void writeToChat(String message) {\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.sendMessage(Text.of(message));\n }\n }\n\n public static void clickSlot(SlotClick click) {\n MinecraftClient client = MinecraftClient.getInstance();\n assert client.player != null;\n assert client.interactionManager != null;\n client.interactionManager.clickSlot(client.player.currentScreenHandler.syncId, click.slotId(), click.button(), click.actionType(), client.player);\n }\n}" }, { "identifier": "Recording", "path": "src/main/java/net/jasper/mod/util/data/Recording.java", "snippet": "public class Recording implements Serializable {\n public record RecordEntry(\n List<Boolean> keysPressed,\n LookingDirection lookingDirection,\n int slotSelection,\n SlotClick slotClicked, Class<?> currentScreen\n ) implements Serializable {}\n\n public final List<RecordEntry> entries = new ArrayList<>();\n\n public String toString() {\n return \"Recording[\" + this.entries.size() + \"]\";\n }\n\n public void clear() {\n entries.clear();\n }\n\n public void add(RecordEntry entry) {\n entries.add(entry);\n }\n public boolean isEmpty() {\n return entries.isEmpty();\n }\n\n public Recording copy() {\n Recording copy = new Recording();\n copy.entries.addAll(this.entries);\n return copy;\n }\n}" }, { "identifier": "TaskQueue", "path": "src/main/java/net/jasper/mod/util/data/TaskQueue.java", "snippet": "public class TaskQueue {\n\n public static final long LOW_PRIORITY = -1;\n public static final long MEDIUM_PRIORITY = 0;\n public static final long HIGH_PRIORITY = 1;\n public static final HashMap<String, TaskQueue> QUEUES = new HashMap<>();\n private static boolean done = false; // if work for this tick is done\n\n private final long priority;\n private final List<Runnable> tasks;\n\n public TaskQueue(long priority) {\n this.priority = priority;\n this.tasks = new ArrayList<>();\n }\n\n public boolean isEmpty() {\n return this.tasks.isEmpty();\n }\n\n public void add(Runnable r) {\n this.tasks.add(r);\n }\n\n public void clear() {\n this.tasks.clear();\n }\n\n public Runnable poll() {\n Runnable result = this.tasks.get(0);\n this.tasks.remove(0);\n return result;\n }\n\n private static boolean isHighestPriority(long priority) {\n // If other queues are empty or have lower priority return true\n return QUEUES.values().stream().allMatch(queue -> queue.priority <= priority || queue.isEmpty());\n }\n public void register(String name) {\n QUEUES.put(name, this);\n\n // Clear done flag on client tick start\n ClientTickEvents.START_CLIENT_TICK.register(client -> {\n if (client.player == null) {\n return;\n }\n done = false;\n });\n\n ClientTickEvents.END_CLIENT_TICK.register(client -> {\n if (client.player == null || done) {\n return;\n }\n\n // Only run the task if it has the highest priority or if no other queue is busy\n if (!isHighestPriority(this.priority) || this.isEmpty()) {\n return;\n }\n\n this.poll().run();\n done = true;\n });\n }\n}" }, { "identifier": "State", "path": "src/main/java/net/jasper/mod/automation/PlayerRecorder.java", "snippet": "public enum State {\n RECORDING,\n REPLAYING,\n LOOPING,\n IDLE;\n\n public boolean isLooping() {\n return this == LOOPING;\n }\n\n public boolean isRecording() {\n return this == RECORDING;\n }\n\n public boolean isReplaying() {\n return this == REPLAYING;\n }\n\n public boolean isAny(State... states) {\n for (State state : states) {\n if (this == state) {\n return true;\n }\n }\n return false;\n }\n}" } ]
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.jasper.mod.PlayerAutomaClient; import net.jasper.mod.util.PlayerController; import net.jasper.mod.util.data.LookingDirection; import net.jasper.mod.util.data.Recording; import net.jasper.mod.util.data.SlotClick; import net.jasper.mod.util.data.TaskQueue; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.ingame.InventoryScreen; import net.minecraft.client.option.KeyBinding; import org.slf4j.Logger; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedDeque; import static net.jasper.mod.automation.PlayerRecorder.State.*;
1,642
package net.jasper.mod.automation; /** * Class records player input and allows to replay those */ public class PlayerRecorder { private static final Logger LOGGER = PlayerAutomaClient.LOGGER; public static Recording record = new Recording();
package net.jasper.mod.automation; /** * Class records player input and allows to replay those */ public class PlayerRecorder { private static final Logger LOGGER = PlayerAutomaClient.LOGGER; public static Recording record = new Recording();
public static State state = IDLE;
4
2023-10-25 11:30:02+00:00
4k