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 |
---|---|---|---|---|---|---|---|---|---|---|
quentin452/DangerRPG-Continuation | src/main/java/mixac1/hooklib/minecraft/PrimaryClassTransformer.java | [
{
"identifier": "AsmHook",
"path": "src/main/java/mixac1/hooklib/asm/AsmHook.java",
"snippet": "public class AsmHook implements Cloneable, Comparable<AsmHook> {\n\n private String targetClassName;\n private String targetMethodName;\n private List<Type> targetMethodParameters = new ArrayList<Type>(2);\n private Type targetMethodReturnType;\n\n private String hooksClassName;\n private String hookMethodName;\n\n private List<Integer> transmittableVariableIds = new ArrayList<Integer>(2);\n private List<Type> hookMethodParameters = new ArrayList<Type>(2);\n private Type hookMethodReturnType = Type.VOID_TYPE;\n private boolean hasReturnValueParameter;\n\n private ReturnCondition returnCondition = ReturnCondition.NEVER;\n private ReturnValue returnValue = ReturnValue.VOID;\n private Object primitiveConstant;\n\n private HookInjectorFactory injectorFactory = ON_ENTER_FACTORY;\n private HookPriority priority = HookPriority.NORMAL;\n\n public static final HookInjectorFactory ON_ENTER_FACTORY = MethodEnter.INSTANCE;\n public static final HookInjectorFactory ON_EXIT_FACTORY = MethodExit.INSTANCE;\n\n private String targetMethodDescription;\n private String hookMethodDescription;\n private String returnMethodName;\n private String returnMethodDescription;\n\n protected String getTargetClassName() {\n return targetClassName;\n }\n\n protected String getTargetMethodName() {\n return targetMethodName;\n }\n\n protected boolean isTargetMethod(String name, String desc) {\n return (targetMethodReturnType == null && desc.startsWith(targetMethodDescription)\n || desc.equals(targetMethodDescription)) && name.equals(targetMethodName);\n }\n\n protected HookInjectorFactory getInjectorFactory() {\n return injectorFactory;\n }\n\n private boolean hasHookMethod() {\n return hookMethodName != null && hooksClassName != null;\n }\n\n protected void inject(HookInjectorMethodVisitor inj) {\n Type targetMethodReturnType = inj.methodType.getReturnType();\n\n int returnLocalId = -1;\n if (hasReturnValueParameter) {\n returnLocalId = inj.newLocal(targetMethodReturnType);\n inj.storeLocal(returnLocalId, targetMethodReturnType);\n }\n\n int hookResultLocalId = -1;\n if (hasHookMethod()) {\n injectInvokeStatic(inj, returnLocalId, hookMethodName, hookMethodDescription);\n\n if (returnValue == ReturnValue.HOOK_RETURN_VALUE || returnCondition.requiresCondition) {\n hookResultLocalId = inj.newLocal(hookMethodReturnType);\n inj.storeLocal(hookResultLocalId, hookMethodReturnType);\n }\n }\n\n if (returnCondition != ReturnCondition.NEVER) {\n Label label = inj.newLabel();\n\n if (returnCondition != ReturnCondition.ALWAYS) {\n inj.loadLocal(hookResultLocalId, hookMethodReturnType);\n if (returnCondition == ReturnCondition.ON_TRUE) {\n inj.visitJumpInsn(IFEQ, label);\n } else if (returnCondition == ReturnCondition.ON_NULL) {\n inj.visitJumpInsn(IFNONNULL, label);\n } else if (returnCondition == ReturnCondition.ON_NOT_NULL) {\n inj.visitJumpInsn(IFNULL, label);\n }\n }\n\n if (returnValue == ReturnValue.NULL) {\n inj.visitInsn(Opcodes.ACONST_NULL);\n } else if (returnValue == ReturnValue.PRIMITIVE_CONSTANT) {\n inj.visitLdcInsn(primitiveConstant);\n } else if (returnValue == ReturnValue.HOOK_RETURN_VALUE) {\n inj.loadLocal(hookResultLocalId, hookMethodReturnType);\n } else if (returnValue == ReturnValue.ANOTHER_METHOD_RETURN_VALUE) {\n String returnMethodDescription = this.returnMethodDescription;\n if (returnMethodDescription.endsWith(\")\")) {\n returnMethodDescription += targetMethodReturnType.getDescriptor();\n }\n injectInvokeStatic(inj, returnLocalId, returnMethodName, returnMethodDescription);\n }\n\n injectReturn(inj, targetMethodReturnType);\n\n inj.visitLabel(label);\n }\n\n if (hasReturnValueParameter) {\n injectVarInsn(inj, targetMethodReturnType, returnLocalId);\n }\n }\n\n private void injectVarInsn(HookInjectorMethodVisitor inj, Type parameterType, int variableId) {\n int opcode;\n if (parameterType == INT_TYPE || parameterType == BYTE_TYPE\n || parameterType == CHAR_TYPE\n || parameterType == BOOLEAN_TYPE\n || parameterType == SHORT_TYPE) {\n opcode = ILOAD;\n } else if (parameterType == LONG_TYPE) {\n opcode = LLOAD;\n } else if (parameterType == FLOAT_TYPE) {\n opcode = FLOAD;\n } else if (parameterType == DOUBLE_TYPE) {\n opcode = DLOAD;\n } else {\n opcode = ALOAD;\n }\n inj.getBasicVisitor()\n .visitVarInsn(opcode, variableId);\n }\n\n private void injectReturn(HookInjectorMethodVisitor inj, Type targetMethodReturnType) {\n if (targetMethodReturnType == INT_TYPE || targetMethodReturnType == SHORT_TYPE\n || targetMethodReturnType == BOOLEAN_TYPE\n || targetMethodReturnType == BYTE_TYPE\n || targetMethodReturnType == CHAR_TYPE) {\n inj.visitInsn(IRETURN);\n } else if (targetMethodReturnType == LONG_TYPE) {\n inj.visitInsn(LRETURN);\n } else if (targetMethodReturnType == FLOAT_TYPE) {\n inj.visitInsn(FRETURN);\n } else if (targetMethodReturnType == DOUBLE_TYPE) {\n inj.visitInsn(DRETURN);\n } else if (targetMethodReturnType == VOID_TYPE) {\n inj.visitInsn(RETURN);\n } else {\n inj.visitInsn(ARETURN);\n }\n }\n\n private void injectInvokeStatic(HookInjectorMethodVisitor inj, int returnLocalId, String name, String desc) {\n for (int i = 0; i < hookMethodParameters.size(); i++) {\n Type parameterType = hookMethodParameters.get(i);\n int variableId = transmittableVariableIds.get(i);\n if (inj.isStatic) {\n if (variableId == 0) {\n inj.visitInsn(Opcodes.ACONST_NULL);\n continue;\n }\n if (variableId > 0) {\n variableId--;\n }\n }\n if (variableId == -1) {\n variableId = returnLocalId;\n }\n injectVarInsn(inj, parameterType, variableId);\n }\n\n inj.visitMethodInsn(INVOKESTATIC, hooksClassName.replace(\".\", \"/\"), name, desc);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"AsmHook: \");\n\n sb.append(targetClassName)\n .append('#')\n .append(targetMethodName);\n sb.append(targetMethodDescription);\n sb.append(\" -> \");\n sb.append(hooksClassName)\n .append('#')\n .append(hookMethodName);\n sb.append(hookMethodDescription);\n\n sb.append(\", ReturnCondition=\" + returnCondition);\n sb.append(\", ReturnValue=\" + returnValue);\n if (returnValue == ReturnValue.PRIMITIVE_CONSTANT) {\n sb.append(\", Constant=\" + primitiveConstant);\n }\n sb.append(\n \", InjectorFactory: \" + injectorFactory.getClass()\n .getName());\n\n return sb.toString();\n }\n\n @Override\n public int compareTo(AsmHook o) {\n if (injectorFactory.isPriorityInverted && o.injectorFactory.isPriorityInverted) {\n return priority.ordinal() > o.priority.ordinal() ? -1 : 1;\n } else if (!injectorFactory.isPriorityInverted && !o.injectorFactory.isPriorityInverted) {\n return priority.ordinal() > o.priority.ordinal() ? 1 : -1;\n } else {\n return injectorFactory.isPriorityInverted ? 1 : -1;\n }\n }\n\n public static Builder newBuilder() {\n return new AsmHook().new Builder();\n }\n\n public class Builder extends AsmHook {\n\n private Builder() {\n\n }\n\n public Builder setTargetClass(String className) {\n AsmHook.this.targetClassName = className;\n return this;\n }\n\n public Builder setTargetMethod(String methodName) {\n AsmHook.this.targetMethodName = methodName;\n return this;\n }\n\n public Builder addTargetMethodParameters(Type... parameterTypes) {\n for (Type type : parameterTypes) {\n AsmHook.this.targetMethodParameters.add(type);\n }\n return this;\n }\n\n public Builder addTargetMethodParameters(String... parameterTypeNames) {\n Type[] types = new Type[parameterTypeNames.length];\n for (int i = 0; i < parameterTypeNames.length; i++) {\n types[i] = TypeHelper.getType(parameterTypeNames[i]);\n }\n return addTargetMethodParameters(types);\n }\n\n public Builder setTargetMethodReturnType(Type returnType) {\n AsmHook.this.targetMethodReturnType = returnType;\n return this;\n }\n\n public Builder setTargetMethodReturnType(String returnType) {\n return setTargetMethodReturnType(TypeHelper.getType(returnType));\n }\n\n public Builder setHookClass(String className) {\n AsmHook.this.hooksClassName = className;\n return this;\n }\n\n public Builder setHookMethod(String methodName) {\n AsmHook.this.hookMethodName = methodName;\n return this;\n }\n\n public Builder addHookMethodParameter(Type parameterType, int variableId) {\n if (!AsmHook.this.hasHookMethod()) {\n throw new IllegalStateException(\n \"Hook method is not specified, so can not append \" + \"parameter to its parameters list.\");\n }\n AsmHook.this.hookMethodParameters.add(parameterType);\n AsmHook.this.transmittableVariableIds.add(variableId);\n return this;\n }\n\n public Builder addHookMethodParameter(String parameterTypeName, int variableId) {\n return addHookMethodParameter(TypeHelper.getType(parameterTypeName), variableId);\n }\n\n public Builder addThisToHookMethodParameters() {\n if (!AsmHook.this.hasHookMethod()) {\n throw new IllegalStateException(\n \"Hook method is not specified, so can not append \" + \"parameter to its parameters list.\");\n }\n AsmHook.this.hookMethodParameters.add(TypeHelper.getType(targetClassName));\n AsmHook.this.transmittableVariableIds.add(0);\n return this;\n }\n\n public Builder addReturnValueToHookMethodParameters() {\n if (!AsmHook.this.hasHookMethod()) {\n throw new IllegalStateException(\n \"Hook method is not specified, so can not append \" + \"parameter to its parameters list.\");\n }\n if (AsmHook.this.targetMethodReturnType == Type.VOID_TYPE) {\n throw new IllegalStateException(\n \"Target method's return type is void, it does not make sense to \"\n + \"transmit its return value to hook method.\");\n }\n AsmHook.this.hookMethodParameters.add(AsmHook.this.targetMethodReturnType);\n AsmHook.this.transmittableVariableIds.add(-1);\n AsmHook.this.hasReturnValueParameter = true;\n return this;\n }\n\n public Builder setReturnCondition(ReturnCondition condition) {\n if (condition.requiresCondition && AsmHook.this.hookMethodName == null) {\n throw new IllegalArgumentException(\n \"Hook method is not specified, so can not use return \" + \"condition that depends on hook method.\");\n }\n\n AsmHook.this.returnCondition = condition;\n Type returnType;\n switch (condition) {\n case NEVER:\n case ALWAYS:\n returnType = VOID_TYPE;\n break;\n case ON_TRUE:\n returnType = BOOLEAN_TYPE;\n break;\n default:\n returnType = getType(Object.class);\n break;\n }\n AsmHook.this.hookMethodReturnType = returnType;\n return this;\n }\n\n public Builder setReturnValue(ReturnValue value) {\n if (AsmHook.this.returnCondition == ReturnCondition.NEVER) {\n throw new IllegalStateException(\n \"Current return condition is ReturnCondition.NEVER, so it does not \"\n + \"make sense to specify the return value.\");\n }\n Type returnType = AsmHook.this.targetMethodReturnType;\n if (value != ReturnValue.VOID && returnType == VOID_TYPE) {\n throw new IllegalArgumentException(\n \"Target method return value is void, so it does not make sense to \" + \"return anything else.\");\n }\n if (value == ReturnValue.VOID && returnType != VOID_TYPE) {\n throw new IllegalArgumentException(\n \"Target method return value is not void, so it is impossible \" + \"to return VOID.\");\n }\n if (value == ReturnValue.PRIMITIVE_CONSTANT && returnType != null && !isPrimitive(returnType)) {\n throw new IllegalArgumentException(\n \"Target method return value is not a primitive, so it is \"\n + \"impossible to return PRIVITIVE_CONSTANT.\");\n }\n if (value == ReturnValue.NULL && returnType != null && isPrimitive(returnType)) {\n throw new IllegalArgumentException(\n \"Target method return value is a primitive, so it is impossible \" + \"to return NULL.\");\n }\n if (value == ReturnValue.HOOK_RETURN_VALUE && !hasHookMethod()) {\n throw new IllegalArgumentException(\n \"Hook method is not specified, so can not use return \" + \"value that depends on hook method.\");\n }\n\n AsmHook.this.returnValue = value;\n if (value == ReturnValue.HOOK_RETURN_VALUE) {\n AsmHook.this.hookMethodReturnType = AsmHook.this.targetMethodReturnType;\n }\n return this;\n }\n\n public Type getHookMethodReturnType() {\n return hookMethodReturnType;\n }\n\n protected void setHookMethodReturnType(Type type) {\n AsmHook.this.hookMethodReturnType = type;\n }\n\n private boolean isPrimitive(Type type) {\n return type.getSort() > 0 && type.getSort() < 9;\n }\n\n public Builder setPrimitiveConstant(Object constant) {\n if (AsmHook.this.returnValue != ReturnValue.PRIMITIVE_CONSTANT) {\n throw new IllegalStateException(\n \"Return value is not PRIMITIVE_CONSTANT, so it does not make sence\" + \"to specify that constant.\");\n }\n Type returnType = AsmHook.this.targetMethodReturnType;\n if (returnType == BOOLEAN_TYPE && !(constant instanceof Boolean)\n || returnType == CHAR_TYPE && !(constant instanceof Character)\n || returnType == BYTE_TYPE && !(constant instanceof Byte)\n || returnType == SHORT_TYPE && !(constant instanceof Short)\n || returnType == INT_TYPE && !(constant instanceof Integer)\n || returnType == LONG_TYPE && !(constant instanceof Long)\n || returnType == FLOAT_TYPE && !(constant instanceof Float)\n || returnType == DOUBLE_TYPE && !(constant instanceof Double)) {\n throw new IllegalArgumentException(\"Given object class does not math target method return type.\");\n }\n\n AsmHook.this.primitiveConstant = constant;\n return this;\n }\n\n public Builder setReturnMethod(String methodName) {\n if (AsmHook.this.returnValue != ReturnValue.ANOTHER_METHOD_RETURN_VALUE) {\n throw new IllegalStateException(\n \"Return value is not ANOTHER_METHOD_RETURN_VALUE, \"\n + \"so it does not make sence to specify that method.\");\n }\n\n AsmHook.this.returnMethodName = methodName;\n return this;\n }\n\n public Builder setInjectorFactory(HookInjectorFactory factory) {\n AsmHook.this.injectorFactory = factory;\n return this;\n }\n\n /**\n * Задает приоритет хука. Хуки с большим приоритетом вызаваются раньше.\n */\n public Builder setPriority(HookPriority priority) {\n AsmHook.this.priority = priority;\n return this;\n }\n\n private String getMethodDesc(Type returnType, List<Type> paramTypes) {\n Type[] paramTypesArray = paramTypes.toArray(new Type[0]);\n if (returnType == null) {\n String voidDesc = Type.getMethodDescriptor(Type.VOID_TYPE, paramTypesArray);\n return voidDesc.substring(0, voidDesc.length() - 1);\n } else {\n return Type.getMethodDescriptor(returnType, paramTypesArray);\n }\n }\n\n public AsmHook build() {\n AsmHook hook = AsmHook.this;\n\n hook.targetMethodDescription = getMethodDesc(targetMethodReturnType, hook.targetMethodParameters);\n\n if (hook.hasHookMethod()) {\n hook.hookMethodDescription = Type\n .getMethodDescriptor(hook.hookMethodReturnType, hook.hookMethodParameters.toArray(new Type[0]));\n }\n if (hook.returnValue == ReturnValue.ANOTHER_METHOD_RETURN_VALUE) {\n hook.returnMethodDescription = getMethodDesc(hook.targetMethodReturnType, hook.hookMethodParameters);\n }\n\n try {\n hook = (AsmHook) AsmHook.this.clone();\n } catch (CloneNotSupportedException impossible) {}\n\n if (hook.targetClassName == null) {\n throw new IllegalStateException(\n \"Target class name is not specified. \" + \"Call setTargetClassName() before build().\");\n }\n\n if (hook.targetMethodName == null) {\n throw new IllegalStateException(\n \"Target method name is not specified. \" + \"Call setTargetMethodName() before build().\");\n }\n\n if (hook.returnValue == ReturnValue.PRIMITIVE_CONSTANT && hook.primitiveConstant == null) {\n throw new IllegalStateException(\n \"Return value is PRIMITIVE_CONSTANT, but the constant is not \"\n + \"specified. Call setReturnValue() before build().\");\n }\n\n if (hook.returnValue == ReturnValue.ANOTHER_METHOD_RETURN_VALUE && hook.returnMethodName == null) {\n throw new IllegalStateException(\n \"Return value is ANOTHER_METHOD_RETURN_VALUE, but the method is not \"\n + \"specified. Call setReturnMethod() before build().\");\n }\n\n if (!(hook.injectorFactory instanceof MethodExit) && hook.hasReturnValueParameter) {\n throw new IllegalStateException(\n \"Can not pass return value to hook method \" + \"because hook location is not return insn.\");\n }\n\n return hook;\n }\n }\n}"
},
{
"identifier": "HookClassTransformer",
"path": "src/main/java/mixac1/hooklib/asm/HookClassTransformer.java",
"snippet": "public class HookClassTransformer {\n\n public HashMap<String, List<AsmHook>> hooksMap = new HashMap<String, List<AsmHook>>();\n private HookContainerParser containerParser = new HookContainerParser(this);\n\n public void registerHook(AsmHook hook) {\n if (hooksMap.containsKey(hook.getTargetClassName())) {\n hooksMap.get(hook.getTargetClassName())\n .add(hook);\n } else {\n List<AsmHook> list = new ArrayList<AsmHook>(2);\n list.add(hook);\n hooksMap.put(hook.getTargetClassName(), list);\n }\n }\n\n public void registerHookContainer(String className) {\n containerParser.parseHooks(className);\n }\n\n public void registerHookContainer(InputStream classData) {\n containerParser.parseHooks(classData);\n }\n\n public byte[] transform(String className, byte[] bytecode) {\n List<AsmHook> hooks = hooksMap.get(className);\n\n if (hooks != null) {\n try {\n Collections.sort(hooks);\n int numHooks = hooks.size();\n\n for (AsmHook hook : hooks) {\n DangerRPG.infoLog(\n String.format(\n \"Hook: patching method %s#%s\",\n hook.getTargetClassName(),\n hook.getTargetMethodName()));\n }\n\n int majorVersion = ((bytecode[6] & 0xFF) << 8) | (bytecode[7] & 0xFF);\n boolean java7 = majorVersion > 50;\n\n ClassReader cr = new ClassReader(bytecode);\n ClassWriter cw = createClassWriter(java7 ? ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS);\n HookInjectorClassVisitor hooksWriter = createInjectorClassVisitor(cw, hooks);\n cr.accept(hooksWriter, java7 ? ClassReader.SKIP_FRAMES : ClassReader.EXPAND_FRAMES);\n\n int numInjectedHooks = numHooks - hooksWriter.hooks.size();\n for (AsmHook hook : hooks) {\n DangerRPG.infoLog(\n String.format(\n \"Warning: unsuccesfull pathing method %s#%s\",\n hook.getTargetClassName(),\n hook.getTargetMethodName()));\n }\n\n return cw.toByteArray();\n } catch (Exception e) {\n DangerRPG.logger.error(\"A problem has occured during transformation of class \" + className + \".\");\n DangerRPG.logger.error(\"Attached hooks:\");\n for (AsmHook hook : hooks) {\n DangerRPG.logger.error(hook.toString());\n }\n DangerRPG.logger.error(\"Stack trace:\", e);\n }\n }\n return bytecode;\n }\n\n protected HookInjectorClassVisitor createInjectorClassVisitor(ClassWriter cw, List<AsmHook> hooks) {\n return new HookInjectorClassVisitor(cw, hooks);\n }\n\n protected ClassWriter createClassWriter(int flags) {\n return new SafeClassWriter(flags);\n }\n}"
},
{
"identifier": "HookInjectorClassVisitor",
"path": "src/main/java/mixac1/hooklib/asm/HookInjectorClassVisitor.java",
"snippet": "public class HookInjectorClassVisitor extends ClassVisitor {\n\n List<AsmHook> hooks;\n boolean visitingHook;\n\n public HookInjectorClassVisitor(ClassWriter cv, List<AsmHook> hooks) {\n super(Opcodes.ASM5, cv);\n this.hooks = hooks;\n }\n\n @Override\n public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {\n MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);\n Iterator<AsmHook> it = hooks.iterator();\n while (it.hasNext()) {\n AsmHook hook = it.next();\n if (isTargetMethod(hook, name, desc)) {\n mv = hook.getInjectorFactory()\n .createHookInjector(mv, access, name, desc, hook, this);\n it.remove();\n }\n }\n return mv;\n }\n\n protected boolean isTargetMethod(AsmHook hook, String name, String desc) {\n return hook.isTargetMethod(name, desc);\n }\n}"
}
] | import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import mixac1.hooklib.asm.AsmHook;
import mixac1.hooklib.asm.HookClassTransformer;
import mixac1.hooklib.asm.HookInjectorClassVisitor;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import java.util.HashMap;
import java.util.List; | 5,450 | package mixac1.hooklib.minecraft;
public class PrimaryClassTransformer extends HookClassTransformer implements IClassTransformer {
static PrimaryClassTransformer instance = new PrimaryClassTransformer();
boolean registeredSecondTransformer;
public PrimaryClassTransformer() {
if (instance != null) {
this.hooksMap.putAll(PrimaryClassTransformer.instance.getHooksMap());
PrimaryClassTransformer.instance.getHooksMap()
.clear();
} else {
registerHookContainer(SecondaryTransformerHook.class.getName());
}
instance = this;
}
@Override
public byte[] transform(String oldName, String newName, byte[] bytecode) {
return transform(newName, bytecode);
}
@Override | package mixac1.hooklib.minecraft;
public class PrimaryClassTransformer extends HookClassTransformer implements IClassTransformer {
static PrimaryClassTransformer instance = new PrimaryClassTransformer();
boolean registeredSecondTransformer;
public PrimaryClassTransformer() {
if (instance != null) {
this.hooksMap.putAll(PrimaryClassTransformer.instance.getHooksMap());
PrimaryClassTransformer.instance.getHooksMap()
.clear();
} else {
registerHookContainer(SecondaryTransformerHook.class.getName());
}
instance = this;
}
@Override
public byte[] transform(String oldName, String newName, byte[] bytecode) {
return transform(newName, bytecode);
}
@Override | protected HookInjectorClassVisitor createInjectorClassVisitor(ClassWriter cw, List<AsmHook> hooks) { | 2 | 2023-10-31 21:00:14+00:00 | 8k |
Tamiflu233/DingVideo | dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/LikeServiceImpl.java | [
{
"identifier": "Comment",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/Comment.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Document(collection = com.dataispower.dingvideobackend.common.TableColumns.COMMENT)\npublic class Comment implements Serializable {\n @Id\n private ObjectId id;\n @Field(value = COMMENT_ID)\n private String commentId; // 主键\n @Field(value = PARENT_ID)\n private String parentId; //父回复id\n @Field(value = TYPE)\n private String type; //回复类型(视频or图文)\n @Indexed\n @Field(value = RESOURCE_ID)\n private String resourceId; //对应视频or图文的id\n @Field(value = CONTENT)\n private String content; //评论内容\n @Field(value = AUTHOR)\n private UserInfo author; // 作者信息\n @Field(value = FROM)\n private String from; //评论作者的昵称\n @Field(value = TO)\n private String to; //被评论的用户的昵称\n @Field(value = CREATE_TIME)\n private Date createTime;\n @Field(value = UPDATE_TIME)\n private Date updateTime;\n @Field(value = LIKE_CNT)\n private Long likeCnt;\n @Field(value = REPLY_CNT)\n private Integer replyCnt;\n @Field(value = STATUS)\n private String status; // 表示是否为二级回复,0表示否,1表示是\n @Field(value = REPLIES)\n private List<Comment> replies;\n\n}"
},
{
"identifier": "UserLike",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/UserLike.java",
"snippet": "@Data\n@Entity\n@Table(name = com.dataispower.dingvideobackend.common.TableColumns.USER_LIKE)\npublic class UserLike extends CommonEntity {\n // 用户id\n @Column(name = USER_ID)\n private String userId;\n // 视频id\n @Column(name = POST_ID)\n private String postId;\n // 点赞状态\n @Column(name = STATUS)\n private Integer status;\n // 点赞类型,type(0:视频;1:评论)\n @Column(name = TYPE)\n private String type;\n // 评论所属的视频\n @Column(name = VIDEO_ID)\n private String videoId;\n\n public UserLike() {\n\n }\n public UserLike(String userId, String postId) {\n this.userId = userId;\n this.postId = postId;\n this.status = 1;\n\n }\n public UserLike(String userId, String postId, String type) {\n this.userId = userId;\n this.postId = postId;\n this.status = 1;\n this.type = type;\n this.videoId = \"\";\n }\n public UserLike(String userId, String postId, String type, String videoId) {\n this.userId = userId;\n this.postId = postId;\n this.status = 1;\n this.type = type;\n this.videoId = videoId;\n }\n\n public UserLike(String userId, String postId, Integer status, String type, String videoId) {\n this.userId = userId;\n this.postId = postId;\n this.status = status;\n this.type = type;\n this.videoId = videoId;\n }\n}"
},
{
"identifier": "Video",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/Video.java",
"snippet": "@Data\n@Entity\n@Table(name = com.dataispower.dingvideobackend.common.TableColumns.VIDEO)\npublic class Video {\n @Id\n @Column(name = VIDEO_ID, unique = true)\n private String videoId;\n\n @Column(name = VIDEO_PATH, columnDefinition = \"text\", unique = true)\n private String videoUrl;\n\n @Column(name = COVER_URL, columnDefinition = \"text\")\n private String coverUrl;\n\n @Column(name = TITLE, columnDefinition = \"text\")\n private String title;\n @Column(name = DESCRIPTION, columnDefinition = \"text\")\n private String description;\n\n @Column(name = CATEGORY)\n private String category;\n\n @Column(name = LIKES)\n @ColumnDefault(\"0\")\n private Long likes;\n\n @Column(name = COLLECTIONS)\n @ColumnDefault(\"0\")\n private Long collections;\n\n @Column(name = COMMENTS)\n @ColumnDefault(\"0\")\n private Long comments;\n\n @Transient\n private Boolean isLiked;\n\n @CreationTimestamp\n @Column(name = CREATE_TIME)\n private Date createTime;\n\n @UpdateTimestamp\n @Column(name = UPDATE_TIME)\n private Date updateTime;\n\n @Column(name = USERID, insertable=false, updatable=false)\n private Long useId;\n @ManyToOne(cascade=CascadeType.ALL)\n @JoinColumn(name = USERID)\n private User user;\n\n}"
},
{
"identifier": "LikeRepository",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/repository/LikeRepository.java",
"snippet": "public interface LikeRepository extends JpaRepository<UserLike, Long> {\n // 根据用户id和postId返回点赞列表\n UserLike findUserLikeByUserIdAndPostId(String userId, String postId);\n List<UserLike> findUserLikeByPostId(String postId);\n\n void deleteUserLikeByUserIdAndPostId(String userId, String postId);\n\n // List<UserLike> findAllByUserId(String userId);\n // 返回用户的视频点赞列表\n// @Query(\"select from UserLike u where u.status=1 and u.userId =?1\")\n List<UserLike> findAllByUserId(String userId);\n // 返回视频的用户点赞列表\n @Query(\"select u.userId from UserLike u where u.status=1 and u.postId =?1\")\n List<String> findUserIdByPostId(String postId);\n\n @Query(\"select count(*) from UserLike u where u.status=1 and u.postId in (select v.videoId from Video v where v.user.username=?1)\")\n Integer countByUserId(String userId);\n\n}"
},
{
"identifier": "UserRepository",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/repository/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User, Long> {\n // 根据用户名获取用户信息\n User getUserByUsername(String username);\n User getUserById(Long id);\n}"
},
{
"identifier": "VideoRepository",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/repository/VideoRepository.java",
"snippet": "@Transactional\npublic interface VideoRepository extends JpaRepository<Video, Long> {\n\n List<Video> findVideosByUser(User user);\n\n Video findVideoByVideoId(String videoId);\n\n @Modifying\n @Query(\"update Video v set v.comments = v.comments + 1 where v.videoId = :videoId\")\n void incrementCommentCnt(@Param(\"videoId\") String videoId);\n\n @Modifying\n @Query(\"update Video v set v.comments = v.comments - 1 where v.videoId = :videoId\")\n void decrementCommentCnt(@Param(\"videoId\") String videoId);\n\n List<Video> findVideosByCoverUrl(String coverUrl);\n void deleteVideoByVideoId(String videoId);\n\n // 批量查找视频\n List<Video> findVideosByVideoIdIn(List<String> videoIds);\n // 根据类别查找视频\n List<Video> getVideosByCategory(String kind);\n List<Video> getVideosByUserId(Long userid);\n @Query(\"select v from Video v ORDER BY RAND()\")\n List<Video> findAllRandomOrder();\n}"
},
{
"identifier": "CommentService",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/interfaces/CommentService.java",
"snippet": "public interface CommentService {\n /*\n * 查询某资源所有评论\n * */\n public List<Comment> findCommentsByResourceId(String type, String resourceId);\n // 查询某一个评论\n public Comment findCommentByCommentId(String commentId);\n // 查询当前资源下所有评论\n public List<Comment> findCommentsByResourceId(String resourceId);\n /*\n * 对指定资源发表评论\n * */\n public Integer saveComment(String type, String resourceId, UserInfo author, String content);\n\n public Integer updateComment(Comment comment);\n /*\n * 回复评论\n *\n * */\n public Integer replyComment(String parentId,UserInfo author,String content) throws Exception;\n /*\n * 回复评论(二级)\n *\n * */\n public Integer replyComment(Comment parentComment,UserInfo author,String content);\n\n public Integer deleteComment(String parentId,String commentId);\n\n}"
},
{
"identifier": "LikeService",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/interfaces/LikeService.java",
"snippet": "public interface LikeService {\n\n // 保存喜爱记录\n void saveLike(UserLike userLike);\n // 喜欢操作,包括保存喜欢记录和更新当前postId喜欢数\n void like(String userId,String postId, String type);\n // 对评论或者问答的喜欢操作\n void like(String userId, String postId, String videoId, String type);\n // 将喜欢记录加载到Redis中\n void loadLikesToRedis(String userId);\n // 将一条点赞记录加载到redis中\n void loadSingleLikeToRedis(String userId, String postId);\n // 将当前postId喜欢数目从mysql更新到redis\n void loadLikesCountToRedis(String postId, String type);\n // 定时任务:将喜欢记录对从redis更新到mysql\n void saveLikesFromRedis();\n // 定时任务:将当前视频喜欢数目从redis更新到mysql\n void saveLikesCountFromRedis();\n // 返回用户所有喜欢的视频列表\n List<String> getCurrentUserLikeVideos(String userId);\n // 返回所有视频的点赞个数\n// List<Map<String, Object>> getVideosCountLike();\n // 返回当前用户点赞视频的点赞个数\n List<Map<String, Object>> getVideosCountLike(String uerId);\n // 获得在redis中存在的视频点赞个数\n Long getSingleVideoCountLike(String videoId);\n // 获得在redis中存在的评论点赞个数\n Long getSingleCommentCountLike(String commentId);\n // 获得在redis中存在的问答点赞个数\n Long getSingleQuestionCountLike(String questionId);\n // 返回当前视频评论的点赞个数\n List<Map<String, Object>> getCommentsCountLike(String userId, String videoId);\n // 返回当前问答的点赞个数\n List<Map<String, Object>> getQuestionsCountLike(String userId, String videoId);\n // 判断用户对postId喜欢状态\n Boolean getCurrentUserLikeState(String userId, String postId, String type);\n // 判断用户对postId喜欢状态(评论或问答)\n Boolean getCurrentUserLikeState(String userId, String postId, String videoId, String type);\n // 判断某一个key是否存在Redis中\n boolean existUserRedisKey(String userId);\n // 判断某一个post是否存在Redis中\n boolean existPostRedisKey(String postId, String type);\n}"
},
{
"identifier": "RedisLikeService",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/interfaces/RedisLikeService.java",
"snippet": "public interface RedisLikeService {\n // 存储喜欢关系对(用户id,postId),type(0:视频;1:评论;2:问答)\n void saveLike(String userId, String postId, String type);\n // 存储喜欢关系三元组(用户id,postId),type(0:视频;1:评论;2:问答),videoId\n void saveLike(String userId, String postId, String videoId, String type);\n\n // 加载点赞数据\n void setLikeCount(String postId, String type, long num);\n // 将对应type的喜欢数+1\n void increaseLikeCount(String postId, String type);\n // 将对应type的喜欢数-1\n void decreaseLikeCount(String postId, String type);\n // 返回所有喜欢对\n List<UserLike> getAllLike();\n // 判断用户对postId喜欢状态\n Boolean getCurrentUserLikeState(String userId, String postId, String type);\n // 判断用户对当前视频下评论或者问答的喜欢状态\n Boolean getCurrentUserLikeState(String userId, String postId, String videoId, String type);\n // 返回用户所有喜欢的视频列表\n List<String> getCurrentUserLikeVideos(String userId);\n // 保存已点赞后取消记录\n void cancelLike(String userId, String postId, String type);\n // 返回所有postId的点赞个数\n List<Map<String, Object>> getCountLike(String type);\n // 返回当前用户每个视频的点赞信息对(视频id,点赞个数)\n List<Map<String, Object>> getVideosCountLike(String userId);\n // 返回当前用户获得点赞的点赞信息(点赞人,点赞人头像,点赞时间,获赞视频id)\n List<Map<String, Object>> getUserBeLikeInfo(String userId);\n // 返回当前视频用户评论的点赞点赞信息对(评论id,点赞个数)\n List<Map<String, Object>> getCommentsCountLike(String userId, String videoId);\n // 返回当前视频用户问答的点赞点赞信息对(问答id,点赞个数)\n List<Map<String, Object>> getQuestionsCountLike(String userId, String videoId);\n // 返回取消点赞列表\n Set<String> getCancelLike(String userId, String type);\n // 判断某一个key是否存在Redis中\n boolean existLikeCount(String postId, String type);\n // 判断是否在mysql中并未导入到redis中\n boolean existLike(String userId, String postId, String type);\n // 判断是否在mysql中并未导入到redis中\n boolean existLike(String userId, String videoId, String postId, String type);\n // 删除redis中的所有数据\n void deleteRedis();\n // 判断某一个用户是否存在Redis中\n boolean existUserRedisKey(String userId);\n // 判断某一个post是否存在Redis中\n boolean existPostRedisKey(String postId, String type);\n Long getSingleVideoCountLike(String videoId);\n\n Long getSingleCommentCountLike(String commentId);\n\n Long getSingleQuestionCountLike(String questionId);\n}"
},
{
"identifier": "VideoService",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/interfaces/VideoService.java",
"snippet": "public interface VideoService {\n List<Video> getVideoList(String kind);\n List<Video> getHomeVideos();\n\n List<Video> getVideoListByUserIdAndType(Integer userid, Integer type);\n\n Map<String, Object> getVideoByVideoId(String videoId, String username);\n}"
}
] | import com.dataispower.dingvideobackend.entity.Comment;
import com.dataispower.dingvideobackend.entity.UserLike;
import com.dataispower.dingvideobackend.entity.Video;
import com.dataispower.dingvideobackend.repository.LikeRepository;
import com.dataispower.dingvideobackend.repository.UserRepository;
import com.dataispower.dingvideobackend.repository.VideoRepository;
import com.dataispower.dingvideobackend.service.interfaces.CommentService;
import com.dataispower.dingvideobackend.service.interfaces.LikeService;
import com.dataispower.dingvideobackend.service.interfaces.RedisLikeService;
import com.dataispower.dingvideobackend.service.interfaces.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | 3,956 | package com.dataispower.dingvideobackend.service;
/**
* author:heroding
* date:2023/11/6 16:06
* description:点赞服务类
**/
@Service
public class LikeServiceImpl implements LikeService {
@Autowired
private LikeRepository userLikeRepository;
@Autowired
private RedisLikeService redisLikeService;
@Autowired
private VideoRepository videoRepository;
@Autowired | package com.dataispower.dingvideobackend.service;
/**
* author:heroding
* date:2023/11/6 16:06
* description:点赞服务类
**/
@Service
public class LikeServiceImpl implements LikeService {
@Autowired
private LikeRepository userLikeRepository;
@Autowired
private RedisLikeService redisLikeService;
@Autowired
private VideoRepository videoRepository;
@Autowired | private UserRepository userRepository; | 4 | 2023-10-25 07:16:43+00:00 | 8k |
MiguelPereiraDantas/E-commerce-Java | src/main/java/br/com/fourstore/controller/SaleController.java | [
{
"identifier": "ServiceSale",
"path": "src/main/java/br/com/fourstore/service/ServiceSale.java",
"snippet": "@Service\npublic class ServiceSale {\n\t\n\t@Autowired\n\tServiceProduct serviceProduct;\n\t\n\t@Autowired\n\tServiceHistoric serviceHistoric;\n\t\n\tprivate static List<Product> cart = new ArrayList<Product>();\n\t\n\t//Listar produtos no carrinho\n\tpublic List<Product> getCart(){\n\t\treturn cart;\n\t}\n\t\n\t//Procurar produto por SKU no carrinho\n\tpublic Product searchProductBySkuInCart(String sku) {\n\t\tfor(int x=0; x<getCart().size(); x++) {\n\t\t\tProduct product = getCart().get(x);\n\t\t\tif(sku.equals(product.getSku())) {\n\t\t\t\treturn product;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t//Adicionar produto no carrinho atraves do SKU\n\tpublic String addProductToCart(String sku, Integer theAmount) {\n\t\tProduct product = serviceProduct.searchProductBySku(sku);\n\t\t\n\t\tif(product == null) {\n\t\t\treturn \"SKU inexistente\";\n\t\t} else if(product.getTheAmount() <= 0) {\n\t\t\treturn \"Sem essa quantidade no estoque\";\n\t\t} else if(theAmount <= 0) {\n\t\t\treturn \"Por favor digite uma quantidade valida\";\n\t\t} else {\n\t\t\t\tproduct.setTheAmount(theAmount);\n\t\t\t\tProduct cartProduct = searchProductBySkuInCart(sku);\n\t\t\t\tif(cartProduct == null) {\n\t\t\t\t\tcart.add(product);\n\t\t\t\t\treturn \"Produto adicionado com sucesso\";\n\t\t\t\t} else {\n\t\t\t\t\tcartProduct.setTheAmount(cartProduct.getTheAmount() + theAmount);\n\t\t\t\t\tif(editProductInCart(cartProduct) == 0) {\n\t\t\t\t\t\treturn \"Produto adicionado com sucesso\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn \"Falha ao adicionar o produto\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\t\t\n\t\t}\n\t}\n\t\n\t//Retirar produto do carrinho\n\tpublic String removeProductFromCart(String sku, Integer theAmount) {\n\t\tProduct product = searchProductBySkuInCart(sku);\n\t\t\n\t\tif(product == null) {\n\t\t\treturn \"SKU inexistente\";\n\t\t} else if(product.getTheAmount() < theAmount) {\n\t\t\treturn \"Nao existe essa quantidade no carrinho\";\n\t\t} else if(theAmount <= 0) {\n\t\t\treturn \"Por favor digite uma quantidade valida\";\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tproduct.setTheAmount(product.getTheAmount() - theAmount);\n\t\t\t\teditProductInCart(product);\n\t\t\t\treturn \"Produto retitado do carrinho\";\t\t\t\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn \"Falha ao retirar o produto do carrinho\";\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//editar produto no carrinho\n\tprivate Integer editProductInCart(Product product) {\n\t\tInteger index = -1;\n\t\tfor(int x=0; x<getCart().size(); x++) {\n \t\tProduct prouctSku = getCart().get(x);\n \t\tif(product.getSku().equals(prouctSku.getSku())) {\n \t\t\tindex = x;\n \t\t}\n \t}\n\t\tswitch(index) {\n\t\tcase -1:\n\t\t\treturn 1;//\"SKU nao encontrado\";\n\t\t\t\n\t\tdefault:\n\t\t\tif(cart.set(index, product) != null) {\n\t\t\t\tcheckZeroProducts();\n\t\t\t\treturn 0;//\"Produto editado com sucesso\";\n\t\t\t} else {\n\t\t\t\treturn 1;//\"Edição do produto falhou\";\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//Esvaziar o carrinho\n\tpublic String emptyCart() {\n\t\tfor(int x=0; x<getCart().size(); x++) {\n \t\tProduct product = getCart().get(x);\n \t\tremoveProductFromCart(product.getSku(), product.getTheAmount());\n \t}\n\t\treturn \"Compra Cancelada...Carrinho Esvaziado\";\n\t}\n\t\n\t//total das compras\n\tpublic Double purchaseTotal() {\n\t\tDouble total = 0.0;\n\t\tfor(int x=0; x<getCart().size(); x++) {\n \t\ttotal = total + (getCart().get(x).getPrice() * getCart().get(x).getTheAmount());\n \t}\n\t\treturn total;\n\t}\n\t\n\t//verificar os produtos que estão zerados e tirar eles\n\tprivate void checkZeroProducts() {\n\t\tfor(int x=0; x<getCart().size(); x++) {\n\t\t\tProduct product = getCart().get(x);\n\t\t\tif(product.getTheAmount() <=0 ) {\n\t\t\t\tcart.remove(product);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//Verificar produtos no estoque da loja antes de finalizar a compra\n\tpublic List<Product> checkCart() {\n\t\tList<Product> insufficientProducts = new ArrayList<Product>();\n\t\t\n\t\tfor(int x=0; x<getCart().size(); x++) {\n\t\t\tProduct productInCart = getCart().get(x);\n\t\t\tProduct productInInventory = serviceProduct.searchProductBySku(productInCart.getSku());\n\t\t\tif(productInInventory == null || productInInventory.getTheAmount() < productInCart.getTheAmount()) {\n\t\t\t\tinsufficientProducts.add(productInInventory);\n\t\t\t\tremoveProductFromCart(productInCart.getSku(), productInCart.getTheAmount());\n\t\t\t}\n\t\t}\n\t\treturn insufficientProducts;\n\t}\n\t\n\t//Retirar produto do iventario\t\t\n\tprivate void removeProductsFromInventory() {\n\t\tInteger theAmount;\n\t\tfor(int x=0; x<getCart().size(); x++) {\n\t\t\tProduct productInCart = getCart().get(x);\n\t\t\ttheAmount = (-1) * productInCart.getTheAmount();\n\t\t\tProduct updatedProduct = new Product(productInCart.getSku(), productInCart.getDescription(), theAmount, productInCart.getPrice());\n\t\t\tserviceProduct.editProduct(updatedProduct.getSku(), updatedProduct);\n\t\t}\n\t}\n\t\n\t//Finalizar compra\n\tpublic Sale checkout(Integer typeOfSale, Sale sale) {\n\t\tif(getCart().size() <= 0 || getCart() == null || purchaseTotal() == null || purchaseTotal() <= 0) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tsale.setTypeOfSale(TypeOfSaleEnum.getTypeOfSaleEnum(typeOfSale));\n\t\t\tsale.setTotal(purchaseTotal());\n\t\t\tsale.setCart(getCart());\n\t\t\t\n\t\t\tif(sale.getTypeOfSale() == TypeOfSaleEnum.CREDITO) {\n\t\t\t\tCredit credit = (Credit) sale;\n\t\t\t\tif(credit.getCardNumber() == null || credit.getCardNumber() == \"\" ||\n\t\t\t\t credit.getExpirationDate() == null || credit.getExpirationDate() == \"\" ||\n\t\t\t\t credit.getSecurityCode() == null || credit.getSecurityCode() < 0 ||\n\t\t\t\t credit.getInstallments() == null || credit.getInstallments() < 0) {\n\t\t\t\t\treturn null;\n\t\t\t\t} else {\n\t\t\t\t\tif(serviceHistoric.saveToHistory(credit) == null) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tremoveProductsFromInventory();\n\t\t\t\t\t\tcart.clear();\n\t\t\t\t\t\treturn serviceHistoric.getHistoricId(credit.getId());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if(sale.getTypeOfSale() == TypeOfSaleEnum.DEBITO) {\n\t\t\t\tDebit debit = (Debit) sale;\n\t\t\t\tif(debit.getCardNumber() == null || debit.getCardNumber() == \"\" ||\n\t\t\t\t debit.getExpirationDate() == null || debit.getExpirationDate() == \"\" ||\n\t\t\t\t debit.getSecurityCode() == null || debit.getSecurityCode() < 0) {\n\t\t\t\t\treturn null;\n\t\t\t\t} else {\n\t\t\t\t\tif(serviceHistoric.saveToHistory(debit) == null) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tremoveProductsFromInventory();\n\t\t\t\t\t\tcart.clear();\n\t\t\t\t\t\treturn serviceHistoric.getHistoricId(debit.getId());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if(sale.getTypeOfSale() == TypeOfSaleEnum.DINHEIRO) {\n\t\t\t\tMoney money = (Money) sale;\n\t\t\t\tif(serviceHistoric.saveToHistory(money) == null) {\n\t\t\t\t\treturn null;\n\t\t\t\t} else {\n\t\t\t\t\tremoveProductsFromInventory();\n\t\t\t\t\tcart.clear();\n\t\t\t\t\treturn serviceHistoric.getHistoricId(money.getId());\n\t\t\t\t}\n\t\t\t} else if(sale.getTypeOfSale() == TypeOfSaleEnum.PIX) {\n\t\t\t\tPix pix = (Pix) sale;\n\t\t\t\tif(pix.getPixKey() == null || pix.getPixKey() == \"\") {\n\t\t\t\t\treturn null;\n\t\t\t\t} else {\n\t\t\t\t\tif(serviceHistoric.saveToHistory(pix) == null) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tremoveProductsFromInventory();\n\t\t\t\t\t\tcart.clear();\n\t\t\t\t\t\treturn serviceHistoric.getHistoricId(pix.getId());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"identifier": "Credit",
"path": "src/main/java/br/com/fourstore/model/Credit.java",
"snippet": "@Document\npublic class Credit extends Sale{\n\t\n\t@NonNull\n\tprivate String cardNumber;\n\t\n\t@NonNull\n\tprivate String expirationDate;\n\t\n\t@NonNull\n\tprivate Integer securityCode;\n\t\n\t@NonNull\n\tprivate Integer installments;\n\n\t\n\tpublic Credit(String cpf, Double total, TypeOfSaleEnum typeOfSale, List<Product> cart, String cardNumber, String expirationDate, Integer securityCode, Integer installments) {\n\t\tsuper();\n\t\tthis.setCpf(cpf);\n\t\tthis.setTotal(total);\n\t\tthis.setTypeOfSale(typeOfSale);\n\t\tthis.setCart(cart);\n\t\tthis.cardNumber = cardNumber;\n\t\tthis.expirationDate = expirationDate;\n\t\tthis.securityCode = securityCode;\n\t\tthis.installments = installments;\n\t}\n\t\n\t\n\tpublic String getCardNumber() {\n\t\treturn cardNumber;\n\t}\n\tpublic void setCardNumber(String cardNumber) {\n\t\tthis.cardNumber = cardNumber;\n\t}\n\t\n\tpublic String getExpirationDate() {\n\t\treturn expirationDate;\n\t}\n\tpublic void setExpirationDate(String expirationDate) {\n\t\tthis.expirationDate = expirationDate;\n\t}\n\t\n\tpublic Integer getSecurityCode() {\n\t\treturn securityCode;\n\t}\n\tpublic void setSecurityCode(Integer securityCode) {\n\t\tthis.securityCode = securityCode;\n\t}\n\t\n\tpublic Integer getInstallments() {\n\t\treturn installments;\n\t}\n\tpublic void setInstallments(Integer installments) {\n\t\tthis.installments = installments;\n\t}\n\t\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CPF: \" + getCpf() + \"\\nData e Hora da Compra: \" + getDate() + \"\\t\" + getTime() \n\t\t\t + \"\\nForma de Pagamento: Credito\" + \"\\nDados do Cartao: \" + \"\\nNumero do cartao: \" \n\t\t\t + cardNumber + \"\\tData de Vencimento: \" + expirationDate + \"\\tCodigo de Seguranca: \"\n\t\t\t + securityCode + \"\\nTotal das compras: R$\" + getTotal() + \"\\tParcelas: \" + installments;\n\t}\n}"
},
{
"identifier": "Debit",
"path": "src/main/java/br/com/fourstore/model/Debit.java",
"snippet": "@Document\npublic class Debit extends Sale{\n\t\n\t@NonNull\n\tprivate String cardNumber;\n\t\n\t@NonNull\n\tprivate String expirationDate;\n\t\n\t@NonNull\n\tprivate Integer securityCode;\n\t\n\t\n\tpublic Debit(String cpf, Double total, TypeOfSaleEnum typeOfSale, List<Product> cart, String cardNumber, String expirationDate, Integer securityCode) {\n\t\tsuper();\n\t\tthis.setCpf(cpf);\n\t\tthis.setTotal(total);\n\t\tthis.setTypeOfSale(typeOfSale);\n\t\tthis.setCart(cart);\n\t\tthis.cardNumber = cardNumber;\n\t\tthis.expirationDate = expirationDate;\n\t\tthis.securityCode = securityCode;\n\t}\n\t\n\t\n\tpublic String getCardNumber() {\n\t\treturn cardNumber;\n\t}\n\tpublic void setCardNumber(String cardNumber) {\n\t\tthis.cardNumber = cardNumber;\n\t}\n\t\n\tpublic String getExpirationDate() {\n\t\treturn expirationDate;\n\t}\n\tpublic void setExpirationDate(String expirationDate) {\n\t\tthis.expirationDate = expirationDate;\n\t}\n\t\n\tpublic Integer getSecurityCode() {\n\t\treturn securityCode;\n\t}\n\tpublic void setSecurityCode(Integer securityCode) {\n\t\tthis.securityCode = securityCode;\n\t}\n\t\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CPF: \" + getCpf() + \"\\nData e Hora da Compra: \" + getDate() + \"\\t\" + getTime() \n\t\t\t + \"\\nForma de Pagamento: Debito\" + \"\\nDados do Cartao: \" + \"\\nNumero do cartao: \" \n\t\t\t + cardNumber + \"\\tData de Vencimento: \" + expirationDate + \"\\tCodigo de Seguranca: \"\n\t\t\t + securityCode + \"\\nTotal das compras: R$\" + getTotal();\n\t}\n}"
},
{
"identifier": "Money",
"path": "src/main/java/br/com/fourstore/model/Money.java",
"snippet": "@Document\npublic class Money extends Sale{\n\t\n\tpublic Money(String cpf, Double total, TypeOfSaleEnum typeOfSale, List<Product> cart) {\n\t\tsuper();\n\t\tthis.setCpf(cpf);\n\t\tthis.setTotal(total);\n\t\tthis.setTypeOfSale(typeOfSale);\n\t\tthis.setCart(cart);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CPF: \" + getCpf() + \"\\nData e Hora da Compra: \" + getDate() + \"\\t\" + getTime() \n\t\t\t + \"\\nForma de Pagamento: Dinheiro\" + \"\\nTotal das compras: R$\" + getTotal();\n\t}\n}"
},
{
"identifier": "Pix",
"path": "src/main/java/br/com/fourstore/model/Pix.java",
"snippet": "@Document\npublic class Pix extends Sale{\n\t\n\t@NonNull\n\tprivate String pixKey;\n\n\t\n\tpublic String getPixKey() {\n\t\treturn pixKey;\n\t}\n\tpublic void setPixKey(String pixKey) {\n\t\tthis.pixKey = pixKey;\n\t}\n\t\n\t\n\tpublic Pix(String cpf, Double total, TypeOfSaleEnum typeOfSale, List<Product> cart, String pixKey) {\n\t\tsuper();\n\t\tthis.setCpf(cpf);\n\t\tthis.setTotal(total);\n\t\tthis.setTypeOfSale(typeOfSale);\n\t\tthis.setCart(cart);\n\t\tthis.pixKey = pixKey;\n\t}\n\t\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CPF: \" + getCpf() + \"\\nData e Hora da Compra: \" + getDate() + \"\\t\" + getTime() \n\t\t\t + \"\\nForma de Pagamento: Pix\" + \"\\nTotal das compras: R$\" + getTotal()\n\t\t\t + \"\\nChave Pix: \" + pixKey;\n\t}\n\t\n}"
},
{
"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": "Sale",
"path": "src/main/java/br/com/fourstore/model/Sale.java",
"snippet": "@Document(collection = \"historic\")\npublic class Sale {\n\t\n\t@Transient //Anotação para não pegar o dateAndTime no bd\n\tDate dateAndTime = new Date();\n\t\n\t@Id\n\tprivate String id;\n\t\n\tprivate String cpf;\n\t\n\tprivate String date = new SimpleDateFormat(\"dd/MM/yyyy\").format(dateAndTime);\n\t\n\tprivate String time = new SimpleDateFormat(\"HH:mm:ss\").format(dateAndTime);\n\t\n\t@NonNull\n\tprivate Double total;\n\t\n\t@NonNull\n\tprivate TypeOfSaleEnum typeOfSale;\n\t\n\t@NonNull\n\tprivate List<Product> cart;\n\t\n\t\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\t\n\tpublic String getCpf() {\n\t\treturn cpf;\n\t}\n\tpublic void setCpf(String cpf) {\n\t\tthis.cpf = cpf;\n\t}\n\t\n\tpublic String getDate() {\n\t\treturn date;\n\t}\n\t\n\tpublic String getTime() {\n\t\treturn time;\n\t}\n\t\n\tpublic Double getTotal() {\n\t\treturn total;\n\t}\n\tpublic void setTotal(Double total) {\n\t\tthis.total = total;\n\t}\n\t\n\tpublic TypeOfSaleEnum getTypeOfSale() {\n\t\treturn typeOfSale;\n\t}\n\tpublic void setTypeOfSale(TypeOfSaleEnum typeOfSale) {\n\t\tthis.typeOfSale = typeOfSale;\n\t}\n\n\tpublic List<Product> getCart() {\n\t\treturn cart;\n\t}\n\tpublic void setCart(List<Product> cart) {\n\t\tthis.cart = cart;\n\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.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.service.ServiceSale;
import br.com.fourstore.model.Credit;
import br.com.fourstore.model.Debit;
import br.com.fourstore.model.Money;
import br.com.fourstore.model.Pix;
import br.com.fourstore.model.Product;
import br.com.fourstore.model.Sale; | 5,305 | package br.com.fourstore.controller;
@RestController
@RequestMapping("/sale")
public class SaleController {
@Autowired
ServiceSale serviceSale;
@GetMapping("/cart")
public List<Product> getCart(){
return serviceSale.getCart();
}
@GetMapping("/cart/{sku}")
public Product getProductInCart(@PathVariable("sku") String sku) {
return serviceSale.searchProductBySkuInCart(sku);
}
@PostMapping("/cart/add/{sku}/{theAmount}")
public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.addProductToCart(sku, theAmount);
}
@DeleteMapping("/cart/delete/{sku}/{theAmount}")
public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.removeProductFromCart(sku, theAmount);
}
@DeleteMapping("/cart/empty")
public String deleteCart() {
return serviceSale.emptyCart();
}
@GetMapping("/cart/total")
public Double getTotal() {
return serviceSale.purchaseTotal();
}
@GetMapping("/cart/checkcart")
public List<Product> getCheckCart(){
return serviceSale.checkCart();
}
@PostMapping("/cart/finalizar/credit")
public Sale postHistoricCredit(@RequestBody Credit credit) {
return serviceSale.checkout(1, credit);
}
@PostMapping("/cart/finalizar/debit")
public Sale postHistoricDebit(@RequestBody Debit debit) {
return serviceSale.checkout(2, debit);
}
@PostMapping("/cart/finalizar/money")
public Sale postHistoricMoney(@RequestBody Money money) {
return serviceSale.checkout(3, money);
}
@PostMapping("/cart/finalizar/pix") | package br.com.fourstore.controller;
@RestController
@RequestMapping("/sale")
public class SaleController {
@Autowired
ServiceSale serviceSale;
@GetMapping("/cart")
public List<Product> getCart(){
return serviceSale.getCart();
}
@GetMapping("/cart/{sku}")
public Product getProductInCart(@PathVariable("sku") String sku) {
return serviceSale.searchProductBySkuInCart(sku);
}
@PostMapping("/cart/add/{sku}/{theAmount}")
public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.addProductToCart(sku, theAmount);
}
@DeleteMapping("/cart/delete/{sku}/{theAmount}")
public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.removeProductFromCart(sku, theAmount);
}
@DeleteMapping("/cart/empty")
public String deleteCart() {
return serviceSale.emptyCart();
}
@GetMapping("/cart/total")
public Double getTotal() {
return serviceSale.purchaseTotal();
}
@GetMapping("/cart/checkcart")
public List<Product> getCheckCart(){
return serviceSale.checkCart();
}
@PostMapping("/cart/finalizar/credit")
public Sale postHistoricCredit(@RequestBody Credit credit) {
return serviceSale.checkout(1, credit);
}
@PostMapping("/cart/finalizar/debit")
public Sale postHistoricDebit(@RequestBody Debit debit) {
return serviceSale.checkout(2, debit);
}
@PostMapping("/cart/finalizar/money")
public Sale postHistoricMoney(@RequestBody Money money) {
return serviceSale.checkout(3, money);
}
@PostMapping("/cart/finalizar/pix") | public Sale postHistoricPix(@RequestBody Pix pix) { | 4 | 2023-10-26 15:48:53+00:00 | 8k |
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; | 5,664 | Assert.assertTrue(!rule7.check(items)); //dont match
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals((121200 * 2) / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
}
@Test
public void testoneSKUSum() {
String ruleString2 = "[#k01#k02].oneSKUSum(20000) -> -50%",
ruleString6 = "[#k01#k02].oneSKUSum(727200) -> -50%",
ruleString7 = "$.oneSKUSum(727201) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
Assert.assertTrue(!rule7.check(items)); //dont match
//#region deprecated api
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals(121200 / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
//#endregion
//#region new api
BestMatch best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneRule);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneTime);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule2), items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//01 * 2,02 * 6
best = Strategy.bestChoice(Collections.singletonList(rule2), items, MatchType.OneTime);
//Assert.assertEquals(121200 / -2, best.totalDiscount());//02 * 1
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
rules = Arrays.asList(rule2,rule6,rule7);
best = Strategy.bestChoice(rules, items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//matches rule2, gets 7 match groups
best = Strategy.bestChoice(rules, items, MatchType.OneTime);
//Assert.assertEquals((121200 * 6) / -2, best.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());
Rule rule8 = Interpreter.parseString("[#k01#k02#k03].oneSKUSum(727200) -> -60%").asRule();
rules=Arrays.asList(rule2,rule6,rule7,rule8);
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6 +50) * 6 / -10 , best.totalDiscount());
//#endregion
}
@Test
public void testDiscountPerPrice(){
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 39000),
new ItemImpl("01", "01", "01", "01", "02", "01", 11000),
new ItemImpl("02", "02", "02", "02", "03", "02", 11000)
);
Rule rule1 = Interpreter.parseString("$.count(3)->-7000/15000").asRule(),
rule2 = Interpreter.parseString("$.count(1)->-1000/10000").asRule(),
rule3 = Interpreter.parseString("$.sum(15000)->-7000/15000").asRule();
List<Rule> rules = Arrays.asList(rule1,rule2); | 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){
//System.out.println(JSON.toJSONString(bestMatch, SerializerFeature.PrettyFormat));
if (bestMatch == null) {
System.out.println("no match");
return;
}
System.out.println("matches:[");
for(Match m : bestMatch.getMatches()){
System.out.println("\tmatch of "+m.getRule()+":[");
for (Item t : m.getItems()) {
System.out.println("\t\t" + ((ItemImpl) t).toString());
}
System.out.println("\t]");
}
System.out.println("]");
System.out.printf("sum price:%d \t\tsum discount: %d\n", bestMatch.totalPrice(), bestMatch.totalDiscount());
System.out.println("left:[");
for (Item t : bestMatch.left()) {
System.out.println("\t" + ((ItemImpl) t).toString());
}
System.out.println("]");
System.out.println("suggestion:");
System.out.println(bestMatch.getSuggestion());
}
@Test
public void bestMatch() {
Rule r1 = Builder.rule().simplex()
.range("[#cc01]")
.predict(P.COUNT)
.expected(2)
.endRule()
.promotion("-200")
.build();
Rule r2 = Builder.rule().simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.COUNT)
.expected(3)
.endRule()
.promotion("-300")
.build();
Rule r3 = Builder.rule().simplex()
.addRangeAll()
.predict(P.COUNT)
.expected(6)
.endRule()
.promotion("-10%")
.build();
List<Item> items = _getSelectedItems();
List<Rule> rules = Arrays.asList(r1, r2);
BestMatch bestMatch = Strategy.bestMatch(rules, items);
Assert.assertEquals(2, bestMatch.getMatches().size());
Assert.assertEquals(r1, bestMatch.getMatches().get(0).getRule());
//System.out.println("best:");
//_logBestMatch(bestMatch);
BestMatch bestMatch1 = Strategy.bestChoice(rules, items, MatchType.OneRule);
Assert.assertEquals(bestMatch.getMatches().get(0).getRule(),bestMatch1.getMatches().get(0).getRule());
Assert.assertEquals(bestMatch.totalDiscount(),bestMatch1.totalDiscount());
BestMatch bestOfOnce = Strategy.bestOfOnlyOnceDiscount(rules, items);
//System.out.println("best of only once discount:");
//_logBestMatch(bestOfOnce);
bestMatch1 = Strategy.bestChoice(rules, items,MatchType.OneTime);
Assert.assertEquals(bestOfOnce.getMatches().get(0).getRule(),bestMatch1.getMatches().get(0).getRule());
Assert.assertEquals(bestOfOnce.totalDiscount(),bestMatch1.totalDiscount());
// 5 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
//BestMatch bestOfMulti = Strategy.bestOfMultiRuleApply(rules,tickets);
BestMatch bestOfMulti = Strategy.bestChoice(rules, items, MatchType.MultiRule);
Assert.assertEquals(2,bestOfMulti.getMatches().size());
Assert.assertEquals(5,bestOfMulti.chosen().size());
Assert.assertEquals(-500,bestOfMulti.totalDiscount());
//System.out.println("best of multi-rule apply:");
//_logBestMatch(bestOfMulti);
// 6 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals(6,bestOfMulti.chosen().size());
Assert.assertEquals(-600,bestOfMulti.totalDiscount());
//System.out.println("best of multi-rule apply:");
//_logBestMatch(bestOfMulti);
// 7 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals(3,bestOfMulti.getMatches().size());
Assert.assertEquals(7,bestOfMulti.chosen().size());
Assert.assertEquals(-700,bestOfMulti.totalDiscount());
System.out.println("best of multi-rule apply:");
_logBestMatch(bestOfMulti);
// 7 tickets matched
Rule r4 = Builder.rule().simplex().addRange(R.SPU,"p02")
.predict(P.COUNT).expected(4).endRule()
.promotion("-2000").build();
rules = Arrays.asList(r1,r2,r3,r4);
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
//Assert.assertEquals(3,bestOfMulti.getMatches().size());
Assert.assertEquals(14,bestOfMulti.chosen().size());
Assert.assertEquals(-400-300-2000-500-600-700-800-900-200-300,bestOfMulti.totalDiscount());
System.out.println("best of multi-rule apply:");
_logBestMatch(bestOfMulti);
r3.setPromotion("-100");
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
_logBestMatch(bestOfMulti);
}
@Test
public void testSum() {
Rule r1 = Builder.rule()
.simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-900")
.build();
List<Item> selectedItems = _getSelectedItems();
BestMatch bestMatch = Strategy.bestMatch(Arrays.asList(r1), selectedItems);
Assert.assertEquals(1, bestMatch.getMatches().size());
//选出20,20,30,40中的20,20,40
Assert.assertEquals(8000, bestMatch.totalPrice());
_logBestMatch(bestMatch);
Rule r2 = Builder.rule()
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
bestMatch = Strategy.bestMatch(Arrays.asList(r1, r2), selectedItems);
Assert.assertEquals(r2, bestMatch.getMatches().get(0).getRule());
_logBestMatch(bestMatch);//选出的是$.sum(8000),且有6组
BestMatch bestOfOnce = Strategy.bestOfOnlyOnceDiscount(Arrays.asList(r1, r2), selectedItems);
System.out.println("best of only once discount:");
_logBestMatch(bestOfOnce);//选出的是[#cc01].sum(8000),因为只算一组的话,这一条规则优惠90,比$这一条多10
}
@Test
public void testSumOfRandomItems() {
Rule r1 = Builder.rule()
.simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
List<Item> selectedItems = _getRandomPriceItems();
BestMatch bestMatch = Strategy.bestMatch(Arrays.asList(r1), selectedItems);
_logBestMatch(bestMatch);
Rule r2 = Builder.rule()
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
bestMatch = Strategy.bestMatch(Arrays.asList(r1, r2), selectedItems);
_logBestMatch(bestMatch);
}
@Test
public void testComposite() {
Rule and = Builder.rule()
.and().simplex()
.range("[#cc01]")
.predict(P.COUNT)
.expected(2)
.end()
.sameRange()
.predict(P.SUM)
.expected(8000)
.end()
.endRule()
.promotion("-800")
.build();
System.out.println(and);
List<Item> items = _getSelectedItems();
List<Rule> rules = Arrays.asList(and);
BestMatch bestMatch = Strategy.bestMatch(rules, items);
_logBestMatch(bestMatch);
Assert.assertEquals(1,bestMatch.getMatches().size());
Assert.assertEquals(3,bestMatch.chosen().size());
Rule or = Builder
.rule()
.or()
.addRule(and.getCondition())
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.end()
.end()
.endRule()
.promotion("-800")
.build();
System.out.println(or);
rules = Arrays.asList(or);
bestMatch = Strategy.bestMatch(rules, items);
_logBestMatch(bestMatch);
Assert.assertEquals(6,bestMatch.getMatches().size());
Assert.assertEquals(11,bestMatch.chosen().size());
}
@Test
public void testOnce() {//总共9个商品,100块的2张,120块的6张,0.5块的1张
Rule r = Interpreter.parseString("[#k6246d389d1812e77f772d1db].sum(15000)&~.countCate(1) -> -2000/15000").asRule();
List<Item> items = Arrays.asList(
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1d6", "SKU01", 10000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1d6", "SKU01", 10000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1db", "SKU02", 19000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1db", "SKU02", 19000)
);
List<Rule> rules = Arrays.asList(r);
BestMatch result = Strategy.bestOfOnlyOnceDiscount(rules, items);
System.out.println(result.totalDiscount());//should be -2000
result = Strategy.bestMatch(rules, items);
System.out.println(result.totalDiscount()); //should be -4000
}
@Test
public void test4DiscountingAlgorithm() {
//规则是100块的和120块的总共要6张,并且两种商品都要有
String ruleString = "[#k01#k02].count(6)&~.countCate(2) -> -50%";
Rule r = Interpreter.parseString(ruleString).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "分类01", "01", "SPU01", "01", "SKU01", 10000),
new ItemImpl("01", "分类01", "01", "SPU01", "01", "SKU01", 10000),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU01", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "03", "SKU03", 50)
);
List<Rule> rules = Arrays.asList(r);
int expected = 0, actual = 0;
//为了做规则推荐的运算,规则本身算折扣的方法里,
// 并没有判定规则是否已达成,所以调用前需做check()
if (r.check(items)) {
//第1种,rule.discountFilteredItems(tickets)
//计算的是规则范围内的这部分商品的折扣
//expected = tickets.stream().filter(r.getFilter()).map(t -> t.getPriceByFen()).reduce(0, (i1, i2) -> i1 + i2) / -2;
expected = items.stream().filter(r.getFilter()).map(t -> t.getPrice()).reduce(0, Integer::sum) / -2;
actual = r.discountFilteredItems(items);
System.out.println(expected);
Assert.assertEquals(expected, actual);
//第2种,rule.discount(tickets)
//计算的是所有商品应用折扣
//expected = tickets.stream().map(t -> t.getPriceByFen()).reduce(0, (i1, i2) -> i1 + i2) / -2;
expected = items.stream().map(t -> t.getPrice()).reduce(0, Integer::sum) / -2;
actual = r.discount(items);
System.out.println(expected);
Assert.assertEquals(expected, actual);
}
//第3种,Strategy.bestMath()
//非比率折扣,计算的是用最低成本达成规则匹配所需要的商品
//expected = (tickets.get(0).getPriceByFen() * 1 + tickets.get(2).getPriceByFen() * 5) / -2;
expected = (10000*2 + 121200 * 6)/-2;
actual = Strategy.bestMatch(rules, items).totalDiscount();
System.out.println(expected);
Assert.assertEquals(expected, actual);
//第4种,Strategy.bestOfOnlyOnceDiscount()
//计算达成规则所需的最少张数,但是是最高价格的商品
//expected = (tickets.get(0).getPriceByFen() * 1 + tickets.get(2).getPriceByFen() * 5) / -2;
BestMatch match = Strategy.bestOfOnlyOnceDiscount(rules, items);
actual = match.totalDiscount();
System.out.println(expected);
Assert.assertEquals(expected, actual);
System.out.println(match.left());
}
@Test
public void test_oneSKU() {
String ruleString2 = "[#k01#k02].oneSKU(2) -> -50%",
ruleString6 = "[#k01#k02].oneSKU(6) -> -50%",
ruleString7 = "$.oneSKU(7) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//-2 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
Assert.assertTrue(!rule7.check(items)); //dont match
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals((121200 * 2) / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
}
@Test
public void testoneSKUSum() {
String ruleString2 = "[#k01#k02].oneSKUSum(20000) -> -50%",
ruleString6 = "[#k01#k02].oneSKUSum(727200) -> -50%",
ruleString7 = "$.oneSKUSum(727201) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
Assert.assertTrue(!rule7.check(items)); //dont match
//#region deprecated api
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals(121200 / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
//#endregion
//#region new api
BestMatch best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneRule);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneTime);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule2), items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//01 * 2,02 * 6
best = Strategy.bestChoice(Collections.singletonList(rule2), items, MatchType.OneTime);
//Assert.assertEquals(121200 / -2, best.totalDiscount());//02 * 1
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
rules = Arrays.asList(rule2,rule6,rule7);
best = Strategy.bestChoice(rules, items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//matches rule2, gets 7 match groups
best = Strategy.bestChoice(rules, items, MatchType.OneTime);
//Assert.assertEquals((121200 * 6) / -2, best.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());
Rule rule8 = Interpreter.parseString("[#k01#k02#k03].oneSKUSum(727200) -> -60%").asRule();
rules=Arrays.asList(rule2,rule6,rule7,rule8);
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6 +50) * 6 / -10 , best.totalDiscount());
//#endregion
}
@Test
public void testDiscountPerPrice(){
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 39000),
new ItemImpl("01", "01", "01", "01", "02", "01", 11000),
new ItemImpl("02", "02", "02", "02", "03", "02", 11000)
);
Rule rule1 = Interpreter.parseString("$.count(3)->-7000/15000").asRule(),
rule2 = Interpreter.parseString("$.count(1)->-1000/10000").asRule(),
rule3 = Interpreter.parseString("$.sum(15000)->-7000/15000").asRule();
List<Rule> rules = Arrays.asList(rule1,rule2); | BestMatch bestMatch = Strategy.bestChoice(rules, items,MatchType.MultiRule, MatchGroup.CrossedMatch); | 2 | 2023-10-28 09:03:45+00:00 | 8k |
llllllxy/tiny-jdbc-boot-starter | src/main/java/org/tinycloud/jdbc/support/IObjectSupport.java | [
{
"identifier": "Criteria",
"path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java",
"snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orLt(String field, R value) {\n String condition = \" OR \" + field + \" < \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria lte(String field, R value) {\n String condition = \" AND \" + field + \" <= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orLte(String field, R value) {\n String condition = \" OR \" + field + \" <= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria gt(String field, R value) {\n String condition = \" AND \" + field + \" > \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orGt(String field, R value) {\n String condition = \" OR \" + field + \" > \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria gte(String field, R value) {\n String condition = \" AND \" + field + \" >= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orGte(String field, R value) {\n String condition = \" OR \" + field + \" >= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria eq(String field, R value) {\n String condition = \" AND \" + field + \" = \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orEq(String field, R value) {\n String condition = \" OR \" + field + \" = \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria notEq(String field, R value) {\n String condition = \" AND \" + field + \" <> \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria orNotEq(String field, R value) {\n String condition = \" OR \" + field + \" = \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <R> Criteria isNull(String field) {\n String condition = \" AND \" + field + \" IS NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <R> Criteria orIsNull(String field) {\n String condition = \" OR \" + field + \" IS NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <R> Criteria isNotNull(String field) {\n String condition = \" AND \" + field + \" IS NOT NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <R> Criteria orIsNotNull(String field) {\n String condition = \" OR \" + field + \" IS NOT NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <R> Criteria in(String field, List<R> values) {\n StringBuilder condition = new StringBuilder();\n condition.append(\" AND \").append(field).append(\" IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <R> Criteria orIn(String field, List<R> values) {\n StringBuilder condition = new StringBuilder();\n condition.append(\" OR \").append(field).append(\" IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <R> Criteria notIn(String field, List<R> values) {\n StringBuilder condition = new StringBuilder();\n condition.append(\" AND \").append(field).append(\" NOT IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <R> Criteria orNotIn(String field, List<R> values) {\n StringBuilder condition = new StringBuilder();\n condition.append(\" OR \").append(field).append(\" NOT IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <R> Criteria like(String field, R value) {\n String condition = \" AND \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <R> Criteria orLike(String field, R value) {\n String condition = \" OR \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <R> Criteria notLike(String field, R value) {\n String condition = \" AND \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <R> Criteria orNotLike(String field, R value) {\n String condition = \" OR \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <R> Criteria leftLike(String field, R value) {\n String condition = \" AND \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <R> Criteria orLeftLike(String field, R value) {\n String condition = \" OR \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <R> Criteria notLeftLike(String field, R value) {\n String condition = \" AND \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <R> Criteria orNotLeftLike(String field, R value) {\n String condition = \" OR \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <R> Criteria rightLike(String field, R value) {\n String condition = \" AND \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <R> Criteria orRightLike(String field, R value) {\n String condition = \" OR \" + field + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <R> Criteria notRightLike(String field, R value) {\n String condition = \" AND \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <R> Criteria orNotRightLike(String field, R value) {\n String condition = \" OR \" + field + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <R> Criteria between(String field, R start, R end) {\n String condition = \" AND \" + \"(\" + field + \" BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <R> Criteria orBetween(String field, R start, R end) {\n String condition = \" OR \" + \"(\" + field + \" BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <R> Criteria notBetween(String field, R start, R end) {\n String condition = \" AND \" + \"(\" + field + \" NOT BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <R> Criteria orNotBetween(String field, R start, R end) {\n String condition = \" OR \" + \"(\" + field + \" NOT BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <R> Criteria and(Criteria criteria) {\n String condition = \" AND \" + criteria.children();\n conditions.add(condition);\n parameters.addAll(criteria.parameters);\n return this;\n }\n\n public <R> Criteria or(Criteria criteria) {\n String condition = \" OR \" + criteria.children();\n conditions.add(condition);\n parameters.addAll(criteria.parameters);\n return this;\n }\n\n public Criteria orderBy(String field, boolean desc) {\n String orderByString = field;\n if (desc) {\n orderByString += \" DESC\";\n }\n orderBy.add(orderByString);\n return this;\n }\n\n public Criteria orderBy(String field) {\n String orderByString = field;\n orderBy.add(orderByString);\n return this;\n }\n}"
},
{
"identifier": "LambdaCriteria",
"path": "src/main/java/org/tinycloud/jdbc/criteria/LambdaCriteria.java",
"snippet": "public class LambdaCriteria extends AbstractCriteria {\n\n public static final Map<String, String> LAMBDA_CACHE = new ConcurrentHashMap<>();\n\n public <T, R> LambdaCriteria lt(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" < \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orLt(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" < \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria lte(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" <= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orLte(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" <= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria gt(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" > \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orGt(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" > \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria gte(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" >= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orGte(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" >= \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria eq(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" = \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orEq(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" = \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria notEq(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" <> \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria orNotEq(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" <> \" + \"?\";\n conditions.add(condition);\n parameters.add(value);\n return this;\n }\n\n public <T, R> LambdaCriteria isNull(TypeFunction<T, R> field) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" IS NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <T, R> LambdaCriteria orIsNull(TypeFunction<T, R> field) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" IS NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <T, R> LambdaCriteria isNotNull(TypeFunction<T, R> field) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" IS NOT NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <T, R> LambdaCriteria orIsNotNull(TypeFunction<T, R> field) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" IS NOT NULL\";\n conditions.add(condition);\n return this;\n }\n\n public <T, R> LambdaCriteria in(TypeFunction<T, R> field, List<R> values) {\n String columnName = getColumnName(field);\n StringBuilder condition = new StringBuilder();\n condition.append(\" AND \").append(columnName).append(\" IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <T, R> LambdaCriteria orIn(TypeFunction<T, R> field, List<R> values) {\n String columnName = getColumnName(field);\n StringBuilder condition = new StringBuilder();\n condition.append(\" OR \").append(columnName).append(\" IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <T, R> LambdaCriteria notIn(TypeFunction<T, R> field, List<R> values) {\n String columnName = getColumnName(field);\n StringBuilder condition = new StringBuilder();\n condition.append(\" AND \").append(columnName).append(\" NOT IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <T, R> LambdaCriteria orNotIn(TypeFunction<T, R> field, List<R> values) {\n String columnName = getColumnName(field);\n StringBuilder condition = new StringBuilder();\n condition.append(\" OR \").append(columnName).append(\" NOT IN (\");\n for (int i = 0; i < values.size(); i++) {\n if (i > 0) {\n condition.append(\", \");\n }\n condition.append(\"?\");\n }\n condition.append(\")\");\n conditions.add(condition.toString());\n parameters.addAll(values);\n return this;\n }\n\n public <T, R> LambdaCriteria like(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria orLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria notLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria orNotLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria leftLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <T, R> LambdaCriteria orLeftLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <T, R> LambdaCriteria notLeftLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <T, R> LambdaCriteria orNotLeftLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(\"%\" + value);\n return this;\n }\n\n public <T, R> LambdaCriteria rightLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria orRightLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria notRightLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria orNotRightLike(TypeFunction<T, R> field, R value) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + columnName + \" NOT LIKE ?\";\n conditions.add(condition);\n parameters.add(value + \"%\");\n return this;\n }\n\n public <T, R> LambdaCriteria between(TypeFunction<T, R> field, R start, R end) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + \"(\" + columnName + \" BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <T, R> LambdaCriteria orBetween(TypeFunction<T, R> field, R start, R end) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + \"(\" + columnName + \" BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <T, R> LambdaCriteria notBetween(TypeFunction<T, R> field, R start, R end) {\n String columnName = getColumnName(field);\n String condition = \" AND \" + \"(\" + columnName + \" NOT BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <T, R> LambdaCriteria orNotBetween(TypeFunction<T, R> field, R start, R end) {\n String columnName = getColumnName(field);\n String condition = \" OR \" + \"(\" + columnName + \" NOT BETWEEN \" +\n \"?\" +\n \" AND \" +\n \"?\" + \")\";\n conditions.add(condition);\n parameters.add(start);\n parameters.add(end);\n return this;\n }\n\n public <R> LambdaCriteria and(LambdaCriteria criteria) {\n String condition = \" AND \" + criteria.children();\n conditions.add(condition);\n parameters.addAll(criteria.parameters);\n return this;\n }\n\n public <R> LambdaCriteria or(LambdaCriteria criteria) {\n String condition = \" OR \" + criteria.children();\n conditions.add(condition);\n parameters.addAll(criteria.parameters);\n return this;\n }\n\n public <T, R> LambdaCriteria orderBy(TypeFunction<T, R> field, boolean desc) {\n String columnName = getColumnName(field);\n if (desc) {\n columnName += \" DESC\";\n }\n orderBy.add(columnName);\n return this;\n }\n\n public <T, R> LambdaCriteria orderBy(TypeFunction<T, R> field) {\n String columnName = getColumnName(field);\n orderBy.add(columnName);\n return this;\n }\n\n private <T, R> String getColumnName(TypeFunction<T, R> field) {\n String fieldName = TypeFunction.getLambdaColumnName(field);\n return fieldName;\n }\n}"
},
{
"identifier": "Page",
"path": "src/main/java/org/tinycloud/jdbc/page/Page.java",
"snippet": "public class Page<T> implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * 当前页(pageNo = offset / limit + 1;)\n */\n private Integer pageNum;\n\n /**\n * 分页大小(等价于limit)\n */\n private Integer pageSize;\n\n /**\n * 总记录数\n */\n private Integer total;\n\n /**\n * 总页数\n */\n private Integer pages;\n\n /**\n * 分页后的数据\n */\n private Collection<T> records;\n\n public Page() {\n\n }\n\n public Page(Integer pageNum, Integer pageSize) {\n this.pageSize = pageSize;\n this.pageNum = pageNum;\n }\n\n public Page(Collection<T> records, int total, Integer pageNum, Integer pageSize) {\n this.records = (records == null ? new ArrayList<T>(0) : records);\n this.total = total;\n this.pageSize = pageSize;\n this.pageNum = pageNum;\n this.pages = (total + pageSize - 1) / pageSize;\n }\n\n public Integer getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(Integer pageNum) {\n this.pageNum = pageNum;\n }\n\n public Integer getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(Integer pageSize) {\n this.pageSize = pageSize;\n }\n\n public Integer getPages() {\n return pages;\n }\n\n public void setPages(Integer pages) {\n this.pages = pages;\n }\n\n public Collection<T> getRecords() {\n return records;\n }\n\n public void setRecords(Collection<T> records) {\n this.records = records;\n }\n\n public Integer getTotal() {\n return total;\n }\n\n public void setTotal(Integer total) {\n this.total = total;\n this.pages = (total + pageSize - 1) / pageSize;\n }\n\n @Override\n public String toString() {\n return \"Page {pageNum=\" + pageNum + \", pageSize=\" + pageSize + \", total=\" + total + \", pages=\" + pages\n + \", records=\" + records + \"}\";\n }\n\n}"
}
] | import org.springframework.util.CollectionUtils;
import org.tinycloud.jdbc.criteria.Criteria;
import org.tinycloud.jdbc.criteria.LambdaCriteria;
import org.tinycloud.jdbc.page.Page;
import java.util.Collection;
import java.util.List; | 7,023 | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/ | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/ | int update(T entity, boolean ignoreNulls, LambdaCriteria lambdaCriteria); | 1 | 2023-10-25 14:44:59+00:00 | 8k |
Angular2Guy/AIDocumentLibraryChat | backend/src/main/java/ch/xxx/aidoclibchat/adapter/client/ImportRestClient.java | [
{
"identifier": "ImportClient",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/client/ImportClient.java",
"snippet": "public interface ImportClient {\n\tList<Artist> importArtists();\n\tList<Museum> importMuseums();\n\tList<MuseumHours> importMuseumHours();\n\tList<Work> importWorks();\n\tList<Subject> importSubjects();\n\tList<WorkLink> importWorkLinks();\n}"
},
{
"identifier": "ArtistDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/ArtistDto.java",
"snippet": "public class ArtistDto {\n\t@JsonProperty(\"artist_id\")\n\tprivate Long id;\n\t@JsonProperty(\"full_name\")\n\tprivate String fullName;\n\t@JsonProperty(\"first_name\")\n\tprivate String firstName;\n\t@JsonProperty(\"middle_names\")\n\tprivate String middleName;\n\t@JsonProperty(\"last_name\")\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}\n}"
},
{
"identifier": "MuseumDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/MuseumDto.java",
"snippet": "public class MuseumDto {\n\t@JsonProperty(\"MUSEUM_ID\")\n\tprivate Long id;\n\t@JsonProperty(\"NAME\")\n\tprivate String name;\n\t@JsonProperty(\"ADDRESS\")\n\tprivate String address;\n\t@JsonProperty(\"CITY\")\n\tprivate String city;\n\t@JsonProperty(\"STATE\")\n\tprivate String state;\n\t@JsonProperty(\"POSTAL\")\n\tprivate String postal;\n\t@JsonProperty(\"COUNTRY\")\n\tprivate String country;\n\t@JsonProperty(\"PHONE\")\n\tprivate String phone;\n\t@JsonProperty(\"URL\")\n\tprivate String url;\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 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}\n}"
},
{
"identifier": "MuseumHoursDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/MuseumHoursDto.java",
"snippet": "public class MuseumHoursDto {\n\t@JsonProperty(\"museum_id\")\n\tprivate Long museumId;\n\tprivate String day;\n\tprivate String open;\n\tprivate String close;\n\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 getDay() {\n\t\treturn day;\n\t}\n\tpublic void setDay(String day) {\n\t\tthis.day = day;\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": "SubjectDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/SubjectDto.java",
"snippet": "public class SubjectDto {\n\t@JsonProperty(\"work_id\")\n\tprivate Long workId;\n\tprivate String subject;\n\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 getSubject() {\n\t\treturn subject;\n\t}\n\tpublic void setSubject(String subject) {\n\t\tthis.subject = subject;\n\t}\n}"
},
{
"identifier": "WorkDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/WorkDto.java",
"snippet": "public class WorkDto {\n\t@JsonProperty(\"WORK_ID\")\n\tprivate Long id;\n\t@JsonProperty(\"NAME\")\n\tprivate String name;\n\t@JsonProperty(\"ARTIST_ID\")\n\tprivate Long artistId;\n\t@JsonProperty(\"STYLE\")\n\tprivate String style;\n\t@JsonProperty(\"MUSEUM_ID\")\n\tprivate Long museumId;\n\t@JsonProperty(\"WIDTH\")\n\tprivate Integer width;\n\t@JsonProperty(\"HEIGHT\")\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": "WorkLinkDto",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/model/dto/WorkLinkDto.java",
"snippet": "public class WorkLinkDto {\n\t@JsonProperty(\"WORK_ID\")\n\tprivate Long workId;\n\t@JsonProperty(\"NAME\")\n\tprivate String name;\n\t@JsonProperty(\"ARTIST_ID\")\n\tprivate Long artistId;\n\t@JsonProperty(\"STYLE\")\n\tprivate String style;\n\t@JsonProperty(\"MUSEUM_ID\")\n\tprivate Long museumId;\n\t@JsonProperty(\"IMAGE_LINK\")\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": "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": "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": "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": "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": "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": "TableMapper",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/usecase/mapping/TableMapper.java",
"snippet": "@Component\npublic class TableMapper {\n\tpublic Work map(WorkDto dto) {\n\t\tvar entity = new Work();\n\t\tentity.setArtistId(dto.getArtistId());\n\t\tentity.setHeight(dto.getHeight());\n\t\tentity.setId(dto.getId());\n\t\tentity.setMuseumId(dto.getMuseumId());\n\t\tentity.setName(dto.getName());\n\t\tentity.setStyle(dto.getStyle());\n\t\tentity.setWidth(dto.getWidth());\n\t\treturn entity;\n\t}\n\n\tpublic MuseumHours map(MuseumHoursDto dto) {\n\t\tvar entity = new MuseumHours();\n\t\tentity.setClose(dto.getClose());\n\t\tentity.setOpen(dto.getOpen());\n\t\tentity.setMuseumHoursId(new MuseumHoursId(dto.getMuseumId(), dto.getDay()));\n\t\treturn entity;\n\t}\n\t\n\tpublic Museum map(MuseumDto dto) {\n\t\tvar entity = new Museum();\n\t\tentity.setAddress(dto.getAddress());\n\t\tentity.setCity(dto.getCity());\n\t\tentity.setCountry(dto.getCountry());\n\t\tentity.setId(dto.getId());\n\t\tentity.setName(dto.getName());\n\t\tentity.setPhone(dto.getPhone());\n\t\tentity.setPostal(dto.getPostal());\n\t\tentity.setState(dto.getState());\n\t\tentity.setUrl(dto.getUrl());\n\t\treturn entity;\n\t}\n\t\n\tpublic Artist map(ArtistDto dto) {\n\t\tvar entity = new Artist();\n\t\tentity.setBirth(dto.getBirth());\n\t\tentity.setDeath(dto.getDeath());\n\t\tentity.setFirstName(dto.getFirstName());\n\t\tentity.setFullName(dto.getFullName());\n\t\tentity.setId(dto.getId());\n\t\tentity.setLastName(dto.getLastName());\n\t\tentity.setMiddleName(dto.getMiddleName());\n\t\tentity.setNationality(dto.getNationality());\n\t\tentity.setStyle(dto.getStyle());\n\t\treturn entity;\n\t}\n\t\n\tpublic Subject map(SubjectDto dto) {\n\t\tvar entity = new Subject();\n\t\tentity.setSubject(dto.getSubject());\n\t\tentity.setWorkId(dto.getWorkId());\n\t\treturn entity;\n\t}\n\t\n\tpublic WorkLink map(WorkLinkDto dto) {\n\t\tvar entity = new WorkLink();\n\t\tentity.setArtistId(dto.getArtistId());\n\t\tentity.setImageLink(dto.getImageLink());\n\t\tentity.setMuseumId(dto.getMuseumId());\n\t\tentity.setName(dto.getName());\n\t\tentity.setStyle(dto.getStyle());\n\t\tentity.setWorkId(dto.getWorkId());\n\t\treturn entity;\n\t}\n}"
}
] | import java.io.IOException;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import ch.xxx.aidoclibchat.domain.client.ImportClient;
import ch.xxx.aidoclibchat.domain.model.dto.ArtistDto;
import ch.xxx.aidoclibchat.domain.model.dto.MuseumDto;
import ch.xxx.aidoclibchat.domain.model.dto.MuseumHoursDto;
import ch.xxx.aidoclibchat.domain.model.dto.SubjectDto;
import ch.xxx.aidoclibchat.domain.model.dto.WorkDto;
import ch.xxx.aidoclibchat.domain.model.dto.WorkLinkDto;
import ch.xxx.aidoclibchat.domain.model.entity.Artist;
import ch.xxx.aidoclibchat.domain.model.entity.Museum;
import ch.xxx.aidoclibchat.domain.model.entity.MuseumHours;
import ch.xxx.aidoclibchat.domain.model.entity.Subject;
import ch.xxx.aidoclibchat.domain.model.entity.Work;
import ch.xxx.aidoclibchat.domain.model.entity.WorkLink;
import ch.xxx.aidoclibchat.usecase.mapping.TableMapper; | 5,629 | /**
* 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.adapter.client;
@Component
public class ImportRestClient implements ImportClient {
private final CsvMapper csvMapper;
private final TableMapper tableMapper;
public ImportRestClient(TableMapper tableMapper) {
this.tableMapper = tableMapper;
this.csvMapper = new CsvMapper();
this.csvMapper.registerModule(new JavaTimeModule());
}
@Override
public List<Artist> importArtists() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/artist.csv")
.retrieve().body(String.class);
return this.mapString(result, ArtistDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
private <T> List<T> mapString(String result, Class<T> myClass) {
List<T> zipcodes = List.of();
try {
zipcodes = this.csvMapper.readerFor(myClass).with(CsvSchema.builder().setUseHeader(true).build())
.<T>readValues(result).readAll();
} catch (IOException e) {
throw new RuntimeException(e);
}
return zipcodes;
}
@Override
public List<Museum> importMuseums() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<MuseumHours> importMuseumHours() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum_hours.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumHoursDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<Work> importWorks() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/work.csv")
.retrieve().body(String.class);
return this.mapString(result, WorkDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override | /**
* 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.adapter.client;
@Component
public class ImportRestClient implements ImportClient {
private final CsvMapper csvMapper;
private final TableMapper tableMapper;
public ImportRestClient(TableMapper tableMapper) {
this.tableMapper = tableMapper;
this.csvMapper = new CsvMapper();
this.csvMapper.registerModule(new JavaTimeModule());
}
@Override
public List<Artist> importArtists() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/artist.csv")
.retrieve().body(String.class);
return this.mapString(result, ArtistDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
private <T> List<T> mapString(String result, Class<T> myClass) {
List<T> zipcodes = List.of();
try {
zipcodes = this.csvMapper.readerFor(myClass).with(CsvSchema.builder().setUseHeader(true).build())
.<T>readValues(result).readAll();
} catch (IOException e) {
throw new RuntimeException(e);
}
return zipcodes;
}
@Override
public List<Museum> importMuseums() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<MuseumHours> importMuseumHours() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum_hours.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumHoursDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<Work> importWorks() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/work.csv")
.retrieve().body(String.class);
return this.mapString(result, WorkDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override | public List<Subject> importSubjects() { | 10 | 2023-10-25 19:05:07+00:00 | 8k |
Fusion-Flux/Portal-Cubed-Rewrite | src/main/java/io/github/fusionflux/portalcubed/content/button/FloorButtonBlock.java | [
{
"identifier": "PortalCubedBlocks",
"path": "src/main/java/io/github/fusionflux/portalcubed/content/PortalCubedBlocks.java",
"snippet": "public class PortalCubedBlocks {\n\tpublic static final RotatedPillarBlock TEST_BLOCK = REGISTRAR.blocks.create(\"test_block\", RotatedPillarBlock::new)\n\t\t\t.copyFrom(Blocks.STONE)\n\t\t\t.settings(QuiltBlockSettings::noCollision)\n\t\t\t.item(BlockItemProvider::noItem)\n\t\t\t.build();\n\n\tpublic static final FloorButtonBlock FLOOR_BUTTON_BLOCK = REGISTRAR.blocks.create(\"floor_button\", FloorButtonBlock::new)\n\t\t\t.copyFrom(Blocks.STONE)\n\t\t\t.item((block, properties) -> new MultiBlockItem(block, properties))\n\t\t\t.settings(settings -> settings.pushReaction(PushReaction.BLOCK).mapColor(MapColor.TERRACOTTA_RED))\n\t\t\t.renderType(RenderTypes.CUTOUT)\n\t\t\t.build();\n\tpublic static final FloorButtonBlock OLD_AP_FLOOR_BUTTON_BLOCK = REGISTRAR.blocks.create(\"old_ap_floor_button\", OldApFloorButtonBlock::new)\n\t\t\t.copyFrom(Blocks.STONE)\n\t\t\t.item((block, properties) -> new MultiBlockItem(block, properties))\n\t\t\t.settings(settings -> settings.pushReaction(PushReaction.BLOCK).mapColor(MapColor.TERRACOTTA_RED))\n\t\t\t.renderType(RenderTypes.CUTOUT)\n\t\t\t.build();\n\tpublic static final FloorButtonBlock PORTAL_1_FLOOR_BUTTON_BLOCK = REGISTRAR.blocks.create(\"portal_1_floor_button\", P1FloorButtonBlock::new)\n\t\t\t.copyFrom(Blocks.STONE)\n\t\t\t.item((block, properties) -> new MultiBlockItem(block, properties))\n\t\t\t.settings(settings -> settings.pushReaction(PushReaction.BLOCK).mapColor(MapColor.TERRACOTTA_RED))\n\t\t\t.renderType(RenderTypes.CUTOUT)\n\t\t\t.build();\n\n\tpublic static void init() {\n\t}\n}"
},
{
"identifier": "PortalCubedSounds",
"path": "src/main/java/io/github/fusionflux/portalcubed/content/PortalCubedSounds.java",
"snippet": "public class PortalCubedSounds {\n\tpublic static final SoundEvent FLOOR_BUTTON_PRESS = register(\"floor_button_press\");\n\tpublic static final SoundEvent FLOOR_BUTTON_RELEASE = register(\"floor_button_release\");\n\tpublic static final SoundEvent OLD_AP_FLOOR_BUTTON_PRESS = register(\"old_ap_floor_button_press\");\n\tpublic static final SoundEvent OLD_AP_FLOOR_BUTTON_RELEASE = register(\"old_ap_floor_button_release\");\n\tpublic static final SoundEvent PORTAL_1_FLOOR_BUTTON_PRESS = register(\"portal_1_floor_button_press\");\n\tpublic static final SoundEvent PORTAL_1_FLOOR_BUTTON_RELEASE = register(\"portal_1_floor_button_release\");\n\n\tpublic static SoundEvent register(String name) {\n\t\tvar id = PortalCubed.id(name);\n\t\treturn Registry.register(BuiltInRegistries.SOUND_EVENT, id, SoundEvent.createVariableRangeEvent(id));\n\t}\n\n\tpublic static void init() {\n\t}\n}"
},
{
"identifier": "PortalCubedEntityTags",
"path": "src/main/java/io/github/fusionflux/portalcubed/data/tags/PortalCubedEntityTags.java",
"snippet": "public class PortalCubedEntityTags {\n\tpublic static final TagKey<EntityType<?>> PRESSES_FLOOR_BUTTONS = create(\"presses_floor_buttons\");\n\n\tprivate static TagKey<EntityType<?>> create(String name) {\n\t\treturn TagKey.create(Registries.ENTITY_TYPE, PortalCubed.id(name));\n\t}\n\n\tpublic static void init() {\n\t}\n}"
},
{
"identifier": "AbstractMultiBlock",
"path": "src/main/java/io/github/fusionflux/portalcubed/framework/block/AbstractMultiBlock.java",
"snippet": "public abstract class AbstractMultiBlock extends DirectionalBlock {\n\tpublic final SizeProperties sizeProperties;\n\tpublic final Size size;\n\n\tprotected AbstractMultiBlock(Properties properties) {\n\t\tsuper(properties);\n\n\t\tthis.sizeProperties = sizeProperties();\n\t\tthis.size = new Size(Direction.SOUTH, sizeProperties.xMax, sizeProperties.yMax, sizeProperties.zMax);\n\n\t\tthis.registerDefaultState(this.stateDefinition.any().setValue(FACING, size.direction));\n\t}\n\n\tpublic abstract SizeProperties sizeProperties();\n\n\tpublic int getX(BlockState state) {\n\t\treturn sizeProperties.x.map(state::getValue).orElse(0);\n\t}\n\n\tpublic int getY(BlockState state) {\n\t\treturn sizeProperties.y.map(state::getValue).orElse(0);\n\t}\n\n\tpublic int getZ(BlockState state) {\n\t\treturn sizeProperties.z.map(state::getValue).orElse(0);\n\t}\n\n\tpublic BlockState setX(BlockState state, int x) {\n\t\treturn sizeProperties.x.map(prop -> state.setValue(prop, x)).orElse(state);\n\t}\n\n\tpublic BlockState setY(BlockState state, int y) {\n\t\treturn sizeProperties.y.map(prop -> state.setValue(prop, y)).orElse(state);\n\t}\n\n\tpublic BlockState setZ(BlockState state, int z) {\n\t\treturn sizeProperties.z.map(prop -> state.setValue(prop, z)).orElse(state);\n\t}\n\n\tpublic boolean isOrigin(BlockState state, Level level) {\n\t\treturn getX(state) == 0 && getY(state) == 0 && getZ(state) == 0;\n\t}\n\n\tpublic BlockPos getOriginPos(BlockPos pos, BlockState state) {\n\t\tint x = getX(state);\n\t\tint y = getY(state);\n\t\tint z = getZ(state);\n\t\treturn switch (state.getValue(FACING)) {\n\t\t\tcase DOWN, UP -> pos.subtract(new BlockPos(x, z, y));\n\t\t\tcase WEST, EAST -> pos.subtract(new BlockPos(z, y, x));\n\t\t\tdefault -> pos.subtract(new BlockPos(x, y, z));\n\t\t};\n\t}\n\n\tpublic Iterable<BlockPos> quadrantIterator(BlockPos pos, BlockState state, Level level) {\n\t\tvar rotatedSize = size.rotated(state.getValue(FACING));\n\t\treturn BlockPos.betweenClosed(pos, pos.offset(rotatedSize.x() - 1, rotatedSize.y() - 1, rotatedSize.z() - 1));\n\t}\n\n\tpublic void playSoundAtCenter(SoundEvent sound, double xOff, double yOff, double zOff, float volume, float pitch, BlockPos pos, BlockState state, Level level) {\n\t\tvar center = size.rotated(state.getValue(FACING)).center(xOff, yOff, zOff)\n\t\t\t.add(pos.getX(), pos.getY(), pos.getZ());\n\t\tlevel.playSound(null, center.x, center.y, center.z, sound, SoundSource.BLOCKS, volume, pitch);\n\t}\n\n\t@Override\n\tprotected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {\n\t\tbuilder.add(FACING);\n\t\tsizeProperties().x.map(builder::add);\n\t\tsizeProperties().y.map(builder::add);\n\t\tsizeProperties().z.map(builder::add);\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\t@Override\n\tpublic void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean moved) {\n\t\tif (!state.is(newState.getBlock())) {\n\t\t\tif (isOrigin(state, level)) {\n\t\t\t\tfor (BlockPos quadrantPos : quadrantIterator(pos, state, level)) level.destroyBlock(quadrantPos, false);\n\t\t\t} else {\n\t\t\t\tvar originPos = getOriginPos(pos, state);\n\t\t\t\tlevel.getBlockState(originPos).onRemove(level, originPos, Blocks.AIR.defaultBlockState(), false);\n\t\t\t}\n\t\t}\n\t\tsuper.onRemove(state, level, pos, newState, moved);\n\t}\n\n\t@Override\n\tpublic BlockState rotate(BlockState state, Rotation rotation) {\n\t\treturn state.setValue(FACING, rotation.rotate(state.getValue(FACING)));\n\t}\n\n\t@Override\n\tpublic BlockState mirror(BlockState state, Mirror mirror) {\n\t\treturn state.rotate(mirror.getRotation(state.getValue(FACING)));\n\t}\n\n\t@Override\n\tpublic BlockState getStateForPlacement(BlockPlaceContext ctx) {\n\t\treturn this.defaultBlockState().setValue(FACING, ctx.getClickedFace());\n\t}\n\n\tpublic record Size(Direction direction, int x, int y, int z) {\n\t\tpublic static final BlockPos.MutableBlockPos TEST_POS = new BlockPos.MutableBlockPos();\n\t\tpublic static final Direction[][] HORIZONTAL_DIRECTIONS = new Direction[][]{\n\t\t\tnew Direction[]{Direction.WEST, Direction.EAST},\n\t\t\tnew Direction[]{Direction.NORTH, Direction.SOUTH}\n\t\t};\n\t\tpublic static final Direction[][] VERTICAL_DIRECTIONS = new Direction[][]{\n\t\t\tnew Direction[]{Direction.DOWN, Direction.UP},\n\t\t\tnew Direction[]{Direction.NORTH, Direction.SOUTH}\n\t\t};\n\n\t\tpublic Vec3 center(double xOff, double yOff, double zOff) {\n\t\t\tdouble xOffRotated = direction.getAxis() == Direction.Axis.X ? zOff : xOff;\n\t\t\tdouble yOffRotated = direction.getAxis() == Direction.Axis.Y ? zOff : yOff;\n\t\t\tdouble zOffRotated = direction.getAxis() == Direction.Axis.X ? xOff : direction.getAxis() == Direction.Axis.Y ? yOff : zOff;\n\t\t\treturn new Vec3((x / 2) + xOffRotated, (y / 2) + yOffRotated, (z / 2) + zOffRotated);\n\t\t}\n\n\t\tpublic Vec3i relative(Vec3i origin, Vec3i pos) {\n\t\t\tvar relative = pos.subtract(origin);\n\t\t\treturn switch (direction.getAxis()) {\n\t\t\t\tcase Y -> new Vec3i(relative.getX(), relative.getZ(), relative.getY());\n\t\t\t\tcase X -> new Vec3i(relative.getZ(), relative.getY(), relative.getX());\n\t\t\t\tcase Z -> relative;\n\t\t\t};\n\t\t}\n\n\t\tpublic Size rotated(Direction direction) {\n\t\t\treturn switch (direction.getAxis()) {\n\t\t\t\tcase Y -> new Size(direction, x, z, y);\n\t\t\t\tcase X -> new Size(direction, z, y, x);\n\t\t\t\tcase Z -> new Size(direction, x, y, z);\n\t\t\t};\n\t\t}\n\n\t\tpublic boolean canFit(Level level, Vec3i origin, Predicate<BlockPos> placePredicate) {\n\t\t\tfor (int y = 0; y < this.y; y++) {\n\t\t\t\tfor (int x = 0; x < this.x; x++) {\n\t\t\t\t\tfor (int z = 0; z < this.z; z++) {\n\t\t\t\t\t\tTEST_POS.set(origin.getX() + x, origin.getY() + y, origin.getZ() + z);\n\t\t\t\t\t\tif (!placePredicate.test(TEST_POS)) return false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic Optional<BlockPos> moveToFit(BlockPlaceContext context, BlockPos origin, Predicate<BlockPos> placePredicate) {\n\t\t\tvar level = context.getLevel();\n\t\t\tvar testOrigin = origin;\n\t\t\tif (canFit(level, testOrigin, placePredicate)) return Optional.of(testOrigin);\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tif (canFit(level, testOrigin, placePredicate)) return Optional.of(testOrigin);\n\t\t\t\ttestOrigin = testOrigin.relative(HORIZONTAL_DIRECTIONS[direction.getAxis() == Direction.Axis.X ? 1 : 0][i]);\n\t\t\t\tfor (int j = 0; j < 2; j++) {\n\t\t\t\t\tif (canFit(level, testOrigin, placePredicate)) return Optional.of(testOrigin);\n\t\t\t\t\ttestOrigin = testOrigin.relative(VERTICAL_DIRECTIONS[direction.getAxis().isVertical() ? 1 : 0][j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Optional.empty();\n\t\t}\n\t}\n\n\tpublic record SizeProperties(int xMax, int yMax, int zMax, Optional<IntegerProperty> x, Optional<IntegerProperty> y, Optional<IntegerProperty> z) {\n\t\tpublic static SizeProperties create(int x, int y, int z) {\n\t\t\treturn new SizeProperties(\n\t\t\t\tx, y, z,\n\t\t\t\tx > 1 ? Optional.of(IntegerProperty.create(\"x\", 0, x - 1)) : Optional.empty(),\n\t\t\t\ty > 1 ? Optional.of(IntegerProperty.create(\"y\", 0, y - 1)) : Optional.empty(),\n\t\t\t\tz > 1 ? Optional.of(IntegerProperty.create(\"z\", 0, z - 1)) : Optional.empty()\n\t\t\t);\n\t\t}\n\t}\n}"
},
{
"identifier": "VoxelShaper",
"path": "src/main/java/io/github/fusionflux/portalcubed/framework/util/VoxelShaper.java",
"snippet": "public class VoxelShaper {\n\tprivate static final Vec3 BLOCK_CENTER = new Vec3(8, 8, 8);\n\n\tprivate final Map<Direction, VoxelShape> shapes = new HashMap<>();\n\n\tpublic VoxelShape get(Direction direction) {\n\t\treturn shapes.get(direction);\n\t}\n\n\tpublic VoxelShape get(Axis axis) {\n\t\treturn shapes.get(axisAsFace(axis));\n\t}\n\n\tpublic static VoxelShaper forHorizontal(VoxelShape shape, Direction facing) {\n\t\treturn forDirectionsWithRotation(shape, facing, Direction.Plane.HORIZONTAL, new HorizontalRotationValues());\n\t}\n\n\tpublic static VoxelShaper forHorizontalAxis(VoxelShape shape, Axis along) {\n\t\treturn forDirectionsWithRotation(shape, axisAsFace(along), Arrays.asList(Direction.SOUTH, Direction.EAST),\n\t\t\t\tnew HorizontalRotationValues());\n\t}\n\n\tpublic static VoxelShaper forDirectional(VoxelShape shape, Direction facing) {\n\t\treturn forDirectionsWithRotation(shape, facing, Arrays.asList(Direction.values()), new DefaultRotationValues());\n\t}\n\n\tpublic static VoxelShaper forAxis(VoxelShape shape, Axis along) {\n\t\treturn forDirectionsWithRotation(shape, axisAsFace(along),\n\t\t\t\tArrays.asList(Direction.SOUTH, Direction.EAST, Direction.UP), new DefaultRotationValues());\n\t}\n\n\tpublic VoxelShaper withVerticalShapes(VoxelShape upShape) {\n\t\tshapes.put(Direction.UP, upShape);\n\t\tshapes.put(Direction.DOWN, rotatedCopy(upShape, new Vec3(180, 0, 0), BLOCK_CENTER));\n\t\treturn this;\n\t}\n\n\tpublic VoxelShaper withShape(VoxelShape shape, Direction facing) {\n\t\tshapes.put(facing, shape);\n\t\treturn this;\n\t}\n\n\tpublic static Direction axisAsFace(Axis axis) {\n\t\treturn Direction.get(AxisDirection.POSITIVE, axis);\n\t}\n\n\tprotected static float horizontalAngleFromDirection(Direction direction) {\n\t\treturn (float) ((Math.max(direction.get2DDataValue(), 0) & 3) * 90);\n\t}\n\n\tprotected static VoxelShaper forDirectionsWithRotation(VoxelShape shape, Direction facing,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Iterable<Direction> directions, Function<Direction, Vec3> rotationValues) {\n\t\tVoxelShaper voxelShaper = new VoxelShaper();\n\t\tfor (Direction dir : directions) {\n\t\t\tvoxelShaper.shapes.put(dir, rotate(shape, facing, dir, rotationValues));\n\t\t}\n\t\treturn voxelShaper;\n\t}\n\n\tpublic static VoxelShape rotate(VoxelShape shape, Direction from, Direction to,\n\t\t\t\t\t\t\t\t\t Function<Direction, Vec3> usingValues) {\n\t\tif (from == to)\n\t\t\treturn shape;\n\n\t\treturn rotatedCopy(\n\t\t\tshape,\n\t\t\tusingValues.apply(from)\n\t\t\t\t.reverse()\n\t\t\t\t.add(usingValues.apply(to)),\n\t\t\tBLOCK_CENTER\n\t\t);\n\t}\n\n\tpublic static VoxelShape rotatedCopy(VoxelShape shape, Vec3 rotation, Vec3 origin) {\n\t\tif (rotation.equals(Vec3.ZERO))\n\t\t\treturn shape;\n\n\t\tMutableObject<VoxelShape> result = new MutableObject<>(Shapes.empty());\n\n\t\tshape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> {\n\t\t\tVec3 v1 = new Vec3(x1, y1, z1).scale(16)\n\t\t\t\t\t.subtract(origin);\n\t\t\tVec3 v2 = new Vec3(x2, y2, z2).scale(16)\n\t\t\t\t\t.subtract(origin);\n\n\t\t\tv1 = rotate(v1, (float) rotation.x, Axis.X);\n\t\t\tv1 = rotate(v1, (float) rotation.y, Axis.Y);\n\t\t\tv1 = rotate(v1, (float) rotation.z, Axis.Z)\n\t\t\t\t\t.add(origin);\n\n\t\t\tv2 = rotate(v2, (float) rotation.x, Axis.X);\n\t\t\tv2 = rotate(v2, (float) rotation.y, Axis.Y);\n\t\t\tv2 = rotate(v2, (float) rotation.z, Axis.Z)\n\t\t\t\t\t.add(origin);\n\n\t\t\tVoxelShape rotated = blockBox(v1, v2);\n\t\t\tresult.setValue(Shapes.or(result.getValue(), rotated));\n\t\t});\n\n\t\treturn result.getValue();\n\t}\n\n\tprotected static VoxelShape blockBox(Vec3 v1, Vec3 v2) {\n\t\treturn Block.box(\n\t\t\t\tMath.min(v1.x, v2.x),\n\t\t\t\tMath.min(v1.y, v2.y),\n\t\t\t\tMath.min(v1.z, v2.z),\n\t\t\t\tMath.max(v1.x, v2.x),\n\t\t\t\tMath.max(v1.y, v2.y),\n\t\t\t\tMath.max(v1.z, v2.z)\n\t\t);\n\t}\n\n\tprotected static class DefaultRotationValues implements Function<Direction, Vec3> {\n\t\t// assume facing up as the default rotation\n\t\t@Override\n\t\tpublic Vec3 apply(Direction direction) {\n\t\t\treturn new Vec3(direction == Direction.UP ? 0 : (Direction.Plane.VERTICAL.test(direction) ? 180 : 90),\n\t\t\t\t\t-horizontalAngleFromDirection(direction), 0);\n\t\t}\n\t}\n\n\tprotected static class HorizontalRotationValues implements Function<Direction, Vec3> {\n\t\t@Override\n\t\tpublic Vec3 apply(Direction direction) {\n\t\t\treturn new Vec3(0, -horizontalAngleFromDirection(direction), 0);\n\t\t}\n\t}\n\n\t// this method is from VecHelper: https://github.com/Creators-of-Create/Create/blob/39ef3da5df0fad2054d8b95f15b51b4199479774/src/main/java/com/simibubi/create/foundation/utility/VecHelper.java#L46\n\tpublic static Vec3 rotate(Vec3 vec, double deg, Axis axis) {\n\t\tif (deg == 0)\n\t\t\treturn vec;\n\t\tif (vec == Vec3.ZERO)\n\t\t\treturn vec;\n\n\t\tfloat angle = (float) (deg / 180f * Math.PI);\n\t\tdouble sin = Mth.sin(angle);\n\t\tdouble cos = Mth.cos(angle);\n\t\tdouble x = vec.x;\n\t\tdouble y = vec.y;\n\t\tdouble z = vec.z;\n\n\t\tif (axis == Axis.X)\n\t\t\treturn new Vec3(x, y * cos - z * sin, z * cos + y * sin);\n\t\tif (axis == Axis.Y)\n\t\t\treturn new Vec3(x * cos + z * sin, y, z * cos - x * sin);\n\t\tif (axis == Axis.Z)\n\t\t\treturn new Vec3(x * cos - y * sin, y * cos + x * sin, z);\n\t\treturn vec;\n\t}\n\n}"
}
] | import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import io.github.fusionflux.portalcubed.content.PortalCubedBlocks;
import io.github.fusionflux.portalcubed.content.PortalCubedSounds;
import io.github.fusionflux.portalcubed.data.tags.PortalCubedEntityTags;
import io.github.fusionflux.portalcubed.framework.block.AbstractMultiBlock;
import io.github.fusionflux.portalcubed.framework.util.VoxelShaper;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySelector;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; | 6,417 | public FloorButtonBlock(Properties properties, VoxelShaper[][] shapes, VoxelShape buttonShape, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, shapes, buttonShape, entity -> entity instanceof LivingEntity || entity.getType().is(PortalCubedEntityTags.PRESSES_FLOOR_BUTTONS), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, new VoxelShaper[][]{
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 4, 16, 3, 16)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 4, 12, 3, 16)), Direction.UP)
},
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 0, 16, 3, 12)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 0, 12, 3, 12)), Direction.UP)
}
}, box(7.5, 7.5, 3, 16, 16, 4), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties) {
this(properties, PortalCubedSounds.FLOOR_BUTTON_PRESS, PortalCubedSounds.FLOOR_BUTTON_RELEASE);
}
public AABB getButtonBounds(Direction direction) {
return buttonBounds.computeIfAbsent(direction, blah -> {
var baseButtonBounds = buttonBounds.get(Direction.SOUTH);
var min = new Vec3(baseButtonBounds.minX, baseButtonBounds.minY, baseButtonBounds.minZ);
var max = new Vec3(baseButtonBounds.maxX, baseButtonBounds.maxY, baseButtonBounds.maxZ);
if (direction.getAxisDirection() == Direction.AxisDirection.NEGATIVE) {
min = VoxelShaper.rotate(min.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
max = VoxelShaper.rotate(max.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
}
var rotatedBounds = switch (direction.getAxis()) {
case Y -> new AABB(min.x, min.z, min.y, max.x, max.z, max.y);
case X -> new AABB(min.z, min.y, min.x, max.z, max.y, max.x);
case Z -> new AABB(min.x, min.y, min.z, max.x, max.y, max.z);
};
return rotatedBounds;
});
}
public void toggle(BlockState state, Level level, BlockPos pos, @Nullable Entity entity, boolean currentState) {
for (BlockPos quadrantPos : quadrantIterator(pos, state, level)) {
var quadrantState = level.getBlockState(quadrantPos);
if (!quadrantState.is(this)) return;
level.setBlock(quadrantPos, quadrantState.setValue(ACTIVE, !currentState), UPDATE_ALL);
}
SoundEvent toggleSound;
if (currentState) {
level.gameEvent(entity, GameEvent.BLOCK_DEACTIVATE, pos);
toggleSound = releaseSound;
} else {
level.scheduleTick(pos, this, PRESSED_TIME);
level.gameEvent(entity, GameEvent.BLOCK_ACTIVATE, pos);
toggleSound = pressSound;
}
playSoundAtCenter(toggleSound, 0, 0, -.5, 1f, 1f, pos, state, level);
}
@Override
public SizeProperties sizeProperties() {
return SIZE_PROPERTIES;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(ACTIVE);
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) {
int y = getY(state);
int x = getX(state);
var facing = state.getValue(FACING);
var quadrantShape = switch (facing) {
case NORTH, EAST -> shapes[y == 1 ? 0 : 1][x == 1 ? 0 : 1];
case DOWN, WEST, SOUTH -> shapes[y == 1 ? 0 : 1][x];
default -> shapes[y][x];
};
return quadrantShape.get(facing);
}
@Override
public VoxelShape getOcclusionShape(BlockState state, BlockGetter level, BlockPos pos) {
return Shapes.empty();
}
@Override
public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
return state.getValue(ACTIVE) ? 15 : 0;
}
@Override
public boolean isSignalSource(BlockState state) {
return true;
}
@Override
public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) {
if (level.getEntitiesOfClass(Entity.class, getButtonBounds(state.getValue(FACING)).move(pos), entityPredicate).size() > 0) {
level.scheduleTick(pos, this, PRESSED_TIME);
} else if (state.getValue(ACTIVE)) {
toggle(state, level, pos, null, true);
}
}
@Override
public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) {
if (!level.isClientSide) {
var originPos = getOriginPos(pos, state);
boolean entityPressing = entityPredicate.test(entity) && getButtonBounds(state.getValue(FACING)).move(originPos).intersects(entity.getBoundingBox());
if (entityPressing && !state.getValue(ACTIVE))
toggle(state, level, originPos, entity, false);
}
}
@Override
public String getDescriptionId() { | package io.github.fusionflux.portalcubed.content.button;
public class FloorButtonBlock extends AbstractMultiBlock {
public static final SizeProperties SIZE_PROPERTIES = SizeProperties.create(2, 2, 1);
public static final BooleanProperty ACTIVE = BooleanProperty.create("active");
public static final int PRESSED_TIME = 5;
public static int easterEggTrigger = 0;
public final VoxelShaper[][] shapes;
public final Map<Direction, AABB> buttonBounds = new HashMap<>();
public final Predicate<? super Entity> entityPredicate;
public final SoundEvent pressSound;
public final SoundEvent releaseSound;
public FloorButtonBlock(
Properties properties,
VoxelShaper[][] shapes,
VoxelShape buttonShape,
Predicate<? super Entity> entityPredicate,
SoundEvent pressSound,
SoundEvent releaseSound
) {
super(properties);
this.shapes = shapes;
this.buttonBounds.put(Direction.SOUTH, new AABB(
buttonShape.min(Direction.Axis.X) * 2,
buttonShape.min(Direction.Axis.Y) * 2,
buttonShape.min(Direction.Axis.Z),
buttonShape.max(Direction.Axis.X) * 2,
buttonShape.max(Direction.Axis.Y) * 2,
buttonShape.max(Direction.Axis.Z)
).move(-buttonShape.min(Direction.Axis.X), -buttonShape.min(Direction.Axis.Y), 0));
for (Direction direction : Direction.values()) getButtonBounds(direction);
this.entityPredicate = EntitySelector.NO_SPECTATORS.and(entity -> !entity.isIgnoringBlockTriggers()).and(entityPredicate);
this.pressSound = pressSound;
this.releaseSound = releaseSound;
this.registerDefaultState(this.stateDefinition.any().setValue(ACTIVE, false));
}
public FloorButtonBlock(Properties properties, VoxelShaper[][] shapes, VoxelShape buttonShape, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, shapes, buttonShape, entity -> entity instanceof LivingEntity || entity.getType().is(PortalCubedEntityTags.PRESSES_FLOOR_BUTTONS), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, new VoxelShaper[][]{
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 4, 16, 3, 16)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 4, 12, 3, 16)), Direction.UP)
},
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 0, 16, 3, 12)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 0, 12, 3, 12)), Direction.UP)
}
}, box(7.5, 7.5, 3, 16, 16, 4), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties) {
this(properties, PortalCubedSounds.FLOOR_BUTTON_PRESS, PortalCubedSounds.FLOOR_BUTTON_RELEASE);
}
public AABB getButtonBounds(Direction direction) {
return buttonBounds.computeIfAbsent(direction, blah -> {
var baseButtonBounds = buttonBounds.get(Direction.SOUTH);
var min = new Vec3(baseButtonBounds.minX, baseButtonBounds.minY, baseButtonBounds.minZ);
var max = new Vec3(baseButtonBounds.maxX, baseButtonBounds.maxY, baseButtonBounds.maxZ);
if (direction.getAxisDirection() == Direction.AxisDirection.NEGATIVE) {
min = VoxelShaper.rotate(min.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
max = VoxelShaper.rotate(max.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
}
var rotatedBounds = switch (direction.getAxis()) {
case Y -> new AABB(min.x, min.z, min.y, max.x, max.z, max.y);
case X -> new AABB(min.z, min.y, min.x, max.z, max.y, max.x);
case Z -> new AABB(min.x, min.y, min.z, max.x, max.y, max.z);
};
return rotatedBounds;
});
}
public void toggle(BlockState state, Level level, BlockPos pos, @Nullable Entity entity, boolean currentState) {
for (BlockPos quadrantPos : quadrantIterator(pos, state, level)) {
var quadrantState = level.getBlockState(quadrantPos);
if (!quadrantState.is(this)) return;
level.setBlock(quadrantPos, quadrantState.setValue(ACTIVE, !currentState), UPDATE_ALL);
}
SoundEvent toggleSound;
if (currentState) {
level.gameEvent(entity, GameEvent.BLOCK_DEACTIVATE, pos);
toggleSound = releaseSound;
} else {
level.scheduleTick(pos, this, PRESSED_TIME);
level.gameEvent(entity, GameEvent.BLOCK_ACTIVATE, pos);
toggleSound = pressSound;
}
playSoundAtCenter(toggleSound, 0, 0, -.5, 1f, 1f, pos, state, level);
}
@Override
public SizeProperties sizeProperties() {
return SIZE_PROPERTIES;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(ACTIVE);
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) {
int y = getY(state);
int x = getX(state);
var facing = state.getValue(FACING);
var quadrantShape = switch (facing) {
case NORTH, EAST -> shapes[y == 1 ? 0 : 1][x == 1 ? 0 : 1];
case DOWN, WEST, SOUTH -> shapes[y == 1 ? 0 : 1][x];
default -> shapes[y][x];
};
return quadrantShape.get(facing);
}
@Override
public VoxelShape getOcclusionShape(BlockState state, BlockGetter level, BlockPos pos) {
return Shapes.empty();
}
@Override
public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
return state.getValue(ACTIVE) ? 15 : 0;
}
@Override
public boolean isSignalSource(BlockState state) {
return true;
}
@Override
public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) {
if (level.getEntitiesOfClass(Entity.class, getButtonBounds(state.getValue(FACING)).move(pos), entityPredicate).size() > 0) {
level.scheduleTick(pos, this, PRESSED_TIME);
} else if (state.getValue(ACTIVE)) {
toggle(state, level, pos, null, true);
}
}
@Override
public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) {
if (!level.isClientSide) {
var originPos = getOriginPos(pos, state);
boolean entityPressing = entityPredicate.test(entity) && getButtonBounds(state.getValue(FACING)).move(originPos).intersects(entity.getBoundingBox());
if (entityPressing && !state.getValue(ACTIVE))
toggle(state, level, originPos, entity, false);
}
}
@Override
public String getDescriptionId() { | boolean hasEasterEgg = this == PortalCubedBlocks.FLOOR_BUTTON_BLOCK || this == PortalCubedBlocks.PORTAL_1_FLOOR_BUTTON_BLOCK; | 0 | 2023-10-25 05:32:39+00:00 | 8k |
ansforge/SAMU-Hub-Modeles | src/test/java/com/hubsante/model/builders/ReferenceWrapperBuilderTest.java | [
{
"identifier": "DistributionElement",
"path": "src/main/java/com/hubsante/model/common/DistributionElement.java",
"snippet": "@JsonPropertyOrder({DistributionElement.JSON_PROPERTY_MESSAGE_ID,\n DistributionElement.JSON_PROPERTY_SENDER,\n DistributionElement.JSON_PROPERTY_SENT_AT,\n DistributionElement.JSON_PROPERTY_KIND,\n DistributionElement.JSON_PROPERTY_STATUS,\n DistributionElement.JSON_PROPERTY_RECIPIENT})\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class DistributionElement extends ContentMessage {\n public static final String JSON_PROPERTY_MESSAGE_ID = \"messageId\";\n private String messageId;\n\n public static final String JSON_PROPERTY_SENDER = \"sender\";\n private Sender sender;\n\n public static final String JSON_PROPERTY_SENT_AT = \"sentAt\";\n private OffsetDateTime sentAt;\n\n /**\n * Gets or Sets kind\n */\n public enum KindEnum {\n REPORT(\"Report\"),\n\n UPDATE(\"Update\"),\n\n CANCEL(\"Cancel\"),\n\n ACK(\"Ack\"),\n\n ERROR(\"Error\");\n\n private String value;\n\n KindEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static KindEnum fromValue(String value) {\n for (KindEnum b : KindEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_KIND = \"kind\";\n private KindEnum kind;\n\n /**\n * Gets or Sets status\n */\n public enum StatusEnum {\n ACTUAL(\"Actual\"),\n\n EXERCISE(\"Exercise\"),\n\n SYSTEM(\"System\");\n\n private String value;\n\n StatusEnum(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n\n @JsonCreator\n public static StatusEnum fromValue(String value) {\n for (StatusEnum b : StatusEnum.values()) {\n if (b.value.equals(value)) {\n return b;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n }\n\n public static final String JSON_PROPERTY_STATUS = \"status\";\n private StatusEnum status;\n\n public static final String JSON_PROPERTY_RECIPIENT = \"recipient\";\n private List<Recipient> recipient = new ArrayList<>();\n\n public DistributionElement() {}\n\n public DistributionElement messageId(String messageId) {\n\n this.messageId = messageId;\n return this;\n }\n\n /**\n * Get messageId\n * @return messageId\n **/\n @JsonProperty(JSON_PROPERTY_MESSAGE_ID)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public String getMessageId() {\n return messageId;\n }\n\n @JsonProperty(JSON_PROPERTY_MESSAGE_ID)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setMessageId(String messageId) {\n this.messageId = messageId;\n }\n\n public DistributionElement sender(Sender sender) {\n\n this.sender = sender;\n return this;\n }\n\n /**\n * Get sender\n * @return sender\n **/\n @JsonProperty(JSON_PROPERTY_SENDER)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public Sender getSender() {\n return sender;\n }\n\n @JsonProperty(JSON_PROPERTY_SENDER)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setSender(Sender sender) {\n this.sender = sender;\n }\n\n public DistributionElement sentAt(OffsetDateTime sentAt) {\n\n this.sentAt = sentAt;\n return this;\n }\n\n /**\n * Get sentAt\n * @return sentAt\n **/\n @JsonProperty(JSON_PROPERTY_SENT_AT)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public OffsetDateTime getSentAt() {\n return sentAt;\n }\n\n @JsonProperty(JSON_PROPERTY_SENT_AT)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setSentAt(OffsetDateTime sentAt) {\n this.sentAt = sentAt;\n }\n\n public DistributionElement kind(KindEnum kind) {\n\n this.kind = kind;\n return this;\n }\n\n /**\n * Get kind\n * @return kind\n **/\n @JsonProperty(JSON_PROPERTY_KIND)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public KindEnum getKind() {\n return kind;\n }\n\n @JsonProperty(JSON_PROPERTY_KIND)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setKind(KindEnum kind) {\n this.kind = kind;\n }\n\n public DistributionElement status(StatusEnum status) {\n\n this.status = status;\n return this;\n }\n\n /**\n * Get status\n * @return status\n **/\n @JsonProperty(JSON_PROPERTY_STATUS)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public StatusEnum getStatus() {\n return status;\n }\n\n @JsonProperty(JSON_PROPERTY_STATUS)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setStatus(StatusEnum status) {\n this.status = status;\n }\n\n public DistributionElement recipient(List<Recipient> recipient) {\n\n this.recipient = recipient;\n return this;\n }\n\n public DistributionElement addRecipientItem(Recipient recipientItem) {\n if (this.recipient == null) {\n this.recipient = new ArrayList<>();\n }\n this.recipient.add(recipientItem);\n return this;\n }\n\n /**\n * Get recipient\n * @return recipient\n **/\n @JsonProperty(JSON_PROPERTY_RECIPIENT)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n\n public List<Recipient> getRecipient() {\n return recipient;\n }\n\n @JsonProperty(JSON_PROPERTY_RECIPIENT)\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setRecipient(List<Recipient> recipient) {\n if (recipient == null) {\n return;\n }\n if (this.recipient == null) {\n this.recipient = new ArrayList<>();\n }\n this.recipient.addAll(recipient);\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 DistributionElement distributionElement = (DistributionElement)o;\n return Objects.equals(this.messageId, distributionElement.messageId) &&\n Objects.equals(this.sender, distributionElement.sender) &&\n Objects.equals(this.sentAt, distributionElement.sentAt) &&\n Objects.equals(this.kind, distributionElement.kind) &&\n Objects.equals(this.status, distributionElement.status) &&\n Objects.equals(this.recipient, distributionElement.recipient);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(messageId, sender, sentAt, kind, status, recipient);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class DistributionElement {\\n\");\n sb.append(\" messageId: \")\n .append(toIndentedString(messageId))\n .append(\"\\n\");\n sb.append(\" sender: \").append(toIndentedString(sender)).append(\"\\n\");\n sb.append(\" sentAt: \").append(toIndentedString(sentAt)).append(\"\\n\");\n sb.append(\" kind: \").append(toIndentedString(kind)).append(\"\\n\");\n sb.append(\" status: \").append(toIndentedString(status)).append(\"\\n\");\n sb.append(\" recipient: \")\n .append(toIndentedString(recipient))\n .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": "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": "ReferenceWrapper",
"path": "src/main/java/com/hubsante/model/common/ReferenceWrapper.java",
"snippet": "@JsonPropertyOrder({ReferenceWrapper.JSON_PROPERTY_REFERENCE})\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class ReferenceWrapper extends DistributionElement {\n @JacksonXmlProperty(isAttribute = true)\n String xmlns = \"urn:emergency:cisu:2.0\";\n public static final String JSON_PROPERTY_REFERENCE = \"reference\";\n private Reference reference;\n\n public ReferenceWrapper() {}\n\n public ReferenceWrapper reference(Reference reference) {\n\n this.reference = reference;\n return this;\n }\n\n /**\n * Get reference\n * @return reference\n **/\n @JsonProperty(JSON_PROPERTY_REFERENCE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n public Reference getReference() {\n return reference;\n }\n\n @JsonProperty(JSON_PROPERTY_REFERENCE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setReference(Reference reference) {\n this.reference = reference;\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 ReferenceWrapper referenceWrapper = (ReferenceWrapper)o;\n return Objects.equals(this.reference, referenceWrapper.reference) &&\n super.equals(o);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(reference, super.hashCode());\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ReferenceWrapper {\\n\");\n sb.append(\" \").append(toIndentedString(super.toString())).append(\"\\n\");\n sb.append(\" reference: \")\n .append(toIndentedString(reference))\n .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": "DistributionKind",
"path": "src/main/java/com/hubsante/model/edxl/DistributionKind.java",
"snippet": "public enum DistributionKind {\n\n REPORT(\"Report\"),\n UPDATE(\"Update\"),\n CANCEL(\"Cancel\"),\n ACK(\"Ack\"),\n ERROR(\"Error\");\n\n private String value;\n DistributionKind(String value) { this.value = value; }\n\n @JsonValue\n public String getValue() {\n return value;\n }\n\n @JsonCreator\n public static DistributionKind fromValue(String value) {\n for (DistributionKind e : DistributionKind.values()) {\n if (e.value.equals(value)) {\n return e;\n }\n }\n throw new IllegalArgumentException(\"Unexpected value '\" + value + \"'\");\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n}"
},
{
"identifier": "EdxlMessage",
"path": "src/main/java/com/hubsante/model/edxl/EdxlMessage.java",
"snippet": "@JsonPropertyOrder({\n \"distributionID\",\n \"senderID\",\n \"dateTimeSent\",\n \"dateTimeExpires\",\n \"distributionStatus\",\n \"distributionKind\",\n \"descriptor\",\n \"content\"})\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class EdxlMessage extends EdxlEnvelope {\n private List<ContentObject> content;\n\n public EdxlMessage() {\n super();\n }\n\n public EdxlMessage(String distributionID, String senderID, OffsetDateTime dateTimeSent, OffsetDateTime dateTimeExpires,\n DistributionStatus distributionStatus, DistributionKind distributionKind, Descriptor descriptor,\n ContentMessage innerMessage) {\n super(distributionID, senderID, dateTimeSent, dateTimeExpires, distributionStatus, distributionKind, descriptor);\n this.setContentFrom(innerMessage);\n }\n\n public EdxlMessage content(List<ContentObject> content) {\n this.content = content;\n return this;\n }\n\n public EdxlMessage addContentObject(ContentObject contentObject) {\n if (this.content == null) {\n this.content = new ArrayList<>();\n }\n this.content.add(contentObject);\n return this;\n }\n\n @JacksonXmlElementWrapper(useWrapping = true, localName = \"content\")\n @JsonProperty(value = \"content\")\n @JacksonXmlProperty(localName = \"contentObject\")\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public List<ContentObject> getContent() {\n return content;\n }\n\n @JacksonXmlElementWrapper(useWrapping = true, localName = \"content\")\n @JsonProperty(value = \"content\")\n @JacksonXmlProperty(localName = \"contentObject\")\n @JsonInclude(value = JsonInclude.Include.ALWAYS)\n public void setContent(List<ContentObject> content) {\n this.content = content;\n }\n\n public <T extends ContentMessage> void setContentFrom(T embeddedContent) {\n List<ContentObject> contentObjectList = new ArrayList<>();\n contentObjectList.add(new ContentObject(new ContentWrapper(new EmbeddedContent(embeddedContent))));\n this.setContent(contentObjectList);\n }\n\n public ContentMessage getFirstContentMessage() {\n return this.getContent().stream().findFirst().orElseThrow(ArrayIndexOutOfBoundsException::new)\n .getContentWrapper().getEmbeddedContent().getMessage();\n }\n\n public List<ContentMessage> getAllContentMessages() {\n return this.content.stream()\n .map(contentObject -> ((ContentMessage) contentObject.getContentWrapper().getEmbeddedContent().getMessage()))\n .collect(Collectors.toList());\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 EdxlMessage that = (EdxlMessage) o;\n return Objects.equals(content, that.content);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), content);\n }\n\n @Override\n public String toString() {\n return \"class EdxlMessage {\\n\" +\n \" distributionID: \" + toIndentedString(super.getDistributionID()) + \"\\n\" +\n \" senderId: \" + toIndentedString(super.getSenderID()) + \"\\n\" +\n \" dateTimeSent: \" + toIndentedString(super.getDateTimeSent()) + \"\\n\" +\n \" dateTimeExpires: \" + toIndentedString(super.getDateTimeExpires()) + \"\\n\" +\n \" distributionStatus: \" + toIndentedString(super.getDistributionStatus()) + \"\\n\" +\n \" distributionKind: \" + toIndentedString(super.getDistributionKind()) + \"\\n\" +\n \" descriptor: \" + toIndentedString(super.getDescriptor()) + \"\\n\" +\n \" content: \" + toIndentedString(content) + \"\\n\" +\n \"}\";\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 com.hubsante.model.common.DistributionElement;
import com.hubsante.model.common.Recipient;
import com.hubsante.model.common.ReferenceWrapper;
import com.hubsante.model.edxl.DistributionKind;
import com.hubsante.model.edxl.EdxlMessage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; | 4,887 | /**
* 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.builders;
public class ReferenceWrapperBuilderTest {
private final String DISTRIBUTION_ID = "id-12345";
private final String SENDER_ID = "sender-x";
private final String RECIPIENT_ID = "recipient-y";
/*
* Test the builder with a RC-REF built from builders
* first we build a RC-DE
* then we build a RC-REF from the RC-DE
* then we build an EDXL Message from the RC-REF
*/
@Test
@DisplayName("should build an EDXL Message from a built RC-REF")
public void shouldBuildEdxlFromRcRef() {
Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID);
List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList());
| /**
* 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.builders;
public class ReferenceWrapperBuilderTest {
private final String DISTRIBUTION_ID = "id-12345";
private final String SENDER_ID = "sender-x";
private final String RECIPIENT_ID = "recipient-y";
/*
* Test the builder with a RC-REF built from builders
* first we build a RC-DE
* then we build a RC-REF from the RC-DE
* then we build an EDXL Message from the RC-REF
*/
@Test
@DisplayName("should build an EDXL Message from a built RC-REF")
public void shouldBuildEdxlFromRcRef() {
Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID);
List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList());
| DistributionElement distributionElement = new DistributionElementBuilder(DISTRIBUTION_ID, SENDER_ID, recipientList) | 0 | 2023-10-25 14:24:31+00:00 | 8k |
yaroslav318/shop-telegram-bot | telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/CartCommandHandler.java | [
{
"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": "UpdateHandler",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/UpdateHandler.java",
"snippet": "public interface UpdateHandler extends Handler {\n\n boolean canHandleUpdate(Update update);\n\n void handleUpdate(AbsSender absSender, Update update) 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": "CartItem",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/CartItem.java",
"snippet": "public class CartItem implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer id;\n private Product product;\n private int quantity;\n\n public CartItem() {\n }\n\n public CartItem(Product product, Integer quantity) {\n this.product = product;\n this.quantity = quantity;\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Product getProduct() {\n return product;\n }\n\n public void setProduct(Product product) {\n this.product = product;\n }\n\n public int getQuantity() {\n return quantity;\n }\n\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n\n public Long getTotalPrice() {\n return quantity * product.getPrice();\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 CartItem cartItem = (CartItem) o;\n return Objects.equals(id, cartItem.id) && \n Objects.equals(product, cartItem.product) && \n Objects.equals(quantity, cartItem.quantity);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, product, quantity);\n }\n\n @Override\n public String toString() {\n return \"CartItem [id=\" + id +\n \", product=\" + product +\n \", quantity=\" + quantity + \"]\";\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": "MessagePlaceholder",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/domain/MessagePlaceholder.java",
"snippet": "public class MessagePlaceholder {\n\n private final String placeholder;\n private final Object replacement;\n\n private MessagePlaceholder(String placeholder, Object replacement) {\n this.placeholder = placeholder;\n this.replacement = replacement;\n }\n\n public static MessagePlaceholder of(String placeholder, Object replacement) {\n return new MessagePlaceholder(placeholder, replacement);\n }\n\n public String getPlaceholder() {\n return placeholder;\n }\n\n public Object getReplacement() {\n return replacement;\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 MessagePlaceholder that = (MessagePlaceholder) o;\n return Objects.equals(placeholder, that.placeholder) &&\n Objects.equals(replacement, that.replacement);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(placeholder, replacement);\n }\n\n @Override\n public String toString() {\n return \"MessagePlaceholder [placeholder=\" + placeholder +\n \", replacement=\" + replacement + \"]\";\n }\n\n}"
},
{
"identifier": "Client",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/entities/Client.java",
"snippet": "@Entity\n@Table(name = \"clients\")\npublic class Client implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"clients_seq\")\n @SequenceGenerator(name = \"clients_seq\", sequenceName = \"clients_id_seq\", allocationSize = 1)\n private Integer id;\n\n @Column(name = \"chat_id\", unique = true, nullable = false)\n private Long chatId;\n\n @Column\n private String name;\n\n @Column(name = \"phone_number\")\n private String phoneNumber;\n\n @Column\n private String city;\n\n @Column\n private String address;\n\n @Column(name = \"is_active\", nullable = false)\n private boolean active;\n\n public Client() {\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Long getChatId() {\n return chatId;\n }\n\n public void setChatId(Long chatId) {\n this.chatId = chatId;\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 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 public boolean isActive() {\n return active;\n }\n\n public void setActive(boolean active) {\n this.active = active;\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 Client client = (Client) o;\n return active == client.active && \n Objects.equals(id, client.id) && \n Objects.equals(chatId, client.chatId) && \n Objects.equals(name, client.name) && \n Objects.equals(phoneNumber, client.phoneNumber) && \n Objects.equals(city, client.city) && \n Objects.equals(address, client.address);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, chatId, name, phoneNumber, city, address, active);\n }\n\n @Override\n public String toString() {\n return \"Client [id=\" + id + \n \", chatId=\" + chatId + \n \", name=\" + name + \n \", phoneNumber=\" + phoneNumber + \n \", city=\" + city + \n \", address=\" + address + \n \", active=\" + active + \"]\";\n }\n\n}"
},
{
"identifier": "Message",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/entities/Message.java",
"snippet": "@Entity\n@Table(name = \"messages\")\npublic class Message implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"messages_seq\")\n @SequenceGenerator(name = \"messages_seq\", sequenceName = \"messages_id_seq\", allocationSize = 1)\n private Integer id;\n\n @Column(nullable = false)\n private String name;\n\n @Column(nullable = false)\n private String description;\n\n @Column(length = 4096, nullable = false)\n private String text;\n\n public Message() {\n }\n\n public void applyPlaceholder(MessagePlaceholder placeholder) {\n text = text.replace(placeholder.getPlaceholder(), placeholder.getReplacement().toString());\n }\n\n public void removeTextBetweenPlaceholder(String placeholderName) {\n text = text.replaceAll(placeholderName + \"(?s).*\" + placeholderName, \"\");\n }\n\n public void removeAllPlaceholders() {\n text = text.replaceAll(\"%.*%\", \"\");\n }\n\n public String buildText() {\n removeAllPlaceholders();\n return text;\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\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 getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\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 Message message = (Message) o;\n return Objects.equals(id, message.id) && \n Objects.equals(name, message.name) && \n Objects.equals(description, message.description) && \n Objects.equals(text, message.text);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, name, description, text);\n }\n\n @Override\n public String toString() {\n return \"Message [id=\" + id + \n \", name=\" + name + \n \", description=\" + description + \n \", text=\" + text + \"]\";\n }\n\n}"
},
{
"identifier": "Product",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/models/entities/Product.java",
"snippet": "@Entity\n@Table(name = \"products\")\npublic class Product implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"products_seq\")\n @SequenceGenerator(name = \"products_seq\", sequenceName = \"products_id_seq\", allocationSize = 1)\n private Integer id;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"category_id\")\n private Category category;\n\n @Column(name = \"photo_url\", nullable = false)\n private String photoUrl;\n\n @Column(nullable = false)\n private String name;\n\n @Column(length = 2550, nullable = false)\n private String description;\n\n @Column(nullable = false)\n private Long price;\n\n public Product() {\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public void setCategory(Category category) {\n this.category = category;\n }\n\n public String getPhotoUrl() {\n return photoUrl;\n }\n\n public void setPhotoUrl(String photoUrl) {\n this.photoUrl = photoUrl;\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 getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Long getPrice() {\n return price;\n }\n\n public void setPrice(Long price) {\n this.price = price;\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 Product product = (Product) o;\n return Objects.equals(id, product.id) && \n Objects.equals(category, product.category) && \n Objects.equals(photoUrl, product.photoUrl) && \n Objects.equals(name, product.name) && \n Objects.equals(description, product.description) && \n Objects.equals(price, product.price);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, category, photoUrl, name, description, price);\n }\n\n @Override\n public String toString() {\n return \"Product [id=\" + id + \n \", category=\" + category + \n \", photoUrl=\" + photoUrl + \n \", name=\" + name + \n \", description=\" + description + \n \", price=\" + price + \"]\";\n }\n\n}"
},
{
"identifier": "CartRepository",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/CartRepository.java",
"snippet": "public interface CartRepository {\n\n void saveCartItem(Long chatId, CartItem cartItem);\n\n void updateCartItem(Long chatId, CartItem cartItem);\n\n void deleteCartItem(Long chatId, Integer cartItemId);\n\n CartItem findCartItemByChatIdAndProductId(Long chatId, Integer productId);\n\n List<CartItem> findAllCartItemsByChatId(Long chatId);\n\n void deleteAllCartItemsByChatId(Long chatId);\n\n void updatePageNumberByChatId(Long chatId, Integer pageNumber);\n\n Integer findPageNumberByChatId(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}"
},
{
"identifier": "ClientRepository",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/repositories/ClientRepository.java",
"snippet": "public interface ClientRepository {\n\n Client findByChatId(Long chatId);\n\n void save(Client client);\n\n void update(Client client);\n\n}"
},
{
"identifier": "MessageService",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/services/MessageService.java",
"snippet": "public interface MessageService {\n\n Message findByName(String messageName);\n\n}"
}
] | import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ua.ivanzaitsev.bot.handlers.CommandHandler;
import ua.ivanzaitsev.bot.handlers.UpdateHandler;
import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry;
import ua.ivanzaitsev.bot.models.domain.Button;
import ua.ivanzaitsev.bot.models.domain.CartItem;
import ua.ivanzaitsev.bot.models.domain.ClientOrder;
import ua.ivanzaitsev.bot.models.domain.Command;
import ua.ivanzaitsev.bot.models.domain.MessagePlaceholder;
import ua.ivanzaitsev.bot.models.entities.Client;
import ua.ivanzaitsev.bot.models.entities.Message;
import ua.ivanzaitsev.bot.models.entities.Product;
import ua.ivanzaitsev.bot.repositories.CartRepository;
import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientRepository;
import ua.ivanzaitsev.bot.services.MessageService; | 5,221 | package ua.ivanzaitsev.bot.handlers.commands;
public class CartCommandHandler implements CommandHandler, UpdateHandler {
private static final int MAX_QUANTITY_PER_PRODUCT = 50;
private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity";
private static final String CURRENT_PAGE_CALLBACK = "cart=current-page";
private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product";
private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product";
private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product";
private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product";
private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product";
private static final String PROCESS_ORDER_CALLBACK = "cart=process-order";
private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK,
PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK);
private final CommandHandlerRegistry commandHandlerRegistry;
private final ClientCommandStateRepository clientCommandStateRepository;
private final ClientOrderStateRepository clientOrderStateRepository;
private final CartRepository cartRepository;
private final ClientRepository clientRepository;
private final MessageService messageService;
public CartCommandHandler(
CommandHandlerRegistry commandHandlerRegistry,
ClientCommandStateRepository clientCommandStateRepository,
ClientOrderStateRepository clientOrderStateRepository,
CartRepository cartRepository,
ClientRepository clientRepository,
MessageService messageService) {
this.commandHandlerRegistry = commandHandlerRegistry;
this.clientCommandStateRepository = clientCommandStateRepository;
this.clientOrderStateRepository = clientOrderStateRepository;
this.cartRepository = cartRepository;
this.clientRepository = clientRepository;
this.messageService = messageService;
}
@Override | package ua.ivanzaitsev.bot.handlers.commands;
public class CartCommandHandler implements CommandHandler, UpdateHandler {
private static final int MAX_QUANTITY_PER_PRODUCT = 50;
private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity";
private static final String CURRENT_PAGE_CALLBACK = "cart=current-page";
private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product";
private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product";
private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product";
private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product";
private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product";
private static final String PROCESS_ORDER_CALLBACK = "cart=process-order";
private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK,
PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK);
private final CommandHandlerRegistry commandHandlerRegistry;
private final ClientCommandStateRepository clientCommandStateRepository;
private final ClientOrderStateRepository clientOrderStateRepository;
private final CartRepository cartRepository;
private final ClientRepository clientRepository;
private final MessageService messageService;
public CartCommandHandler(
CommandHandlerRegistry commandHandlerRegistry,
ClientCommandStateRepository clientCommandStateRepository,
ClientOrderStateRepository clientOrderStateRepository,
CartRepository cartRepository,
ClientRepository clientRepository,
MessageService messageService) {
this.commandHandlerRegistry = commandHandlerRegistry;
this.clientCommandStateRepository = clientCommandStateRepository;
this.clientOrderStateRepository = clientOrderStateRepository;
this.cartRepository = cartRepository;
this.clientRepository = clientRepository;
this.messageService = messageService;
}
@Override | public Command getCommand() { | 6 | 2023-10-29 15:49:41+00:00 | 8k |
MikiP98/HumilityAFM | src/main/java/io/github/mikip98/helpers/WoodenMosaicHelper.java | [
{
"identifier": "HumilityAFM",
"path": "src/main/java/io/github/mikip98/HumilityAFM.java",
"snippet": "public class HumilityAFM implements ModInitializer {\n\t// This logger is used to write text to the console and the log file.\n\t// It is considered best practice to use your mod id as the logger's name.\n\t// That way, it's clear which mod wrote info, warnings, and errors.\n\tpublic static final String MOD_ID = \"humility-afm\";\n\tpublic static final String MOD_NAME = \"Humility AFM\";\n\tpublic static final String MOD_CAMEL = \"HumilityAFM\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL);\n\n\n\t//Cabinet block\n\tprivate static final float CabinetBlockStrength = 2.0f;\n\tprivate static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque();\n\tpublic static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings);\n\tpublic static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings());\n\tprivate static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2);\n\tpublic static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings);\n\n\t//Cabinet block entity\n\tpublic static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY;\n\tpublic static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY;\n\n\t// LED block entity\n\tpublic static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY;\n\n\t// Stairs\n\tprivate static final float WoodenStairsBlockStrength = 2.0f;\n\tprivate static final FabricBlockSettings StairsBlockSettings = FabricBlockSettings.create().strength(WoodenStairsBlockStrength).requiresTool();\n\tpublic static final Block OUTER_STAIRS = new OuterStairs(StairsBlockSettings);\n\tpublic static final Block INNER_STAIRS = new InnerStairs(StairsBlockSettings);\n\tpublic static final Item OUTER_STAIRS_ITEM = new BlockItem(OUTER_STAIRS, new FabricItemSettings());\n\tpublic static final Item INNER_STAIRS_ITEM = new BlockItem(INNER_STAIRS, new FabricItemSettings());\n\n\t// Wooden mosaic\n\tprivate static final float WoodenMosaicStrength = 3.0f * 1.5f;\n\tprivate static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD);\n\tpublic static final Block WOODEN_MOSAIC = new Block(WoodenMosaicSettings);\n\tpublic static final Item WOODEN_MOSAIC_ITEM = new BlockItem(WOODEN_MOSAIC, new FabricItemSettings());\n\n\t// LED\n\tpublic static Block LED_BLOCK;\n\tpublic static Item LED_ITEM;\n\n\t// Candlestick\n//\tpublic static Block CANDLESTICK = new JustHorizontalFacingBlock(FabricBlockSettings.create().strength(0.5f).nonOpaque());\n//\tpublic static Item CANDLESTICK_ITEM = new BlockItem(CANDLESTICK, new FabricItemSettings());\n\n\tprivate Block[] getCabinetBlockVariantsToRegisterBlockEntity() {\n\t\tfinal Block[] cabinetBlockVariants = CabinetBlockHelper.cabinetBlockVariants;\n\t\tBlock[] blocks = new Block[cabinetBlockVariants.length + 1];\n\t\tblocks[0] = CABINET_BLOCK;\n System.arraycopy(cabinetBlockVariants, 0, blocks, 1, cabinetBlockVariants.length);\n\t\treturn blocks;\n\t}\n\tprivate Block[] getIlluminatedCabinetBlockVariantsToRegisterBlockEntity() {\n\t\tfinal Block[] illuminatedCabinetBlockVariants = CabinetBlockHelper.illuminatedCabinetBlockVariants;\n\t\tBlock[] blocks = new Block[illuminatedCabinetBlockVariants.length + 1];\n\t\tblocks[0] = ILLUMINATED_CABINET_BLOCK;\n System.arraycopy(illuminatedCabinetBlockVariants, 0, blocks, 1, illuminatedCabinetBlockVariants.length);\n\t\treturn blocks;\n\t}\n\n\n\t@Override\n\tpublic void onInitialize() {\n\t\t// This code runs as soon as Minecraft is in a mod-load-ready state.\n\t\t// However, some things (like resources) may still be uninitialized.\n\t\t// Proceed with mild caution.\n\n\t\t// ------------------------------------ INITIALIZATION ------------------------------------\n\t\tLOGGER.info(MOD_NAME + \" is initializing!\");\n\n\t\tConfigJSON.loadConfigFromFile();\n\t\tConfigJSON.checkShimmerSupportConfig();\n\t\tcheckForSupportedMods();\n\n\t\tCabinetBlockHelper.init();\n\t\tInnerOuterStairsHelper.init();\n\t\tWoodenMosaicHelper.init();\n\t\tTerracottaTilesHelper.init();\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tLEDHelper.init();\n\t\t}\n\t\tPumpkinHelper.init();\n\t\tCandlestickHelper.init();\n\n\n\t\t// ------------------------------------ REGISTRATION ------------------------------------\n\t\t// ............ ITEM GROUPS ............\n\t\t// Register Cabinet item group\n\t\tfinal ItemGroup CABINETS_ITEM_GROUP = FabricItemGroup.builder()\n\t\t\t\t.icon(() -> new ItemStack(HumilityAFM.CABINET_BLOCK))\n\t\t\t\t.displayName(Text.translatable(\"itemGroup.cabinets\"))\n\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\tfor (int i = 0; i < CabinetBlockHelper.cabinetBlockVariants.length; i++) {\n\t\t\t\t\t\tentries.add(new ItemStack(CabinetBlockHelper.cabinetBlockVariants[i]));\n\t\t\t\t\t}\n\t\t\t\t\tfor (int i = 0; i < CabinetBlockHelper.illuminatedCabinetBlockVariants.length; i++) {\n\t\t\t\t\t\tentries.add(new ItemStack(CabinetBlockHelper.illuminatedCabinetBlockVariants[i]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.build();\n\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"cabinets_group\"), CABINETS_ITEM_GROUP);\n\n\t\t// Register InnerOuterStairs item group\n\t\tfinal ItemGroup INNER_OUTER_STAIRS_ITEM_GROUP = FabricItemGroup.builder()\n\t\t\t\t.icon(() -> new ItemStack(HumilityAFM.OUTER_STAIRS))\n\t\t\t\t.displayName(Text.translatable(\"itemGroup.innerOuterStairs\"))\n\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\tfor (int i = 0; i < InnerOuterStairsHelper.innerStairsBlockVariants.length; i++) {\n\t\t\t\t\t\tentries.add(new ItemStack(InnerOuterStairsHelper.innerStairsBlockVariants[i]));\n\t\t\t\t\t}\n\t\t\t\t\tfor (int i = 0; i < InnerOuterStairsHelper.outerStairsBlockVariants.length; i++) {\n\t\t\t\t\t\tentries.add(new ItemStack(InnerOuterStairsHelper.outerStairsBlockVariants[i]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.build();\n\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"inner_outer_stairs_group\"), INNER_OUTER_STAIRS_ITEM_GROUP);\n\n\t\t// Register WoodenMosaic item group\n\t\tfinal ItemGroup WOODEN_MOSAIC_ITEM_GROUP = FabricItemGroup.builder()\n\t\t\t\t.icon(() -> new ItemStack(WoodenMosaicHelper.woodenMosaicVariants[0]))\n\t\t\t\t.displayName(Text.translatable(\"itemGroup.woodenMosaics\"))\n\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\tfor (int i = 0; i < WoodenMosaicHelper.woodenMosaicVariants.length; i++) {\n//\t\t\t\t\t\tLOGGER.info(\"Adding wooden mosaic variant to item group: \" + WoodenMosaicHelper.woodenMosaicVariants[i]);\n\t\t\t\t\t\tentries.add(new ItemStack(WoodenMosaicHelper.woodenMosaicVariants[i])); // TODO: Fix this\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.build();\n\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"wooden_mosaics_group\"), WOODEN_MOSAIC_ITEM_GROUP);\n\n\t\t// Register TerracottaTiles item group\n\t\tfinal ItemGroup TERRACOTTA_TILES_ITEM_GROUP = FabricItemGroup.builder()\n\t\t\t\t.icon(() -> new ItemStack(TerracottaTilesHelper.terracottaTilesVariants[0]))\n\t\t\t\t.displayName(Text.translatable(\"itemGroup.terracottaTiles\"))\n\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\tfor (int i = 0; i < TerracottaTilesHelper.terracottaTilesVariants.length; i++) {\n//\t\t\t\t\t\tLOGGER.info(\"Adding terracotta tiles variant to item group: \" + TerracottaTilesHelper.terracottaTilesVariants[i]);\n\t\t\t\t\t\tentries.add(new ItemStack(TerracottaTilesHelper.terracottaTilesVariants[i]));\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.build();\n\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"terracotta_tiles_group\"), TERRACOTTA_TILES_ITEM_GROUP);\n\n\t\t// Register LED item group\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tfinal ItemGroup LED_ITEM_GROUP = FabricItemGroup.builder()\n\t\t\t\t\t.icon(() -> new ItemStack(LEDHelper.LEDBlockVariants[0]))\n\t\t\t\t\t.displayName(Text.translatable(\"itemGroup.leds\"))\n\t\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\t\tfor (int i = 0; i < LEDHelper.LEDBlockVariants.length; i++) {\n//\t\t\t\t\t\t\tLOGGER.info(\"Adding LED variant to item group: \" + LEDHelper.LEDBlockVariants[i]);\n\t\t\t\t\t\t\tentries.add(new ItemStack(LEDHelper.LEDBlockVariants[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.build();\n\t\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"leds_group\"), LED_ITEM_GROUP);\n\t\t}\n\n\t\t// Register Miscellaneous (Humility Misc) item group\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tfinal ItemGroup HUMILITY_MISCELLANEOUS_GROUP = FabricItemGroup.builder()\n\t\t\t\t\t.icon(() -> new ItemStack(LEDHelper.LEDPowderVariants[0]))\n\t\t\t\t\t.displayName(Text.translatable(\"itemGroup.humilityMisc\"))\n\t\t\t\t\t.entries((displayContext, entries) -> {\n\t\t\t\t\t\tfor (int i = 0; i < LEDHelper.LEDPowderVariants.length; i++) {\n\t\t\t\t\t\t\tentries.add(new ItemStack(LEDHelper.LEDPowderVariants[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int i = 0; i < PumpkinHelper.PumpkinsVariants.length; i++) {\n\t\t\t\t\t\t\tentries.add(new ItemStack(PumpkinHelper.PumpkinsVariants[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.build();\n\t\t\tRegistry.register(Registries.ITEM_GROUP, new Identifier(MOD_ID, \"humility_misc_group\"), HUMILITY_MISCELLANEOUS_GROUP);\n\t\t}\n\n\n\t\t// ............ TEST BLOCKS & ITEMS ............\n\t\t// Register cabinet\n\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"cabinet_block\"), CABINET_BLOCK);\n\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"cabinet_block\"), CABINET_BLOCK_ITEM);\n\t\t// Register illuminated cabinet\n\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"illuminated_cabinet_block\"), ILLUMINATED_CABINET_BLOCK);\n\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"illuminated_cabinet_block\"), new BlockItem(ILLUMINATED_CABINET_BLOCK, new FabricItemSettings()));\n\t\t// Register always corner stair\n\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"outer_stairs\"), OUTER_STAIRS);\n\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"outer_stairs\"), OUTER_STAIRS_ITEM);\n\t\t// Register always full stair\n\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"inner_stairs\"), INNER_STAIRS);\n\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"inner_stairs\"), INNER_STAIRS_ITEM);\n\t\t// Register wooden mosaic\n\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"wooden_mosaic\"), WOODEN_MOSAIC);\n\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"wooden_mosaic\"), WOODEN_MOSAIC_ITEM);\n\t\t// Register LED\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tLED_BLOCK = new LEDBlock(FabricBlockSettings.create().strength(0.5f).nonOpaque().sounds(BlockSoundGroup.GLASS).luminance(10));\n\t\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"led\"), LED_BLOCK);\n\n\t\t\tLED_ITEM = new BlockItem(LED_BLOCK, new FabricItemSettings());\n\t\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"led\"), LED_ITEM);\n\t\t}\n\t\t// Register candlesticks\n//\t\tRegistry.register(Registries.BLOCK, new Identifier(MOD_ID, \"candlestick_gold\"), CANDLESTICK);\n//\t\tRegistry.register(Registries.ITEM, new Identifier(MOD_ID, \"candlestick_gold\"), CANDLESTICK_ITEM);\n\n\n\t\t// ............ FINAL BLOCKS & ITEMS ............\n\t\t// Register cabinet block variants\n\t\tCabinetBlockHelper.registerCabinetBlockVariants();\n\t\t// Register innerOuter stairs variants\n\t\tInnerOuterStairsHelper.registerInnerOuterStairsVariants();\n\t\t// Register wooden mosaic variants\n\t\tWoodenMosaicHelper.registerWoodenMosaicVariants();\n\t\t// Register terracotta tiles variants\n\t\tTerracottaTilesHelper.registerTerracottaTilesVariants();\n\t\t// Register LED block variants\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tLEDHelper.registerLEDBlockVariants();\n\t\t}\n\t\t// Register red and blue pumpkins\n\t\tPumpkinHelper.registerPumpkins();\n\t\t// Register candlestick variants\n\t\tCandlestickHelper.registerCandlestickVariants();\n\n\n\t\t// ............ MAKE THINGS FLAMMABLE ............\n\t\t// No test blocks are currently flammable\n\n\n\t\t// ............ BLOCK ENTITIES ............\n\t\t//Register cabinet block entity\n\t\tCABINET_BLOCK_ENTITY = Registry.register(\n\t\t\t\tRegistries.BLOCK_ENTITY_TYPE,\n\t\t\t\tnew Identifier(MOD_ID, \"cabinet_block_entity\"),\n\t\t\t\tFabricBlockEntityTypeBuilder.create(CabinetBlockEntity::new, getCabinetBlockVariantsToRegisterBlockEntity()).build()\n\t\t\t\t//, CABINET_BLOCK_BIRCH_WHITE, CABINET_BLOCK_BIRCH_ORANGE, CABINET_BLOCK_BIRCH_MAGENTA, CABINET_BLOCK_BIRCH_LIGHT_BLUE, CABINET_BLOCK_BIRCH_YELLOW, CABINET_BLOCK_BIRCH_LIME, CABINET_BLOCK_BIRCH_PINK, CABINET_BLOCK_BIRCH_GRAY, CABINET_BLOCK_BIRCH_LIGHT_GRAY, CABINET_BLOCK_BIRCH_CYAN, CABINET_BLOCK_BIRCH_PURPLE, CABINET_BLOCK_BIRCH_BLUE, CABINET_BLOCK_BIRCH_BROWN, CABINET_BLOCK_BIRCH_GREEN, CABINET_BLOCK_BIRCH_RED, CABINET_BLOCK_BIRCH_BLACK\n\t\t);\n\t\t//Register illuminated cabinet block entity\n\t\tILLUMINATED_CABINET_BLOCK_ENTITY = Registry.register(\n\t\t\t\tRegistries.BLOCK_ENTITY_TYPE,\n\t\t\t\tnew Identifier(MOD_ID, \"illuminated_cabinet_block_entity\"),\n\t\t\t\tFabricBlockEntityTypeBuilder.create(IlluminatedCabinetBlockEntity::new, getIlluminatedCabinetBlockVariantsToRegisterBlockEntity()).build()\n\t\t);\n\n\t\t//Register LED block entity\n\t\tif (ModConfig.enableLEDs) {\n\t\t\tLED_BLOCK_ENTITY = Registry.register(\n\t\t\t\t\tRegistries.BLOCK_ENTITY_TYPE,\n\t\t\t\t\tnew Identifier(MOD_ID, \"led_block_entity\"),\n\t\t\t\t\tFabricBlockEntityTypeBuilder.create(LEDBlockEntity::new, LEDHelper.LEDBlockVariants).build()\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate static void checkForSupportedMods() {\n\t\tcheckIfShimmerModIsPresent();\n\t\tcheckForBetterNether();\n\t}\n\n\tprivate static void checkForBetterNether() {\n\t\tif (getInstance().isModLoaded(\"betternether\")) {\n\t\t\tModConfig.betterNetherDetected = true;\n\t\t\tLOGGER.info(\"Better Nether mod detected! Enabling Better Nether support.\");\n\t\t} else {\n\t\t\t// Go through all mods in the mods folder and check if any of them are Better Nether\n\t\t\tPath gameDirPath = FabricLoader.getInstance().getGameDir();\n\t\t\tFile modsFolder = new File(gameDirPath + \"/mods\");\n\t\t\tFile[] mods = modsFolder.listFiles();\n\t\t\tif (mods != null) {\n\t\t\t\tfor (File mod : mods) {\n\t\t\t\t\tif (mod.getName().startsWith(\"betternether\")) {\n\t\t\t\t\t\tModConfig.betterNetherDetected = true;\n\t\t\t\t\t\tLOGGER.info(\"Better Nether mod detected! Enabling Better Nether support.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void checkIfShimmerModIsPresent() {\n\t\tif (getInstance().isModLoaded(\"shimmer\")) {\n\t\t\tModConfig.shimmerDetected = true;\n\t\t\tLOGGER.info(\"Shimmer mod detected! Disabling LEDs brightening.\");\n\t\t} else {\n\t\t\t// Go through all mods in the mods folder and check if any of them are Shimmer\n\t\t\tPath gameDirPath = FabricLoader.getInstance().getGameDir();\n\t\t\tFile modsFolder = new File(gameDirPath + \"/mods\");\n\t\t\tFile[] mods = modsFolder.listFiles();\n\t\t\tif (mods != null) {\n\t\t\t\tfor (File mod : mods) {\n\t\t\t\t\tif (mod.getName().startsWith(\"Shimmer\")) {\n\t\t\t\t\t\tModConfig.shimmerDetected = true;\n\t\t\t\t\t\tLOGGER.info(\"Shimmer mod detected! Disabling LEDs brightening.\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"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}"
}
] | import io.github.mikip98.HumilityAFM;
import io.github.mikip98.config.ModConfig;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
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.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.Identifier; | 5,411 | package io.github.mikip98.helpers;
public class WoodenMosaicHelper {
public WoodenMosaicHelper() {
throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerWoodenMosaicVariants()\" instead!");
}
private static final float WoodenMosaicStrength = 3.0f * ModConfig.mosaicsAndTilesStrengthMultiplayer; //1.5f
private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD);
public static String[] woodenMosaicVariantsNames;
public static Block[] woodenMosaicVariants;
public static Item[] woodenMosaicItemVariants;
public static void init() {
//Create wooden mosaic variants
String[] woodTypes = MainHelper.vanillaWoodTypes;
short woodenMosaicVariantsCount = (short) (woodTypes.length * (woodTypes.length-1));
woodenMosaicVariantsNames = new String[woodenMosaicVariantsCount];
woodenMosaicVariants = new Block[woodenMosaicVariantsCount];
woodenMosaicItemVariants = new Item[woodenMosaicVariantsCount];
short i = 0;
for (String woodType1 : woodTypes) {
for (String woodType2 : woodTypes) {
if (woodType1.equals(woodType2)) {
continue;
}
String woodenMosaicVariantName = woodType1 + "_" + woodType2;
woodenMosaicVariantsNames[i] = woodenMosaicVariantName;
//LOGGER.info("Creating wooden mosaic variant: " + woodenMosaicVariantsNames[i]);
// Create wooden mosaic variant
woodenMosaicVariants[i] = new Block(WoodenMosaicSettings);
// Create wooden mosaic variant item
woodenMosaicItemVariants[i] = new BlockItem(woodenMosaicVariants[i], new FabricItemSettings());
i++;
}
}
}
public static void registerWoodenMosaicVariants() {
//Register wooden mosaic variants
short i = 0;
for (String woodenMosaicVariantName : woodenMosaicVariantsNames) {
//LOGGER.info("Registering wooden mosaic variant: " + woodenMosaicVariantName);
// Register wooden mosaic variant | package io.github.mikip98.helpers;
public class WoodenMosaicHelper {
public WoodenMosaicHelper() {
throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerWoodenMosaicVariants()\" instead!");
}
private static final float WoodenMosaicStrength = 3.0f * ModConfig.mosaicsAndTilesStrengthMultiplayer; //1.5f
private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD);
public static String[] woodenMosaicVariantsNames;
public static Block[] woodenMosaicVariants;
public static Item[] woodenMosaicItemVariants;
public static void init() {
//Create wooden mosaic variants
String[] woodTypes = MainHelper.vanillaWoodTypes;
short woodenMosaicVariantsCount = (short) (woodTypes.length * (woodTypes.length-1));
woodenMosaicVariantsNames = new String[woodenMosaicVariantsCount];
woodenMosaicVariants = new Block[woodenMosaicVariantsCount];
woodenMosaicItemVariants = new Item[woodenMosaicVariantsCount];
short i = 0;
for (String woodType1 : woodTypes) {
for (String woodType2 : woodTypes) {
if (woodType1.equals(woodType2)) {
continue;
}
String woodenMosaicVariantName = woodType1 + "_" + woodType2;
woodenMosaicVariantsNames[i] = woodenMosaicVariantName;
//LOGGER.info("Creating wooden mosaic variant: " + woodenMosaicVariantsNames[i]);
// Create wooden mosaic variant
woodenMosaicVariants[i] = new Block(WoodenMosaicSettings);
// Create wooden mosaic variant item
woodenMosaicItemVariants[i] = new BlockItem(woodenMosaicVariants[i], new FabricItemSettings());
i++;
}
}
}
public static void registerWoodenMosaicVariants() {
//Register wooden mosaic variants
short i = 0;
for (String woodenMosaicVariantName : woodenMosaicVariantsNames) {
//LOGGER.info("Registering wooden mosaic variant: " + woodenMosaicVariantName);
// Register wooden mosaic variant | Registry.register(Registries.BLOCK, new Identifier(HumilityAFM.MOD_ID, "wooden_mosaic_" + woodenMosaicVariantName), woodenMosaicVariants[i]); | 0 | 2023-10-30 12:11:22+00:00 | 8k |
admin4j/admin4j-dict | dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/autoconfigure/SqlProviderAutoconfigure.java | [
{
"identifier": "SqlDictManager",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/SqlDictManager.java",
"snippet": "public interface SqlDictManager {\n\n /**\n * 获取字典显示值\n *\n * @param dictType\n * @param code\n * @param codeFiled\n * @param labelFiled\n * @param whereSql\n * @return\n */\n String dictLabel(String dictType, Object code, String codeFiled, String labelFiled, String whereSql);\n\n /**\n * 批量获取使用 in 查询\n */\n Map<Object, String> dictLabels(String dictType, Collection<Object> dictCodes, String codeFiled, String labelFiled, String whereSql);\n\n /**\n * 根据label 获取字典code\n *\n * @param dictType\n * @param dictLabel\n * @return\n */\n\n Object dictCode(String dictType, String dictLabel, String codeFiled, String labelFiled, String whereSql);\n\n}"
},
{
"identifier": "SqlDictProperties",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/SqlDictProperties.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"admin4j.dict\")\npublic class SqlDictProperties {\n\n /**\n * 使用 ymal 的方式 sql 配置字典\n */\n private Map<String, SqlDict> sqlDictMap;\n /**\n * 是否开启sql 配置字典\n */\n private boolean sqlDict = false;\n\n @Data\n public static class SqlDict {\n \n // private String dictType;\n /**\n * 字典值字段\n */\n private String codeFiled;\n /**\n * 字典显示字段\n */\n private String labelFiled;\n /**\n * 字典添加字段\n */\n private String whereSql;\n }\n}"
},
{
"identifier": "SqlDictProvider",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/SqlDictProvider.java",
"snippet": "public class SqlDictProvider implements DictProvider {\n\n public static final String DICT_STRATEGY = \"sql\";\n private final SqlDictManager sqlDictManager;\n private final SqlDictService sqlDictService;\n\n public SqlDictProvider(SqlDictManager sqlDictManager, @Autowired(required = false) SqlDictService sqlDictService) {\n this.sqlDictManager = sqlDictManager;\n this.sqlDictService = sqlDictService;\n }\n\n /**\n * 根据dictCode获取字典显示值\n *\n * @param field\n * @param dictType 字典分类\n * @param dictCode 字典code\n * @return 获取字典显示值\n */\n @Override\n public String dictLabel(Field field, String dictType, Object dictCode) {\n\n DictSql dictSql = field.getAnnotation(DictSql.class);\n if (dictSql == null && sqlDictService != null) {\n return sqlDictService.dictLabel(dictType, dictCode);\n } else {\n Assert.notNull(dictSql, \"table cannot be null\");\n return sqlDictManager.dictLabel(dictType, dictCode, dictSql.codeField(), dictSql.labelField(), dictSql.whereSql());\n }\n }\n\n /**\n * 批量获取\n */\n @Override\n public Map<Object, String> dictLabels(Field field, String dictType, Collection<Object> dictCodes) {\n\n DictSql dictSql = field.getAnnotation(DictSql.class);\n if (dictSql == null && sqlDictService != null) {\n return sqlDictService.dictLabels(dictType, dictCodes);\n }\n Assert.notNull(dictSql, \"table cannot be null\");\n return sqlDictManager.dictLabels(dictType, dictCodes, dictSql.codeField(), dictSql.labelField(), dictSql.whereSql());\n }\n\n /**\n * 根据dictLabel获取字典Code\n *\n * @param field\n * @param dictType 字典分类\n * @param dictLabel 字典label\n * @return 获取字典显示值\n */\n @Override\n public Object dictCode(Field field, String dictType, String dictLabel) {\n\n\n DictSql dictSql = field.getAnnotation(DictSql.class);\n if (dictSql == null && sqlDictService != null) {\n return sqlDictService.dictCode(dictType, dictLabel);\n }\n Assert.notNull(dictSql, \"table cannot be null\");\n return sqlDictManager.dictCode(dictType, dictLabel, dictSql.codeField(), dictSql.labelField(), dictSql.whereSql());\n }\n\n /**\n * 支持什么类型\n *\n * @return\n */\n @Override\n public String support() {\n return DICT_STRATEGY;\n }\n}"
},
{
"identifier": "SqlDictService",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/SqlDictService.java",
"snippet": "public interface SqlDictService {\n /**\n * 通过 字典code 获取字典显示值\n *\n * @param tableType 表类型,或者表的 代码,由实现类转化\n * @param dictCode\n * @return\n */\n String dictLabel(String tableType, Object dictCode);\n\n /**\n * 通过 字典code数组 批量的获取字典显示值\n *\n * @param dictType 表类型,或者表的 代码,由实现类转化\n * @param dictCodes\n * @return\n */\n Map<Object, String> dictLabels(String dictType, Collection<Object> dictCodes);\n\n /**\n * 通过字典显示label 获取字典值值\n *\n * @param dictType\n * @param dictLabel\n * @return\n */\n Object dictCode(String dictType, String dictLabel);\n}"
},
{
"identifier": "JdbcSqlDictManager",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/impl/JdbcSqlDictManager.java",
"snippet": "@Slf4j\n@AllArgsConstructor\npublic class JdbcSqlDictManager implements SqlDictManager {\n\n private final JdbcTemplate jdbcTemplate;\n\n /**\n * 根据label 获取字典code\n *\n * @param dictType\n * @param dictLabel\n * @param codeFiled\n * @param labelFiled\n * @param whereSql\n * @return\n */\n @Override\n public Object dictCode(String dictType, String dictLabel, String codeFiled, String labelFiled, String whereSql) {\n if (dictLabel == null) {\n return null;\n }\n StringBuilder sql = new StringBuilder(\"select \" + codeFiled + \" as `code` from \" + dictType);\n\n\n List<String> wheres = new ArrayList<>(2);\n if (StringUtils.isNotBlank(whereSql)) {\n wheres.add(whereSql);\n }\n\n wheres.add(labelFiled + \"= ? \");\n\n sql.append(\" WHERE \");\n boolean isFirst = true;\n for (String where : wheres) {\n if (!isFirst) {\n sql.append(\" AND \");\n }\n sql.append(where);\n isFirst = false;\n }\n\n sql.append(\" LIMIT 1\");\n String sqlStr = sql.toString();\n if (log.isDebugEnabled()) {\n log.debug(\"dict SQL: {},code: {}\", sqlStr, dictLabel);\n }\n\n // TODO: 租户\n try {\n Map<String, Object> map = jdbcTemplate.queryForMap(sqlStr, dictLabel);\n return map.get(\"code\").toString();\n } catch (EmptyResultDataAccessException exception) {\n return \"\";\n }\n }\n\n /**\n * 获取字典显示值\n *\n * @param dictType\n * @param code\n * @param codeFiled\n * @param labelFiled\n * @param whereSql\n * @return\n */\n @Override\n public String dictLabel(String dictType, Object code, String codeFiled, String labelFiled, String whereSql) {\n\n if (code == null) {\n return null;\n }\n StringBuilder sql = new StringBuilder(\"select \" + labelFiled + \" as `label` from \" + dictType);\n\n\n List<String> wheres = new ArrayList<>(2);\n if (StringUtils.isNotBlank(whereSql)) {\n wheres.add(whereSql);\n }\n\n wheres.add(codeFiled + \"= ? \");\n\n sql.append(\" WHERE \");\n boolean isFirst = true;\n for (String where : wheres) {\n if (!isFirst) {\n sql.append(\" AND \");\n }\n sql.append(where);\n isFirst = false;\n }\n\n sql.append(\" LIMIT 1\");\n String sqlStr = sql.toString();\n if (log.isDebugEnabled()) {\n log.debug(\"dict SQL: {},code: {}\", sqlStr, code);\n }\n\n // TODO: 租户\n try {\n Map<String, Object> map = jdbcTemplate.queryForMap(sqlStr, code);\n return map.get(\"label\").toString();\n } catch (EmptyResultDataAccessException exception) {\n return \"\";\n }\n }\n\n /**\n * 批量获取使用 in 查询\n */\n @Override\n public Map<Object, String> dictLabels(String dictType, Collection<Object> dictCodes, String codeFiled, String labelFiled, String whereSql) {\n if (dictCodes == null || dictCodes.isEmpty()) {\n return Collections.emptyMap();\n }\n\n if (dictCodes.size() == 1) {\n Object code = dictCodes.iterator().next();\n String dictLabel = dictLabel(dictType, code, codeFiled, labelFiled, whereSql);\n if (dictLabel == null) {\n return Collections.emptyMap();\n }\n Map<Object, String> dict = new HashMap<>(2);\n dict.put(code, dictLabel);\n return dict;\n }\n\n StringBuilder sql = new StringBuilder(\"select \" + labelFiled + \" as `value`,\" + codeFiled + \" as `key` from \" + dictType);\n sql.append(\" WHERE \");\n\n // inSql\n sql.append(codeFiled).append(\" IN (\");\n\n boolean isFirst = true;\n for (Object code : dictCodes) {\n sql.append(isFirst ? \"?\" : \",?\");\n isFirst = false;\n }\n sql.append(\") \");\n\n\n if (StringUtils.isNotBlank(whereSql)) {\n sql.append(\" AND \");\n sql.append(whereSql);\n }\n\n String sqlStr = sql.toString();\n if (log.isDebugEnabled()) {\n log.debug(\"dict SQL: {},code: {}\", sqlStr, dictCodes);\n }\n\n // TODO: 租户\n try {\n Object[] dictCodesArray = dictCodes.toArray();\n\n List<Map<String, Object>> maps = jdbcTemplate.queryForList(sqlStr, dictCodesArray);\n\n Map<Object, String> result = new HashMap<>(dictCodes.size());\n for (Map<String, Object> map : maps) {\n result.put(map.get(\"key\"), map.get(\"value\").toString());\n }\n return result;\n } catch (EmptyResultDataAccessException exception) {\n return Collections.emptyMap();\n }\n }\n}"
},
{
"identifier": "MybatisSqlDictManager",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/impl/MybatisSqlDictManager.java",
"snippet": "@RequiredArgsConstructor\npublic class MybatisSqlDictManager implements SqlDictManager {\n\n private final SqlDictMapper sqlDictMapper;\n\n /**\n * 获取字典显示值\n *\n * @param dictType\n * @param code\n * @param codeFiled\n * @param labelFiled\n * @param whereSql\n * @return\n */\n @Override\n public String dictLabel(String dictType, Object code, String codeFiled, String labelFiled, String whereSql) {\n return sqlDictMapper.dictLabel(dictType, code, codeFiled, labelFiled, whereSql);\n }\n\n /**\n * 批量获取使用 in 查询\n */\n @Override\n public Map<Object, String> dictLabels(String dictType, Collection<Object> dictCodes, String codeFiled, String labelFiled, String whereSql) {\n if (dictCodes == null || dictCodes.isEmpty()) {\n return Collections.emptyMap();\n }\n if (codeFiled.length() == 1) {\n Object code = dictCodes.iterator().next();\n String label = dictLabel(dictType, code, codeFiled, labelFiled, whereSql);\n if (StringUtils.isBlank(label)) {\n return Collections.emptyMap();\n }\n\n Map<Object, String> dict = new HashMap<>(2);\n dict.put(code, label);\n return dict;\n }\n ArrayList<HashMap<String, Object>> hashMaps = sqlDictMapper.dictLabels(dictType, dictCodes, codeFiled, labelFiled, whereSql);\n\n Map<Object, String> result = new HashMap<>(codeFiled.length());\n for (HashMap<String, Object> map : hashMaps) {\n Object o = map.get(\"label\");\n if (o instanceof String) {\n result.put(map.get(\"code\"), (String) o);\n } else {\n result.put(map.get(\"code\"), o.toString());\n }\n }\n return result;\n }\n\n /**\n * 根据label 获取字典code\n *\n * @param dictType\n * @param dictLabel\n * @param codeFiled\n * @param labelFiled\n * @param whereSql\n * @return\n */\n @Override\n public Object dictCode(String dictType, String dictLabel, String codeFiled, String labelFiled, String whereSql) {\n return sqlDictMapper.dictCode(dictType, dictLabel, codeFiled, labelFiled, whereSql);\n }\n}"
},
{
"identifier": "PropertiesSqlDictService",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/impl/PropertiesSqlDictService.java",
"snippet": "@RequiredArgsConstructor\npublic class PropertiesSqlDictService implements SqlDictService {\n\n\n protected final SqlDictProperties sqlDictProperties;\n\n protected final SqlDictManager sqlDictManager;\n\n /**\n * 通过 字典code 获取字典显示值\n *\n * @param tableType 表类型,或者表的 代码,由实现类转化\n * @param dictCode\n * @return\n */\n @Override\n public String dictLabel(String tableType, Object dictCode) {\n SqlDictProperties.SqlDict sqlDict = sqlDictProperties.getSqlDictMap().get(tableType);\n Assert.notNull(sqlDict, \"sqlDictProperties cannot null\");\n return sqlDictManager.dictLabel(tableType, dictCode, sqlDict.getCodeFiled(), sqlDict.getLabelFiled(), sqlDict.getWhereSql());\n }\n\n /**\n * 通过 字典code数组 批量的获取字典显示值\n *\n * @param dictType 表类型,或者表的 代码,由实现类转化\n * @param dictCodes\n * @return\n */\n @Override\n public Map<Object, String> dictLabels(String dictType, Collection<Object> dictCodes) {\n SqlDictProperties.SqlDict sqlDict = sqlDictProperties.getSqlDictMap().get(dictType);\n Assert.notNull(sqlDict, \"sqlDictProperties cannot null\");\n return sqlDictManager.dictLabels(dictType, dictCodes, sqlDict.getCodeFiled(), sqlDict.getLabelFiled(), sqlDict.getWhereSql());\n }\n\n /**\n * 通过字典显示label 获取字典值值\n *\n * @param dictType\n * @param dictLabel\n * @return\n */\n @Override\n public Object dictCode(String dictType, String dictLabel) {\n SqlDictProperties.SqlDict sqlDict = sqlDictProperties.getSqlDictMap().get(dictType);\n Assert.notNull(sqlDict, \"sqlDictProperties cannot null\");\n return sqlDictManager.dictCode(dictType, dictLabel, sqlDict.getCodeFiled(), sqlDict.getLabelFiled(), sqlDict.getWhereSql());\n }\n}"
},
{
"identifier": "SqlDictMapper",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/impl/mapper/SqlDictMapper.java",
"snippet": "@Mapper\npublic interface SqlDictMapper {\n\n @Select(\"<script>SELECT ${labelFiled} as `label` from ${dictType} \" +\n \"where ${codeFiled} = #{code}\" +\n \" <if test=\\\"whereSql !=null and whereSql !=\\'\\' \\\"> AND ${whereSql} </if> LIMIT 1</script>\")\n String dictLabel(@Param(\"dictType\") String dictType, @Param(\"code\") Object code,\n @Param(\"codeFiled\") String codeFiled, @Param(\"labelFiled\") String labelFiled,\n @Param(\"whereSql\") String whereSql);\n\n\n @Select(\"<script>select ${labelFiled} as `label`, ${codeFiled} as `code` from ${dictType} \" +\n \"where ${codeFiled} in\" +\n \" <foreach collection=\\\"codes\\\" item=\\\"code\\\" separator=\\\",\\\" open=\\\"(\\\" close=\\\")\\\">\" +\n \" #{code}\" +\n \" </foreach>\" +\n \" <if test=\\\"whereSql !=null and whereSql !=\\'\\' \\\"> AND ${whereSql} </if></script>\")\n\n @ResultType(HashMap.class)\n ArrayList<HashMap<String, Object>> dictLabels(@Param(\"dictType\") String dictType, @Param(\"codes\") Collection<Object> codes,\n @Param(\"codeFiled\") String codeFiled, @Param(\"labelFiled\") String labelFiled,\n @Param(\"whereSql\") String whereSql);\n\n @Select(\"<script>SELECT ${codeFiled} as `code` from ${dictType} \" +\n \"where ${labelFiled} = #{label}\" +\n \" <if test=\\\"whereSql !=null and whereSql !=\\'\\' \\\"> AND ${whereSql} </if> LIMIT 1</script>\")\n Object dictCode(@Param(\"dictType\") String dictType, @Param(\"label\") Object label,\n @Param(\"codeFiled\") String codeFiled, @Param(\"labelFiled\") String labelFiled,\n @Param(\"whereSql\") String whereSql);\n}"
}
] | import com.admin4j.dict.provider.sql.SqlDictManager;
import com.admin4j.dict.provider.sql.SqlDictProperties;
import com.admin4j.dict.provider.sql.SqlDictProvider;
import com.admin4j.dict.provider.sql.SqlDictService;
import com.admin4j.dict.provider.sql.impl.JdbcSqlDictManager;
import com.admin4j.dict.provider.sql.impl.MybatisSqlDictManager;
import com.admin4j.dict.provider.sql.impl.PropertiesSqlDictService;
import com.admin4j.dict.provider.sql.impl.mapper.SqlDictMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate; | 4,944 | package com.admin4j.dict.provider.sql.autoconfigure;
/**
* @author andanyang
* @since 2022/10/25 16:55
*/
@AutoConfigureOrder(value = Integer.MAX_VALUE)
@EnableConfigurationProperties(SqlDictProperties.class)
public class SqlProviderAutoconfigure {
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
public MapperFactoryBean<SqlDictMapper> sqlDictMapper(SqlSessionFactory sqlSessionFactory) {
MapperFactoryBean<SqlDictMapper> sqlDictMapperMapperFactoryBean = new MapperFactoryBean<>(SqlDictMapper.class);
sqlDictMapperMapperFactoryBean.setSqlSessionFactory(sqlSessionFactory);
return sqlDictMapperMapperFactoryBean;
}
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
@ConditionalOnBean(SqlDictMapper.class)
public MybatisSqlDictManager mybatisSqlDictManager(SqlDictMapper sqlDictMapper) {
return new MybatisSqlDictManager(sqlDictMapper);
}
@Bean
@ConditionalOnBean({SqlDictManager.class})
@ConditionalOnMissingBean(SqlDictService.class)
public PropertiesSqlDictService propertiesSqlDictService(SqlDictManager sqlDictManager, SqlDictProperties sqlDictProperties) {
return new PropertiesSqlDictService(sqlDictProperties, sqlDictManager);
}
@Bean
@ConditionalOnBean(SqlDictManager.class)
public SqlDictProvider sqlDictProvider(SqlDictManager sqlDictManager, SqlDictService sqlDictService) {
return new SqlDictProvider(sqlDictManager, sqlDictService);
}
@Bean
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate")
@ConditionalOnBean(name = {"jdbcTemplate"})
@ConditionalOnMissingBean(MybatisSqlDictManager.class) | package com.admin4j.dict.provider.sql.autoconfigure;
/**
* @author andanyang
* @since 2022/10/25 16:55
*/
@AutoConfigureOrder(value = Integer.MAX_VALUE)
@EnableConfigurationProperties(SqlDictProperties.class)
public class SqlProviderAutoconfigure {
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
public MapperFactoryBean<SqlDictMapper> sqlDictMapper(SqlSessionFactory sqlSessionFactory) {
MapperFactoryBean<SqlDictMapper> sqlDictMapperMapperFactoryBean = new MapperFactoryBean<>(SqlDictMapper.class);
sqlDictMapperMapperFactoryBean.setSqlSessionFactory(sqlSessionFactory);
return sqlDictMapperMapperFactoryBean;
}
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
@ConditionalOnBean(SqlDictMapper.class)
public MybatisSqlDictManager mybatisSqlDictManager(SqlDictMapper sqlDictMapper) {
return new MybatisSqlDictManager(sqlDictMapper);
}
@Bean
@ConditionalOnBean({SqlDictManager.class})
@ConditionalOnMissingBean(SqlDictService.class)
public PropertiesSqlDictService propertiesSqlDictService(SqlDictManager sqlDictManager, SqlDictProperties sqlDictProperties) {
return new PropertiesSqlDictService(sqlDictProperties, sqlDictManager);
}
@Bean
@ConditionalOnBean(SqlDictManager.class)
public SqlDictProvider sqlDictProvider(SqlDictManager sqlDictManager, SqlDictService sqlDictService) {
return new SqlDictProvider(sqlDictManager, sqlDictService);
}
@Bean
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate")
@ConditionalOnBean(name = {"jdbcTemplate"})
@ConditionalOnMissingBean(MybatisSqlDictManager.class) | public JdbcSqlDictManager jdbcSqlDictManager(JdbcTemplate jdbcTemplate) { | 4 | 2023-10-26 08:36:17+00:00 | 8k |
Nolij/Zume | src/main/java/dev/nolij/zume/ForgeZumeBootstrapper.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": "LexZume",
"path": "lexforge/src/main/java/dev/nolij/zume/lexforge/LexZume.java",
"snippet": "@Mod(Zume.MOD_ID)\n@OnlyIn(Dist.CLIENT)\npublic class LexZume implements IZumeProvider {\n\t\n\tpublic LexZume() {\n\t\tZume.LOGGER.info(\"Loading LexZume...\");\n\t\t\n\t\tZume.init(this, new File(FMLPaths.CONFIGDIR.get().toFile(), Zume.CONFIG_FILE_NAME));\n\t\t\n\t\tFMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerKeyBindings);\n\t\tMinecraftForge.EVENT_BUS.addListener(this::render);\n\t\tMinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::calculateFOV);\n\t\tMinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::onMouseScroll);\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\tprivate void registerKeyBindings(RegisterKeyMappingsEvent event) {\n\t\tfor (final ZumeKeyBind keyBind : ZumeKeyBind.values()) {\n\t\t\tevent.register(keyBind.value);\n\t\t}\n\t}\n\t\n\tprivate void render(TickEvent.RenderTickEvent event) {\n\t\tif (event.phase == TickEvent.Phase.START) {\n\t\t\tZume.render();\n\t\t}\n\t}\n\t\n\tprivate void calculateFOV(ViewportEvent.ComputeFov event) {\n\t\tif (Zume.isActive()) {\n\t\t\tevent.setFOV(Zume.transformFOV(event.getFOV()));\n\t\t}\n\t}\n\t\n\tprivate void onMouseScroll(InputEvent.MouseScrollingEvent event) {\n\t\tfinal int scrollAmount = (int) event.getScrollDelta();\n\t\tif (scrollAmount != 0 &&\n\t\t\t!Zume.transformHotbarScroll(scrollAmount)) {\n\t\t\tevent.setCanceled(true);\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "LexZume18",
"path": "lexforge18/src/main/java/dev/nolij/zume/lexforge18/LexZume18.java",
"snippet": "@Mod(Zume.MOD_ID)\npublic class LexZume18 implements IZumeProvider {\n\t\n\tpublic LexZume18() {\n\t\tZume.LOGGER.info(\"Loading LexZume18...\");\n\t\t\n\t\tfor (final ZumeKeyBind keyBind : ZumeKeyBind.values()) {\n\t\t\tClientRegistry.registerKeyBinding(keyBind.value);\n\t\t}\n\t\t\n\t\tZume.init(this, new File(FMLPaths.CONFIGDIR.get().toFile(), Zume.CONFIG_FILE_NAME));\n\t\t\n\t\tMinecraftForge.EVENT_BUS.addListener(this::render);\n\t\tMinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::onMouseScroll);\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\tprivate void render(TickEvent.RenderTickEvent event) {\n\t\tif (event.phase == TickEvent.Phase.START) {\n\t\t\tZume.render();\n\t\t}\n\t}\n\t\n\tprivate void onMouseScroll(InputEvent.MouseScrollEvent event) {\n\t\tfinal int scrollAmount = (int) event.getScrollDelta();\n\t\tif (scrollAmount != 0 &&\n\t\t\t!Zume.transformHotbarScroll(scrollAmount)) {\n\t\t\tevent.setCanceled(true);\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "LexZume16",
"path": "lexforge16/src/main/java/dev/nolij/zume/lexforge16/LexZume16.java",
"snippet": "@Mod(Zume.MOD_ID)\npublic class LexZume16 implements IZumeProvider {\n\t\n\tpublic LexZume16() {\n\t\tZume.LOGGER.info(\"Loading LexZume16...\");\n\t\t\n\t\tfor (final ZumeKeyBind keyBind : ZumeKeyBind.values()) {\n\t\t\tClientRegistry.registerKeyBinding(keyBind.value);\n\t\t}\n\t\t\n\t\tZume.init(this, new File(FMLPaths.CONFIGDIR.get().toFile(), Zume.CONFIG_FILE_NAME));\n\t\t\n\t\tMinecraftForge.EVENT_BUS.addListener(this::render);\n\t\tMinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::calculateFOV);\n\t\tMinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::onMouseScroll);\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\tprivate void render(TickEvent.RenderTickEvent event) {\n\t\tif (event.phase == TickEvent.Phase.START) {\n\t\t\tZume.render();\n\t\t}\n\t}\n\t\n\tprivate void calculateFOV(EntityViewRenderEvent.FOVModifier event) {\n\t\tif (Zume.isActive()) {\n\t\t\tevent.setFOV(Zume.transformFOV(event.getFOV()));\n\t\t}\n\t}\n\t\n\tprivate void onMouseScroll(InputEvent.MouseScrollEvent event) {\n\t\tfinal int scrollAmount = (int) event.getScrollDelta();\n\t\tif (scrollAmount != 0 &&\n\t\t\t!Zume.transformHotbarScroll(scrollAmount)) {\n\t\t\tevent.setCanceled(true);\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "VintageZume",
"path": "vintage/src/main/java/dev/nolij/zume/vintage/VintageZume.java",
"snippet": "@Mod(\n\tmodid = Zume.MOD_ID,\n\tname = Constants.MOD_NAME,\n\tversion = Constants.MOD_VERSION, \n\tacceptedMinecraftVersions = Constants.VINTAGE_VERSION_RANGE,\n\tguiFactory = \"dev.nolij.zume.vintage.VintageConfigProvider\")\npublic class VintageZume implements IZumeProvider {\n\t\n\tpublic VintageZume() {\n\t\tZume.LOGGER.info(\"Loading Vintage Zume...\");\n\t\t\n\t\tfor (final ZumeKeyBind keyBind : ZumeKeyBind.values()) {\n\t\t\tClientRegistry.registerKeyBinding(keyBind.value);\n\t\t}\n\t\t\n\t\tZume.init(this, new File(Launch.minecraftHome, \"config\" + File.separator + Zume.CONFIG_FILE_NAME));\n\t\t\n\t\tMinecraftForge.EVENT_BUS.register(this);\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 && !Minecraft.getMinecraft().gameSettings.smoothCamera) {\n\t\t\tfinal EntityRendererAccessor entityRenderer = (EntityRendererAccessor) Minecraft.getMinecraft().entityRenderer;\n\t\t\tentityRenderer.setMouseFilterXAxis(new MouseFilter());\n\t\t\tentityRenderer.setMouseFilterYAxis(new MouseFilter());\n\t\t\tentityRenderer.setSmoothCamYaw(0F);\n\t\t\tentityRenderer.setSmoothCamPitch(0F);\n\t\t\tentityRenderer.setSmoothCamFilterX(0F);\n\t\t\tentityRenderer.setSmoothCamFilterY(0F);\n\t\t\tentityRenderer.setSmoothCamPartialTicks(0F);\n\t\t}\n\t}\n\t\n\t@SubscribeEvent\n\tpublic void render(TickEvent.RenderTickEvent event) {\n\t\tif (event.phase == TickEvent.Phase.START) {\n\t\t\tZume.render();\n\t\t}\n\t}\n\t\n\t@SubscribeEvent(priority = EventPriority.LOWEST)\n\tpublic void calculateFOV(EntityViewRenderEvent.FOVModifier event) {\n\t\tif (Zume.isActive()) {\n\t\t\tevent.setFOV((float) Zume.transformFOV(event.getFOV()));\n\t\t}\n\t}\n\t\n\t@SubscribeEvent(priority = EventPriority.HIGHEST)\n\tpublic void mouseEvent(MouseEvent mouseEvent) {\n\t\tfinal int scrollAmount = mouseEvent.getDwheel();\n\t\tif (scrollAmount != 0 &&\n\t\t\t!Zume.transformHotbarScroll(scrollAmount)) {\n\t\t\tmouseEvent.setCanceled(true);\n\t\t}\n\t}\n\t\n}"
}
] | import dev.nolij.zume.common.Constants;
import dev.nolij.zume.common.Zume;
import dev.nolij.zume.lexforge.LexZume;
import dev.nolij.zume.lexforge18.LexZume18;
import dev.nolij.zume.lexforge16.LexZume16;
import dev.nolij.zume.vintage.VintageZume;
import net.minecraftforge.fml.common.Mod; | 4,317 | package dev.nolij.zume;
@Mod(
value = Zume.MOD_ID,
modid = Zume.MOD_ID,
name = Constants.MOD_NAME,
version = Constants.MOD_VERSION,
acceptedMinecraftVersions = Constants.VINTAGE_VERSION_RANGE,
guiFactory = "dev.nolij.zume.vintage.VintageConfigProvider")
public class ForgeZumeBootstrapper {
public ForgeZumeBootstrapper() {
if (Zume.ZUME_VARIANT == null)
throw new AssertionError("""
Mixins did not load! Zume requires Mixins in order to work properly.
Please install one of the following mixin loaders:
14.4 - 16.0: MixinBootstrap
8.9 - 12.2: MixinBooter >= 5.0
7.10 - 12.2: UniMixins >= 0.1.15""");
switch (Zume.ZUME_VARIANT) {
case LEXFORGE -> new LexZume();
case LEXFORGE18 -> new LexZume18();
case LEXFORGE16 -> new LexZume16(); | package dev.nolij.zume;
@Mod(
value = Zume.MOD_ID,
modid = Zume.MOD_ID,
name = Constants.MOD_NAME,
version = Constants.MOD_VERSION,
acceptedMinecraftVersions = Constants.VINTAGE_VERSION_RANGE,
guiFactory = "dev.nolij.zume.vintage.VintageConfigProvider")
public class ForgeZumeBootstrapper {
public ForgeZumeBootstrapper() {
if (Zume.ZUME_VARIANT == null)
throw new AssertionError("""
Mixins did not load! Zume requires Mixins in order to work properly.
Please install one of the following mixin loaders:
14.4 - 16.0: MixinBootstrap
8.9 - 12.2: MixinBooter >= 5.0
7.10 - 12.2: UniMixins >= 0.1.15""");
switch (Zume.ZUME_VARIANT) {
case LEXFORGE -> new LexZume();
case LEXFORGE18 -> new LexZume18();
case LEXFORGE16 -> new LexZume16(); | case VINTAGE_FORGE -> new VintageZume(); | 4 | 2023-10-25 21:00:22+00:00 | 8k |
sanxiaoshitou/tower-boot | tower-boot-redis/src/main/java/com/hxl/redis/ExecuteRedisAutoConfiguration.java | [
{
"identifier": "CustomRedisProperties",
"path": "tower-boot-redis/src/main/java/com/hxl/redis/config/CustomRedisProperties.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"spring.redis\")\npublic class CustomRedisProperties {\n\n /**\n * redis key前缀,一般用项目名做区分,数据隔离\n */\n private String redisKeyPrefix = \"\";\n}"
},
{
"identifier": "DefaultRedisServiceImpl",
"path": "tower-boot-redis/src/main/java/com/hxl/redis/load/DefaultRedisServiceImpl.java",
"snippet": "@Slf4j\npublic class DefaultRedisServiceImpl implements RedisService {\n\n private final ObjectMapper objectMapper;\n\n private final RedisTemplate<String, Object> redisTemplate;\n\n public DefaultRedisServiceImpl(ObjectMapper objectMapper, RedisTemplate<String, Object> redisTemplate) {\n this.objectMapper = objectMapper;\n this.redisTemplate = redisTemplate;\n }\n\n @Override\n public Boolean exists(String key) {\n return redisTemplate.hasKey(key);\n }\n\n @Override\n public Boolean expire(String key, long timeout) {\n return expire(key, timeout, TimeUnit.SECONDS);\n }\n\n @Override\n public Boolean expire(String key, long timeout, TimeUnit unit) {\n return redisTemplate.expire(key, timeout, unit);\n }\n\n @Override\n public int delete(String... keys) {\n int i = 0;\n for (String key : keys) {\n Boolean success = redisTemplate.delete(key);\n if (success) {\n i++;\n }\n }\n log.info(\"删除key,影响条数:{}\", i);\n return i;\n }\n\n @Override\n public Boolean delete(String key) {\n if (StringUtils.isEmpty(key)) {\n return false;\n }\n try {\n return redisTemplate.delete(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n @Override\n public Boolean set(String key, Object value) {\n if (!StringUtils.isEmpty(key)) {\n try {\n redisTemplate.opsForValue().set(key, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }\n return false;\n }\n\n @Override\n public Boolean set(String key, Object value, long expireTime) {\n return set(key, value, expireTime, TimeUnit.SECONDS);\n }\n\n @Override\n public Boolean set(String key, Object value, long expireTime, TimeUnit timeUnit) {\n if (!StringUtils.isEmpty(key)) {\n try {\n redisTemplate.opsForValue().set(key, value, expireTime, timeUnit);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n }\n return false;\n }\n\n @Override\n public String get(String key) {\n Object result;\n try {\n result = redisTemplate.opsForValue().get(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n return result == null ? null : String.valueOf(result);\n }\n\n @Override\n public <T> T getObject(String key, Class<T> type) {\n Object result;\n result = redisTemplate.opsForValue().get(key);\n if (result == null) {\n return null;\n }\n return transitionClass(result, type);\n }\n\n @Override\n public <T> List<T> getObjectList(String key, Class<T> type) {\n Object result = redisTemplate.opsForValue().get(key);\n if (result == null) {\n return null;\n }\n try {\n JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, type);\n return this.objectMapper.readValue(this.objectMapper.writeValueAsBytes(result), javaType);\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n\n @Override\n public Long setCacheList(String key, Object value) {\n return redisTemplate.opsForList().rightPush(key, value);\n }\n\n @Override\n public Long setCacheList(String key, List<Object> values) {\n if (StrUtil.isBlank(key) || CollectionUtil.isEmpty(values)) {\n return 0L;\n }\n try {\n return redisTemplate.opsForList().rightPushAll(key, values);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return 0L;\n }\n\n @Override\n public Long setLeftCacheList(String key, Object value) {\n return redisTemplate.opsForList().leftPush(key, value);\n }\n\n @Override\n public Long setLeftCacheList(String key, List<Object> values) {\n if (StrUtil.isBlank(key) || CollectionUtil.isEmpty(values)) {\n return 0L;\n }\n try {\n return redisTemplate.opsForList().leftPushAll(key, values);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return 0L;\n }\n\n @Override\n public <T> T rightPop(String key, Class<T> type) {\n Object result = redisTemplate.opsForList().rightPop(key);\n if (result == null) {\n return null;\n }\n return transitionClass(result, type);\n }\n\n @Override\n public <T> T leftPop(String key, Class<T> type) {\n Object result = redisTemplate.opsForList().leftPop(key);\n if (result == null) {\n return null;\n }\n return transitionClass(result, type);\n }\n\n @Override\n public <T> List<T> getCacheList(String key, Class<T> type) {\n List<Object> resultList = redisTemplate.opsForList().range(key, 0, -1);\n if (CollectionUtil.isNotEmpty(resultList)) {\n return resultList.stream().map(i -> transitionClass(i, type)).collect(Collectors.toList());\n }\n return null;\n }\n\n @Override\n public Long size(String key) {\n return redisTemplate.opsForList().size(key);\n }\n\n @Override\n public Boolean hPut(String key, String hashKey, Object value) {\n if (StrUtil.isBlank(key) || StrUtil.isBlank(hashKey)) {\n return false;\n }\n try {\n redisTemplate.opsForHash().put(key, hashKey, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public Boolean hPutAll(String key, Map<String, String> maps) {\n if (StrUtil.isBlank(key) || CollectionUtil.isEmpty(maps)) {\n return false;\n }\n try {\n redisTemplate.opsForHash().putAll(key, maps);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public Boolean hExists(String key, String field) {\n return redisTemplate.opsForHash().hasKey(key, field);\n }\n\n @Override\n public Long hDelete(String key, Object... fields) {\n return redisTemplate.opsForHash().delete(key, fields);\n }\n\n @Override\n public Map<Object, Object> hGetAll(String key) {\n return redisTemplate.opsForHash().entries(key);\n }\n\n @Override\n public Object hGet(String key, String field) {\n return redisTemplate.opsForHash().get(key, field);\n }\n\n @Override\n public List<Object> hMultiGet(String key, Collection<Object> fields) {\n return redisTemplate.opsForHash().multiGet(key, fields);\n }\n\n @Override\n public Long hSize(String key) {\n return redisTemplate.opsForHash().size(key);\n }\n\n @Override\n public boolean addSet(String key, Object value) {\n if (Objects.isNull(value)) {\n return false;\n }\n try {\n Long ret = redisTemplate.opsForSet().add(key, value);\n return ret > 0;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public boolean removeSet(String key, Object... value) {\n if (Objects.isNull(value)) {\n return false;\n }\n try {\n Long ret = redisTemplate.opsForSet().remove(key, value);\n return ret > 0;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public Set<Object> getAllSet(String key) {\n return redisTemplate.opsForSet().members(key);\n }\n\n @Override\n public Boolean addZSet(String key, Object value, double score) {\n if (Objects.isNull(value)) {\n return false;\n }\n try {\n return redisTemplate.opsForZSet().add(key, value, score);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public Long removeZSet(String key, Object... value) {\n return redisTemplate.opsForZSet().remove(key,value);\n }\n\n @Override\n public Double incrZSet(String key, Object value, double delta) {\n return redisTemplate.opsForZSet().incrementScore(key, value, delta);\n }\n\n @Override\n public Set<Object> zSetRangeByScore(String key, double min, double max) {\n return redisTemplate.opsForZSet().rangeByScore(key, min, max);\n }\n\n @Override\n public Set<Object> zSetRangeDescByScore(String key, double min, double max) {\n return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);\n }\n\n /**\n * 公共转换\n *\n * @param <T>\n * @return\n */\n private <T> T transitionClass(Object result, Class<T> type) {\n String expectClass = type.toString();\n String actualClass = result.getClass().toString();\n if (!expectClass.equals(actualClass)) {\n log.error(\"class not match.expect class:\" + expectClass + \",actualClass:\" + actualClass);\n return null;\n }\n try {\n return this.objectMapper.readValue(this.objectMapper.writeValueAsBytes(result), type);\n } catch (IOException e) {\n e.printStackTrace();\n log.error(e.getMessage(), e);\n return null;\n }\n }\n}"
},
{
"identifier": "RedisService",
"path": "tower-boot-redis/src/main/java/com/hxl/redis/load/RedisService.java",
"snippet": "public interface RedisService {\n\n /**\n * *公共基础操作*\n **/\n Boolean exists(String key);\n\n Boolean expire(String key, long timeout);\n\n Boolean expire(final String key, final long timeout, final TimeUnit unit);\n\n int delete(String... keys);\n\n Boolean delete(String key);\n\n /**\n * *基础类型(Integer、String、实体类等) 操作*\n **/\n Boolean set(String key, Object value);\n\n Boolean set(String key, Object value, long expireTime);\n\n Boolean set(String key, Object value, long expireTime, TimeUnit timeUnit);\n\n String get(String key);\n\n <T> T getObject(String key, Class<T> type);\n\n <T> List<T> getObjectList(String key, Class<T> type);\n\n /**\n * *双向列表 list操作*\n **/\n Long setCacheList(String key, Object value);\n\n Long setCacheList(String key, List<Object> values);\n\n Long setLeftCacheList(String key, Object value);\n\n Long setLeftCacheList(String key, List<Object> values);\n\n <T> T rightPop(String key, Class<T> type);\n\n <T> T leftPop(String key, Class<T> type);\n\n <T> List<T> getCacheList(String key, Class<T> type);\n\n Long size(String key);\n\n /**\n * *hash map操作*\n */\n Boolean hPut(String key, String hashKey, Object value);\n\n Boolean hPutAll(String key, Map<String, String> maps);\n\n Boolean hExists(String key, String field);\n\n Long hDelete(String key, Object... fields);\n\n Map<Object, Object> hGetAll(String key);\n\n Object hGet(String key, String field);\n\n List<Object> hMultiGet(String key, Collection<Object> fields);\n\n Long hSize(String key);\n\n /**\n * *set 集合 不重复*\n */\n boolean addSet(String key, Object value);\n\n boolean removeSet(String key, Object... value);\n\n Set<Object> getAllSet(String key);\n\n /**\n * *set 有序集合 不重复*\n */\n Boolean addZSet(String key, Object value, double score);\n\n Long removeZSet(String key, Object... value);\n\n /**\n * ZSet数据增加分数\n *\n * @param key key\n * @param value value\n * @param delta 分数\n * @return duuble\n */\n Double incrZSet(String key, Object value, double delta);\n\n /**\n * 升序 区间查询\n *\n * @param key key\n * @param min 最小分数\n * @param max 最大分数\n * @return Set<Object>\n */\n Set<Object> zSetRangeByScore(String key, double min, double max);\n\n /**\n * 降序 区间查询\n *\n * @param key key\n * @param min 最小分数\n * @param max 最大分数\n * @return Set<Object>\n */\n Set<Object> zSetRangeDescByScore(String key, double min, double max);\n}"
},
{
"identifier": "KeyStringSerializer",
"path": "tower-boot-redis/src/main/java/com/hxl/redis/serializer/KeyStringSerializer.java",
"snippet": "@Slf4j\npublic class KeyStringSerializer implements RedisSerializer<String> {\n\n private final Charset charset;\n\n public KeyStringSerializer() {\n this.charset = StandardCharsets.UTF_8;\n }\n\n @Autowired\n private CustomRedisProperties redisProperties;\n\n @Override\n public byte[] serialize(String s) throws SerializationException {\n String newValue = getKeyPrefix() + s;\n return newValue.getBytes(charset);\n }\n\n @Override\n public String deserialize(byte[] bytes) throws SerializationException {\n String saveKey = new String(bytes, charset);\n String keyPrefix = getKeyPrefix();\n if (StrUtil.isNotBlank(keyPrefix)) {\n int indexOf = saveKey.indexOf(keyPrefix);\n if (indexOf > 0) {\n log.info(\"key缺少前缀\");\n } else {\n saveKey = saveKey.substring(indexOf);\n }\n log.info(\"saveKey:{}\", saveKey);\n }\n return saveKey;\n }\n\n private String getKeyPrefix() {\n return redisProperties.getRedisKeyPrefix();\n }\n}"
}
] | import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxl.redis.config.CustomRedisProperties;
import com.hxl.redis.load.DefaultRedisServiceImpl;
import com.hxl.redis.load.RedisService;
import com.hxl.redis.serializer.KeyStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import javax.annotation.PostConstruct; | 4,237 | package com.hxl.redis;
/**
* @Author hxl
* @description
* @Date 2023-06-14 17:17
**/
@Slf4j
@EnableCaching
@Configuration
@EnableConfigurationProperties(CustomRedisProperties.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class ExecuteRedisAutoConfiguration {
@Autowired
private RedisProperties redisProperties;
@PostConstruct
public void init() {
log.info("enabled Redis ,ip: {}", redisProperties.getHost());
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
ObjectMapper objectMapper, KeyStringSerializer keyStringSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//key序列化方式
RedisSerializer<String> defalutSerializer = template.getStringSerializer();
//值序列化方式
RedisSerializer<Object> jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
//设置key 的序列化方式
template.setKeySerializer(keyStringSerializer);
template.setHashKeySerializer(keyStringSerializer);
//设置值 的序列化方式
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
//设置默认的序列化方式
template.setDefaultSerializer(defalutSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyStringSerializer keyStringSerializer() {
return new KeyStringSerializer();
}
@Bean | package com.hxl.redis;
/**
* @Author hxl
* @description
* @Date 2023-06-14 17:17
**/
@Slf4j
@EnableCaching
@Configuration
@EnableConfigurationProperties(CustomRedisProperties.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class ExecuteRedisAutoConfiguration {
@Autowired
private RedisProperties redisProperties;
@PostConstruct
public void init() {
log.info("enabled Redis ,ip: {}", redisProperties.getHost());
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
ObjectMapper objectMapper, KeyStringSerializer keyStringSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//key序列化方式
RedisSerializer<String> defalutSerializer = template.getStringSerializer();
//值序列化方式
RedisSerializer<Object> jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
//设置key 的序列化方式
template.setKeySerializer(keyStringSerializer);
template.setHashKeySerializer(keyStringSerializer);
//设置值 的序列化方式
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
//设置默认的序列化方式
template.setDefaultSerializer(defalutSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyStringSerializer keyStringSerializer() {
return new KeyStringSerializer();
}
@Bean | public RedisService redisService(ObjectMapper objectMapper, RedisTemplate<String, Object> redisTemplate) { | 2 | 2023-10-30 06:30:41+00:00 | 8k |
simply-kel/AlinLib | src/main/java/ru/kelcuprum/alinlib/gui/components/sliders/SliderPercent.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": "Localization",
"path": "src/main/java/ru/kelcuprum/alinlib/config/Localization.java",
"snippet": "public class Localization {\r\n private static final int codes = 23;\r\n private static final Map<String, String> formatCodes = IntStream.range(0, codes)\r\n .boxed()\r\n .collect(Collectors.toMap(List.of(new String[]{\r\n \"&4\", \"&c\", \"&6\", \"&e\", \"&z\", \"&a\", \"&b\", \"&3\", \"&1\", \"&9\", \"&d\", \"&5\", \"&f\", \"&7\", \"&8\", \"&0\",\r\n \"&r\", \"&l\", \"&o\", \"&n\", \"&m\", \"&k\", \"&x\"\r\n })::get, List.of(new String[]{\r\n \"§4\", \"§c\", \"§6\", \"§e\", \"§z\", \"§a\", \"§b\", \"§3\", \"§1\", \"§9\", \"§d\", \"§5\", \"§f\", \"§7\", \"§8\", \"§0\",\r\n \"§r\", \"§l\", \"§o\", \"§n\", \"§m\", \"§k\", \"§x\"\r\n })::get));\r\n public String modID;\r\n public String filePath;\r\n public Localization(String modID, String filePath){\r\n this.modID = modID;\r\n this.filePath = filePath;\r\n }\r\n private String getCodeLocalization(){\r\n try{\r\n return Minecraft.getInstance().options.languageCode;\r\n } catch (Exception e){\r\n return \"en_us\";\r\n }\r\n }\r\n public JsonObject getJSONFile(){\r\n try {\r\n Minecraft CLIENT = Minecraft.getInstance();\r\n File localizationFile = new File(CLIENT.gameDirectory + filePath + getCodeLocalization() + \".json\");\r\n if (localizationFile.exists()) {\r\n return GsonHelper.parse(Files.readString(localizationFile.toPath()));\r\n } else {\r\n return new JsonObject();\r\n }\r\n } catch (Exception ex){\r\n AlinLib.log(ex.getLocalizedMessage());\r\n return new JsonObject();\r\n }\r\n }\r\n public String getLocalization(String key){\r\n return getLocalization(key, false);\r\n }\r\n public String getLocalization(String key, boolean clearColor){\r\n String text;\r\n try {\r\n JsonObject JSONLocalization = getJSONFile();\r\n if(JSONLocalization.get(key) != null && !JSONLocalization.get(key).isJsonNull()) text = getText(modID+ \".\" + key).getString();\r\n else text = JSONLocalization.get(key).getAsString();\r\n } catch (Exception ex) {\r\n AlinLib.log(ex.getLocalizedMessage());\r\n text = getText(modID+ \".\" + key).getString();\r\n }\r\n return clearColor ? clearFormatCodes(text) : fixFormatCodes(text);\r\n }\r\n public void setLocalization(String type, String text){\r\n try {\r\n JsonObject JSONLocalization = getJSONFile();\r\n JSONLocalization.addProperty(type, text);\r\n Minecraft CLIENT = Minecraft.getInstance();\r\n File localizationFile = new File(CLIENT.gameDirectory + filePath+getCodeLocalization()+\".json\");\r\n Files.createDirectories(localizationFile.toPath().getParent());\r\n Files.writeString(localizationFile.toPath(), JSONLocalization.toString());\r\n } catch (Exception e){\r\n e.printStackTrace();\r\n }\r\n }\r\n // FOR EVERYTHING FUNCTION NOT IN THIS CLASS\r\n public static String getRounding(double number){return getRounding(number, false);}\r\n public static String getRounding(double number, boolean isToInt){\r\n String text = String.format(\"%.3f\", number);\r\n if(isToInt) text = text.substring(0, text.length()-4);\r\n return text;\r\n }\r\n\r\n /**\r\n * Получение локализации через функцию Minecraft\r\n * @param key\r\n * @return\r\n */\r\n public static Component getText(String key){\r\n return Component.translatable(key);\r\n }\r\n\r\n /**\r\n * Перевод String в MutableText\r\n * @return MutableText\r\n */\r\n public static Component toText(String text){\r\n return Component.literal(text);\r\n }\r\n\r\n /**\r\n * Перевод Text в String\r\n * @return MutableText\r\n */\r\n public static String toString(Component text){\r\n return text.getString();\r\n }\r\n public static String clearFormatCodes(String text) {\r\n return text.replaceAll(\"([§&][a-f0-9k-orz])\", \"\").replaceAll(\"#[a-fA-F0-9]{6}\", \"\");\r\n }\r\n\r\n public static String fixFormatCodes(String text) {\r\n for (String formatCode : formatCodes.keySet()) {\r\n text = text.replaceAll(formatCode, formatCodes.get(formatCode));\r\n }\r\n return text;\r\n }\r\n}\r"
},
{
"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.AbstractSliderButton;
import net.minecraft.network.chat.Component;
import ru.kelcuprum.alinlib.Colors;
import ru.kelcuprum.alinlib.config.Config;
import ru.kelcuprum.alinlib.config.Localization;
import ru.kelcuprum.alinlib.gui.InterfaceUtils;
| 4,717 | package ru.kelcuprum.alinlib.gui.components.sliders;
public class SliderPercent extends AbstractSliderButton {
private final InterfaceUtils.DesignType type;
public final double defaultConfig;
public final Config config;
public final String typeConfig;
public final String buttonMessage;
Component volumeState;
public SliderPercent(int x, int y, int width, int height, Config config, String typeConfig, int defaultConfig, Component component) {
this(x, y, width, height, InterfaceUtils.DesignType.ALINA, config, typeConfig, defaultConfig, component);
}
public SliderPercent(int x, int y, int width, int height, InterfaceUtils.DesignType type, Config config, String typeConfig, double defaultConfig, Component component) {
super(x, y, width, height, component, config.getNumber(typeConfig, defaultConfig).doubleValue());
this.type = type;
this.config = config;
this.typeConfig = typeConfig;
this.defaultConfig = defaultConfig;
this.buttonMessage = component.getString();
}
public void setActive(boolean active){
this.active = active;
}
@Override
public void setX(int x) {
super.setX(x);
}
@Override
public void setY(int y) {
super.setY(y);
}
@Override
public void setPosition(int x, int y) {
super.setPosition(x, y);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float tick) {
this.type.renderSliderBackground(guiGraphics, getX(), getY(), getWidth(), getHeight(), this.active, this.isHoveredOrFocused(), Colors.SEADRIVE, this.value, this);
| package ru.kelcuprum.alinlib.gui.components.sliders;
public class SliderPercent extends AbstractSliderButton {
private final InterfaceUtils.DesignType type;
public final double defaultConfig;
public final Config config;
public final String typeConfig;
public final String buttonMessage;
Component volumeState;
public SliderPercent(int x, int y, int width, int height, Config config, String typeConfig, int defaultConfig, Component component) {
this(x, y, width, height, InterfaceUtils.DesignType.ALINA, config, typeConfig, defaultConfig, component);
}
public SliderPercent(int x, int y, int width, int height, InterfaceUtils.DesignType type, Config config, String typeConfig, double defaultConfig, Component component) {
super(x, y, width, height, component, config.getNumber(typeConfig, defaultConfig).doubleValue());
this.type = type;
this.config = config;
this.typeConfig = typeConfig;
this.defaultConfig = defaultConfig;
this.buttonMessage = component.getString();
}
public void setActive(boolean active){
this.active = active;
}
@Override
public void setX(int x) {
super.setX(x);
}
@Override
public void setY(int y) {
super.setY(y);
}
@Override
public void setPosition(int x, int y) {
super.setPosition(x, y);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float tick) {
this.type.renderSliderBackground(guiGraphics, getX(), getY(), getWidth(), getHeight(), this.active, this.isHoveredOrFocused(), Colors.SEADRIVE, this.value, this);
| volumeState = Component.translatable(Localization.getRounding(this.value * 100, true)+"%");
| 2 | 2023-10-29 13:30:26+00:00 | 8k |
sergei-nazarov/friend-s_letter | src/main/java/com/example/friendsletter/controllers/AuthorizationController.java | [
{
"identifier": "User",
"path": "src/main/java/com/example/friendsletter/data/User.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\n@ToString\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(nullable = false)\n private String username;\n\n @Column(nullable = false, unique = true)\n private String email;\n\n @Column(nullable = false)\n private String password;\n\n @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n @JoinTable(\n name = \"users_roles\",\n joinColumns = {@JoinColumn(name = \"USER_ID\", referencedColumnName = \"ID\")},\n inverseJoinColumns = {@JoinColumn(name = \"ROLE_ID\", referencedColumnName = \"ID\")})\n private List<Role> roles = new ArrayList<>();\n\n @OneToMany\n @JoinTable(\n name = \"users_letters\",\n joinColumns = {@JoinColumn(name = \"USER_ID\", referencedColumnName = \"ID\")},\n inverseJoinColumns = {@JoinColumn(name = \"LETTER_SHORT_CODE\", referencedColumnName = \"letterShortCode\")})\n @ToString.Exclude\n @Transient\n List<LetterMetadata> letters;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return roles.stream()\n .map(role -> new SimpleGrantedAuthority(role.getName()))\n .collect(Collectors.toList());\n }\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\n public UserDto toUserDto() {\n return new UserDto(username, null, email);\n }\n}"
},
{
"identifier": "UserDto",
"path": "src/main/java/com/example/friendsletter/data/UserDto.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@ToString\npublic class UserDto {\n\n @NotNull(message = \"{registration.error.not_empty_username}\")\n @NotEmpty(message = \"{registration.error.not_empty_username}\")\n @Pattern(regexp = \"^(?=[a-zA-Z0-9._]{2,40}$)(?!.*[_.]{2})[^_.].*[^_.]$\",\n message = \"{registration.error.username_error}\")\n private String username;\n private String password;\n @NotNull(message = \"{registration.error.not_empty_email}\")\n @NotEmpty(message = \"{registration.error.not_empty_email}\")\n @Email(message = \"{registration.error.email_incorrect}\")\n private String email;\n\n}"
},
{
"identifier": "UserUpdateException",
"path": "src/main/java/com/example/friendsletter/errors/UserUpdateException.java",
"snippet": "public class UserUpdateException extends Exception {\n\n List<UserErrorHolder> userErrors;\n\n public UserUpdateException(List<UserErrorHolder> userErrors) {\n this.userErrors = userErrors;\n }\n\n public List<UserErrorHolder> getUserErrors() {\n return userErrors;\n }\n}"
},
{
"identifier": "CustomUserDetailsService",
"path": "src/main/java/com/example/friendsletter/services/CustomUserDetailsService.java",
"snippet": "@Service\npublic class CustomUserDetailsService implements UserDetailsService, IUserService {\n\n private final UserRepository userRepository;\n private final RoleRepository roleRepository;\n private final PasswordEncoder passwordEncoder;\n\n @Autowired\n public CustomUserDetailsService(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {\n this.userRepository = userRepository;\n this.roleRepository = roleRepository;\n this.passwordEncoder = passwordEncoder;\n }\n\n\n @Override\n public User loadUserByUsername(String username) throws UsernameNotFoundException {\n User user = loadUserByUsernameOrEmail(username, username);\n if (user == null) {\n throw new UsernameNotFoundException(\"Can't authenticate user \" + username);\n }\n return user;\n }\n\n @Override\n public User loadUserByUsernameOrEmail(String username, String email) throws UsernameNotFoundException {\n return userRepository.findFirstByUsernameOrEmail(username, email);\n }\n\n @Override\n public User saveUser(UserDto userDto) {\n User user = new User();\n user.setUsername(userDto.getUsername());\n user.setEmail(userDto.getEmail());\n user.setPassword(passwordEncoder.encode(userDto.getPassword()));\n\n Role role = roleRepository.findByName(\"ROLE_USER\");\n if (role == null) {\n role = checkRoleExist();\n }\n user.setRoles(List.of(role));\n return userRepository.save(user);\n }\n\n @Override\n public User updateUser(User user, UserDto updatedDto) throws UserUpdateException {\n List<UserErrorHolder> errors = new ArrayList<>();\n\n String newUsername = updatedDto.getUsername();\n if (!user.getUsername().equals(newUsername)) {\n User byUsername = userRepository.findByUsername(newUsername);\n if (byUsername == null) {\n user.setUsername(newUsername);\n } else {\n errors.add(new UserErrorHolder(USER_ERRORS.USERNAME_ALREADY_REGISTERED, newUsername));\n }\n }\n\n String newEmail = updatedDto.getEmail();\n if (!user.getEmail().equals(newEmail)) {\n User byEmail = userRepository.findByEmail(newEmail);\n if (byEmail == null) {\n user.setEmail(newEmail);\n } else {\n errors.add(new UserErrorHolder(USER_ERRORS.EMAIL_ALREADY_REGISTERED, newEmail));\n }\n }\n if (!updatedDto.getPassword().isBlank()) {\n user.setPassword(passwordEncoder.encode(updatedDto.getPassword()));\n }\n if (errors.size() == 0) {\n return userRepository.save(user);\n } else {\n throw new UserUpdateException(errors);\n }\n }\n\n private Role checkRoleExist() {\n Role role = new Role();\n role.setName(\"ROLE_USER\");\n return roleRepository.save(role);\n }\n\n private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) {\n return roles.stream()\n .map(role -> new SimpleGrantedAuthority(role.getName()))\n .collect(Collectors.toList());\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.User;
import com.example.friendsletter.data.UserDto;
import com.example.friendsletter.errors.UserUpdateException;
import com.example.friendsletter.services.CustomUserDetailsService;
import com.example.friendsletter.services.LetterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Locale; | 3,879 | package com.example.friendsletter.controllers;
@Controller
@Slf4j
public class AuthorizationController { | package com.example.friendsletter.controllers;
@Controller
@Slf4j
public class AuthorizationController { | private final CustomUserDetailsService userService; | 3 | 2023-10-31 09:53:27+00:00 | 8k |
footcricket05/Whisp | src/chat/Client.java | [
{
"identifier": "CaptureView",
"path": "src/GUI/CaptureView.java",
"snippet": "public class CaptureView extends javax.swing.JDialog {\n \n private String ipMachine;\n private int portMachine;\n private String clientName;\n\n /**\n * Creates new form CaptureView\n */\n public CaptureView(java.awt.Frame parent, boolean modal) {\n super(parent, modal);\n initComponents();\n this.setTitle(\"Login\");\n this.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing (WindowEvent e) {\n System.exit(0);\n }\n });\n setLocationRelativeTo(null);\n }\n \n /**\n * Get introduced IP\n */\n public String GetIP() {\n return ipMachine;\n }\n /**\n * Get selected port\n */\n public int GetPort() {\n return portMachine;\n }\n /**\n * Get user's name\n */\n public String GetUsername() {\n return clientName;\n }\n\n /**\n * Set the title text of the window\n */\n public void SetTitleText(String text) {\n titleText.setText(text);\n this.repaint();\n }\n /**\n * Enable/disable the field IP\n * Server is not interested in entering an IP address\n */\n public void SetIpEnable(boolean ipStatus) {\n ipField.setEnabled(ipStatus);\n this.repaint();\n }\n /**\n * Set fields\n */\n public void SetIpField(String ipAddress) {\n ipField.setText(ipAddress);\n }\n public void SetPortField(int port) {\n portField.setText(Integer.toString(port));\n }\n \n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n titleText = new javax.swing.JLabel();\n jPanel1 = new javax.swing.JPanel();\n ipField = new javax.swing.JTextField();\n portField = new javax.swing.JTextField();\n jPanel2 = new javax.swing.JPanel();\n nameField = new javax.swing.JTextField();\n loginButton = new javax.swing.JButton();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);\n\n titleText.setFont(new java.awt.Font(\"Noto Sans\", 1, 24)); // NOI18N\n titleText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);\n titleText.setText(\"Client login\");\n\n jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, \"Connection\", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(\"Dialog\", 0, 12), new java.awt.Color(120, 120, 120))); // NOI18N\n\n ipField.setText(\"IP Address\");\n ipField.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n ipFieldActionPerformed(evt);\n }\n });\n\n portField.setText(\"Port\");\n\n javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);\n jPanel1.setLayout(jPanel1Layout);\n jPanel1Layout.setHorizontalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(ipField, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addContainerGap())\n );\n jPanel1Layout.setVerticalGroup(\n jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel1Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(ipField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n\n jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, \"Client options\", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(\"Dialog\", 0, 12), new java.awt.Color(120, 120, 120))); // NOI18N\n\n nameField.setText(\"Name\");\n\n loginButton.setText(\"Login\");\n loginButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n loginButtonActionPerformed(evt);\n }\n });\n\n javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);\n jPanel2.setLayout(jPanel2Layout);\n jPanel2Layout.setHorizontalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(loginButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n jPanel2Layout.setVerticalGroup(\n jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(jPanel2Layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addComponent(loginButton))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n getContentPane().setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(titleText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n .addContainerGap())\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(titleText)\n .addGap(18, 18, 18)\n .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n\n pack();\n }// </editor-fold>//GEN-END:initComponents\n\n private void ipFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ipFieldActionPerformed\n // TODO add your handling code here:\n }//GEN-LAST:event_ipFieldActionPerformed\n\n private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed\n ipMachine = ipField.getText();\n portMachine = Integer.parseInt(portField.getText());\n clientName = nameField.getText();\n \n this.dispose();\n }//GEN-LAST:event_loginButtonActionPerformed\n\n /**\n * @param args the command line arguments\n */\n public static void main(String args[]) {\n /* Set the Nimbus look and feel */\n //<editor-fold defaultstate=\"collapsed\" desc=\" Look and feel setting code (optional) \">\n /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.\n * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html \n */\n try {\n for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {\n if (\"Nimbus\".equals(info.getName())) {\n javax.swing.UIManager.setLookAndFeel(info.getClassName());\n break;\n }\n }\n } catch (ClassNotFoundException ex) {\n java.util.logging.Logger.getLogger(CaptureView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (InstantiationException ex) {\n java.util.logging.Logger.getLogger(CaptureView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n java.util.logging.Logger.getLogger(CaptureView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (javax.swing.UnsupportedLookAndFeelException ex) {\n java.util.logging.Logger.getLogger(CaptureView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n }\n //</editor-fold>\n\n /* Create and display the dialog */\n java.awt.EventQueue.invokeLater(new Runnable() {\n public void run() {\n CaptureView dialog = new CaptureView(new javax.swing.JFrame(), true);\n dialog.addWindowListener(new java.awt.event.WindowAdapter() {\n @Override\n public void windowClosing(java.awt.event.WindowEvent e) {\n System.exit(0);\n }\n });\n dialog.setVisible(true);\n }\n });\n }\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JTextField ipField;\n private javax.swing.JPanel jPanel1;\n private javax.swing.JPanel jPanel2;\n private javax.swing.JButton loginButton;\n private javax.swing.JTextField nameField;\n private javax.swing.JTextField portField;\n private javax.swing.JLabel titleText;\n // End of variables declaration//GEN-END:variables\n}"
},
{
"identifier": "ChatView",
"path": "src/GUI/ChatView.java",
"snippet": "public class ChatView extends javax.swing.JFrame {\n\n private Client client;\n private Server server;\n private int mode;\n \n /**\n * Creates new form ChatView\n */\n public ChatView() {\n initComponents();\n this.setTitle(\"Chatroom\");\n messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.Y_AXIS));\n mode = 0;\n }\n \n /**\n * Set the users name that is displayed at the title\n */\n public void SetUsername(String username) {\n chatroomTitle.setText(\"Chatroom: \" + username);\n this.repaint();\n }\n /**\n * Set client class\n */\n public void SetClient(Client cli) {\n mode = 1;\n client = cli;\n }\n /**\n * Set server class\n */\n public void SetServer(Server srv) {\n mode = 2;\n server = srv;\n }\n \n /**\n * Add a message sent from this host\n */\n public void AddClientMessage(String msg) {\n if (mode == 1) {\n Message message = new Message(client.getUsername(), msg);\n String msgAdd = \"[\" + message.getTime() + \" \" + message.getUsername() + \"]->\\t\" + message.getText();\n messagePanel.append(msgAdd + \"\\n\");\n } else {\n Message message = new Message(server.getUsername(), msg);\n String msgAdd = \"[\" + message.getTime() + \" \" + message.getUsername() + \"]->\\t\" + message.getText();\n messagePanel.append(msgAdd + \"\\n\");\n }\n }\n \n /**\n * Add a message from a remote sender\n */\n public void AddRemoteMessage(String msg) {\n if (mode == 1) {\n Message message = new Message(\"Partner\", msg);\n String msgAdd = \"[\" + message.getTime() + \" \" + message.getUsername() + \"]->\\t\" + message.getText();\n messagePanel.append(msgAdd + \"\\n\");\n } else {\n Message message = new Message(\"Partner\", msg);\n String msgAdd = \"[\" + message.getTime() + \" \" + message.getUsername() + \"]->\\t\" + message.getText();\n messagePanel.append(msgAdd + \"\\n\");\n }\n }\n \n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n messageField = new javax.swing.JTextField();\n sendButton = new javax.swing.JButton();\n chatroomTitle = new javax.swing.JLabel();\n logoutButton = new javax.swing.JButton();\n jScrollPane1 = new javax.swing.JScrollPane();\n messagePanel = new javax.swing.JTextArea();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n\n messageField.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n messageFieldActionPerformed(evt);\n }\n });\n\n sendButton.setText(\"Send\");\n sendButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n sendButtonActionPerformed(evt);\n }\n });\n\n chatroomTitle.setFont(new java.awt.Font(\"Noto Sans\", 0, 36)); // NOI18N\n chatroomTitle.setForeground(new java.awt.Color(120, 120, 120));\n chatroomTitle.setText(\"Chatroom: David\");\n\n logoutButton.setText(\"Logout\");\n logoutButton.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent evt) {\n logoutButtonActionPerformed(evt);\n }\n });\n\n messagePanel.setEditable(false);\n messagePanel.setColumns(20);\n messagePanel.setLineWrap(true);\n messagePanel.setRows(5);\n messagePanel.setWrapStyleWord(true);\n jScrollPane1.setViewportView(messagePanel);\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n getContentPane().setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jScrollPane1)\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()\n .addComponent(messageField)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))\n .addGroup(layout.createSequentialGroup()\n .addComponent(chatroomTitle)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 206, Short.MAX_VALUE)\n .addComponent(logoutButton, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))\n .addContainerGap())\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)\n .addComponent(chatroomTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(logoutButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)\n .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n .addComponent(messageField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addComponent(sendButton))\n .addContainerGap())\n );\n\n pack();\n }// </editor-fold>//GEN-END:initComponents\n\n private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutButtonActionPerformed\n if(mode == 1) {\n client.CloseConnection();\n } else {\n server.CloseConnection();\n }\n this.dispose();\n System.exit(0);\n }//GEN-LAST:event_logoutButtonActionPerformed\n\n private void messageFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_messageFieldActionPerformed\n // TODO add your handling code here:\n }//GEN-LAST:event_messageFieldActionPerformed\n\n private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed\n String msg = messageField.getText();\n if (mode == 1) client.SendMessage(msg);\n else server.SendMessage(msg);\n AddClientMessage(msg);\n messageField.setText(\"\");\n }//GEN-LAST:event_sendButtonActionPerformed\n\n /**\n * @param args the command line arguments\n */\n public static void main(String args[]) {\n /* Set the Nimbus look and feel */\n //<editor-fold defaultstate=\"collapsed\" desc=\" Look and feel setting code (optional) \">\n /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.\n * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html \n */\n try {\n for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {\n if (\"Nimbus\".equals(info.getName())) {\n javax.swing.UIManager.setLookAndFeel(info.getClassName());\n break;\n }\n }\n } catch (ClassNotFoundException ex) {\n java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (InstantiationException ex) {\n java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (IllegalAccessException ex) {\n java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n } catch (javax.swing.UnsupportedLookAndFeelException ex) {\n java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);\n }\n //</editor-fold>\n\n /* Create and display the form */\n java.awt.EventQueue.invokeLater(new Runnable() {\n public void run() {\n new ChatView().setVisible(true);\n }\n });\n }\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel chatroomTitle;\n private javax.swing.JScrollPane jScrollPane1;\n private javax.swing.JButton logoutButton;\n private javax.swing.JTextField messageField;\n private javax.swing.JTextArea messagePanel;\n private javax.swing.JButton sendButton;\n // End of variables declaration//GEN-END:variables\n}"
}
] | import GUI.CaptureView;
import GUI.ChatView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger; | 4,707 | package chat;
/**
*
* @author dvcarrillo
*/
public class Client {
// Properties
private String clientName;
// Socket
private Socket clientSocket ;
// Streams
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream inData;
private DataOutputStream outData;
private boolean option = true;
private ChatView chatView;
public Client(ChatView chatView) {
this.chatView = chatView;
}
public String getUsername() {
return clientName;
}
public void SetConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
while (option) {
ListenData(chatView);
}
}
});
th1.start();
System.out.println("Successfully connected to " + ip + ":" + port);
} catch (IOException ex) {
System.err.println("ERROR: connection error");
System.exit(0);
}
}
public void SendMessage(String msg) {
try {
outputStream = clientSocket.getOutputStream();
outData = new DataOutputStream(outputStream);
outData.writeUTF(msg);
outData.flush();
} catch (IOException ex) {
System.err.println("ERROR: error sending data");
}
}
public void ListenData(ChatView chatView) {
try {
inputStream = clientSocket.getInputStream();
inData = new DataInputStream(inputStream);
chatView.AddRemoteMessage(inData.readUTF());
} catch (IOException ex) {
System.err.println("ERROR: error listening data");
}
}
public void CloseConnection() {
try {
outData.close();
inData.close();
clientSocket.close();
} catch (IOException ex) {
System.err.println("ERROR: error closing connection");
}
}
public void SetClientProperties(String name) {
clientName = name;
}
public static void main(String [] args) {
ChatView chatView = new ChatView();
Client cli = new Client(chatView);
| package chat;
/**
*
* @author dvcarrillo
*/
public class Client {
// Properties
private String clientName;
// Socket
private Socket clientSocket ;
// Streams
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream inData;
private DataOutputStream outData;
private boolean option = true;
private ChatView chatView;
public Client(ChatView chatView) {
this.chatView = chatView;
}
public String getUsername() {
return clientName;
}
public void SetConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
while (option) {
ListenData(chatView);
}
}
});
th1.start();
System.out.println("Successfully connected to " + ip + ":" + port);
} catch (IOException ex) {
System.err.println("ERROR: connection error");
System.exit(0);
}
}
public void SendMessage(String msg) {
try {
outputStream = clientSocket.getOutputStream();
outData = new DataOutputStream(outputStream);
outData.writeUTF(msg);
outData.flush();
} catch (IOException ex) {
System.err.println("ERROR: error sending data");
}
}
public void ListenData(ChatView chatView) {
try {
inputStream = clientSocket.getInputStream();
inData = new DataInputStream(inputStream);
chatView.AddRemoteMessage(inData.readUTF());
} catch (IOException ex) {
System.err.println("ERROR: error listening data");
}
}
public void CloseConnection() {
try {
outData.close();
inData.close();
clientSocket.close();
} catch (IOException ex) {
System.err.println("ERROR: error closing connection");
}
}
public void SetClientProperties(String name) {
clientName = name;
}
public static void main(String [] args) {
ChatView chatView = new ChatView();
Client cli = new Client(chatView);
| CaptureView captureView = new CaptureView(chatView, true); | 0 | 2023-10-31 07:52:11+00:00 | 8k |
naraazi/TerminalChess | src/chess/pieces/Pawn.java | [
{
"identifier": "Board",
"path": "src/boardgame/Board.java",
"snippet": "public class Board {\n private final Integer rows;\n private final Integer columns;\n private final Piece[][] pieces;\n\n public Board(Integer rows, Integer columns) {\n if (rows < 1 || columns < 1) {\n throw new BoardException(\"Error creating board: there must be at least 1 row and 1 column\");\n }\n\n this.rows = rows;\n this.columns = columns;\n pieces = new Piece[rows][columns];\n }\n\n public Integer getRows() {\n return rows;\n }\n\n\n public Integer getColumns() {\n return columns;\n }\n\n\n public Piece piece(int row, int column) {\n if (!positionExists(row, column)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return pieces[row][column];\n }\n\n public Piece piece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return pieces[position.getRow()][position.getColumn()];\n }\n\n public void placePiece(Piece piece, Position position) {\n if (thereIsAPiece(position)) {\n throw new BoardException(\"There is already a piece on position \" + position);\n }\n\n pieces[position.getRow()][position.getColumn()] = piece;\n piece.position = position;\n }\n\n public Piece removePiece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n if (piece(position) == null) {\n return null;\n }\n\n Piece aux = piece(position);\n aux.position = null;\n pieces[position.getRow()][position.getColumn()] = null;\n return aux;\n }\n\n private boolean positionExists(int row, int column) {\n return row >= 0 && row < rows && column >= 0 && column < columns;\n }\n\n public boolean positionExists(Position position) {\n return positionExists(position.getRow(), position.getColumn());\n }\n\n public boolean thereIsAPiece(Position position) {\n if (!positionExists(position)) {\n throw new BoardException(\"Position not on the board\");\n }\n\n return piece(position) != null;\n }\n}"
},
{
"identifier": "Position",
"path": "src/boardgame/Position.java",
"snippet": "public class Position {\n private Integer row;\n private Integer column;\n\n public Position(Integer row, Integer column) {\n this.row = row;\n this.column = column;\n }\n\n public Integer getRow() {\n return row;\n }\n\n public void setRow(Integer row) {\n this.row = row;\n }\n\n public Integer getColumn() {\n return column;\n }\n\n public void setColumn(Integer column) {\n this.column = column;\n }\n\n public void setValues(int row, int column) {\n this.row = row;\n this.column = column;\n }\n\n @Override\n public String toString() {\n return row + \", \" + column;\n }\n}"
},
{
"identifier": "ChessMatch",
"path": "src/chess/ChessMatch.java",
"snippet": "public class ChessMatch {\n private Integer turn;\n private Color currentPlayer;\n private final Board board;\n private boolean check;\n private boolean checkMate;\n private ChessPiece enPassantVulnerable;\n private ChessPiece promoted;\n\n private final List<Piece> piecesOnTheBoard = new ArrayList<>();\n protected final List<Piece> capturedPieces = new ArrayList<>();\n\n public ChessMatch() {\n board = new Board(8, 8);\n turn = 1;\n currentPlayer = Color.WHITE;\n initialSetup();\n }\n\n public Integer getTurn() {\n return turn;\n }\n\n public Color getCurrentPlayer() {\n return currentPlayer;\n }\n\n public boolean getCheck() {\n return check;\n }\n\n public boolean getCheckMate() {\n return !checkMate;\n }\n\n public ChessPiece getEnPassantVulnerable() {\n return enPassantVulnerable;\n }\n\n public ChessPiece getPromoted() {\n return promoted;\n }\n\n public ChessPiece[][] getPieces() {\n ChessPiece[][] mat = new ChessPiece[board.getRows()][board.getColumns()];\n for (int i = 0; i < board.getRows(); i++) {\n for (int j = 0; j < board.getColumns(); j++) {\n mat[i][j] = (ChessPiece) board.piece(i, j);\n }\n }\n return mat;\n }\n\n public boolean[][] possibleMoves(ChessPosition sourcePosition) {\n Position position = sourcePosition.toPosition();\n validationSourcePosition(position);\n\n return board.piece(position).possibleMoves();\n }\n\n public ChessPiece performChessMove(ChessPosition sourcePosition, ChessPosition targetPosition) {\n Position source = sourcePosition.toPosition();\n Position target = targetPosition.toPosition();\n validationSourcePosition(source);\n validateTargetPosition(source, target);\n\n Piece capturedPiece = makeMove(source, target);\n\n if (testCheck(currentPlayer)) {\n undoMove(source, target, capturedPiece);\n throw new ChessException(\"You can't put yourself in check\");\n }\n\n ChessPiece movedPiece = (ChessPiece) board.piece(target);\n\n //promotion\n promoted = null;\n if (movedPiece instanceof Pawn) {\n if ((movedPiece.getColor() == Color.WHITE && target.getRow() == 0) || (movedPiece.getColor() == Color.BLACK && target.getRow() == 7)) {\n promoted = (ChessPiece) board.piece(target);\n promoted = replacePromotedPiece(\"Q\");\n }\n }\n\n check = testCheck(opponent(currentPlayer));\n\n if (testCheckMate(opponent(currentPlayer))) {\n checkMate = true;\n }\n else {\n nextTurn();\n }\n\n //en passant\n if (movedPiece instanceof Pawn && (target.getRow() == source.getRow() - 2 || target.getRow() == source.getRow() + 2)) {\n enPassantVulnerable = movedPiece;\n }\n else {\n enPassantVulnerable = null;\n }\n\n return (ChessPiece) capturedPiece;\n }\n\n public ChessPiece replacePromotedPiece(String type) {\n if (promoted == null) {\n throw new IllegalStateException(\"There is no piece to be promoted\");\n }\n if (!type.equals(\"B\") && !type.equals(\"N\") && !type.equals(\"R\") && !type.equals(\"Q\")) {\n return promoted; //queen\n }\n\n Position pos = promoted.getChessPosition().toPosition();\n Piece p = board.removePiece(pos);\n piecesOnTheBoard.remove(p);\n\n ChessPiece newPiece = newPiece(type, promoted.getColor());\n board.placePiece(newPiece, pos);\n piecesOnTheBoard.add(newPiece);\n\n return newPiece;\n }\n\n private ChessPiece newPiece(String type, Color color) {\n if (type.equals(\"B\")) return new Bishop(board, color);\n if (type.equals(\"N\")) return new Knight(board, color);\n if (type.equals(\"Q\")) return new Queen(board, color);\n return new Rook(board, color);\n }\n\n private Piece makeMove(Position source, Position target) {\n ChessPiece p = (ChessPiece) board.removePiece(source);\n p.increaseMoveCount();\n Piece capturedPiece = board.removePiece(target);\n board.placePiece(p, target);\n\n if (capturedPiece != null) {\n piecesOnTheBoard.remove(capturedPiece);\n capturedPieces.add(capturedPiece);\n }\n\n //king-side rook\n if (p instanceof King && target.getColumn() == source.getColumn() + 2) {\n Position sourceT = new Position(source.getRow(), source.getColumn() + 3);\n Position targetT = new Position(source.getRow(), source.getColumn() + 1);\n ChessPiece rook = (ChessPiece) board.removePiece(sourceT);\n\n board.placePiece(rook, targetT);\n rook.increaseMoveCount();\n }\n\n //queen-side rook\n if (p instanceof King && target.getColumn() == source.getColumn() - 2) {\n Position sourceT = new Position(source.getRow(), source.getColumn() - 4);\n Position targetT = new Position(source.getRow(), source.getColumn() - 1);\n ChessPiece rook = (ChessPiece) board.removePiece(sourceT);\n\n board.placePiece(rook, targetT);\n rook.increaseMoveCount();\n }\n\n //en passant\n if (p instanceof Pawn) {\n if (!Objects.equals(source.getColumn(), target.getColumn()) && capturedPiece == null) {\n Position pawnPosition;\n\n if (p.getColor() == Color.WHITE) {\n pawnPosition = new Position(target.getRow() + 1, target.getColumn());\n }\n else {\n pawnPosition = new Position(target.getRow() - 1, target.getColumn());\n }\n\n capturedPiece = board.removePiece(pawnPosition);\n capturedPieces.add(capturedPiece);\n piecesOnTheBoard.remove(capturedPiece);\n }\n }\n\n return capturedPiece;\n }\n\n private void undoMove(Position source, Position target, Piece capturedPiece) {\n ChessPiece p = (ChessPiece) board.removePiece(target);\n p.decreaseMoveCount();\n board.placePiece(p, source);\n\n if (capturedPiece != null) {\n board.placePiece(capturedPiece, target);\n\n capturedPieces.remove(capturedPiece);\n piecesOnTheBoard.add(capturedPiece);\n }\n\n //king-side rook\n if (p instanceof King && target.getColumn() == source.getColumn() + 2) {\n Position sourceT = new Position(source.getRow(), source.getColumn() + 3);\n Position targetT = new Position(source.getRow(), source.getColumn() + 1);\n ChessPiece rook = (ChessPiece) board.removePiece(targetT);\n\n board.placePiece(rook, sourceT);\n rook.decreaseMoveCount();\n }\n\n //queen-side rook\n if (p instanceof King && target.getColumn() == source.getColumn() - 2) {\n Position sourceT = new Position(source.getRow(), source.getColumn() - 4);\n Position targetT = new Position(source.getRow(), source.getColumn() - 1);\n ChessPiece rook = (ChessPiece) board.removePiece(targetT);\n\n board.placePiece(rook, sourceT);\n rook.decreaseMoveCount();\n }\n\n //en passant\n if (p instanceof Pawn) {\n if (!Objects.equals(source.getColumn(), target.getColumn()) && capturedPiece == enPassantVulnerable) {\n ChessPiece pawn = (ChessPiece) board.removePiece(target);\n Position pawnPosition;\n\n if (p.getColor() == Color.WHITE) {\n pawnPosition = new Position(3, target.getColumn());\n }\n else {\n pawnPosition = new Position(4, target.getColumn());\n }\n\n board.placePiece(pawn, pawnPosition);\n }\n }\n }\n\n private void validationSourcePosition(Position position) {\n if (!board.thereIsAPiece(position)) {\n throw new ChessException(\"There is no piece on source position\");\n }\n if (currentPlayer != ((ChessPiece) board.piece(position)).getColor()) {\n throw new ChessException(\"The chosen piece is not yours\");\n }\n if (!board.piece(position).isThereAnyPossibleMove()) {\n throw new ChessException(\"There is no possible moves for the chosen piece\");\n }\n }\n\n private void validateTargetPosition(Position source, Position target) {\n if (!board.piece(source).possibleMove(target)) {\n throw new ChessException(\"The chosen piece can't move to target position\");\n }\n }\n\n private void nextTurn() {\n turn++;\n currentPlayer = (currentPlayer == Color.WHITE) ? Color.BLACK : Color.WHITE;\n }\n\n\n private Color opponent(Color color) {\n return (color == Color.WHITE) ? Color.BLACK : Color.WHITE;\n }\n\n private ChessPiece king(Color color) {\n List<Piece> list = piecesOnTheBoard.stream().filter(x -> ((ChessPiece) x).getColor() == color).toList();\n\n for (Piece p : list) {\n if (p instanceof King) {\n return (ChessPiece) p;\n }\n }\n //if the user see this, the game is broken\n throw new IllegalStateException(\"There is no \" + color + \" king on the board\");\n }\n\n private boolean testCheck(Color color) {\n Position kingPosition = king(color).getChessPosition().toPosition();\n List<Piece> opponentPieces = piecesOnTheBoard.stream().filter(x -> ((ChessPiece) x).getColor() == opponent(color)).toList();\n\n for (Piece p : opponentPieces) {\n boolean[][] mat = p.possibleMoves();\n\n if (mat[kingPosition.getRow()][kingPosition.getColumn()]) {\n return true;\n }\n }\n\n return false;\n }\n\n private boolean testCheckMate(Color color) {\n if (!testCheck(color)) {\n return false;\n }\n\n List<Piece> list = piecesOnTheBoard.stream().filter(x -> ((ChessPiece) x).getColor() == color).toList();\n for (Piece p : list) {\n boolean[][] mat = p.possibleMoves();\n\n for (int i = 0; i < board.getRows(); i++) {\n for (int j = 0; j < board.getColumns(); j++) {\n if (mat[i][j]) {\n Position source = ((ChessPiece) p).getChessPosition().toPosition();\n Position target = new Position(i, j);\n Piece capturedPiece = makeMove(source, target);\n boolean testCheck = testCheck(color);\n\n undoMove(source, target, capturedPiece);\n\n if (!testCheck) {\n return false;\n }\n }\n }\n }\n }\n\n return true;\n }\n\n private void placeNewPiece(char column, int row, ChessPiece piece) {\n board.placePiece(piece, new ChessPosition(column, row).toPosition());\n piecesOnTheBoard.add(piece);\n }\n\n private void initialSetup() {\n placeNewPiece('a', 1, new Rook(board, Color.WHITE));\n placeNewPiece('b', 1, new Knight(board, Color.WHITE));\n placeNewPiece('c', 1, new Bishop(board, Color.WHITE));\n placeNewPiece('d', 1, new Queen(board, Color.WHITE));\n placeNewPiece('e', 1, new King(board, Color.WHITE, this));\n placeNewPiece('f', 1, new Bishop(board, Color.WHITE));\n placeNewPiece('g', 1, new Knight(board, Color.WHITE));\n placeNewPiece('h', 1, new Rook(board, Color.WHITE));\n placeNewPiece('a', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('b', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('c', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('d', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('e', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('f', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('g', 2, new Pawn(board, Color.WHITE, this));\n placeNewPiece('h', 2, new Pawn(board, Color.WHITE, this));\n\n placeNewPiece('a', 8, new Rook(board, Color.BLACK));\n placeNewPiece('b', 8, new Knight(board, Color.BLACK));\n placeNewPiece('c', 8, new Bishop(board, Color.BLACK));\n placeNewPiece('d', 8, new Queen(board, Color.BLACK));\n placeNewPiece('e', 8, new King(board, Color.BLACK, this));\n placeNewPiece('f', 8, new Bishop(board, Color.BLACK));\n placeNewPiece('g', 8, new Knight(board, Color.BLACK));\n placeNewPiece('h', 8, new Rook(board, Color.BLACK));\n placeNewPiece('a', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('b', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('c', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('d', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('e', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('f', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('g', 7, new Pawn(board, Color.BLACK, this));\n placeNewPiece('h', 7, new Pawn(board, Color.BLACK, this));\n }\n}"
},
{
"identifier": "ChessPiece",
"path": "src/chess/ChessPiece.java",
"snippet": "public abstract class ChessPiece extends Piece {\n private final Color color;\n private int moveCount;\n\n public ChessPiece(Board board, Color color) {\n super(board);\n this.color = color;\n }\n\n public Color getColor() {\n return color;\n }\n\n public int getMoveCount() {\n return moveCount;\n }\n\n protected void increaseMoveCount() {\n moveCount++;\n }\n\n protected void decreaseMoveCount() {\n moveCount--;\n }\n\n public ChessPosition getChessPosition() {\n return ChessPosition.fromPosition(position);\n }\n\n protected boolean isThereOpponentPiece(Position position) {\n ChessPiece p = (ChessPiece) getBoard().piece(position);\n\n return p != null && p.getColor() != color;\n }\n}"
},
{
"identifier": "Color",
"path": "src/chess/Color.java",
"snippet": "public enum Color {\n BLACK,\n WHITE\n}"
}
] | import boardgame.Board;
import boardgame.Position;
import chess.ChessMatch;
import chess.ChessPiece;
import chess.Color; | 4,428 | package chess.pieces;
public class Pawn extends ChessPiece {
private final ChessMatch chessMatch;
public Pawn(Board board, Color color, ChessMatch chessMatch) {
super(board, color);
this.chessMatch = chessMatch;
}
@Override
public boolean[][] possibleMoves() {
boolean[][] mat = new boolean[getBoard().getRows()][getBoard().getColumns()]; | package chess.pieces;
public class Pawn extends ChessPiece {
private final ChessMatch chessMatch;
public Pawn(Board board, Color color, ChessMatch chessMatch) {
super(board, color);
this.chessMatch = chessMatch;
}
@Override
public boolean[][] possibleMoves() {
boolean[][] mat = new boolean[getBoard().getRows()][getBoard().getColumns()]; | Position p = new Position(0, 0); | 1 | 2023-10-26 19:27:08+00:00 | 8k |
llllllxy/tiny-security-boot-starter | src/main/java/org/tinycloud/security/provider/AbstractAuthProvider.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": "AuthUtil",
"path": "src/main/java/org/tinycloud/security/util/AuthUtil.java",
"snippet": "public class AuthUtil {\n\n /**\n * 获取当前请求对象\n *\n * @return HttpServletRequest\n */\n public static HttpServletRequest getRequest() {\n HttpServletRequest request = null;\n try {\n request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();\n return request;\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * 获取当前响应对象\n *\n * @return HttpServletResponse\n */\n public static HttpServletResponse getResponse() {\n HttpServletResponse response = null;\n try {\n response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();\n return response;\n } catch (Exception e) {\n return null;\n }\n }\n\n\n /**\n * 获取用户token\n *\n * @return token\n */\n public static String getToken(String tokenName) {\n HttpServletRequest request = null;\n try {\n request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();\n // 从请求中获取token,先从Header里取,取不到的话再从cookie里取(适配前后端分离的模式)\n String token = request.getHeader(tokenName);\n if (StringUtils.isEmpty(token)) {\n token = CookieUtil.getCookie(request, tokenName);\n }\n // cookie里取不到,再从请求参数里面取\n if (StringUtils.isEmpty(token)) {\n token = request.getParameter(tokenName);\n }\n return token;\n } catch (Exception e) {\n return null;\n }\n }\n\n\n /**\n * 获取用户token\n *\n * @return token\n */\n public static String getToken(HttpServletRequest request, String tokenName) {\n // 从请求中获取token,先从Header里取,取不到的话再从cookie里取(适配前后端分离的模式)\n String token = request.getHeader(tokenName);\n if (StringUtils.isEmpty(token)) {\n token = CookieUtil.getCookie(request, tokenName);\n }\n // cookie里取不到,再从请求参数里面取\n if (StringUtils.isEmpty(token)) {\n token = request.getParameter(tokenName);\n }\n return token;\n }\n\n\n /**\n * 检查Method上是否有@Ignore注解,决定是否忽略会话认证\n *\n * @param method Method\n * @return true or false\n */\n public static boolean checkIgnore(Method method) {\n // 先获取方法上的注解\n Ignore annotation = method.getAnnotation(Ignore.class);\n // 方法上没有注解再检查类上面有没有注解\n if (annotation == null) {\n annotation = method.getDeclaringClass().getAnnotation(Ignore.class);\n }\n return annotation != null;\n }\n\n\n /**\n * 检查Method上是否有@RequiresPermissions注解,并检验其值,通过返回true,拒绝返回false\n *\n * @param method Method\n * @param permissionSet 权限列表\n * @return true or false\n */\n public static boolean checkPermission(Method method, Set<String> permissionSet) {\n // 当permissionSet为空时,赋初值,防止空指针错误\n if (permissionSet == null) {\n permissionSet = new HashSet<>();\n }\n\n RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);\n // 方法上没有注解再检查类上面有没有注解\n if (annotation == null) {\n annotation = method.getDeclaringClass().getAnnotation(RequiresPermissions.class);\n }\n // 接口上没有注解,说明这个接口无权限控制,直接通过\n if (annotation == null) {\n return true;\n }\n\n String[] permissions = annotation.value();\n Logical logical = annotation.logical();\n if (logical == Logical.OR) {\n // 如果有任何一个权限,返回true,否则返回false(拥有其一)\n for (String perm : permissions) {\n if (permissionSet.contains(perm)) {\n return true;\n }\n }\n return false;\n } else if (logical == Logical.AND) {\n // 只要有一个权限不是true的,就返回false(同时拥有)\n for (String perm : permissions) {\n if (!permissionSet.contains(perm)) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n\n /**\n * 检查Method上是否有@RequiresPermissions注解,并检验其值,通过返回true,拒绝返回false\n *\n * @param method Method\n * @param roleSet 角色列表\n * @return true or false\n */\n public static boolean checkRole(Method method, Set<String> roleSet) {\n // 当roleSet为空时,赋初值,防止空指针错误\n if (roleSet == null) {\n roleSet = new HashSet<>();\n }\n\n RequiresRoles annotation = method.getAnnotation(RequiresRoles.class);\n // 方法上没有注解再检查类上面有没有注解\n if (annotation == null) {\n annotation = method.getDeclaringClass().getAnnotation(RequiresRoles.class);\n }\n // 接口上没有注解,说明这个接口无权限控制,直接通过\n if (annotation == null) {\n return true;\n }\n\n String[] roles = annotation.value();\n Logical logical = annotation.logical();\n\n if (logical == Logical.OR) {\n // 如果有任何一个角色,返回true,否则返回false(拥有其一)\n for (String ro : roles) {\n if (roleSet.contains(ro)) {\n return true;\n }\n }\n return false;\n } else if (logical == Logical.AND) {\n // 只要有一个角色不是true的,就返回false(同时拥有)\n for (String ro : roles) {\n if (!roleSet.contains(ro)) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n\n /**\n * 获取当前登录用户的LoginId\n *\n * @return Object\n */\n public static Object getLoginId() {\n return AuthenticeHolder.getLoginId();\n }\n\n /**\n * 判断拥有角色:role1\n *\n * @return\n */\n public static boolean hasRole(String role) {\n Set<String> roleSet = RoleHolder.getRoleSet();\n if (roleSet == null || roleSet.isEmpty()) {\n return false;\n }\n return roleSet.contains(role);\n }\n\n /**\n * 判断拥有角色:role1 and role2\n *\n * @param roles\n * @return\n */\n public static boolean hasAllRole(String... roles) {\n Set<String> roleSet = RoleHolder.getRoleSet();\n if (roleSet == null || roleSet.isEmpty()) {\n return false;\n }\n // 只要有一个角色不是true的,就返回false(同时拥有)\n for (String ro : roles) {\n if (!roleSet.contains(ro)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * 判断拥有角色:role1 or role2 or role3 有其一即可\n *\n * @param roles\n * @return\n */\n public static boolean hasAnyRole(String... roles) {\n Set<String> roleSet = RoleHolder.getRoleSet();\n if (roleSet == null || roleSet.isEmpty()) {\n return false;\n }\n // 如果有任何一个角色,返回true,否则返回false(拥有其一)\n for (String ro : roles) {\n if (roleSet.contains(ro)) {\n return true;\n }\n }\n return false;\n }\n\n\n /**\n * 判断拥有权限:permission1\n *\n * @return\n */\n public static boolean hasPermission(String permission) {\n Set<String> permissionSet = PermissionHolder.getPermissionSet();\n if (permissionSet == null || permissionSet.isEmpty()) {\n return false;\n }\n return permissionSet.contains(permission);\n }\n\n /**\n * 判断拥有角色:permission1 and permission2\n *\n * @param permissions\n * @return\n */\n public static boolean hasAllPermission(String... permissions) {\n Set<String> permissionSet = PermissionHolder.getPermissionSet();\n if (permissionSet == null || permissionSet.isEmpty()) {\n return false;\n }\n // 只要有一个权限不是true的,就返回false(同时拥有)\n for (String pe : permissions) {\n if (!permissionSet.contains(pe)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * 判断拥有权限:permission1 or permission2 or permission3 有其一即可\n *\n * @param permissions\n * @return\n */\n public static boolean hasAnyPermission(String... permissions) {\n Set<String> permissionSet = PermissionHolder.getPermissionSet();\n if (permissionSet == null || permissionSet.isEmpty()) {\n return false;\n }\n // 如果有任何一个权限,返回true,否则返回false(拥有其一)\n for (String pe : permissions) {\n if (permissionSet.contains(pe)) {\n return true;\n }\n }\n return false;\n }\n}"
},
{
"identifier": "CookieUtil",
"path": "src/main/java/org/tinycloud/security/util/CookieUtil.java",
"snippet": "public class CookieUtil {\n private static Logger logger = LoggerFactory.getLogger(CookieUtil.class);\n\n /**\n * 设置 Cookie(生成时间为1天)\n *\n * @param response 响应对象\n * @param name 名称\n * @param value 值\n */\n public static void setCookie(HttpServletResponse response, String name, String value) {\n setCookie(response, name, value, 60 * 60 * 24);\n }\n\n /**\n * 设置 Cookie\n *\n * @param response 响应对象\n * @param name 名称\n * @param value 值\n * @param path 上下文路径\n */\n public static void setCookie(HttpServletResponse response, String name, String value, String path) {\n setCookie(response, name, value, path, 60 * 60 * 24);\n }\n\n /**\n * 设置 Cookie\n *\n * @param response 响应对象\n * @param name 名称\n * @param value 值\n * @param maxAge 生存时间(单位秒)\n */\n public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {\n setCookie(response, name, value, \"/\", maxAge);\n }\n\n /**\n * 设置 Cookie\n *\n * @param response 响应对象\n * @param name 名称\n * @param value 值\n * @param maxAge 生存时间(单位秒)\n * @param path 上下文路径\n */\n public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {\n if (!StringUtils.isEmpty(name)) {\n Cookie cookie = new Cookie(name, null);\n cookie.setPath(path);\n cookie.setMaxAge(maxAge);\n cookie.setHttpOnly(true);\n try {\n cookie.setValue(URLEncoder.encode(value, \"utf-8\"));\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n response.addCookie(cookie);\n }\n }\n\n /**\n * 获得指定Cookie的值\n * @param request 请求对象\n * @param name 名称\n * @return 值\n */\n public static String getCookie(HttpServletRequest request, String name) {\n return getCookie(request, null, name, false);\n }\n\n /**\n * 获得指定Cookie的值,并删除。\n *\n * @param request 请求对象\n * @param response 响应对象\n * @param name 名称\n * @return 值\n */\n public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {\n return getCookie(request, response, name, false);\n }\n\n /**\n * 获得指定Cookie的值\n *\n * @param request 请求对象\n * @param response 响应对象\n * @param name 名字\n * @param path 上下文路径\n * @return 值\n */\n public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path) {\n return getCookie(request, response, name, path, false);\n }\n\n /**\n * 获得指定Cookie的值\n *\n * @param request 请求对象\n * @param response 响应对象\n * @param name 名字\n * @param isRemove 是否移除\n * @return 值\n */\n public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) {\n return getCookie(request, response, name, \"/\", isRemove);\n }\n\n /**\n * 获得指定Cookie的值\n *\n * @param request 请求对象\n * @param response 响应对象\n * @param name 名字\n * @param isRemove 是否移除\n * @return 值\n */\n public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, boolean isRemove) {\n String value = null;\n if (!StringUtils.isEmpty(name)) {\n Cookie[] cookies = request.getCookies();\n if (cookies != null) {\n for (Cookie cookie : cookies) {\n if (cookie.getName().equals(name)) {\n try {\n value = URLDecoder.decode(cookie.getValue(), \"utf-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n if (isRemove && response != null) {\n cookie.setPath(path);\n cookie.setMaxAge(0);\n response.addCookie(cookie);\n }\n }\n }\n }\n }\n return value;\n }\n\n\n}"
}
] | import org.tinycloud.security.AuthProperties;
import org.tinycloud.security.util.AuthUtil;
import org.tinycloud.security.util.CookieUtil;
import javax.servlet.http.HttpServletRequest; | 4,264 | package org.tinycloud.security.provider;
public abstract class AbstractAuthProvider implements AuthProvider {
protected abstract AuthProperties getAuthProperties();
/**
* 获取token
* @return
*/
@Override
public String getToken() {
String token = AuthUtil.getToken(this.getAuthProperties().getTokenName());
return token;
}
/**
* 获取token
* @param request HttpServletRequest
* @return
*/
@Override
public String getToken(HttpServletRequest request) {
String token = AuthUtil.getToken(request, this.getAuthProperties().getTokenName());
return token;
}
/**
* 执行登录操作
*
* @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等
*/
@Override
public String login(Object loginId) {
String token = this.createToken(loginId);
// 设置 Cookie,通过 Cookie 上下文返回给前端 | package org.tinycloud.security.provider;
public abstract class AbstractAuthProvider implements AuthProvider {
protected abstract AuthProperties getAuthProperties();
/**
* 获取token
* @return
*/
@Override
public String getToken() {
String token = AuthUtil.getToken(this.getAuthProperties().getTokenName());
return token;
}
/**
* 获取token
* @param request HttpServletRequest
* @return
*/
@Override
public String getToken(HttpServletRequest request) {
String token = AuthUtil.getToken(request, this.getAuthProperties().getTokenName());
return token;
}
/**
* 执行登录操作
*
* @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等
*/
@Override
public String login(Object loginId) {
String token = this.createToken(loginId);
// 设置 Cookie,通过 Cookie 上下文返回给前端 | CookieUtil.setCookie(AuthUtil.getResponse(), this.getAuthProperties().getTokenName(), token); | 2 | 2023-10-26 08:13:08+00:00 | 8k |
0-Gixty-0/Grupp-11-OOPP | sailinggame/src/main/java/com/group11/application/SailingGameApplication.java | [
{
"identifier": "AControllerInterpretor",
"path": "sailinggame/src/main/java/com/group11/controller/AControllerInterpretor.java",
"snippet": "public abstract class AControllerInterpretor{\n\n private GlobalKeyListener globalKeyListener;\n\n protected AControllerInterpretor() {\n this.globalKeyListener = new GlobalKeyListener();\n }\n\n /**\n * Takes the inputSet and returns a direction based on the inputSet\n * @param inputSet Set of currently pressed keys.\n * @param up Keycode for up.\n * @param down Keycode for down.\n * @param left Keycode for left.\n * @param right Keycode for right.\n * @return Returns a direction based on the inputSet.\n */\n protected int keycodeToDir(Set<Integer> inputSet, int up, int down, int left, int right) {\n\n boolean containsUp = inputSet.contains(up);\n boolean containsDown = inputSet.contains(down);\n boolean containsLeft = inputSet.contains(left);\n boolean containsRight = inputSet.contains(right);\n\n /*Direction up-left */\n if (containsUp && containsRight && !containsLeft && !containsDown) {\n return 1;\n }\n /*Direction down-left */\n if (containsDown && containsRight && !containsUp && !containsLeft) {\n return 3;\n }\n /*Direction down-right */\n if (containsLeft && containsDown && !containsRight && !containsUp) {\n return 5;\n }\n /*Direction up-left */\n if (containsUp && containsLeft && !containsRight && !containsDown) {\n return 7;\n }\n /* Direction up*/\n if (containsUp && !containsDown) {\n return 0;\n }\n /*Direction right */\n if (containsRight && !containsLeft) {\n return 2;\n }\n /*Direction down */\n if (containsDown && !containsUp) {\n return 4;\n }\n /*Direction left */\n if (containsLeft && !containsRight) {\n return 6;\n }\n\n /*Returns -1 if none of the inputs corresponds to a direction (-1) is not a valid direction */\n return -1;\n }\n\n /**\n * Returns the inputSet, primarily used for testing.\n * @return Returns the inputSet\n */\n public Set<Integer> getInputSet() {\n return this.globalKeyListener.getInput();\n }\n\n /**\n * Returns the movement input\n * @return Returns the movement input\n */\n public abstract int getMovementInput();\n\n /**\n * Returns the fire input\n * @return Returns the fire input\n */\n public abstract int getFireInput();\n}"
},
{
"identifier": "KeyboardInterpretor",
"path": "sailinggame/src/main/java/com/group11/controller/KeyboardInterpretor.java",
"snippet": "public class KeyboardInterpretor extends AControllerInterpretor{\n\n @Override\n public int getMovementInput() {\n Set<Integer> inputSet = this.getInputSet();\n return this.keycodeToDir(inputSet, 87, 83, 65, 68);\n }\n\n @Override\n public int getFireInput() {\n Set<Integer> inputSet = this.getInputSet();\n return this.keycodeToDir(inputSet, 38, 40, 37,39);\n }\n}"
},
{
"identifier": "AModelInitializer",
"path": "sailinggame/src/main/java/com/group11/model/modelinitialization/AModelInitializer.java",
"snippet": "public abstract class AModelInitializer {\n \n World world;\n Map map;\n List<CommandableEntity> enemyList;\n List<List<AEntity>> entityMatrix;\n EntitySpawner entitySpawner;\n List<AEntity> entityList;\n CommandableEntity player;\n AICommander aiCommander;\n PlayerManager playerManager;\n EntityManager entityManager;\n int worldWidth;\n int worldHeight;\n\n protected AModelInitializer(int worldWidth, int worldHeight) {\n this.worldWidth = worldWidth;\n this.worldHeight = worldHeight;\n this.world = initializeWorld(worldWidth, worldHeight);\n this.map = initializeMap();\n this.entitySpawner = initializeEntitySpawner();\n this.enemyList = initializeEnemyList();\n this.player = initializePlayer();\n this.entityList = initializeEntityList();\n this.entityMatrix = initializeEntityMatrix();\n UMovement.setTileMatrix(map.getTileMatrix());\n UEntityCollision.setEntityMatrix(entityMatrix);\n UViewTileMatrixDecoder.setTilematrix(map.getTileMatrix());\n UEntityMatrixDecoder.setEntityMatrix(entityMatrix);\n this.aiCommander = initializeAICommander();\n this.playerManager = new PlayerManager(player);\n this.entityManager = new EntityManager(enemyList, entityList, player);\n }\n\n /**\n * Initializes the world\n *\n * @param worldWidth the width of the world\n * @param worldHeight the height of the world\n * @return the world\n */\n protected abstract World initializeWorld(int worldWidth, int worldHeight);\n\n /**\n * Initializes the map\n * @return the map\n */\n protected abstract Map initializeMap();\n\n /**\n * Initializes the enemy list\n * @return the enemy list\n */\n protected abstract List<CommandableEntity> initializeEnemyList();\n\n /**\n * Initializes the player\n * @return the player\n */\n protected abstract CommandableEntity initializePlayer();\n\n /**\n * Initializes the entity matrix\n * @return the entity matrix\n */\n protected abstract List<List<AEntity>> initializeEntityMatrix();\n\n /**\n * Initializes the AI commander\n * @return the AI commander\n */\n protected abstract AICommander initializeAICommander();\n\n /**\n * Initializes the entity spawner\n * @return the entity spawner\n */\n protected abstract EntitySpawner initializeEntitySpawner();\n\n /**\n * Initializes the entity list\n * @return the entity list\n */\n protected abstract List<AEntity> initializeEntityList();\n\n /**\n * Accessor for getting an up to date version of the entity matrix\n * @return the entity matrix in integer format\n */\n public List<List<Integer>> getDecodedEntityMatrix() {\n return UEntityMatrixDecoder.decodeIntoIntMatrix();\n }\n\n /**\n * Accessor for getting an up to date version of the terrain matrix\n * @return the terrain matrix in integer format\n */\n public List<List<Integer>> getDecodedTerrainMatrix() {\n return UViewTileMatrixDecoder.decodeIntoIntMatrix();\n }\n\n /**\n * Accessor for getting the player hit points\n * @return the player hit points\n */\n public int getPlayerHitPoints() {\n return player.getHitPoints();\n }\n\n /**\n * Accessor for getting the player score\n * @return the player score\n */\n public int getPlayerScore() {\n return playerManager.getPlayerScore();\n }\n\n protected EntityManager getEntityManager() {\n return this.entityManager;\n }\n\n protected PlayerManager getPlayerManager() {\n return this.playerManager;\n }\n\n protected World getWorld() {\n return this.world;\n }\n\n protected Map getMap() {\n return this.map;\n }\n\n protected List<CommandableEntity> getEnemyList() {\n return this.enemyList;\n }\n\n protected CommandableEntity getPlayer() {\n return this.player;\n }\n\n protected List<List<AEntity>> getEntityMatrix() {\n return this.entityMatrix;\n }\n\n protected AICommander getAICommander() {\n return this.aiCommander;\n }\n\n protected EntitySpawner getEntitySpawner() {\n return this.entitySpawner;\n }\n\n protected List<AEntity> getEntityList() {\n return this.entityList;\n }\n}"
},
{
"identifier": "IGameLoop",
"path": "sailinggame/src/main/java/com/group11/model/modelinitialization/IGameLoop.java",
"snippet": "public interface IGameLoop {\n\n public void runLoopOnce(int movementInput, int fireInput);\n\n public boolean isGameOver();\n}"
},
{
"identifier": "SailingGameLoop",
"path": "sailinggame/src/main/java/com/group11/model/modelinitialization/SailingGameLoop.java",
"snippet": "public class SailingGameLoop implements IGameLoop {\n \n AICommander aiCommander;\n EntityManager entityManager;\n PlayerManager playerManager;\n Map map;\n List<List<AEntity>> entityMatrix;\n List<CommandableEntity> enemyList;\n List<AEntity> entityList;\n EntitySpawner entitySpawner;\n CommandableEntity player;\n int waveNumber;\n\n public SailingGameLoop(AModelInitializer initializedModel) {\n this.waveNumber = 1;\n this.map = initializedModel.getMap();\n this.enemyList = initializedModel.getEnemyList();\n this.player = initializedModel.getPlayer();\n this.entityMatrix = initializedModel.getEntityMatrix();\n this.aiCommander = initializedModel.getAICommander();\n this.entitySpawner = initializedModel.getEntitySpawner();\n this.entityList = initializedModel.getEntityList();\n this.playerManager = initializedModel.getPlayerManager();\n this.entityManager = initializedModel.getEntityManager();\n }\n\n @Override\n public void runLoopOnce(int movementInput, int fireInput) {\n\n if (enemyList.isEmpty()) {\n waveNumber++;\n enemyList.addAll(entitySpawner.createEnemyWave(waveNumber));\n entityList.addAll(enemyList);\n player.setHitPoints(112);\n }\n\n playerManager.updatePlayer(movementInput, fireInput);\n aiCommander.moveEnemies(enemyList);\n aiCommander.fireWeapons(enemyList);\n\n UProjectile.updateProjectiles(entityList); // Adds new projectiles to an entity list and removes old dead projectiles.\n\n UProjectile.moveProjectiles(entityList); // Moves the projectiles.\n UEntityMatrixGenerator.updateEntityMatrix(entityList); // Updates the entity matrix.\n UProjectile.checkProjectileCollisions(entityList); // Checks for collisions.\n \n // Two iterations so that projectiles move faster than other entities.\n UProjectile.moveProjectiles(entityList);\n UEntityMatrixGenerator.updateEntityMatrix(entityList);\n UProjectile.checkProjectileCollisions(entityList);\n \n // Removes dead entities\n entityManager.removeEntitiesWithZeroHp(waveNumber);\n }\n\n @Override\n public boolean isGameOver() {\n return player.getHitPoints() <= 0;\n }\n}"
},
{
"identifier": "SailingGameModel",
"path": "sailinggame/src/main/java/com/group11/model/modelinitialization/SailingGameModel.java",
"snippet": "public class SailingGameModel extends AModelInitializer {\n\n /**\n * Constructs a SailingGameModel with the specified world width and height.\n *\n * @param worldWidth the width of the world\n * @param worldHeight the height of the world\n */\n public SailingGameModel(int worldWidth, int worldHeight) {\n super(worldWidth, worldHeight);\n }\n\n /**\n * Initializes the world with the specified width and height.\n *\n * @param worldWidth the width of the world\n * @param worldHeight the height of the world\n * @return the initialized world\n */\n @Override\n protected World initializeWorld(int worldWidth, int worldHeight) {\n AdvancedMapGenerator mapGenerator = new AdvancedMapGenerator();\n BasicWorldGenerator worldGenerator = new BasicWorldGenerator(mapGenerator);\n return worldGenerator.generateWorld(worldWidth, worldHeight);\n }\n\n /**\n * Initializes the map for the game world.\n *\n * @return the initialized map\n */\n @Override\n protected Map initializeMap() {\n return this.world.getMap();\n }\n\n /**\n * Initializes the list of enemy entities for the game.\n *\n * @return the initialized list of enemy entities\n */\n @Override\n protected List<CommandableEntity> initializeEnemyList() {\n return this.entitySpawner.createEnemyWave(1);\n }\n\n /**\n * Initializes the player entity for the game.\n *\n * @return the initialized player entity\n */\n @Override\n protected CommandableEntity initializePlayer() {\n return this.entitySpawner.spawnPlayer();\n }\n\n /**\n * Initializes the entity matrix for the game.\n *\n * @return the initialized entity matrix\n */\n @Override\n protected List<List<AEntity>> initializeEntityMatrix() {\n int mapWidth = this.map.getMapWidth();\n int mapHeight = this.map.getMapHeight();\n return UEntityMatrixGenerator.createEntityMatrix(mapWidth, mapHeight, this.entityList);\n }\n\n /**\n * Initializes the AI commander for the game.\n *\n * @return the initialized AI commander\n */\n @Override\n protected AICommander initializeAICommander() {\n return new AICommander(this.entityMatrix);\n }\n\n /**\n * Initializes the entity spawner for the game.\n *\n * @return the initialized entity spawner\n */\n @Override\n protected EntitySpawner initializeEntitySpawner() {\n IEntityBuilder builder = new ShipBuilder();\n return new EntitySpawner(this.map, builder);\n }\n\n /**\n * Initializes the list of entities for the game.\n *\n * @return the initialized list of entities\n */\n @Override\n protected List<AEntity> initializeEntityList() {\n List<AEntity> entityList = new ArrayList<>();\n entityList.addAll(this.enemyList);\n entityList.add(this.player);\n return entityList;\n }\n}"
},
{
"identifier": "AppFrame",
"path": "sailinggame/src/main/java/com/group11/view/uicomponents/AppFrame.java",
"snippet": "public class AppFrame extends JFrame {\n\n private GameOverPanel gameOverView;\n private GamePanel gameView;\n private MainMenuPanel mainMenuView;\n\n private static final int TILEWIDTH = 16;\n private static final int TILEHEIGHT = 16;\n\n /**\n * Constructor for creating an AppFrame.\n *\n * @param width width of the frame\n * @param height height of the frame\n */\n public AppFrame (int width, int height, int mapWidth, int mapHeight) {\n super();\n Dimension size = new Dimension(width, height);\n this.setPreferredSize(size);\n this.setTitle(\"Sailing Game\");\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.getContentPane().setBackground(java.awt.Color.GRAY);\n this.setLayout(new FlowLayout(FlowLayout.CENTER));\n this.setVisible(true);\n this.gameOverView = new GameOverPanel(width, height);\n this.gameView = new GamePanel(width, height, mapWidth, mapHeight, TILEWIDTH, TILEHEIGHT);\n this.mainMenuView = new MainMenuPanel(width, height);\n }\n\n /**\n * Displays the game view.\n */\n public void displayGameView() {\n this.removeViewFromWindow(this.mainMenuView);\n this.removeViewFromWindow(this.gameOverView);\n this.addViewToWindow(this.gameView);\n }\n\n /**\n * Displays the main menu view.\n */\n public void displayMainMenuView() {\n this.removeViewFromWindow(this.gameView);\n this.removeViewFromWindow(this.gameOverView);\n this.addViewToWindow(this.mainMenuView);\n }\n\n /**\n * Displays the game over view.\n */\n public void displayGameOverView() {\n this.removeViewFromWindow(this.gameView);\n this.removeViewFromWindow(this.mainMenuView);\n this.addViewToWindow(this.gameOverView);\n }\n\n /**\n * Gets the value from the start button and resets it\n *\n * @return boolean value of the start button\n */\n public boolean getStartButtonPressed() {\n boolean isPressed = this.mainMenuView.getStartButtonPressed();\n mainMenuView.resetStartButtonPressed();\n return isPressed;\n }\n\n /**\n * Gets the value from the back to menu button and resets it\n *\n * @return boolean value of the back to menu button\n */\n public boolean getBackToMenuButtonPressed() {\n boolean isPressed = this.gameOverView.getBackToMenuButtonPressed();\n gameOverView.resetBackToMenuButtonPressed();\n return isPressed;\n }\n\n /**\n * Updates the entities in the game view.\n *\n * @param entityMatrix the matrix of entities to be updated\n */\n public void updateEntities(List<List<Integer>> entityMatrix) {\n this.gameView.updateEntities(entityMatrix);\n }\n\n /**\n * Updates the terrain in the game view.\n *\n * @param terrainMatrix the matrix of terrain to be updated\n */\n public void updateTerrain(List<List<Integer>> terrainMatrix) {\n this.gameView.updateTerrain(terrainMatrix);\n }\n\n /**\n * Updates the score in the game view.\n *\n * @param score the score to be updated\n */\n public void updateScore(int score) {\n this.gameView.updateScore(score);\n this.gameOverView.setScoreLabel(score);\n }\n\n /**\n * Updates the hp in the game view.\n *\n * @param hp the hp to be updated\n */\n public void updateHp(int hp) {\n this.gameView.updateHp(hp);\n }\n\n /**\n * Removes a view from the window\n *\n * @param view The view to be removed\n */\n private void removeViewFromWindow(JComponent view) {\n this.remove(view);\n this.repaint();\n }\n\n /**\n * Adds a view to the window\n *\n * @param view The view to be added\n */\n private void addViewToWindow(JComponent view) {\n this.add(view);\n this.validate();\n }\n}"
}
] | import com.group11.controller.AControllerInterpretor;
import com.group11.controller.KeyboardInterpretor;
import com.group11.model.modelinitialization.AModelInitializer;
import com.group11.model.modelinitialization.IGameLoop;
import com.group11.model.modelinitialization.SailingGameLoop;
import com.group11.model.modelinitialization.SailingGameModel;
import com.group11.view.uicomponents.AppFrame; | 4,452 | package com.group11.application;
/**
* A class containing logic specific to the SailingGame application. The idea of our project was to make the source
* code as extendable as possible, therefore, if you wanted to create a new game you would only need to change this class.
*/
public class SailingGameApplication extends AApplication {
private static final int WINDOWWITH = 1100;
private static final int WINDOWHEIGHT = 1000;
private static final int MAPWIDTH = 65;
private static final int MAPHEIGHT = 30;
IGameLoop gameLoop;
AModelInitializer model; | package com.group11.application;
/**
* A class containing logic specific to the SailingGame application. The idea of our project was to make the source
* code as extendable as possible, therefore, if you wanted to create a new game you would only need to change this class.
*/
public class SailingGameApplication extends AApplication {
private static final int WINDOWWITH = 1100;
private static final int WINDOWHEIGHT = 1000;
private static final int MAPWIDTH = 65;
private static final int MAPHEIGHT = 30;
IGameLoop gameLoop;
AModelInitializer model; | AControllerInterpretor keyBoardInterpretor; | 0 | 2023-10-31 11:40:56+00:00 | 8k |
MattiDragon/JsonPatcher | src/main/java/io/github/mattidragon/jsonpatcher/patch/Patcher.java | [
{
"identifier": "JsonPatcher",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/JsonPatcher.java",
"snippet": "public class JsonPatcher implements ModInitializer {\n private static final Set<String> SUPPORTED_VERSIONS = new HashSet<>(Set.of(\"1\"));\n public static final String MOD_ID = \"jsonpatcher\";\n public static final Logger MAIN_LOGGER = LoggerFactory.getLogger(MOD_ID);\n private static final String RELOAD_LOGGER_NAME = \"JsonPatcher Reload\";\n public static final Logger RELOAD_LOGGER = LoggerFactory.getLogger(RELOAD_LOGGER_NAME);\n\n static {\n hackLog4j();\n }\n\n public static Identifier id(String path) {\n return new Identifier(MOD_ID, path);\n }\n\n @Override\n public void onInitialize() {\n Config.MANAGER.get();\n DumpManager.cleanDump(\"\");\n }\n\n /**\n * Uses log4j core apis to reconfigure logging of patches into a custom file.\n * Should be stable enough, but just in case we handle errors gracefully.\n */\n private static void hackLog4j() {\n MAIN_LOGGER.debug(\"About to hack log4j config\");\n try {\n var log4jLogger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(RELOAD_LOGGER_NAME);\n var configuration = log4jLogger.getContext().getConfiguration();\n\n var appender = RandomAccessFileAppender.newBuilder()\n .setName(\"JsonPatcherFile\")\n .setFileName(\"logs/jsonpatcher.log\")\n .setLayout(PatternLayout.newBuilder().withPattern(\"[%d{HH:mm:ss}] [%t/%level] (%logger) %msg{nolookups}%n\").build())\n .setAppend(false)\n .build();\n appender.start();\n\n configuration.addAppender(appender);\n configuration.addLoggerAppender(log4jLogger, appender);\n configuration.setLoggerAdditive(log4jLogger, false);\n\n log4jLogger.setLevel(Level.toLevel(System.getProperty(\"jsonpatcher.log.level\"), Level.INFO));\n\n MAIN_LOGGER.debug(\"Successfully hacked log4j config. Now we have our own file!\");\n } catch (IncompatibleClassChangeError | NoClassDefFoundError | RuntimeException e) {\n MAIN_LOGGER.error(\"Failed to hack log4j. All output will be logged to main log.\", e);\n }\n }\n\n public static boolean isSupportedVersion(String version) {\n return SUPPORTED_VERSIONS.contains(version);\n }\n}"
},
{
"identifier": "MetapatchLibrary",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/metapatch/MetapatchLibrary.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class MetapatchLibrary {\n @DontBind\n private final Map<Identifier, JsonObject> addedFiles = new HashMap<>();\n @DontBind\n private final List<Identifier> deletedFiles = new ArrayList<>();\n @DontBind\n private final ResourceManager resourceManager;\n\n public MetapatchLibrary(ResourceManager resourceManager) {\n this.resourceManager = resourceManager;\n }\n\n @DontBind\n public void apply(MetapatchResourcePack metaPack) {\n metaPack.set(addedFiles, deletedFiles);\n }\n\n public void addFile(LibraryBuilder.FunctionContext context, Value.StringValue idString, Value.ObjectValue file) {\n var id = Identifier.tryParse(idString.value());\n if (id == null) throw new EvaluationException(\"Invalid identifier: \" + idString.value(), context.callPos());\n try {\n deletedFiles.remove(id);\n addedFiles.put(id, GsonConverter.toGson(file));\n } catch (IllegalStateException e) {\n throw new EvaluationException(\"Failed to convert to json: \" + e.getMessage(), context.callPos());\n }\n }\n\n public void deleteFile(LibraryBuilder.FunctionContext context, Value.StringValue idString) {\n var id = Identifier.tryParse(idString.value());\n if (id == null) throw new EvaluationException(\"Invalid identifier: \" + idString.value(), context.callPos());\n\n addedFiles.remove(id);\n deletedFiles.add(id);\n }\n\n public Value getFile(LibraryBuilder.FunctionContext context, Value.StringValue idString) {\n var id = Identifier.tryParse(idString.value());\n if (id == null) throw new EvaluationException(\"Invalid identifier: \" + idString.value(), context.callPos());\n\n try (var __ = PatchingContext.disablePatching()) {\n var resource = resourceManager.getResource(id);\n if (resource.isPresent()) {\n try {\n return GsonConverter.fromGson(MetapatchResourcePack.GSON.fromJson(new InputStreamReader(resource.get().getInputStream()), JsonObject.class));\n } catch (IllegalStateException e) {\n throw new EvaluationException(\"Failed to convert from json: \" + e.getMessage(), context.callPos());\n } catch (IOException e) {\n throw new EvaluationException(\"Failed to read file: \" + e.getMessage(), context.callPos());\n }\n }\n }\n\n return Value.NullValue.NULL;\n }\n}"
},
{
"identifier": "DumpManager",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/misc/DumpManager.java",
"snippet": "public class DumpManager {\n private static final Gson DUMP_GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();\n\n public static void dumpIfEnabled(Identifier id, ReloadDescription description, JsonElement patchedData) {\n if (Config.MANAGER.get().dumpPatchedFiles() && description.dumpPath() != null) {\n try {\n var file = getDumpPath(description.dumpPath())\n .resolve(Path.of(id.getNamespace(), id.getPath().split(\"/\")));\n Files.createDirectories(file.getParent());\n try (var writer = new OutputStreamWriter(Files.newOutputStream(file))) {\n DUMP_GSON.toJson(patchedData, writer);\n }\n } catch (IOException e) {\n JsonPatcher.RELOAD_LOGGER.error(\"Failed to dump patched file {}\", id, e);\n }\n }\n }\n\n public static void cleanDump(@Nullable String dumpLocation) {\n if (dumpLocation == null) return;\n\n var file = getDumpPath(dumpLocation);\n if (Files.exists(file)) {\n var errors = new ArrayList<IOException>();\n try (var stream = Files.walk(file)) {\n stream.sorted(Comparator.reverseOrder())\n .forEach(path -> {\n try {\n Files.delete(path);\n } catch (IOException e) {\n errors.add(e);\n }\n });\n if (!errors.isEmpty()) {\n var error = new IOException(\"Errors while deleting dumped files\");\n errors.forEach(error::addSuppressed);\n throw error;\n }\n } catch (IOException e) {\n JsonPatcher.RELOAD_LOGGER.error(\"Failed to clean dump directory\", e);\n }\n }\n }\n\n private static Path getDumpPath(String dumpLocation) {\n return FabricLoader.getInstance().getGameDir()\n .resolve(\"jsonpatcher-dump\")\n .resolve(dumpLocation);\n }\n}"
},
{
"identifier": "GsonConverter",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/misc/GsonConverter.java",
"snippet": "public class GsonConverter {\n private static final ThreadLocal<Set<Value>> TO_GSON_RECURSION_TRACKER = ThreadLocal.withInitial(Sets::newIdentityHashSet);\n private static final ThreadLocal<Set<JsonElement>> FROM_GSON_RECURSION_TRACKER = ThreadLocal.withInitial(Sets::newIdentityHashSet);\n\n private GsonConverter() {\n }\n\n public static JsonElement toGson(Value value) {\n try {\n if (!TO_GSON_RECURSION_TRACKER.get().add(value)) {\n throw new IllegalStateException(\"recursive value tree\");\n }\n if (value instanceof Value.ObjectValue objectValue) return toGson(objectValue);\n if (value instanceof Value.ArrayValue arrayValue) return toGson(arrayValue);\n if (value instanceof Value.NumberValue numberValue) return new JsonPrimitive(numberValue.value());\n if (value instanceof Value.StringValue stringValue) return new JsonPrimitive(stringValue.value());\n if (value instanceof Value.BooleanValue booleanValue) return new JsonPrimitive(booleanValue.value());\n if (value instanceof Value.NullValue) return JsonNull.INSTANCE;\n throw new IllegalStateException(\"Can't convert %s to gson\".formatted(value));\n } finally {\n TO_GSON_RECURSION_TRACKER.get().remove(value);\n }\n }\n\n public static JsonObject toGson(Value.ObjectValue value) {\n JsonObject object = new JsonObject();\n for (var entry : value.value().entrySet()) {\n object.add(entry.getKey(), toGson(entry.getValue()));\n }\n return object;\n }\n\n public static JsonArray toGson(Value.ArrayValue value) {\n JsonArray array = new JsonArray();\n for (var entry : value.value()) {\n array.add(toGson(entry));\n }\n return array;\n }\n\n public static Value fromGson(JsonElement json) {\n try {\n if (!FROM_GSON_RECURSION_TRACKER.get().add(json)) {\n throw new IllegalStateException(\"recursive gson json tree\");\n }\n if (json instanceof JsonObject jsonObject) return fromGson(jsonObject);\n if (json instanceof JsonArray jsonArray) return fromGson(jsonArray);\n if (json instanceof JsonPrimitive primitive) {\n if (primitive.isBoolean()) return Value.BooleanValue.of(primitive.getAsBoolean());\n if (primitive.isNumber()) return new Value.NumberValue(primitive.getAsNumber().doubleValue());\n if (primitive.isString()) return new Value.StringValue(primitive.getAsString());\n }\n if (json instanceof JsonNull) return Value.NullValue.NULL;\n throw new IllegalStateException(\"Can't convert %s to value\".formatted(json));\n } finally {\n FROM_GSON_RECURSION_TRACKER.get().remove(json);\n }\n }\n\n public static Value.ObjectValue fromGson(JsonObject object) {\n Value.ObjectValue value = new Value.ObjectValue();\n for (var entry : object.entrySet()) {\n value.value().put(entry.getKey(), fromGson(entry.getValue()));\n }\n return value;\n }\n\n public static Value.ArrayValue fromGson(JsonArray array) {\n Value.ArrayValue value = new Value.ArrayValue();\n for (var entry : array) {\n value.value().add(fromGson(entry));\n }\n return value;\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.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonWriter;
import io.github.mattidragon.jsonpatcher.JsonPatcher;
import io.github.mattidragon.jsonpatcher.config.Config;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationContext;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationException;
import io.github.mattidragon.jsonpatcher.lang.runtime.Value;
import io.github.mattidragon.jsonpatcher.lang.runtime.stdlib.LibraryBuilder;
import io.github.mattidragon.jsonpatcher.metapatch.MetapatchLibrary;
import io.github.mattidragon.jsonpatcher.misc.DumpManager;
import io.github.mattidragon.jsonpatcher.misc.GsonConverter;
import io.github.mattidragon.jsonpatcher.misc.MetaPatchPackAccess;
import io.github.mattidragon.jsonpatcher.misc.ReloadDescription;
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourceManager;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.JsonHelper;
import org.apache.commons.lang3.mutable.MutableObject;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.concurrent.*;
import java.util.function.Consumer; | 3,988 | package io.github.mattidragon.jsonpatcher.patch;
public class Patcher {
private static final ExecutorService PATCHING_EXECUTOR = new ThreadPoolExecutor(0,
Integer.MAX_VALUE,
5,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadFactoryBuilder().setNameFormat("JsonPatch Patcher (%s)").build());
private static final Gson GSON = new Gson();
private final ReloadDescription description;
private final PatchStorage patches;
public Patcher(ReloadDescription description, PatchStorage patches) {
this.description = description;
this.patches = patches;
}
private boolean hasPatches(Identifier id) {
return patches.hasPatches(id);
}
private JsonElement applyPatches(JsonElement json, Identifier id) {
var errors = new ArrayList<Exception>();
var activeJson = new MutableObject<>(JsonHelper.asObject(json, "patched file"));
try {
for (var patch : patches.getPatches(id)) {
var root = GsonConverter.fromGson(activeJson.getValue());
var timeBeforePatch = System.nanoTime();
var success = runPatch(patch, PATCHING_EXECUTOR, errors::add, patches, root, Settings.builder()
.target(id.toString())
.build());
var timeAfterPatch = System.nanoTime();
JsonPatcher.RELOAD_LOGGER.debug("Patched {} with {} in {}ms", id, patch.id(), (timeAfterPatch - timeBeforePatch) / 1e6);
if (success) {
activeJson.setValue(GsonConverter.toGson(root));
}
}
} catch (RuntimeException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
errors.forEach(error -> JsonPatcher.RELOAD_LOGGER.error("Error while patching {}", id, error));
var message = "Encountered %s error(s) while patching %s. See logs/jsonpatch.log for details".formatted(errors.size(), id);
description.errorConsumer().accept(Text.literal(message).formatted(Formatting.RED));
if (Config.MANAGER.get().abortOnFailure()) {
throw new PatchingException(message);
} else {
JsonPatcher.MAIN_LOGGER.error(message);
}
}
return activeJson.getValue();
}
/**
* Runs a patch with proper error handling.
* @param patch The patch to run.
* @param executor An executor to run the patch on, required to run on another thread for timeout to work
* @param errorConsumer A consumer the receives errors from the patch.
* Errors are either {@link EvaluationException EvaluationExceptions} for errors within the patch,
* or {@link RuntimeException RuntimeExceptions} for timeouts and other errors not from the patch itself
* @param patchStorage A patch storage for resolution of libraries
* @param root The root object for the patch context, will be modified
* @return {@code true} if the patch completed successfully. If {@code false} the {@code errorConsumer} should have received an error.
*/
public static boolean runPatch(Patch patch, Executor executor, Consumer<RuntimeException> errorConsumer, PatchStorage patchStorage, Value.ObjectValue root, Settings settings) {
try {
var context = buildContext(patch.id(), patchStorage, root, settings);
CompletableFuture.runAsync(() -> patch.program().execute(context), executor)
.get(Config.MANAGER.get().patchTimeoutMillis(), TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException e) {
if (e.getCause() instanceof EvaluationException cause) {
errorConsumer.accept(cause);
} else if (e.getCause() instanceof StackOverflowError cause) {
errorConsumer.accept(new PatchingException("Stack overflow while applying patch %s".formatted(patch.id()), cause));
} else {
errorConsumer.accept(new RuntimeException("Unexpected error while applying patch %s".formatted(patch.id()), e));
}
} catch (InterruptedException e) {
errorConsumer.accept(new PatchingException("Async error while applying patch %s".formatted(patch.id()), e));
} catch (TimeoutException e) {
errorConsumer.accept(new PatchingException("Timeout while applying patch %s. Check for infinite loops and increase the timeout in the config.".formatted(patch.id()), e));
}
return false;
}
private static EvaluationContext buildContext(Identifier patchId, EvaluationContext.LibraryLocator libraryLocator, Value.ObjectValue root, Settings settings) {
var builder = EvaluationContext.builder();
builder.root(root);
builder.libraryLocator(libraryLocator);
builder.debugConsumer(value -> JsonPatcher.RELOAD_LOGGER.info("Debug from {}: {}", patchId, value));
builder.variable("_isLibrary", settings.isLibrary());
builder.variable("_target", settings.targetAsValue());
builder.variable("_isMetapatch", settings.isMetaPatch());
if (settings.isMetaPatch()) {
builder.variable("metapatch", new LibraryBuilder(MetapatchLibrary.class, settings.metaPatchLibrary).build());
}
return builder.build();
}
public InputSupplier<InputStream> patchInputStream(Identifier id, InputSupplier<InputStream> stream) {
if (!hasPatches(id)) return stream;
try {
JsonPatcher.RELOAD_LOGGER.debug("Patching {}", id);
var json = GSON.fromJson(new InputStreamReader(stream.get()), JsonElement.class);
json = applyPatches(json, id);
var out = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(out);
GSON.toJson(json, new JsonWriter(writer));
writer.close();
DumpManager.dumpIfEnabled(id, description, json);
return () -> new ByteArrayInputStream(out.toByteArray());
} catch (JsonParseException | IOException e) {
JsonPatcher.RELOAD_LOGGER.error("Failed to patch json at {}", id, e);
if (Config.MANAGER.get().abortOnFailure()) {
throw new RuntimeException("Failed to patch json at %s".formatted(id), e);
}
return stream;
}
}
public void runMetaPatches(ResourceManager manager, Executor executor) { | package io.github.mattidragon.jsonpatcher.patch;
public class Patcher {
private static final ExecutorService PATCHING_EXECUTOR = new ThreadPoolExecutor(0,
Integer.MAX_VALUE,
5,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadFactoryBuilder().setNameFormat("JsonPatch Patcher (%s)").build());
private static final Gson GSON = new Gson();
private final ReloadDescription description;
private final PatchStorage patches;
public Patcher(ReloadDescription description, PatchStorage patches) {
this.description = description;
this.patches = patches;
}
private boolean hasPatches(Identifier id) {
return patches.hasPatches(id);
}
private JsonElement applyPatches(JsonElement json, Identifier id) {
var errors = new ArrayList<Exception>();
var activeJson = new MutableObject<>(JsonHelper.asObject(json, "patched file"));
try {
for (var patch : patches.getPatches(id)) {
var root = GsonConverter.fromGson(activeJson.getValue());
var timeBeforePatch = System.nanoTime();
var success = runPatch(patch, PATCHING_EXECUTOR, errors::add, patches, root, Settings.builder()
.target(id.toString())
.build());
var timeAfterPatch = System.nanoTime();
JsonPatcher.RELOAD_LOGGER.debug("Patched {} with {} in {}ms", id, patch.id(), (timeAfterPatch - timeBeforePatch) / 1e6);
if (success) {
activeJson.setValue(GsonConverter.toGson(root));
}
}
} catch (RuntimeException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
errors.forEach(error -> JsonPatcher.RELOAD_LOGGER.error("Error while patching {}", id, error));
var message = "Encountered %s error(s) while patching %s. See logs/jsonpatch.log for details".formatted(errors.size(), id);
description.errorConsumer().accept(Text.literal(message).formatted(Formatting.RED));
if (Config.MANAGER.get().abortOnFailure()) {
throw new PatchingException(message);
} else {
JsonPatcher.MAIN_LOGGER.error(message);
}
}
return activeJson.getValue();
}
/**
* Runs a patch with proper error handling.
* @param patch The patch to run.
* @param executor An executor to run the patch on, required to run on another thread for timeout to work
* @param errorConsumer A consumer the receives errors from the patch.
* Errors are either {@link EvaluationException EvaluationExceptions} for errors within the patch,
* or {@link RuntimeException RuntimeExceptions} for timeouts and other errors not from the patch itself
* @param patchStorage A patch storage for resolution of libraries
* @param root The root object for the patch context, will be modified
* @return {@code true} if the patch completed successfully. If {@code false} the {@code errorConsumer} should have received an error.
*/
public static boolean runPatch(Patch patch, Executor executor, Consumer<RuntimeException> errorConsumer, PatchStorage patchStorage, Value.ObjectValue root, Settings settings) {
try {
var context = buildContext(patch.id(), patchStorage, root, settings);
CompletableFuture.runAsync(() -> patch.program().execute(context), executor)
.get(Config.MANAGER.get().patchTimeoutMillis(), TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException e) {
if (e.getCause() instanceof EvaluationException cause) {
errorConsumer.accept(cause);
} else if (e.getCause() instanceof StackOverflowError cause) {
errorConsumer.accept(new PatchingException("Stack overflow while applying patch %s".formatted(patch.id()), cause));
} else {
errorConsumer.accept(new RuntimeException("Unexpected error while applying patch %s".formatted(patch.id()), e));
}
} catch (InterruptedException e) {
errorConsumer.accept(new PatchingException("Async error while applying patch %s".formatted(patch.id()), e));
} catch (TimeoutException e) {
errorConsumer.accept(new PatchingException("Timeout while applying patch %s. Check for infinite loops and increase the timeout in the config.".formatted(patch.id()), e));
}
return false;
}
private static EvaluationContext buildContext(Identifier patchId, EvaluationContext.LibraryLocator libraryLocator, Value.ObjectValue root, Settings settings) {
var builder = EvaluationContext.builder();
builder.root(root);
builder.libraryLocator(libraryLocator);
builder.debugConsumer(value -> JsonPatcher.RELOAD_LOGGER.info("Debug from {}: {}", patchId, value));
builder.variable("_isLibrary", settings.isLibrary());
builder.variable("_target", settings.targetAsValue());
builder.variable("_isMetapatch", settings.isMetaPatch());
if (settings.isMetaPatch()) {
builder.variable("metapatch", new LibraryBuilder(MetapatchLibrary.class, settings.metaPatchLibrary).build());
}
return builder.build();
}
public InputSupplier<InputStream> patchInputStream(Identifier id, InputSupplier<InputStream> stream) {
if (!hasPatches(id)) return stream;
try {
JsonPatcher.RELOAD_LOGGER.debug("Patching {}", id);
var json = GSON.fromJson(new InputStreamReader(stream.get()), JsonElement.class);
json = applyPatches(json, id);
var out = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(out);
GSON.toJson(json, new JsonWriter(writer));
writer.close();
DumpManager.dumpIfEnabled(id, description, json);
return () -> new ByteArrayInputStream(out.toByteArray());
} catch (JsonParseException | IOException e) {
JsonPatcher.RELOAD_LOGGER.error("Failed to patch json at {}", id, e);
if (Config.MANAGER.get().abortOnFailure()) {
throw new RuntimeException("Failed to patch json at %s".formatted(id), e);
}
return stream;
}
}
public void runMetaPatches(ResourceManager manager, Executor executor) { | if (!(manager instanceof MetaPatchPackAccess packAccess)) { | 4 | 2023-10-30 14:09:36+00:00 | 8k |
Abbas-Rizvi/p2p-social | src/main/backend/blockchain/PrivateMsg.java | [
{
"identifier": "KeyGen",
"path": "src/main/backend/crypt/KeyGen.java",
"snippet": "public class KeyGen implements Serializable {\n\n private static final long serialVersionUID = 123456789L;\n\n private static final String RSA = \"RSA\";\n\n private KeyPair kp;\n\n // Generating public & private keys\n // using RSA algorithm.\n public void generateRSAKkeyPair() {\n\n try {\n SecureRandom secureRandom = new SecureRandom();\n KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);\n\n keyPairGenerator.initialize(4096, secureRandom);\n\n kp = keyPairGenerator.generateKeyPair();\n\n storeKey(kp.getPrivate(), \"./data/id_rsa\");\n storeKey(kp.getPublic(), \"./data/id_rsa.pub\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n // store key for later use\n private void storeKey(Key key, String filePath) throws Exception {\n\n byte[] keyBytes = key.getEncoded();\n\n // encode key as base64\n // byte[] encodedKey = new String(Base64.getEncoder().encode(keyBytes));\n byte[] encodedKey = Base64.getEncoder().encode(keyBytes);\n\n try (FileOutputStream fos = new FileOutputStream(filePath)) {\n fos.write(encodedKey);\n }\n\n // try (PrintWriter out = new PrintWriter(filePath)) {\n // out.println(encodedKey);\n // }\n\n }\n\n // check keys\n public boolean checkKeysExist() {\n\n String file1Path = \"./data/id_rsa\";\n String file2Path = \"./data/id_rsa.pub\";\n\n // Create an instance of File with the specified path\n File file1 = new File(file1Path);\n File file2 = new File(file2Path);\n\n if (file1.exists() && file2.exists())\n return true;\n else\n return false;\n\n }\n\n // ##########################\n // Public key functions\n // ##########################\n\n // connverts encoded public key to publicKey object\n public PublicKey convertPublicKey(String pubKeyStr) {\n\n // Decode the Base64-encoded public key\n byte[] decodedKey = Base64.getDecoder().decode(pubKeyStr);\n\n X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);\n\n KeyFactory keyFactory;\n\n try {\n\n keyFactory = KeyFactory.getInstance(\"RSA\");\n PublicKey pubKey = keyFactory.generatePublic(keySpec);\n return pubKey;\n\n } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n\n }\n\n public PublicKey getPublicKey() {\n\n // read public key from file\n Path filePath = Paths.get(\"./data/id_rsa.pub\").toAbsolutePath();\n\n String key;\n\n try {\n\n key = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);\n PublicKey pubkey = convertPublicKey(key);\n return pubkey;\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n }\n\n public String getPublicKeyStr() {\n\n // read public key from file\n Path filePath = Paths.get(\"./data/id_rsa.pub\").toAbsolutePath();\n\n String pubKeyStr;\n\n try {\n\n pubKeyStr = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);\n return pubKeyStr;\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n }\n\n // ##########################\n // Private key functions\n // ##########################\n\n public String getPrivateKeyString() {\n\n // read public key from file\n Path filePath = Paths.get(\"./data/id_rsa\").toAbsolutePath();\n\n String privKeyString;\n\n try {\n\n privKeyString = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);\n return privKeyString;\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n }\n\n // connverts encoded public key to publicKey object\n public PrivateKey convertPrivateKey(String privKeyString) {\n\n // Decode the Base64-encoded public key\n byte[] decodedKey = Base64.getDecoder().decode(privKeyString);\n\n PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);\n\n KeyFactory keyFactory;\n\n try {\n\n keyFactory = KeyFactory.getInstance(\"RSA\");\n PrivateKey privKey = keyFactory.generatePrivate(keySpec);\n return privKey;\n\n } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n\n }\n\n public PrivateKey getPrivatKey() {\n\n // read public key from file\n Path filePath = Paths.get(\"./data/id_rsa\").toAbsolutePath();\n\n String key;\n\n try {\n\n key = new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);\n PrivateKey privKey = convertPrivateKey(key);\n return privKey;\n\n } catch (IOException e) {\n\n e.printStackTrace();\n\n }\n\n return null;\n }\n\n}"
},
{
"identifier": "NTPTimeService",
"path": "src/main/network/NTPTimeService.java",
"snippet": "public class NTPTimeService implements Serializable {\n\n private static final long serialVersionUID = 123456789L;\n\n public Date getNTPDate() {\n\n // time server\n String[] hosts = new String[] {\n \"pool.ntp.org\",\n \"time-a-g.nist.gov\" };\n\n // create NTP UDP client`\n NTPUDPClient client = new NTPUDPClient();\n\n client.setDefaultTimeout(5000);\n\n for (String host : hosts) {\n\n try {\n InetAddress hostAddr = InetAddress.getByName(host);\n TimeInfo info = client.getTime(hostAddr);\n Date date = new Date(info.getReturnTime());\n return date;\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n client.close();\n\n return null;\n\n }\n\n public String formatedTime(long time) {\n\n Date date = new Date(time);\n return date.toString();\n\n }\n\n}"
},
{
"identifier": "PeersDatabase",
"path": "src/main/network/PeersDatabase.java",
"snippet": "public class PeersDatabase implements Serializable {\n private static final long serialVersionUID = 123456789L;\n\n private static final String URL = \"jdbc:sqlite:data/known_peers.db\";\n\n // Constructor\n public PeersDatabase() {\n try {\n // Create the table if it doesn't exist\n createTable();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n private Connection connect() {\n Connection connection = null;\n try {\n // Register SQLite driver\n Class.forName(\"org.sqlite.JDBC\");\n \n // Try to establish a connection\n connection = DriverManager.getConnection(URL);\n \n } catch (ClassNotFoundException | SQLException e) {\n // Handle exceptions\n e.printStackTrace();\n }\n \n if (connection == null) {\n System.err.println(\"Failed to establish a connection to the database.\");\n System.exit(1); // Terminate the program if the connection fails\n }\n \n return connection;\n }\n \n\n private void createTable() throws SQLException {\n try (Connection connection = connect();\n Statement statement = connection.createStatement()) {\n String createTableQuery = \"CREATE TABLE IF NOT EXISTS known_peers (\" +\n \"id INTEGER PRIMARY KEY AUTOINCREMENT,\" +\n \"name TEXT NOT NULL,\" +\n \"public_key TEXT NOT NULL,\" +\n \"ip_address TEXT NOT NULL)\";\n statement.executeUpdate(createTableQuery);\n }\n }\n\n public int insertRecord(String name, String publicKey, String ipAddress) {\n\n if (isNameExists(name)) {\n return 1;\n }\n\n try (Connection connection = connect();\n Statement statement = connection.createStatement()) {\n String insertDataQuery = \"INSERT INTO known_peers (name, public_key, ip_address) VALUES \" +\n \"('\" + name + \"', '\" + publicKey + \"', '\" + ipAddress + \"')\";\n statement.executeUpdate(insertDataQuery);\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return 0;\n }\n\n public int insertRecord(Node node) {\n\n if (isNameExists(node.getUsername())) {\n return 1;\n }\n\n try (Connection connection = connect();\n Statement statement = connection.createStatement()) {\n String insertDataQuery = \"INSERT INTO known_peers (name, public_key, ip_address) VALUES \" +\n \"('\" + node.getUsername() + \"', '\" + node.getPubKeyStr() + \"', '\" + node.getIp() + \"')\";\n statement.executeUpdate(insertDataQuery);\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return 0;\n }\n\n public boolean isNameExists(String name) {\n try (Connection connection = connect();\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"SELECT COUNT(*) AS count FROM known_peers WHERE name = ?\")) {\n\n preparedStatement.setString(1, name);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n if (resultSet.next()) {\n int count = resultSet.getInt(\"count\");\n return count > 0;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return false;\n }\n\n public String lookupPublicKeyByName(String name) {\n try (Connection connection = connect();\n Statement statement = connection.createStatement()) {\n String query = \"SELECT public_key FROM known_peers WHERE name = '\" + name + \"'\";\n try (ResultSet resultSet = statement.executeQuery(query)) {\n if (resultSet.next()) {\n return resultSet.getString(\"public_key\");\n } else {\n return null; // Name not found\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public String lookupIPAddressByName(String name) {\n try (Connection connection = connect();\n Statement statement = connection.createStatement()) {\n String query = \"SELECT ip_address FROM known_peers WHERE name = '\" + name + \"'\";\n try (ResultSet resultSet = statement.executeQuery(query)) {\n if (resultSet.next()) {\n return resultSet.getString(\"ip_address\");\n } else {\n return null; // Name not found\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public String lookupNameByPublicKey(String publicKey) {\n try (Connection connection = connect();\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"SELECT name FROM known_peers WHERE public_key = ?\")) {\n\n preparedStatement.setString(1, publicKey);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n if (resultSet.next()) {\n return resultSet.getString(\"name\");\n } else {\n return null;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public List<String> getAllMatchingRows(String name) {\n List<String> matchingRows = new ArrayList<>();\n\n try (Connection connection = connect();\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"SELECT * FROM known_peers WHERE name = ?\")) {\n\n preparedStatement.setString(1, name);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n while (resultSet.next()) {\n String row = String.format(\"ID: %d, Name: %s, Public Key: %s, IP Address: %s\",\n resultSet.getInt(\"id\"),\n resultSet.getString(\"name\"),\n resultSet.getString(\"public_key\"),\n resultSet.getString(\"ip_address\"));\n matchingRows.add(row);\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return matchingRows;\n }\n\n public void deleteRowsByName(String name) {\n try (Connection connection = connect();\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"DELETE FROM known_peers WHERE name = ?\")) {\n\n preparedStatement.setString(1, name);\n preparedStatement.executeUpdate();\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n public List<Node> readAllNodes() {\n List<Node> allNodes = new ArrayList<>();\n\n try (Connection connection = connect();\n Statement statement = connection.createStatement();\n ResultSet resultSet = statement.executeQuery(\"SELECT * FROM known_peers\")) {\n\n while (resultSet.next()) {\n\n Node node = new Node(\n resultSet.getString(\"name\"),\n resultSet.getString(\"public_key\"),\n resultSet.getString(\"ip_address\"));\n\n allNodes.add(node);\n }\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return allNodes;\n }\n\n public byte[] serialize() {\n\n // get node list\n List<Node> nodeList = readAllNodes();\n\n try {\n ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);\n\n // write to object stream\n objectStream.writeObject(nodeList);\n\n // get byte array\n return byteStream.toByteArray();\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n // Deserialize byte[] to List<Node>\n public void mergeDatabase(byte[] nodesSerial) {\n\n try {\n ByteArrayInputStream byteStream = new ByteArrayInputStream(nodesSerial);\n ObjectInputStream objectStream = new ObjectInputStream(byteStream);\n\n // Read the List<Node> from the ObjectInputStream\n\n for (Node node : (List<Node>) objectStream.readObject()) {\n\n // check if node exists already\n if (!isNameExists(node.getUsername())) {\n\n // insert if does not exist\n insertRecord(node);\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n }\n\n}"
}
] | import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
import javax.crypto.Cipher;
import backend.crypt.KeyGen;
import network.NTPTimeService;
import network.PeersDatabase; | 3,835 | package backend.blockchain;
public class PrivateMsg implements Block {
private static final long serialVersionUID = 123456789L;
private NTPTimeService timeService; // for contacting time server
// header includes recipient, sender, time, msgtype
public BlockHeader header;
private String prevHash;
private String hash;
private String storedSignature; // sig encoded as string Base64
private String data;
private String sender;
private String recipient;
// ######################
// constructor
// ######################
public PrivateMsg(String previousHash, String data, BlockHeader header, PrivateKey privKey) {
this.header = header;
this.prevHash = previousHash;
this.hash = currentHash();
this.storedSignature = signBlock(privKey);
this.data = encrypt(data, privKey, header.getRecipient());
}
// ######################
// header functions
// ######################
@Override
public void genHeader(String recipientString, String msgType, String sender) {
header = new BlockHeader(
timeService.getNTPDate().getTime(),
recipientString,
msgType,
sender);
}
@Override
public BlockHeader readHeader() {
return header;
}
// ######################
// Block functions
// ######################
// encrypt message to sender
private String encrypt(String data, PrivateKey privKey, String recipient) {
// find user public key in string format
PeersDatabase db = new PeersDatabase();
String recipientPubKeyStr = db.lookupPublicKeyByName(recipient);
// convert string to a public key object | package backend.blockchain;
public class PrivateMsg implements Block {
private static final long serialVersionUID = 123456789L;
private NTPTimeService timeService; // for contacting time server
// header includes recipient, sender, time, msgtype
public BlockHeader header;
private String prevHash;
private String hash;
private String storedSignature; // sig encoded as string Base64
private String data;
private String sender;
private String recipient;
// ######################
// constructor
// ######################
public PrivateMsg(String previousHash, String data, BlockHeader header, PrivateKey privKey) {
this.header = header;
this.prevHash = previousHash;
this.hash = currentHash();
this.storedSignature = signBlock(privKey);
this.data = encrypt(data, privKey, header.getRecipient());
}
// ######################
// header functions
// ######################
@Override
public void genHeader(String recipientString, String msgType, String sender) {
header = new BlockHeader(
timeService.getNTPDate().getTime(),
recipientString,
msgType,
sender);
}
@Override
public BlockHeader readHeader() {
return header;
}
// ######################
// Block functions
// ######################
// encrypt message to sender
private String encrypt(String data, PrivateKey privKey, String recipient) {
// find user public key in string format
PeersDatabase db = new PeersDatabase();
String recipientPubKeyStr = db.lookupPublicKeyByName(recipient);
// convert string to a public key object | KeyGen keys = new KeyGen(); | 0 | 2023-10-28 06:29:00+00:00 | 8k |
nailuj1992/OracionesCatolicas | app/src/main/java/com/prayers/app/activity/rosary/RosaryApostlesCreedActivity.java | [
{
"identifier": "AbstractClosableActivity",
"path": "app/src/main/java/com/prayers/app/activity/AbstractClosableActivity.java",
"snippet": "public abstract class AbstractClosableActivity extends AbstractActivity {\n\n private Button btnHome;\n\n /**\n * Prepare all view fields.\n */\n public abstract void prepareOthersActivity();\n\n @Override\n public final void prepareActivity() {\n btnHome = (Button) findViewById(R.id.btn_home);\n btnHome.setOnClickListener(v -> gotoHome());\n\n prepareOthersActivity();\n }\n\n /**\n * Goes to main activity.\n */\n private final void gotoHome() {\n String txtCloseDialog = getString(R.string.txt_close_dialog);\n String txtYesChoice = getString(R.string.txt_yes_choice);\n String txtNoChoice = getString(R.string.txt_no_choice);\n CloseDialogFragment dialog = CloseDialogFragment.newInstance(txtCloseDialog, txtYesChoice, txtNoChoice);\n dialog.show(getSupportFragmentManager(), \"closeDialog\");\n }\n\n protected final void redirectToHome() {\n FieldsUtils.toastMakeTest(getApplicationContext(), getResources().getText(R.string.title_home));\n RedirectionUtils.redirectToAnotherActivity(this, MainActivity.class);\n }\n\n public void doPositiveClick() {\n redirectToHome();\n }\n\n public void doNegativeClick() {\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": "RedirectionConstants",
"path": "app/src/main/java/com/prayers/app/constants/RedirectionConstants.java",
"snippet": "public class RedirectionConstants {\n\n public static final String SELECTED_MYSTERIES = \"SELECTED_MYSTERIES\";\n public static final String SELECTED_MYSTERY = \"SELECTED_MYSTERY\";\n public static final String SELECTED_NINTH_DAY = \"SELECTED_NINTH_DAY\";\n public static final String HAIL_MARY_TYPE = \"HAIL_MARY_TYPE\";\n public static final String HAIL_MARY_FROM_END = \"HAIL_MARY_FROM_END\";\n public static final String GLORY_BE_FROM_END = \"GLORY_BE_FROM_END\";\n public static final String JOYS_FROM_END = \"JOYS_FROM_END\";\n\n private RedirectionConstants() {\n }\n\n}"
},
{
"identifier": "RosaryMapper",
"path": "app/src/main/java/com/prayers/app/mapper/RosaryMapper.java",
"snippet": "public class RosaryMapper {\n\n public static Mysteries prepopulateJoyfulMysteries(AbstractActivity activity, String reflection, String pause) throws PrayersException {\n Mystery first = new Mystery(GeneralConstants.FIRST_MYSTERY, activity.getString(R.string.txt_rosary_joyful_1), reflection, activity.getString(R.string.txt_rosary_joyful_1_paragrafh_1), activity.getString(R.string.txt_rosary_joyful_1_paragrafh_2), pause);\n Mystery second = new Mystery(GeneralConstants.SECOND_MYSTERY, activity.getString(R.string.txt_rosary_joyful_2), reflection, activity.getString(R.string.txt_rosary_joyful_2_paragrafh_1), activity.getString(R.string.txt_rosary_joyful_2_paragrafh_2), pause);\n Mystery third = new Mystery(GeneralConstants.THIRD_MYSTERY, activity.getString(R.string.txt_rosary_joyful_3), reflection, activity.getString(R.string.txt_rosary_joyful_3_paragrafh_1), activity.getString(R.string.txt_rosary_joyful_3_paragrafh_2), pause);\n Mystery fourth = new Mystery(GeneralConstants.FOURTH_MYSTERY, activity.getString(R.string.txt_rosary_joyful_4), reflection, activity.getString(R.string.txt_rosary_joyful_4_paragrafh_1), activity.getString(R.string.txt_rosary_joyful_4_paragrafh_2), pause, activity.getString(R.string.txt_rosary_joyful_4_paragrafh_3));\n Mystery fifth = new Mystery(GeneralConstants.FIFTH_MYSTERY, activity.getString(R.string.txt_rosary_joyful_5), reflection, activity.getString(R.string.txt_rosary_joyful_5_paragrafh_1), activity.getString(R.string.txt_rosary_joyful_5_paragrafh_2), pause);\n\n return new Mysteries(GeneralConstants.JOYFUL_MYSTERIES, activity.getString(R.string.title_rosary_joyful), activity.getString(R.string.title_rosary_joyful_only_days), first, second, third, fourth, fifth);\n }\n\n public static Mysteries prepopulateSorrowfulMysteries(AbstractActivity activity, String reflection, String pause) throws PrayersException {\n Mystery first = new Mystery(GeneralConstants.FIRST_MYSTERY, activity.getString(R.string.txt_rosary_sorrowful_1), reflection, activity.getString(R.string.txt_rosary_sorrowful_1_paragrafh_1), activity.getString(R.string.txt_rosary_sorrowful_1_paragrafh_2), pause);\n Mystery second = new Mystery(GeneralConstants.SECOND_MYSTERY, activity.getString(R.string.txt_rosary_sorrowful_2), reflection, activity.getString(R.string.txt_rosary_sorrowful_2_paragrafh_1), activity.getString(R.string.txt_rosary_sorrowful_2_paragrafh_2), pause);\n Mystery third = new Mystery(GeneralConstants.THIRD_MYSTERY, activity.getString(R.string.txt_rosary_sorrowful_3), reflection, activity.getString(R.string.txt_rosary_sorrowful_3_paragrafh_1), pause);\n Mystery fourth = new Mystery(GeneralConstants.FOURTH_MYSTERY, activity.getString(R.string.txt_rosary_sorrowful_4), reflection, activity.getString(R.string.txt_rosary_sorrowful_4_paragrafh_1), activity.getString(R.string.txt_rosary_sorrowful_4_paragrafh_2), pause);\n Mystery fifth = new Mystery(GeneralConstants.FIFTH_MYSTERY, activity.getString(R.string.txt_rosary_sorrowful_5), reflection, activity.getString(R.string.txt_rosary_sorrowful_5_paragrafh_1), activity.getString(R.string.txt_rosary_sorrowful_5_paragrafh_2), activity.getString(R.string.txt_rosary_sorrowful_5_paragrafh_3), pause);\n\n return new Mysteries(GeneralConstants.SORROWFUL_MYSTERIES, activity.getString(R.string.title_rosary_sorrowful), activity.getString(R.string.title_rosary_sorrowful_only_days), first, second, third, fourth, fifth);\n }\n\n public static Mysteries prepopulateGloriousMysteries(AbstractActivity activity, String reflection, String pause) throws PrayersException {\n Mystery first = new Mystery(GeneralConstants.FIRST_MYSTERY, activity.getString(R.string.txt_rosary_glorious_1), reflection, activity.getString(R.string.txt_rosary_glorious_1_paragrafh_1), activity.getString(R.string.txt_rosary_glorious_1_paragrafh_2), pause);\n Mystery second = new Mystery(GeneralConstants.SECOND_MYSTERY, activity.getString(R.string.txt_rosary_glorious_2), reflection, activity.getString(R.string.txt_rosary_glorious_2_paragrafh_1), activity.getString(R.string.txt_rosary_glorious_2_paragrafh_2), pause);\n Mystery third = new Mystery(GeneralConstants.THIRD_MYSTERY, activity.getString(R.string.txt_rosary_glorious_3), reflection, activity.getString(R.string.txt_rosary_glorious_3_paragrafh_1), activity.getString(R.string.txt_rosary_glorious_3_paragrafh_2), pause);\n Mystery fourth = new Mystery(GeneralConstants.FOURTH_MYSTERY, activity.getString(R.string.txt_rosary_glorious_4), reflection, activity.getString(R.string.txt_rosary_glorious_4_paragrafh_1), activity.getString(R.string.txt_rosary_glorious_4_paragrafh_2), activity.getString(R.string.txt_rosary_glorious_4_paragrafh_3), pause);\n Mystery fifth = new Mystery(GeneralConstants.FIFTH_MYSTERY, activity.getString(R.string.txt_rosary_glorious_5), reflection, activity.getString(R.string.txt_rosary_glorious_5_paragrafh_1), activity.getString(R.string.txt_rosary_glorious_5_paragrafh_2), activity.getString(R.string.txt_rosary_glorious_5_paragrafh_3), pause);\n\n return new Mysteries(GeneralConstants.GLORIOUS_MYSTERIES, activity.getString(R.string.title_rosary_glorious), activity.getString(R.string.title_rosary_glorious_only_days), first, second, third, fourth, fifth);\n }\n\n public static Mysteries prepopulateLuminousMysteries(AbstractActivity activity, String reflection, String pause) throws PrayersException {\n Mystery first = new Mystery(GeneralConstants.FIRST_MYSTERY, activity.getString(R.string.txt_rosary_luminous_1), reflection, activity.getString(R.string.txt_rosary_luminous_1_paragrafh_1), activity.getString(R.string.txt_rosary_luminous_1_paragrafh_2), pause);\n Mystery second = new Mystery(GeneralConstants.SECOND_MYSTERY, activity.getString(R.string.txt_rosary_luminous_2), reflection, activity.getString(R.string.txt_rosary_luminous_2_paragrafh_1), activity.getString(R.string.txt_rosary_luminous_2_paragrafh_2), activity.getString(R.string.txt_rosary_luminous_2_paragrafh_3), pause);\n Mystery third = new Mystery(GeneralConstants.THIRD_MYSTERY, activity.getString(R.string.txt_rosary_luminous_3), reflection, activity.getString(R.string.txt_rosary_luminous_3_paragrafh_1), activity.getString(R.string.txt_rosary_luminous_3_paragrafh_2), activity.getString(R.string.txt_rosary_luminous_3_paragrafh_3), activity.getString(R.string.txt_rosary_luminous_3_paragrafh_4), pause);\n Mystery fourth = new Mystery(GeneralConstants.FOURTH_MYSTERY, activity.getString(R.string.txt_rosary_luminous_4), reflection, activity.getString(R.string.txt_rosary_luminous_4_paragrafh_1), activity.getString(R.string.txt_rosary_luminous_4_paragrafh_2), pause);\n Mystery fifth = new Mystery(GeneralConstants.FIFTH_MYSTERY, activity.getString(R.string.txt_rosary_luminous_5), reflection, activity.getString(R.string.txt_rosary_luminous_5_paragrafh_1), activity.getString(R.string.txt_rosary_luminous_5_paragrafh_2), pause);\n\n return new Mysteries(GeneralConstants.LUMINOUS_MYSTERIES, activity.getString(R.string.title_rosary_luminous), activity.getString(R.string.title_rosary_luminous_only_days), first, second, third, fourth, fifth);\n }\n\n public static void changeImageForRosary(AbstractActivity activity, Mysteries selectedMysteries, ImageView imgMysteriesBackground) {\n int orientation = activity.getResources().getConfiguration().orientation;\n if (orientation == Configuration.ORIENTATION_LANDSCAPE) {\n switch (selectedMysteries.getValue()) {\n case GeneralConstants.JOYFUL_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.joyful_horiz);\n break;\n case GeneralConstants.SORROWFUL_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.sorrowful_horiz);\n break;\n case GeneralConstants.GLORIOUS_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.glorious_horiz);\n break;\n case GeneralConstants.LUMINOUS_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.luminous_horiz);\n break;\n }\n } else {\n switch (selectedMysteries.getValue()) {\n case GeneralConstants.JOYFUL_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.joyful_vert);\n break;\n case GeneralConstants.SORROWFUL_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.sorrowful_vert);\n break;\n case GeneralConstants.GLORIOUS_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.glorious_vert);\n break;\n case GeneralConstants.LUMINOUS_MYSTERIES:\n imgMysteriesBackground.setImageResource(R.mipmap.luminous_vert);\n break;\n }\n }\n }\n\n public static String getCurrentMysteryLocation(AbstractActivity activity, int currentMysteries, Mystery selectedMystery) {\n String ordinal = activity.getString(R.string.txt_blank);\n switch (selectedMystery.getValue()) {\n case GeneralConstants.FIRST_MYSTERY:\n ordinal = activity.getString(R.string.txt_first);\n break;\n case GeneralConstants.SECOND_MYSTERY:\n ordinal = activity.getString(R.string.txt_second);\n break;\n case GeneralConstants.THIRD_MYSTERY:\n ordinal = activity.getString(R.string.txt_third);\n break;\n case GeneralConstants.FOURTH_MYSTERY:\n ordinal = activity.getString(R.string.txt_fourth);\n break;\n case GeneralConstants.FIFTH_MYSTERY:\n ordinal = activity.getString(R.string.txt_fifth);\n break;\n }\n\n String mystery = activity.getString(R.string.txt_blank);\n switch (currentMysteries) {\n case GeneralConstants.JOYFUL_MYSTERIES:\n mystery = activity.getString(R.string.txt_rosary_joyful_mystery_single);\n break;\n case GeneralConstants.SORROWFUL_MYSTERIES:\n mystery = activity.getString(R.string.txt_rosary_sorrowful_mystery_single);\n break;\n case GeneralConstants.GLORIOUS_MYSTERIES:\n mystery = activity.getString(R.string.txt_rosary_glorious_mystery_single);\n break;\n case GeneralConstants.LUMINOUS_MYSTERIES:\n mystery = activity.getString(R.string.txt_rosary_luminous_mystery_single);\n break;\n }\n return String.format(\"%s %s\", ordinal, mystery);\n }\n\n public static int getCurrentMysteryHailMaryImg(Mystery selectedMystery, HailMary hailMary) {\n if (selectedMystery == null) {\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_6_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_6_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_6_3;\n }\n }\n switch (selectedMystery.getValue()) {\n case GeneralConstants.FIRST_MYSTERY:\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_1_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_1_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_1_3;\n case GeneralConstants.HAIL_MARY_4:\n return R.mipmap.rosary_1_4;\n case GeneralConstants.HAIL_MARY_5:\n return R.mipmap.rosary_1_5;\n case GeneralConstants.HAIL_MARY_6:\n return R.mipmap.rosary_1_6;\n case GeneralConstants.HAIL_MARY_7:\n return R.mipmap.rosary_1_7;\n case GeneralConstants.HAIL_MARY_8:\n return R.mipmap.rosary_1_8;\n case GeneralConstants.HAIL_MARY_9:\n return R.mipmap.rosary_1_9;\n case GeneralConstants.HAIL_MARY_10:\n return R.mipmap.rosary_1_10;\n }\n case GeneralConstants.SECOND_MYSTERY:\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_2_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_2_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_2_3;\n case GeneralConstants.HAIL_MARY_4:\n return R.mipmap.rosary_2_4;\n case GeneralConstants.HAIL_MARY_5:\n return R.mipmap.rosary_2_5;\n case GeneralConstants.HAIL_MARY_6:\n return R.mipmap.rosary_2_6;\n case GeneralConstants.HAIL_MARY_7:\n return R.mipmap.rosary_2_7;\n case GeneralConstants.HAIL_MARY_8:\n return R.mipmap.rosary_2_8;\n case GeneralConstants.HAIL_MARY_9:\n return R.mipmap.rosary_2_9;\n case GeneralConstants.HAIL_MARY_10:\n return R.mipmap.rosary_2_10;\n }\n case GeneralConstants.THIRD_MYSTERY:\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_3_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_3_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_3_3;\n case GeneralConstants.HAIL_MARY_4:\n return R.mipmap.rosary_3_4;\n case GeneralConstants.HAIL_MARY_5:\n return R.mipmap.rosary_3_5;\n case GeneralConstants.HAIL_MARY_6:\n return R.mipmap.rosary_3_6;\n case GeneralConstants.HAIL_MARY_7:\n return R.mipmap.rosary_3_7;\n case GeneralConstants.HAIL_MARY_8:\n return R.mipmap.rosary_3_8;\n case GeneralConstants.HAIL_MARY_9:\n return R.mipmap.rosary_3_9;\n case GeneralConstants.HAIL_MARY_10:\n return R.mipmap.rosary_3_10;\n }\n case GeneralConstants.FOURTH_MYSTERY:\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_4_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_4_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_4_3;\n case GeneralConstants.HAIL_MARY_4:\n return R.mipmap.rosary_4_4;\n case GeneralConstants.HAIL_MARY_5:\n return R.mipmap.rosary_4_5;\n case GeneralConstants.HAIL_MARY_6:\n return R.mipmap.rosary_4_6;\n case GeneralConstants.HAIL_MARY_7:\n return R.mipmap.rosary_4_7;\n case GeneralConstants.HAIL_MARY_8:\n return R.mipmap.rosary_4_8;\n case GeneralConstants.HAIL_MARY_9:\n return R.mipmap.rosary_4_9;\n case GeneralConstants.HAIL_MARY_10:\n return R.mipmap.rosary_4_10;\n }\n case GeneralConstants.FIFTH_MYSTERY:\n switch (hailMary.getCurrent()) {\n case GeneralConstants.MIN_HAIL_MARY:\n return R.mipmap.rosary_5_1;\n case GeneralConstants.HAIL_MARY_2:\n return R.mipmap.rosary_5_2;\n case GeneralConstants.HAIL_MARY_3:\n return R.mipmap.rosary_5_3;\n case GeneralConstants.HAIL_MARY_4:\n return R.mipmap.rosary_5_4;\n case GeneralConstants.HAIL_MARY_5:\n return R.mipmap.rosary_5_5;\n case GeneralConstants.HAIL_MARY_6:\n return R.mipmap.rosary_5_6;\n case GeneralConstants.HAIL_MARY_7:\n return R.mipmap.rosary_5_7;\n case GeneralConstants.HAIL_MARY_8:\n return R.mipmap.rosary_5_8;\n case GeneralConstants.HAIL_MARY_9:\n return R.mipmap.rosary_5_9;\n case GeneralConstants.HAIL_MARY_10:\n return R.mipmap.rosary_5_10;\n }\n }\n return R.mipmap.rosary_empty;\n }\n\n public static int getCurrentMysteryGloryBeImg(Mystery selectedMystery) {\n if (selectedMystery != null) {\n switch (selectedMystery.getValue()) {\n case GeneralConstants.FIRST_MYSTERY:\n return R.mipmap.rosary_1_11;\n case GeneralConstants.SECOND_MYSTERY:\n return R.mipmap.rosary_2_11;\n case GeneralConstants.THIRD_MYSTERY:\n return R.mipmap.rosary_3_11;\n case GeneralConstants.FOURTH_MYSTERY:\n return R.mipmap.rosary_4_11;\n case GeneralConstants.FIFTH_MYSTERY:\n return R.mipmap.rosary_5_11;\n }\n } else {\n return R.mipmap.rosary_6_4;\n }\n return R.mipmap.rosary_empty;\n }\n\n public static int getCurrentMysteryOurFatherImg(Mystery selectedMystery) {\n if (selectedMystery != null) {\n return R.mipmap.rosary_empty;\n } else {\n return R.mipmap.rosary_6_0;\n }\n }\n\n}"
},
{
"identifier": "Mysteries",
"path": "app/src/main/java/com/prayers/app/model/rosary/Mysteries.java",
"snippet": "public class Mysteries implements Serializable {\n\n private int value;\n private String name;\n private String schedule;\n private Mystery[] mysteries;\n\n public Mysteries(int value, String name, String schedule, Mystery... mysteries) throws PrayersException {\n setValue(value);\n setName(name);\n setSchedule(schedule);\n setMysteries(mysteries);\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 Mystery[] getMysteries() {\n if (mysteries == null) {\n mysteries = new Mystery[GeneralConstants.MAX_MYSTERIES];\n }\n return mysteries;\n }\n\n public void setMysteries(Mystery... mysteries) throws PrayersException {\n if (mysteries == null || mysteries.length != GeneralConstants.MAX_MYSTERIES) {\n throw new PrayersException(GeneralConstants.MYSTERIES_ITEMS_LENGTH_5);\n }\n this.mysteries = mysteries;\n }\n\n}"
},
{
"identifier": "FieldsUtils",
"path": "app/src/main/java/com/prayers/app/utils/FieldsUtils.java",
"snippet": "public class FieldsUtils {\n\n private FieldsUtils() {\n }\n\n public static void justifyText(TextView textView) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n textView.setJustificationMode(LineBreaker.JUSTIFICATION_MODE_INTER_WORD);\n }\n }\n\n public static RecyclerView configureRecyclerView(AbstractActivity activity, int viewId) {\n RecyclerView view_paragraphs = (RecyclerView) activity.findViewById(viewId);\n view_paragraphs.setHasFixedSize(true);\n RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity.getApplicationContext());\n view_paragraphs.setLayoutManager(layoutManager);\n return view_paragraphs;\n }\n\n public static void toastMakeTest(Context context, CharSequence string) {\n Toast.makeText(context, string, Toast.LENGTH_SHORT).show();\n }\n\n public static void toastMakeTest(Context context, String string) {\n Toast.makeText(context, string, Toast.LENGTH_SHORT).show();\n }\n\n}"
},
{
"identifier": "RedirectionUtils",
"path": "app/src/main/java/com/prayers/app/utils/RedirectionUtils.java",
"snippet": "public class RedirectionUtils {\n\n private RedirectionUtils() {\n }\n\n public static void redirectToAnotherActivity(Activity activity, Class<? extends Activity> clazz) {\n Intent intent = new Intent(activity, clazz);\n activity.startActivity(intent);\n activity.finish();\n }\n\n public static void redirectToAnotherActivityWithExtras(Activity activity, Bundle bundle, Class<? extends Activity> clazz) {\n Intent intent = new Intent(activity, clazz);\n intent.putExtras(bundle);\n activity.startActivity(intent);\n activity.finish();\n }\n\n}"
}
] | import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.prayers.app.activity.AbstractClosableActivity;
import com.prayers.app.activity.R;
import com.prayers.app.constants.GeneralConstants;
import com.prayers.app.constants.RedirectionConstants;
import com.prayers.app.mapper.RosaryMapper;
import com.prayers.app.model.rosary.Mysteries;
import com.prayers.app.utils.FieldsUtils;
import com.prayers.app.utils.RedirectionUtils; | 7,099 | package com.prayers.app.activity.rosary;
public class RosaryApostlesCreedActivity extends AbstractClosableActivity {
private Mysteries selectedMysteries;
private ImageView imgMysteriesBackground;
private TextView txtApostlesCreed1;
private TextView txtApostlesCreed2;
private Button btnPrev;
private Button btnNext;
@Override
public int getActivity() {
return R.layout.rosary_apostles_creed_activity;
}
@Override
public void prepareOthersActivity() {
imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background);
txtApostlesCreed1 = (TextView) findViewById(R.id.txt_apostles_creed_1);
FieldsUtils.justifyText(txtApostlesCreed1);
txtApostlesCreed2 = (TextView) findViewById(R.id.txt_apostles_creed_2);
FieldsUtils.justifyText(txtApostlesCreed2);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnNext = (Button) findViewById(R.id.btn_next);
btnNext.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
try {
selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES);
RosaryMapper.changeImageForRosary(this, selectedMysteries, imgMysteriesBackground);
} catch (Exception ex) {
// TODO Log exception
}
}
@Override
public void backAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries);
RedirectionUtils.redirectToAnotherActivityWithExtras(this, bundle, RosaryBeginActivity.class);
}
@Override
public void nextAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries); | package com.prayers.app.activity.rosary;
public class RosaryApostlesCreedActivity extends AbstractClosableActivity {
private Mysteries selectedMysteries;
private ImageView imgMysteriesBackground;
private TextView txtApostlesCreed1;
private TextView txtApostlesCreed2;
private Button btnPrev;
private Button btnNext;
@Override
public int getActivity() {
return R.layout.rosary_apostles_creed_activity;
}
@Override
public void prepareOthersActivity() {
imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background);
txtApostlesCreed1 = (TextView) findViewById(R.id.txt_apostles_creed_1);
FieldsUtils.justifyText(txtApostlesCreed1);
txtApostlesCreed2 = (TextView) findViewById(R.id.txt_apostles_creed_2);
FieldsUtils.justifyText(txtApostlesCreed2);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnNext = (Button) findViewById(R.id.btn_next);
btnNext.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
try {
selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES);
RosaryMapper.changeImageForRosary(this, selectedMysteries, imgMysteriesBackground);
} catch (Exception ex) {
// TODO Log exception
}
}
@Override
public void backAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries);
RedirectionUtils.redirectToAnotherActivityWithExtras(this, bundle, RosaryBeginActivity.class);
}
@Override
public void nextAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries); | bundle.putInt(RedirectionConstants.SELECTED_MYSTERY, GeneralConstants.FIRST_MYSTERY); | 1 | 2023-10-25 17:17:47+00:00 | 8k |
LeoK99/swtw45WS21_reupload | src/main/java/com/buschmais/Application.java | [
{
"identifier": "ADR",
"path": "backup/java/com/buschmais/adr/ADR.java",
"snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRContainer parent;\n\n\[email protected]\n\t@Indexed\n\tprivate String name;\n\n\[email protected]\n\t@Indexed\n\tprivate String title;\n\n\[email protected]\n\tprivate String content;\n\n\[email protected]\n\tprivate String decision;\n\n\[email protected]\n\tprivate String consequences;\n\n\[email protected]\n\t@Indexed\n\tprivate ADRStatus sts;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@Indexed\n\tprivate List<ADRTag> tags;\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate List<ExternalContent> externalContents;\n\n\t@Setter(AccessLevel.PRIVATE)\n\tprivate List<ADRComment> comments;\n\n\tprivate ADR(){}\n\n\tpublic ADR(@NonNull final ADRContainer parent,\n\t\t\t @NonNull final String name,\n\t\t\t @NonNull final ADRStatus sts){\n\n\t\tthis.parent = parent;\n\t\tthis.name = name.trim();\n\t\tthis.sts = sts;\n\t\tthis.tags = new ArrayList<>();\n\t\tthis.externalContents = new ArrayList<>();\n\t\tthis.comments = new ArrayList<>();\n\t}\n\n\tpublic boolean addTag(@NonNull final ADRTag tag){\n\t\treturn tags.add(tag);\n\t}\n\n\tpublic boolean removeTag(@NonNull final ADRTag tag){\n\t\treturn tags.remove(tag);\n\t}\n\n\tpublic boolean addExternalContent(@NonNull final ExternalContent content){\n\t\treturn externalContents.add(content);\n\t}\n\n\tpublic boolean removeExternalContent(@NonNull final ExternalContent content){\n\t\treturn externalContents.remove(content);\n\t}\n\n\tpublic boolean addADRComment(@NonNull final ADRComment comment){\n\t\treturn comments.remove(comment);\n\t}\n\n\tpublic boolean removeADRComment(@NonNull final ADRComment comment){\n\t\treturn comments.remove(comment);\n\t}\n\n\tpublic ADRPath getParentPath(){\n\t\treturn parent.getFullPath();\n\t}\n\n\tpublic ADRPath getFullPath(){\n\t\treturn getParentPath().add(name);\n\t}\n}"
},
{
"identifier": "ADRContainer",
"path": "backup/java/com/buschmais/adr/ADRContainer.java",
"snippet": "@Data\n@Document\npublic class ADRContainer {\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\[email protected]\n\tprivate String name;\n\n\t@DBRef\n\tprivate ADRContainer parent;\n\n\tprivate ADRContainer(){}\n\n\tpublic ADRContainer(@NonNull final String name){\n\t\tthis.parent = null;\n\t\tthis.name = name.trim();\n\t}\n\tpublic ADRContainer(@NonNull final ADRContainer parent,\n\t\t\t\t\t\t@NonNull final String name){\n\t\tthis.parent = parent;\n\t\tthis.name = name.trim();\n\t}\n\n\tpublic ADRPath getParentPath(){\n\t\treturn parent.getFullPath();\n\t}\n\n\tpublic ADRPath getFullPath(){\n\t\treturn getParentPath().add(name);\n\t}\n}"
},
{
"identifier": "ADRContainerRepository",
"path": "backup/java/com/buschmais/adr/ADRContainerRepository.java",
"snippet": "public interface ADRContainerRepository extends MongoRepository<ADRContainer, String> {\n\n\tList<ADRContainer> findAllByName(String name);\n\tOptional<ADRContainer> findByFullPath(ADRPath path);\n\tList<ADRContainer> findAllByParentPath(ADRPath folderPath);\n\n\tvoid deleteByFullPath(ADRPath path);\n\tvoid deleteAllByParentPath(ADRPath parentPath);\n}"
},
{
"identifier": "ADRDao",
"path": "src/main/java/com/buschmais/backend/adr/dataAccess/ADRDao.java",
"snippet": "@Service\npublic class ADRDao {\n\n\tprivate final ADRRepository repo;\n\tprivate final MongoOperations mongoOperations;\n\n\tADRDao(@Autowired ADRRepository repo,\n\t\t @Autowired MongoOperations mongoOperations){\n\t\tthis.repo = repo;\n\t\tthis.mongoOperations = mongoOperations;\n\t}\n\n\tpublic List<ADR> findAll() {\n\t\treturn this.repo.findAll();\n\t}\n\n\tpublic Optional<ADR> findById(String id) {\n\t\treturn repo.findById(id);\n\t}\n\n\tpublic List<ADR> findAllByName(String name) {\n\t\treturn repo.findAllByName(name);\n\t}\n\n\tpublic List<ADR> findAllByAuthor(User author) {\n\t\treturn repo.findAllByAuthor(author);\n\t}\n\n\tpublic Optional<ADR> findByFullPath(ADRPath path) {\n\t\treturn repo.findByFullPath(path);\n\t}\n\n\tpublic List<ADR> findAllByParentPath(ADRPath folderPath) {\n\t\treturn repo.findAllByParentPath(folderPath);\n\t}\n\n\tpublic List<ADR> findAllByStatus(ADRStatus status) {\n\t\treturn repo.findAllByStatus(status);\n\t}\n\n\tpublic List<ADR> findAllByStatusType(ADRStatusType statusType) {\n\t\treturn repo.findAllByStatusType(statusType);\n\t}\n\n\tpublic List<ADR> findAllRelevantByStatusType(ADRStatusType statusType, int number) {\n\t\tList<ADR> adrs = repo.findAllByStatusType(statusType);\n\n\t\tif(adrs.isEmpty()) return adrs;\n\n\t\tadrs.sort((a1, a2) -> a2.getTimeStamp().compareTo(a1.getTimeStamp()));\n\t\tnumber = Math.max(0, number);\n\t\tint endIndex = Math.min(number, adrs.size());\n\n\t\treturn adrs.subList(0, endIndex);\n\t}\n\n\tpublic List<ADR> findAllByTagsIsContaining(List<ADRTag> tags) {\n\t\treturn repo.findAllByTagsIsContaining(tags);\n\t}\n\n\tpublic List<ADR> findAllByTitle(String title) {\n\t\treturn repo.findAllByTitle(title);\n\t}\n\n\tpublic void deleteAll() {\n\t\trepo.deleteAll();\n\t}\n\n\tpublic ADR save(@NonNull final ADR adr) {\n\t\tadr.setTimeStamp(Instant.now());\n\t\treturn repo.save(adr);\n\t}\n\n\tpublic void deleteByFullPath(ADRPath path) {\n\t\trepo.deleteByFullPath(path);\n\t}\n\n\tpublic void deleteAllByParentPath(ADRPath parentPath) {\n\t\trepo.deleteAllByParentPath(parentPath);\n\t}\n\n\tpublic List<ADRTag> findAllTagsMatchRegex(@NonNull String regex){\n\t\tif (regex.isEmpty()) {\n\t\t\treturn repo.findAll()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.map(ADR::getTags)\n\t\t\t\t\t.flatMap(List::stream)\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t}\n\n\t\tQuery q = new Query();\n\t\tq.addCriteria(Criteria.where(\"tags\").elemMatch(Criteria.where(\"tagText\").regex(regex)));\n\t\tList<ADR> found = mongoOperations.find(q, ADR.class);\n\n\t\tPattern p = Pattern.compile(regex);\n\n\t\treturn found.stream()\n\t\t\t\t.map(ADR::getTags)\n\t\t\t\t.flatMap(List::stream)\n\t\t\t\t.filter(t -> p.matcher(t.getTagText()).find())\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\n\tpublic List<String> findAllPathsAsStrings(){\n\t\treturn repo.findAll()\n\t\t\t\t.stream()\n\t\t\t\t.map(adr -> adr.getFullPath().toString())\n\t\t\t\t.toList();\n\t}\n}"
},
{
"identifier": "ADRStatusApproved",
"path": "backup/java/com/buschmais/adr/status/ADRStatusApproved.java",
"snippet": "public class ADRStatusApproved implements ADRStatus {\n\t@Override\n\tpublic ADRStatusType getType() {\n\t\treturn ADRStatusType.APPROVED;\n\t}\n}"
},
{
"identifier": "ADRStatusProposed",
"path": "backup/java/com/buschmais/adr/status/ADRStatusProposed.java",
"snippet": "public class ADRStatusProposed implements ADRStatus {\n\n\t@Override\n\tpublic ADRStatusType getType() {\n\t\treturn ADRStatusType.PROPOSED;\n\t}\n}"
},
{
"identifier": "ADRStatusSuperseded",
"path": "backup/java/com/buschmais/adr/status/ADRStatusSuperseded.java",
"snippet": "public class ADRStatusSuperseded implements ADRStatus{\n\t@Override\n\tpublic ADRStatusType getType() {\n\t\treturn ADRStatusType.SUPERSEDED;\n\t}\n}"
},
{
"identifier": "AccessGroup",
"path": "src/main/java/com/buschmais/backend/adrAccess/AccessGroup.java",
"snippet": "@Document\n@Data\npublic class AccessGroup implements Comparable<AccessGroup> {\n\n\t@Setter(AccessLevel.PRIVATE)\n\[email protected]\n\t@Id\n\tprivate String id;\n\n\t@Indexed\n\t@NonNull\n\t@Unique\n\tprivate String name;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@NonNull\n\t@DBRef\n\tprivate Set<User> users;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@NonNull\n\tprivate AccessRights rights;\n\n\t@PersistenceConstructor\n\tAccessGroup(@NonNull String name) {\n\t\tthis.name = name;\n\t\tthis.users = new HashSet<>();\n\t\tthis.rights = new AccessRights();\n\t}\n\n\tpublic AccessGroup(@NonNull String name, @NonNull AccessRights rights) {\n\t\tthis.name = name;\n\t\tthis.users = new HashSet<>();\n\t\tthis.rights = rights;\n\t}\n\n\tpublic AccessGroup(@NonNull String name, @NonNull AccessRights rights, @NonNull Collection<User> users) {\n\t\tthis.name = name;\n\t\tthis.users = new HashSet<>();\n\t\tthis.users.addAll(users);\n\t\tthis.rights = rights;\n\t}\n\n\t/**\n\t * Checks whether the User is contained in the AccessGroup or not\n\t * @param user the User for whom the group should be checked\n\t * @return true if the user is contained\n\t */\n\tpublic boolean containsUser(User user) {\n\t\treturn this.users.contains(user);\n\t}\n\n\t/**\n\t * Add User to AccessGroup\n\t * @param user the User to be added\n\t * @return true if eligible users changed\n\t */\n\tpublic boolean addUser(User user) {\n\t\treturn this.users.add(user);\n\t}\n\n\t/**\n\t * Add all Users contained in User Collection\n\t * @param users Collection of new users\n\t * @return true if eligible users changed\n\t */\n\tpublic boolean addUsers(Collection<User> users) {\n\t\treturn this.users.addAll(users);\n\t}\n\n\t/**\n\t * Remove User from AccessGroup\n\t * @param user the User to be removed\n\t * @return true if eligible users changed\n\t */\n\tpublic boolean removeUser(User user) {\n\t\treturn this.users.remove(user);\n\t}\n\n\t/**\n\t * Remove all Users contained in User Collection\n\t * @param users Collection of users to be removed\n\t * @return true if eligible users changed\n\t */\n\tpublic boolean removeUsers(Collection<User> users) {\n\t\treturn this.users.removeAll(users);\n\t}\n\n\t/**\n\t * Returns whether the user has at least the given rights\n\t * @param user the user which should be examined\n\t * @param rights the rights the user should have at least\n\t * @return true if the specific user has at least all the rights that are given by the AccessRights argument\n\t */\n\tpublic boolean hasAccessRights(User user, AccessRights rights) {\n\t\treturn this.users.contains(user) && this.rights.hasAtLeast(rights);\n\t}\n\n\t@Override\n\tpublic int compareTo(@NonNull AccessGroup g) {\n\t\treturn this.getName().compareTo(g.getName());\n\t}\n}"
},
{
"identifier": "AccessRights",
"path": "src/main/java/com/buschmais/backend/adrAccess/AccessRights.java",
"snippet": "@Data\npublic class AccessRights {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\tprivate int flags;\n\n\tpublic static final int READABLE = 0x01;\n\tpublic static final int WRITABLE = 0x02;\n\tpublic static final int VOTABLE = 0x04;\n\n\tpublic AccessRights(){\n\t\tthis.flags = 0;\n\t}\n\n\tpublic AccessRights(final int flags){\n\t\tthis.flags = flags;\n\t}\n\n\t/**\n\t * Creates a new AccessRights element with the given rights\n\t * @param read right to read an ADR (true/false)\n\t * @param write right to change attributes of an ADR (true/false)\n\t */\n\tpublic AccessRights(final boolean read, final boolean write) {\n\t\tthis.flags = ((read?1:0) * READABLE + (write?1:0) * WRITABLE);\n\t}\n\n\t/**\n\t * Creates a new AccessRights element with the given rights\n\t * @param read right to read an ADR (true/false)\n\t * @param write right to change attributes of an ADR (true/false)\n\t * @param vote if true, all users in the corresponding AccessGroup become automatically assigned to list of voters\n\t */\n\tpublic AccessRights(final boolean read, final boolean write, final boolean vote) {\n\t\tthis.flags = ((read?1:0) * READABLE + (write?1:0) * WRITABLE);\n\t}\n\n\n\tpublic void setReadable(final boolean val){\n\t\tif(val)\n\t\t\tthis.flags |= READABLE;\n\t\telse\n\t\t\tthis.flags &= ~READABLE;\n\t}\n\n\tpublic void setWritable(final boolean val){\n\t\tif(val)\n\t\t\tthis.flags |= WRITABLE;\n\t\telse\n\t\t\tthis.flags &= ~WRITABLE;\n\t}\n\n\tpublic void setVotable(final boolean val){\n\t\tif(val)\n\t\t\tthis.flags |= VOTABLE;\n\t\telse\n\t\t\tthis.flags &= ~VOTABLE;\n\t}\n\n\tpublic boolean hasAtLeast(AccessRights accessRights) {\n\t\treturn (this.flags & accessRights.flags) == accessRights.flags;\n\t}\n\n\tpublic boolean isReadable(){\n\t\treturn (flags & READABLE) != 0;\n\t}\n\n\tpublic boolean isWritable(){\n\t\treturn (flags & WRITABLE) != 0;\n\t}\n\n\tpublic boolean isVotable(){\n\t\treturn (flags & VOTABLE) != 0;\n\t}\n}"
},
{
"identifier": "ADRAccessDao",
"path": "src/main/java/com/buschmais/backend/adrAccess/dataAccess/ADRAccessDao.java",
"snippet": "@Service\npublic class ADRAccessDao {\n\n\tprivate final ADRAccessRepo repo;\n\n\tADRAccessDao(@Autowired ADRAccessRepo repo) {\n\t\tthis.repo = repo;\n\t}\n\n\tpublic List<AccessGroup> findAll() { return repo.findAll(); }\n\n\tpublic Optional<AccessGroup> findById(@NonNull String id) {\n\t\treturn repo.findById(id);\n\t}\n\n\tpublic Optional<AccessGroup> findByName(@NonNull String name) {\n\t\treturn repo.findByName(name);\n\t}\n\n\tpublic AccessGroup save(@NonNull AccessGroup group) {\n\t\treturn repo.save(group);\n\t}\n\n\tpublic void deleteAll() {\n\t\trepo.deleteAll();\n\t}\n\n\tpublic void delete(@NonNull AccessGroup group) {\n\t\trepo.delete(group);\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}"
},
{
"identifier": "UserDao",
"path": "src/main/java/com/buschmais/backend/users/dataAccess/UserDao.java",
"snippet": "@Service\npublic class UserDao {\n\n\tprivate final UserRepository repo;\n\tprivate final MongoOperations mongoOperations;\n\tprivate final ImageDao imageDao;\n\n\tUserDao(@Autowired UserRepository repo,\n\t\t\t@Autowired MongoOperations mongoOperations,\n\t\t\t@Autowired ImageDao imageDao){\n\t\tthis.repo = repo;\n\t\tthis.mongoOperations = mongoOperations;\n\t\tthis.imageDao = imageDao;\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück\n\t * @return entsprechender Nutzer\n\t */\n\tpublic List<User> findAll() {\n\t\treturn repo.findAll();\n\t}\n\n\tpublic Optional<User> findById(String id) {\n\t\tif(id == null) {\n\t\t\treturn Optional.empty();\n\t\t}\n\n\t\treturn repo.findById(id);\n\t}\n\n\t/**\n\t * Gibt einen Nutzer mit dem entsprechenden Nutzernamen zurück\n\t * @param userName der Nutzername des Nutzers\n\t * @return entsprechender Nutzer\n\t */\n\tpublic Optional<User> findByUserName(@NonNull final String userName) throws UsernameNotFoundException {\n\t\treturn repo.findByUserName(userName);\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück, die genau alle gegebenen Rechte haben.\n\t * Es werden auf true und false gesetzte Werte beachtet.\n\t * Es werden also keine Nutzer zurückgegeben, die mehr (oder weniger) als die angeforderten Rechte besitzen.\n\t * @param rights UserRights Element zum Abgleich der Rechte\n\t * @return entsprechende Nutzer\n\t */\n\tpublic List<User> findAllByRights(@NonNull final UserRights rights) {\n\t\treturn repo.findAllByRights(rights);\n\t}\n\n\t/**\n\t * Gibt alle Nutzer zurück, die mindestens alle gegebenen Rechte haben.\n\t * Es werden nur auf true gesetzte Werte beachtet.\n\t * Es werden also auch alle Nutzer zurückgegeben, die mehr als die angeforderten Rechte besitzen.\n\t * @param rights UserRights Element zum Abgleich der Rechte\n\t * @return entsprechende Nutzer\n\t */\n\tpublic List<User> findAllByHasRights(@NonNull final UserRights rights) {\n\t\tif(rights.getFlags() == 0)\n\t\t\treturn repo.findAll();\n\n\t\tQuery q = new Query();\n\t\tq.addCriteria(Criteria.where(\"rights.flags\").bits().allSet(rights.getFlags()));\n\t\treturn mongoOperations.find(q, User.class);\n\t}\n\n\t/**\n\t * Speichert den angegebenen Nutzer in der Datenbank ab\n\t * @param user zu speichernder Nutzer\n\t * @return user which got saved; null, if a user with the username already exists\n\t */\n\tpublic User save(@NonNull final User user) {\n\t\tif(this.findByUserName(user.getUserName()).isPresent() && this.findById(user.getId()).isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\t\treturn repo.save(user);\n\t}\n\n\t/**\n\t *\n\t * @return currently logged in user; null, if user not logged in or user got deleted\n\t */\n\tpublic User getCurrentUser(){\n\t\ttry {\n\t\t\treturn this.findById(VaadinSession.getCurrent().getAttribute(User.class).getId()).orElse(null);\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic void setCurrentUser(@NonNull final User user){\n\t\tVaadinSession.getCurrent().setAttribute(User.class, user);\n\t}\n\n\tpublic void deleteAll() {\n\t\trepo.findAll().forEach(u -> {if(u.getProfilePicture() != null) imageDao.delete(u.getProfilePicture());});\n\t\trepo.deleteAll();\n\t}\n\n\tpublic void delete(@NonNull User user) {\n\t\tif(user.getProfilePicture() != null){\n\t\t\timageDao.delete(user.getProfilePicture());\n\t\t}\n\t\trepo.delete(user);\n\t}\n}"
},
{
"identifier": "ADRReview",
"path": "backup/java/com/buschmais/adr/voting/ADRReview.java",
"snippet": "public interface ADRReview {\n\n}"
},
{
"identifier": "UserIsNotInvitedException",
"path": "src/main/java/com/buschmais/backend/voting/UserIsNotInvitedException.java",
"snippet": "public class UserIsNotInvitedException extends VotingException{\n}"
},
{
"identifier": "VoteType",
"path": "backup/java/com/buschmais/adr/voting/VoteType.java",
"snippet": "public enum VoteType {\n\tFOR,\n\tAGAINST,\n\tOTHER\n}"
}
] | import com.buschmais.backend.adr.ADR;
import com.buschmais.backend.adr.ADRContainer;
import com.buschmais.backend.adr.ADRContainerRepository;
import com.buschmais.backend.adr.dataAccess.ADRDao;
import com.buschmais.backend.adr.status.ADRStatusApproved;
import com.buschmais.backend.adr.status.ADRStatusProposed;
import com.buschmais.backend.adr.status.ADRStatusSuperseded;
import com.buschmais.backend.adrAccess.AccessGroup;
import com.buschmais.backend.adrAccess.AccessRights;
import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao;
import com.buschmais.backend.users.User;
import com.buschmais.backend.users.dataAccess.UserDao;
import com.buschmais.backend.voting.ADRReview;
import com.buschmais.backend.voting.UserIsNotInvitedException;
import com.buschmais.backend.voting.VoteType;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.component.page.Push;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.theme.Theme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Set; | 6,330 | package com.buschmais;
/**
* The entry point of the Spring Boot application.
*
* Use the @PWA annotation make the application installable on phones, tablets
* and some desktop browsers.
*
*/
@SpringBootApplication
@Theme(value = "swt21w45")
@PWA(name = "swt21w45", shortName = "swt21w45", offlineResources = {"images/logo.png"})
@NpmPackage(value = "line-awesome", version = "1.3.0")
@Push
@EnableMongoRepositories
public class Application extends SpringBootServletInitializer implements AppShellConfigurator, CommandLineRunner {
@Autowired
UserDao userRepo;
@Autowired
ADRDao adrRepo;
@Autowired
ADRAccessDao accessDao;
@Autowired
ADRContainerRepository adrContainerRepository;
public static ADRContainer root = new ADRContainer("root"); //just for testing this will be removed later
public static void main(String[] args) {
/*LaunchUtil.launchBrowserInDevelopmentMode(*/SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
userRepo.deleteAll();
adrRepo.deleteAll();
accessDao.deleteAll();
//ADRContainer root
root = adrContainerRepository.save(root);
/* User */ | package com.buschmais;
/**
* The entry point of the Spring Boot application.
*
* Use the @PWA annotation make the application installable on phones, tablets
* and some desktop browsers.
*
*/
@SpringBootApplication
@Theme(value = "swt21w45")
@PWA(name = "swt21w45", shortName = "swt21w45", offlineResources = {"images/logo.png"})
@NpmPackage(value = "line-awesome", version = "1.3.0")
@Push
@EnableMongoRepositories
public class Application extends SpringBootServletInitializer implements AppShellConfigurator, CommandLineRunner {
@Autowired
UserDao userRepo;
@Autowired
ADRDao adrRepo;
@Autowired
ADRAccessDao accessDao;
@Autowired
ADRContainerRepository adrContainerRepository;
public static ADRContainer root = new ADRContainer("root"); //just for testing this will be removed later
public static void main(String[] args) {
/*LaunchUtil.launchBrowserInDevelopmentMode(*/SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
userRepo.deleteAll();
adrRepo.deleteAll();
accessDao.deleteAll();
//ADRContainer root
root = adrContainerRepository.save(root);
/* User */ | User frode = new User("Frode", "frodemeier"); | 10 | 2023-10-25 15:18:06+00:00 | 8k |
MultiDuels/MultiDuels | common/src/main/java/dev/kafein/multiduels/common/menu/AbstractMenu.java | [
{
"identifier": "InventoryComponent",
"path": "common/src/main/java/dev/kafein/multiduels/common/components/InventoryComponent.java",
"snippet": "public interface InventoryComponent {\n View open(@NotNull PlayerComponent player);\n\n void close(@NotNull PlayerComponent player);\n\n void addItem(@NotNull ItemComponent item);\n\n void setItem(int slot, @NotNull ItemComponent item);\n\n void removeItem(int slot);\n\n interface Properties {\n static Properties create(@NotNull String title, String type) {\n return InventoryPropertiesImpl.create(title, type);\n }\n\n static Properties create(@NotNull String title, int size) {\n return InventoryPropertiesImpl.create(title, size);\n }\n\n String getTitle();\n\n @Nullable String getType();\n\n int getSize();\n }\n\n interface View {\n InventoryComponent getTop();\n\n InventoryComponent getBottom();\n }\n\n interface Factory {\n InventoryComponent create(@NotNull Properties properties);\n\n InventoryComponent create(@NotNull String title, int size);\n\n InventoryComponent create(@NotNull String title, @NotNull String type);\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": "ClickAction",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/action/ClickAction.java",
"snippet": "@FunctionalInterface\npublic interface ClickAction extends BiConsumer<ClickContext, RegisteredClickAction> {\n}"
},
{
"identifier": "ClickActionCollection",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/action/ClickActionCollection.java",
"snippet": "public final class ClickActionCollection {\n private static final ClickActionCollection DEFAULTS;\n\n static {\n DEFAULTS = ClickActionCollection.newBuilder()\n .registerAction(\"CLOSE\", DefaultClickActions.CLOSE)\n .registerAction(\"OPEN\", DefaultClickActions.OPEN)\n .registerAction(\"CONSOLE\", DefaultClickActions.COMMAND_CONSOLE)\n .registerAction(\"PLAYER\", DefaultClickActions.COMMAND_PLAYER)\n .build();\n }\n\n private final Map<String, ClickAction> actions;\n\n public ClickActionCollection() {\n this(ClickActionCollection.DEFAULTS);\n }\n\n public ClickActionCollection(ClickActionCollection collection) {\n this(collection.getActions());\n }\n\n public ClickActionCollection(Map<String, ClickAction> actions) {\n this.actions = actions;\n }\n\n public Map<String, ClickAction> getActions() {\n return this.actions;\n }\n\n public Set<String> getActionNames() {\n return this.actions.keySet();\n }\n\n public Optional<ClickAction> findAction(@NotNull String key) {\n return Optional.ofNullable(this.actions.get(key));\n }\n\n public Optional<ClickAction> findAction(@NotNull RegisteredClickAction action) {\n return this.findAction(action.getKey());\n }\n\n public void registerAction(@NotNull String key, @NotNull ClickAction action) {\n this.actions.put(key, action);\n }\n\n public void unregisterAction(@NotNull String key) {\n this.actions.remove(key);\n }\n\n public void unregisterAction(@NotNull ClickAction action) {\n this.actions.values().remove(action);\n }\n\n public void unregisterAll() {\n this.actions.clear();\n }\n\n public boolean isRegistered(@NotNull String key) {\n return this.actions.containsKey(key);\n }\n\n public boolean isRegistered(@NotNull ClickAction action) {\n return this.actions.containsValue(action);\n }\n\n public boolean isEmpty() {\n return this.actions.isEmpty();\n }\n\n public int size() {\n return this.actions.size();\n }\n\n public Builder toBuilder() {\n return new Builder(this);\n }\n\n public static ClickActionCollection defaults() {\n return ClickActionCollection.DEFAULTS;\n }\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public static final class Builder {\n private final ClickActionCollection collection;\n\n public Builder() {\n this.collection = new ClickActionCollection(Maps.newHashMap());\n }\n\n public Builder(ClickActionCollection collection) {\n this.collection = new ClickActionCollection(collection);\n }\n\n public Builder registerAction(@NotNull String key, @NotNull ClickAction action) {\n this.collection.registerAction(key, action);\n return this;\n }\n\n public Builder unregisterAction(@NotNull String key) {\n this.collection.unregisterAction(key);\n return this;\n }\n\n public Builder unregisterAction(@NotNull ClickAction action) {\n this.collection.unregisterAction(action);\n return this;\n }\n\n public Builder unregisterAll() {\n this.collection.unregisterAll();\n return this;\n }\n\n public ClickActionCollection build() {\n return this.collection;\n }\n }\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": "ClickHandler",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/button/ClickHandler.java",
"snippet": "@FunctionalInterface\npublic interface ClickHandler extends Function<ClickContext, ClickResult> {\n}"
},
{
"identifier": "ClickResult",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/misc/ClickResult.java",
"snippet": "public enum ClickResult {\n CANCELLED,\n CURSORED,\n REFRESH,\n NEXT_PAGE,\n PREVIOUS_PAGE,\n CLOSE\n}"
},
{
"identifier": "OpenCause",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/misc/OpenCause.java",
"snippet": "public enum OpenCause {\n OPEN,\n REFRESH,\n CHANGE_PAGE,\n}"
},
{
"identifier": "ClickContext",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/misc/contexts/ClickContext.java",
"snippet": "public final class ClickContext {\n private final MultiDuels plugin;\n\n private final PlayerComponent player;\n private final Menu menu;\n private final Button button;\n private final ItemComponent item;\n private final ItemComponent cursor;\n private final ClickType clickType;\n private final int slot;\n\n public ClickContext(MultiDuels plugin, Menu menu, PlayerComponent player, Button button, ItemComponent item, ItemComponent cursor, ClickType clickType, int slot) {\n this.plugin = plugin;\n this.menu = menu;\n this.player = player;\n this.button = button;\n this.item = item;\n this.cursor = cursor;\n this.clickType = clickType;\n this.slot = slot;\n }\n\n public static ClickContext create(MultiDuels plugin, Menu menu, PlayerComponent player, Button button, ItemComponent item, ItemComponent cursor, ClickType clickType, int slot) {\n return new ClickContext(plugin, menu, player, button, item, cursor, clickType, slot);\n }\n\n public MultiDuels getPlugin() {\n return this.plugin;\n }\n\n public Menu getMenu() {\n return this.menu;\n }\n\n public PlayerComponent getPlayer() {\n return this.player;\n }\n\n\n public Button getButton() {\n return this.button;\n }\n\n public ItemComponent getItem() {\n return this.item;\n }\n\n public ItemComponent getCursor() {\n return this.cursor;\n }\n\n public ClickType getClickType() {\n return this.clickType;\n }\n\n public int getSlot() {\n return this.slot;\n }\n\n public boolean isLeftClick() {\n return this.clickType == ClickType.LEFT;\n }\n\n public boolean isRightClick() {\n return this.clickType == ClickType.RIGHT;\n }\n\n public boolean isShiftClick() {\n return this.clickType == ClickType.SHIFT_LEFT || this.clickType == ClickType.SHIFT_RIGHT;\n }\n}"
},
{
"identifier": "OpenContext",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/misc/contexts/OpenContext.java",
"snippet": "public final class OpenContext {\n private final PlayerComponent player;\n private final Menu menu;\n private final OpenCause cause;\n private final int page;\n\n public OpenContext(PlayerComponent player, Menu menu, OpenCause cause, int page) {\n this.player = player;\n this.menu = menu;\n this.cause = cause;\n this.page = page;\n }\n\n public static OpenContext create(PlayerComponent player, Menu menu, OpenCause cause, int page) {\n return new OpenContext(player, menu, cause, page);\n }\n\n public PlayerComponent getPlayer() {\n return this.player;\n }\n\n public Menu getMenu() {\n return this.menu;\n }\n\n public OpenCause getCause() {\n return this.cause;\n }\n\n public int getPage() {\n return this.page;\n }\n}"
},
{
"identifier": "Viewer",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/view/Viewer.java",
"snippet": "public final class Viewer {\n private final PlayerComponent player;\n private final InventoryComponent.View view;\n private final String target;\n private int page;\n private boolean closed;\n\n public Viewer(PlayerComponent player, InventoryComponent.View view, String target, int page) {\n this.player = player;\n this.view = view;\n this.target = target;\n this.page = page;\n }\n\n public static Viewer create(PlayerComponent player, InventoryComponent.View view, String target) {\n return create(player, view, target, 0);\n }\n\n public static Viewer create(PlayerComponent player, InventoryComponent.View view, String target, int page) {\n return new Viewer(player, view, target, page);\n }\n\n public PlayerComponent getPlayer() {\n return this.player;\n }\n\n public UUID getUniqueId() {\n return this.player.getUniqueId();\n }\n\n public InventoryComponent.View getView() {\n return this.view;\n }\n\n public String getTarget() {\n return this.target;\n }\n\n public int getPage() {\n return this.page;\n }\n\n public void setPage(int page) {\n this.page = page;\n }\n\n public boolean isClosed() {\n return this.closed;\n }\n\n public void setClosed(boolean closed) {\n this.closed = closed;\n }\n}"
},
{
"identifier": "ViewersHolder",
"path": "common/src/main/java/dev/kafein/multiduels/common/menu/view/ViewersHolder.java",
"snippet": "public final class ViewersHolder {\n private final Map<UUID, Viewer> viewers;\n\n public ViewersHolder() {\n this.viewers = Maps.newHashMap();\n }\n\n public ViewersHolder(Map<UUID, Viewer> viewers) {\n this.viewers = viewers;\n }\n\n public static ViewersHolder create() {\n return new ViewersHolder();\n }\n\n public static ViewersHolder create(Map<UUID, Viewer> viewers) {\n return new ViewersHolder(viewers);\n }\n\n public Map<UUID, Viewer> getViewers() {\n return this.viewers;\n }\n\n public Map<UUID, Viewer> getViewersSafe() {\n return Maps.newHashMap(this.viewers);\n }\n\n public @Nullable Viewer getViewer(@NotNull UUID uuid) {\n return this.viewers.get(uuid);\n }\n\n public Viewer addViewer(@NotNull Viewer viewer) {\n this.viewers.put(viewer.getUniqueId(), viewer);\n return viewer;\n }\n\n public @Nullable Viewer removeViewer(@NotNull UUID uuid) {\n return this.viewers.remove(uuid);\n }\n\n public @Nullable Viewer removeViewer(@NotNull Viewer viewer) {\n return this.viewers.remove(viewer.getUniqueId());\n }\n\n public void clear() {\n this.viewers.clear();\n }\n\n public boolean containsViewer(@NotNull UUID uuid) {\n return this.viewers.containsKey(uuid);\n }\n\n public boolean containsViewer(@NotNull Viewer viewer) {\n return this.viewers.containsKey(viewer.getUniqueId());\n }\n\n public boolean isEmpty() {\n return this.viewers.isEmpty();\n }\n\n public int size() {\n return this.viewers.size();\n }\n\n public Map<UUID, Viewer> toMap() {\n return Maps.newHashMap(this.viewers);\n }\n}"
}
] | import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import dev.kafein.multiduels.common.components.InventoryComponent;
import dev.kafein.multiduels.common.components.ItemComponent;
import dev.kafein.multiduels.common.components.PlayerComponent;
import dev.kafein.multiduels.common.menu.action.ClickAction;
import dev.kafein.multiduels.common.menu.action.ClickActionCollection;
import dev.kafein.multiduels.common.menu.button.Button;
import dev.kafein.multiduels.common.menu.button.ClickHandler;
import dev.kafein.multiduels.common.menu.misc.ClickResult;
import dev.kafein.multiduels.common.menu.misc.OpenCause;
import dev.kafein.multiduels.common.menu.misc.contexts.ClickContext;
import dev.kafein.multiduels.common.menu.misc.contexts.OpenContext;
import dev.kafein.multiduels.common.menu.view.Viewer;
import dev.kafein.multiduels.common.menu.view.ViewersHolder;
import ninja.leaping.configurate.ConfigurationNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*; | 4,944 | /*
* 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;
abstract class AbstractMenu implements Menu {
private final MenuProperties properties;
private final InventoryComponent.Factory inventoryFactory;
private final ItemComponent.Factory itemFactory;
private final Set<Button> buttons;
private final ClickActionCollection clickActions;
private final ViewersHolder viewers;
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = properties.getNode() == null ? Sets.newHashSet() : loadButtonsFromNode();
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory, Set<Button> buttons) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = buttons;
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
@Override
public Viewer open(@NotNull PlayerComponent player) {
return open(player, 0);
}
@Override
public Viewer open(@NotNull PlayerComponent player, int page) { | /*
* 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;
abstract class AbstractMenu implements Menu {
private final MenuProperties properties;
private final InventoryComponent.Factory inventoryFactory;
private final ItemComponent.Factory itemFactory;
private final Set<Button> buttons;
private final ClickActionCollection clickActions;
private final ViewersHolder viewers;
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = properties.getNode() == null ? Sets.newHashSet() : loadButtonsFromNode();
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory, Set<Button> buttons) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = buttons;
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
@Override
public Viewer open(@NotNull PlayerComponent player) {
return open(player, 0);
}
@Override
public Viewer open(@NotNull PlayerComponent player, int page) { | return open(player, page, OpenCause.OPEN); | 8 | 2023-10-31 10:55:38+00:00 | 8k |
aerospike/graph-synth | graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/Generator.java | [
{
"identifier": "GraphSchemaParser",
"path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/GraphSchemaParser.java",
"snippet": "public interface GraphSchemaParser {\n GraphSchema parse();\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": "YAMLSchemaParser",
"path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/seralization/YAMLSchemaParser.java",
"snippet": "public class YAMLSchemaParser implements GraphSchemaParser {\n\n public static class Config extends ConfigurationBase {\n public static final Config INSTANCE = new Config();\n\n private Config() {\n super();\n }\n\n @Override\n public Map<String, String> defaultConfigMap(final Map<String, Object> config) {\n return DEFAULTS;\n }\n\n @Override\n public List<String> getKeys() {\n return ConfigurationUtil.getKeysFromClass(Config.Keys.class);\n }\n\n public static class Keys {\n public static final String YAML_FILE_URI = \"generator.schema.yaml.URI\";\n public static final String YAML_FILE_PATH = \"generator.schema.yaml.path\";\n }\n\n private static final Map<String, String> DEFAULTS = new HashMap<>() {{\n }};\n }\n\n private final File file;\n\n private YAMLSchemaParser(final File file) {\n this.file = file;\n }\n\n public static YAMLSchemaParser open(final Configuration config) {\n if (config.containsKey(Config.Keys.YAML_FILE_PATH)) {\n return from(Path.of(config.getString(Config.Keys.YAML_FILE_PATH)));\n } else if (config.containsKey(Config.Keys.YAML_FILE_URI)) {\n return from(URI.create(Config.INSTANCE.getOrDefault(Config.Keys.YAML_FILE_URI, config)));\n } else {\n throw new RuntimeException(\"must set \" + Config.Keys.YAML_FILE_PATH + \" or \" + Config.Keys.YAML_FILE_URI);\n }\n }\n\n public static YAMLSchemaParser from(final URI yamlSchemaFileURI) {\n if (yamlSchemaFileURI.getScheme().equals(\"http\")) {\n try {\n File tmpFile = Files.createTempFile(\"schema\", \".yaml\").toFile();\n IOUtil.downloadFileFromURL(yamlSchemaFileURI.toURL(), tmpFile);\n return new YAMLSchemaParser(tmpFile);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n } else {\n throw new RuntimeException(\"Unsupported URI scheme: \" + yamlSchemaFileURI.getScheme());\n }\n }\n\n public static YAMLSchemaParser from(final Path yamlSchemaPath) {\n return new YAMLSchemaParser(yamlSchemaPath.toFile());\n }\n\n public GraphSchema parse() {\n try {\n final String yamlText = Files.readAllLines(file.toPath(), Charset.defaultCharset()).stream()\n .reduce(\"\", (a, b) -> a + \"\\n\" + b);\n final Yaml yaml = new Yaml(new Constructor(GraphSchema.class, new LoaderOptions()));\n return yaml.load(yamlText);\n } catch (IOException e) {\n throw new RuntimeException(\"Could not read file: \" + file.toPath(), e);\n }\n }\n}"
},
{
"identifier": "Generate",
"path": "graph-synth/src/main/java/com/aerospike/graph/synth/process/tasks/generator/Generate.java",
"snippet": "public class Generate extends Task {\n static {\n RuntimeUtil.registerTaskAlias(Generate.class.getSimpleName(), Generate.class);\n }\n\n @Override\n public void init(final Configuration config) {\n SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> {\n final long scale = Long.parseLong(Config.INSTANCE.getOrDefault(Config.Keys.SCALE_FACTOR, config));\n return PrimitiveIteratorWrap.wrap(LongStream.range(0, scale).iterator());\n }));\n //@todo phase2 stitching work chunk driver\n }\n\n @Override\n public void close() throws Exception {\n\n }\n\n public static class Config extends ConfigurationBase {\n public static final Config INSTANCE = new Config();\n\n private Config() {\n super();\n }\n\n @Override\n public Map<String, String> defaultConfigMap(final Map<String, Object> config) {\n final long workPerProcessor = Long.parseLong(Generator.Config.INSTANCE.getOrDefault(Generator.Config.Keys.SCALE_FACTOR, config)) / getAvailableProcessors();\n final long scaleFactor = Long.parseLong(Generator.Config.INSTANCE.getOrDefault(Generator.Config.Keys.SCALE_FACTOR, config));\n return new HashMap<>() {{\n put(ConfigurationBase.Keys.EMITTER, Generator.class.getName());\n //alias driver range to generator scale factor\n put(ConfiguredRangeSupplier.Config.Keys.RANGE_TOP, Generator.Config.INSTANCE.getOrDefault(Generator.Config.Keys.SCALE_FACTOR, config));\n put(ConfiguredRangeSupplier.Config.Keys.RANGE_BOTTOM, String.valueOf(0L));\n put(BATCH_SIZE, String.valueOf(Math.min(workPerProcessor, Math.min(scaleFactor / getAvailableProcessors(), 100_000))));\n put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(scaleFactor + 1));\n put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE));\n }};\n }\n\n @Override\n public List<String> getKeys() {\n return ConfigurationUtil.getKeysFromClass(Keys.class);\n }\n\n public static class Keys {\n public static final String EMITTER = \"emitter\";\n public static final String OUTPUT_ID_DRIVER = \"output.idDriver\";\n public static final String WORK_CHUNK_DRIVER = \"emitter.workChunkDriver\";\n public static final String SCALE_FACTOR = Generator.Config.Keys.SCALE_FACTOR;\n }\n\n }\n\n private Generate(final Configuration config) {\n super(Config.INSTANCE, config);\n }\n\n\n public static Generate open(final Configuration config) {\n return new Generate(config);\n }\n\n\n// @Override\n// public Configuration setupConfig(final Configuration inputConfig) {\n// return null;\n// }\n\n @Override\n public Configuration getConfig(final Configuration config) {\n final long workPerProcessor = Long.parseLong(Generator.Config.INSTANCE.getOrDefault(Generator.Config.Keys.SCALE_FACTOR, config)) / getAvailableProcessors();\n final long scaleFactor = Long.parseLong(Generator.Config.INSTANCE.getOrDefault(Generator.Config.Keys.SCALE_FACTOR, config));\n\n /**\n * todo this is a hack\n */\n SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.ONE, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, scaleFactor).iterator())));\n SuppliedWorkChunkDriver.setIteratorSupplierForPhase(Runtime.PHASE.TWO, OneShotIteratorSupplier.of(() -> PrimitiveIteratorWrap.wrap(LongStream.range(0, scaleFactor).iterator())));\n return ConfigurationUtil.configurationWithOverrides(config, new HashMap<>() {{\n put(ConfigurationBase.Keys.EMITTER, Generator.class.getName());\n put(ConfigurationBase.Keys.WORK_CHUNK_DRIVER_PHASE_ONE, SuppliedWorkChunkDriver.class.getName());\n put(ConfigurationBase.Keys.OUTPUT_ID_DRIVER,GeneratedOutputIdDriver.class.getName());\n //alias driver range to generator scale factor\n put(BATCH_SIZE, String.valueOf(Math.min(scaleFactor, 1000)));\n put(GeneratedOutputIdDriver.Config.Keys.RANGE_BOTTOM, String.valueOf(scaleFactor + 1));\n put(GeneratedOutputIdDriver.Config.Keys.RANGE_TOP, String.valueOf(Long.MAX_VALUE));\n }});\n\n }\n\n @Override\n public Map<String, Object> getMetrics() {\n throw ErrorUtil.unimplemented();\n }\n\n @Override\n public boolean isRunning() {\n return false;\n }\n\n @Override\n public boolean succeeded() {\n return false;\n }\n\n @Override\n public boolean failed() {\n return false;\n }\n\n @Override\n public List<Runtime.PHASE> getPhases() {\n return List.of(Runtime.PHASE.ONE);\n }\n\n// public static Generate\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.GraphSchemaParser;
import com.aerospike.graph.synth.emitter.generator.schema.definition.GraphSchema;
import com.aerospike.graph.synth.emitter.generator.schema.definition.VertexSchema;
import com.aerospike.graph.synth.emitter.generator.schema.seralization.YAMLSchemaParser;
import com.aerospike.graph.synth.process.tasks.generator.Generate;
import com.aerospike.movement.config.core.ConfigurationBase;
import com.aerospike.movement.emitter.core.Emitable;
import com.aerospike.movement.emitter.core.Emitter;
import com.aerospike.movement.runtime.core.Runtime;
import com.aerospike.movement.runtime.core.driver.OutputIdDriver;
import com.aerospike.movement.runtime.core.driver.WorkChunkDriver;
import com.aerospike.movement.runtime.core.local.Loadable;
import com.aerospike.movement.test.mock.output.MockOutput;
import com.aerospike.movement.util.core.configuration.ConfigurationUtil;
import com.aerospike.movement.util.core.error.ErrorUtil;
import com.aerospike.movement.util.core.iterator.ext.IteratorUtils;
import com.aerospike.movement.util.core.runtime.RuntimeUtil;
import com.aerospike.graph.synth.util.generator.SchemaUtil;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.MapConfiguration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 3,815 | /*
* @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>)
*/
public class Generator extends Loadable implements Emitter {
@Override
public void init(final Configuration config) {
}
// Configuration first.
public static class Config extends ConfigurationBase {
public static final Config INSTANCE = new Config();
private Config() {
super();
}
@Override
public Map<String, String> defaultConfigMap(final Map<String, Object> config) {
return DEFAULTS;
}
@Override
public List<String> getKeys() {
return ConfigurationUtil.getKeysFromClass(Config.Keys.class);
}
public static class Keys {
public static final String SCALE_FACTOR = "generator.scaleFactor";
public static final String CHANCE_TO_JOIN = "generator.chanceToJoin";
public static final String SCHEMA_PARSER = "generator.schemaGraphParser";
}
private static final Map<String, String> DEFAULTS = new HashMap<>() {{
put(Generate.Config.Keys.EMITTER, Generator.class.getName());
put(Keys.SCALE_FACTOR, "100");
put(Keys.SCHEMA_PARSER, YAMLSchemaParser.class.getName());
}};
}
private final Configuration config;
//Static variables
//...
//Final class variables
private final OutputIdDriver outputIdDriver;
private final Long scaleFactor; | /*
* @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>)
*/
public class Generator extends Loadable implements Emitter {
@Override
public void init(final Configuration config) {
}
// Configuration first.
public static class Config extends ConfigurationBase {
public static final Config INSTANCE = new Config();
private Config() {
super();
}
@Override
public Map<String, String> defaultConfigMap(final Map<String, Object> config) {
return DEFAULTS;
}
@Override
public List<String> getKeys() {
return ConfigurationUtil.getKeysFromClass(Config.Keys.class);
}
public static class Keys {
public static final String SCALE_FACTOR = "generator.scaleFactor";
public static final String CHANCE_TO_JOIN = "generator.chanceToJoin";
public static final String SCHEMA_PARSER = "generator.schemaGraphParser";
}
private static final Map<String, String> DEFAULTS = new HashMap<>() {{
put(Generate.Config.Keys.EMITTER, Generator.class.getName());
put(Keys.SCALE_FACTOR, "100");
put(Keys.SCHEMA_PARSER, YAMLSchemaParser.class.getName());
}};
}
private final Configuration config;
//Static variables
//...
//Final class variables
private final OutputIdDriver outputIdDriver;
private final Long scaleFactor; | private final Map<String, VertexSchema> rootVertexSchemas; | 2 | 2023-10-27 22:54:12+00:00 | 8k |
StarDevelopmentLLC/StarMCLib | src/main/java/com/stardevllc/starmclib/item/material/BookItemBuilder.java | [
{
"identifier": "ColorUtils",
"path": "src/main/java/com/stardevllc/starmclib/color/ColorUtils.java",
"snippet": "public final class ColorUtils {\n private static final char[] COLOR_SYMBOLS = {'&', '~', '`', '!', '@', '$', '%', '^', '*', '?'};\n public static final Pattern COLOR_CODE_PATTERN = Pattern.compile(\"[&~`!@$%^*?][0-9A-Z]\", Pattern.CASE_INSENSITIVE);\n public static final Pattern HEX_VALUE_PATTERN = Pattern.compile(\"^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\", Pattern.CASE_INSENSITIVE);\n\n private static Map<String, CustomColor> customColors = new HashMap<>();\n private static Map<String, SpigotColor> spigotColors = new HashMap<>();\n\n static {\n for (org.bukkit.ChatColor chatColor : org.bukkit.ChatColor.values()) {\n SpigotColor spigotColor = new SpigotColor(null, chatColor);\n spigotColors.put(spigotColor.getChatCode(), spigotColor);\n }\n }\n \n public static void coloredMessage(CommandSender sender, String message) {\n sender.sendMessage(color(message));\n }\n\n /**\n * Colors a string with all options set to true using the {@link #color(String, boolean, boolean, boolean)} method\n *\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String color(String uncolored) {\n return color(null, uncolored);\n }\n\n /**\n * Colors the string with all options set to true using the {@link #color(CommandSender, String, boolean, boolean, boolean)} method and added permission checks\n *\n * @param sender The sender for permission checks\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String color(CommandSender sender, String uncolored) {\n return color(sender, uncolored, true, true, isHexSupported());\n }\n\n /**\n * Colors a String based on settings\n *\n * @param uncolored The uncolored text\n * @param translateBukkit If Default Bukkit Color Codes are translated\n * @param translateCustom If custom color codes are translated\n * @param translateHex If direct hex codes are translated (Note: Hex codes MUST be 6 characters long), will also prevent hex being translated if current Bukkit Version does not support Hex Codes\n * @return The colored text\n */\n public static String color(String uncolored, boolean translateBukkit, boolean translateCustom, boolean translateHex) {\n return color(null, uncolored, translateBukkit, translateCustom, isHexSupported() && translateHex);\n }\n\n /**\n * Translates default bukkit colors without fine-grained permissions\n *\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateBukkit(String uncolored) {\n return translateBukkit(null, uncolored);\n }\n\n /**\n * Colors default bukkit text with fine-grain permissions\n *\n * @param sender The sender (Can be null)\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateBukkit(CommandSender sender, String uncolored) {\n if (sender == null || sender.isOp()) {\n return ChatColor.translateAlternateColorCodes('&', uncolored);\n }\n\n StringBuilder colored = new StringBuilder();\n for (int i = 0; i < uncolored.length(); i++) {\n char c = uncolored.charAt(i);\n if (c == '&') {\n if (uncolored.length() >= i + 1) {\n String code = \"&\" + uncolored.charAt(i + 1);\n SpigotColor spigotColor = spigotColors.get(code.toLowerCase());\n if (spigotColor != null && hasPermission(sender, spigotColor.getPermission())) {\n colored.append(ChatColor.COLOR_CHAR);\n } else {\n colored.append('&');\n }\n }\n } else {\n colored.append(c);\n }\n }\n\n return colored.toString();\n }\n\n /**\n * Translates custom color codes\n *\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateCustom(String uncolored) {\n return translateCustom(null, uncolored);\n }\n\n /**\n * Translates custom color codes\n * \n * @param sender The sender\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateCustom(CommandSender sender, String uncolored) {\n StringBuilder colored = new StringBuilder();\n for (int i = 0; i < uncolored.length(); i++) {\n char c = uncolored.charAt(i);\n if (ColorUtils.isValidSymbol(c)) {\n if (uncolored.length() > i + 1) {\n String code = String.valueOf(c) + uncolored.charAt(i + 1);\n CustomColor color = ColorUtils.getCustomColor(code);\n if (color != null && hasPermission(sender, color.getPermission())) {\n colored.append(color.getSpigotColor());\n i++;\n continue;\n }\n }\n }\n colored.append(c);\n }\n\n return colored.toString();\n }\n\n /**\n * Translates HEX codes\n *\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateHex(String uncolored) {\n return translateHex(null, uncolored);\n }\n \n public static boolean isHexSupported() {\n return NMSVersion.CURRENT_VERSION.ordinal() >= NMSVersion.v1_16_R1.ordinal();\n }\n \n /**\n * Translates HEX colors\n *\n * @param sender The sender\n * @param uncolored The uncolored text\n * @return The colored text\n */\n public static String translateHex(CommandSender sender, String uncolored) {\n StringBuilder colored = new StringBuilder();\n if (!isHexSupported()) {\n Bukkit.getLogger().warning(\"[StarMCLib] Hex Colors are not supported by this Minecraft Version, ignoring them.\");\n return uncolored;\n }\n for (int i = 0; i < uncolored.length(); i++) {\n char c = uncolored.charAt(i);\n if (c == '#') {\n if (hasPermission(sender, \"starmclib.color.hex\")) {\n if (uncolored.length() > i + 6) {\n String colorCode = '#' + uncolored.substring(i + 1, i + 7);\n ChatColor color = ChatColor.of(colorCode);\n colored.append(color);\n i += 6;\n continue;\n }\n }\n }\n colored.append(c);\n }\n return colored.toString();\n }\n\n /**\n * Colors a String based on settings and with permission checks if sender is not null\n *\n * @param sender The sender to check for permission. This can be null though and the permission check is skipped\n * @param uncolored The uncolored text\n * @param translateBukkit If Default Bukkit Color Codes are translated\n * @param translateCustom If custom color codes are translated\n * @param translateHex If direct hex codes are translated (Note: Hex codes MUST be 6 characters long)\n * @return The colored text\n */\n public static String color(CommandSender sender, String uncolored, boolean translateBukkit, boolean translateCustom, boolean translateHex) {\n String text = uncolored;\n if (translateBukkit) {\n text = translateBukkit(sender, text);\n }\n\n if (translateCustom) {\n text = translateCustom(sender, text);\n }\n\n if (translateHex) {\n return translateHex(sender, text);\n }\n\n return text;\n }\n\n private static boolean hasPermission(CommandSender sender, String permission) {\n if (sender == null || permission == null || permission.isEmpty()) {\n return true;\n }\n\n return sender.hasPermission(permission);\n }\n\n /**\n * @param color The color\n * @return The hex code\n */\n public static String getHexCode(ChatColor color) {\n Color awtColor = color.getColor();\n if (awtColor != null) {\n return \"#\" + Integer.toHexString(awtColor.getRGB()).substring(2);\n }\n return \"\";\n }\n\n /**\n * Utility method to check to see if an RGB component is valid\n *\n * @param component The r g b value\n * @return If it is between 0 and 255\n */\n public static boolean isRGBComponentInRange(int component) {\n return component > -1 && component < 256;\n }\n\n /**\n * Utility method to check for if the code matches the pattern\n *\n * @param code The code (can be null)\n * @return If the code is valid according to the pattern\n */\n public static boolean isValidCode(String code) {\n if (code == null || code.isEmpty()) {\n return false;\n }\n return COLOR_CODE_PATTERN.matcher(code).matches();\n }\n\n /**\n * Utility method to check for valid HEX values\n *\n * @param str The string to check\n * @return If the string matches the HEX pattern\n */\n public static boolean isValidHex(String str) {\n if (str == null || str.isEmpty()) {\n return false;\n }\n return HEX_VALUE_PATTERN.matcher(str).matches();\n }\n\n /**\n * Adds a custom color\n *\n * @param customColor The color to add\n */\n public static void addCustomColor(CustomColor customColor) {\n customColors.put(customColor.getChatCode(), customColor);\n }\n\n /**\n * Gets a custom color\n *\n * @param code The code as if it were to be used in chat\n * @return The CustomColor instance\n */\n public static CustomColor getCustomColor(String code) {\n return customColors.get(code);\n }\n\n /**\n * Removes a color\n *\n * @param code The code of the color to remove\n */\n public static void removeColor(String code) {\n customColors.remove(code);\n }\n\n /**\n * Utility method to check to see if the char is a valid prefix symbol\n *\n * @param c The character\n * @return if it is valid\n */\n public static boolean isValidSymbol(char c) {\n for (char colorChar : COLOR_SYMBOLS) {\n if (colorChar == c) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * @return All valid prefix symbols\n */\n public static char[] getPrefixSymbols() {\n return COLOR_SYMBOLS;\n }\n\n /**\n * @return A copy of the color registry\n */\n public static Map<String, CustomColor> getCustomColors() {\n return new HashMap<>(customColors);\n }\n\n /**\n * Strips colors from text\n *\n * @param text The text\n * @return The uncolored text\n */\n public static String stripColor(String text) {\n text = ChatColor.stripColor(text);\n text = HEX_VALUE_PATTERN.matcher(text).replaceAll(\"\");\n return COLOR_CODE_PATTERN.matcher(text).replaceAll(\"\");\n }\n\n public static boolean isSpigotColor(String code) {\n return spigotColors.containsKey(code.toLowerCase());\n }\n}"
},
{
"identifier": "ItemBuilder",
"path": "src/main/java/com/stardevllc/starmclib/item/ItemBuilder.java",
"snippet": "public class ItemBuilder implements Cloneable {\n \n private static final Map<Class<? extends ItemMeta>, Class<? extends ItemBuilder>> META_TO_BUILDERS = new HashMap<>();\n \n static {\n META_TO_BUILDERS.put(ArmorMeta.class, ArmorItemBuilder.class);\n META_TO_BUILDERS.put(AxolotlBucketMeta.class, AxolotlItemBuilder.class);\n META_TO_BUILDERS.put(BannerMeta.class, BannerItemBuilder.class);\n META_TO_BUILDERS.put(BookMeta.class, BookItemBuilder.class);\n META_TO_BUILDERS.put(CrossbowMeta.class, CrossbowItemBuilder.class);\n META_TO_BUILDERS.put(EnchantmentStorageMeta.class, EnchantedBookBuilder.class);\n META_TO_BUILDERS.put(FireworkMeta.class, FireworkItemBuilder.class);\n META_TO_BUILDERS.put(FireworkEffectMeta.class, FireworkStarBuilder.class);\n META_TO_BUILDERS.put(TropicalFishBucketMeta.class, FishBucketBuilder.class);\n META_TO_BUILDERS.put(MusicInstrumentMeta.class, GoatHornBuilder.class);\n META_TO_BUILDERS.put(MapMeta.class, MapItemBuilder.class);\n META_TO_BUILDERS.put(SkullMeta.class, SkullItemBuilder.class);\n META_TO_BUILDERS.put(SuspiciousStewMeta.class, StewItemBuilder.class);\n }\n \n protected XMaterial material;\n protected int amount;\n protected Map<Attribute, AttributeModifier> attributes = new EnumMap<>(Attribute.class);\n protected Map<Enchantment, Integer> enchantments = new HashMap<>();\n protected ItemFlag[] itemFlags;\n protected String displayName;\n protected List<String> lore = new LinkedList<>();\n protected boolean unbreakable;\n protected int repairCost;\n protected int damage;\n \n @SuppressWarnings(\"SuspiciousMethodCalls\")\n public static ItemBuilder fromConfig(ConfigurationSection section) {\n XMaterial material = XMaterial.valueOf(section.getString(\"material\"));\n ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(material.parseMaterial());\n ItemBuilder itemBuilder;\n if (META_TO_BUILDERS.containsKey(itemMeta)) {\n itemBuilder = getSubClassFromMeta(itemMeta, \"createFromConfig\", ConfigurationSection.class, section);\n } else {\n itemBuilder = new ItemBuilder();\n }\n \n itemBuilder.material(material);\n itemBuilder.amount(section.getInt(\"amount\"));\n itemBuilder.displayName(section.getString(\"displayname\"));\n itemBuilder.setLore(section.getStringList(\"lore\"));\n itemBuilder.repairCost(section.getInt(\"repaircost\"));\n itemBuilder.damage(section.getInt(\"damage\"));\n List<String> flagNames = section.getStringList(\"flags\");\n if (!flagNames.isEmpty()) {\n for (String flagName : flagNames) {\n itemBuilder.addItemFlags(ItemFlag.valueOf(flagName));\n }\n }\n \n ConfigurationSection enchantsSection = section.getConfigurationSection(\"enchantments\");\n if (enchantsSection != null) {\n for (String enchantName : enchantsSection.getKeys(false)) {\n Enchantment enchantment = Enchantment.getByKey(NamespacedKey.fromString(enchantName.replace(\"_\", \":\")));\n int level = enchantsSection.getInt(enchantName);\n itemBuilder.addEnchant(enchantment, level);\n }\n }\n \n ConfigurationSection attributesSection = section.getConfigurationSection(\"attributes\");\n if (attributesSection != null) {\n for (String key : attributesSection.getKeys(false)) {\n Attribute attribute = Attribute.valueOf(key.toUpperCase());\n String name = attributesSection.getString(key + \".name\");\n double amount = attributesSection.getDouble(key + \".amount\");\n Operation operation = Operation.valueOf(attributesSection.getString(key + \".operation\"));\n if (!attributesSection.contains(key + \".slot\")) {\n itemBuilder.addAttributeModifier(attribute, name, amount, operation);\n } else {\n EquipmentSlot slot = EquipmentSlot.valueOf(attributesSection.getString(key + \".slot\"));\n itemBuilder.addAttributeModifier(attribute, name, amount, operation, slot);\n }\n }\n }\n\n return itemBuilder;\n }\n \n public void saveToConfig(ConfigurationSection section) {\n section.set(\"material\", material.name());\n section.set(\"amount\", amount);\n section.set(\"displayname\", displayName);\n section.set(\"lore\", lore);\n section.set(\"repaircost\", repairCost);\n section.set(\"damage\", damage);\n List<String> flags = new ArrayList<>();\n if (itemFlags != null) {\n for (ItemFlag itemFlag : itemFlags) {\n flags.add(itemFlag.name());\n }\n }\n section.set(\"flags\", flags);\n \n enchantments.forEach((enchant, level) -> section.set(\"enchantments.\" + enchant.getKey().toString().replace(\":\", \"_\"), level));\n attributes.forEach((attribute, modifier) -> {\n String attributeName = attribute.name().toLowerCase();\n section.set(\"attributes.\" + attributeName + \".amount\", modifier.getAmount());\n section.set(\"attributes.\" + attributeName + \".name\", modifier.getName());\n section.set(\"attributes.\" + attributeName + \".operation\", modifier.getOperation().name());\n if (modifier.getSlot() != null) {\n section.set(\"attributes.\" + attributeName + \".slot\", modifier.getSlot().name());\n }\n });\n }\n\n public static ItemBuilder of(XMaterial material) {\n return new ItemBuilder(material);\n }\n \n public static ItemBuilder fromItemStack(ItemStack itemStack) {\n ItemMeta itemMeta = itemStack.getItemMeta();\n ItemBuilder itemBuilder = getSubClassFromMeta(itemMeta, \"createFromItemStack\", ItemStack.class, itemStack);\n \n itemBuilder.displayName(itemMeta.getDisplayName()).amount(itemStack.getAmount()).addItemFlags(itemMeta.getItemFlags().toArray(new ItemFlag[0]))\n .unbreakable(itemMeta.isUnbreakable()).setLore(itemMeta.getLore()).setEnchants(itemMeta.getEnchants());\n Multimap<Attribute, AttributeModifier> attributeModifiers = itemMeta.getAttributeModifiers();\n if (attributeModifiers != null) {\n attributeModifiers.forEach((attribute, modifier) -> itemBuilder.attributes.put(attribute, modifier));\n }\n \n if (itemMeta instanceof Repairable repairable) {\n itemBuilder.repairCost(repairable.getRepairCost());\n }\n \n if (itemMeta instanceof Damageable damageable) {\n itemBuilder.damage(damageable.getDamage());\n }\n\n return itemBuilder;\n }\n \n protected ItemBuilder() {\n \n }\n \n protected ItemBuilder(XMaterial material) {\n this.material = material;\n }\n \n public ItemBuilder addAttributeModifier(Attribute attribute, String name, double amount, Operation operation, EquipmentSlot slot) {\n this.attributes.put(attribute, new AttributeModifier(UUID.randomUUID(), name, amount, operation, slot));\n return this;\n }\n\n public ItemBuilder addAttributeModifier(Attribute attribute, String name, double amount, Operation operation) {\n this.attributes.put(attribute, new AttributeModifier(UUID.randomUUID(), name, amount, operation));\n return this;\n }\n \n public ItemBuilder addEnchant(Enchantment enchantment, int level) {\n this.enchantments.put(enchantment, level);\n return this;\n }\n \n public ItemBuilder setEnchants(Map<Enchantment, Integer> enchants) {\n this.enchantments.clear();\n this.enchantments.putAll(enchants);\n return this;\n }\n \n public ItemBuilder addItemFlags(ItemFlag... itemFlags) {\n this.itemFlags = itemFlags;\n return this;\n }\n \n public ItemBuilder setLore(List<String> lore) {\n this.lore.clear();\n this.lore.addAll(lore);\n return this;\n }\n \n public ItemBuilder addLoreLine(String line) {\n this.lore.add(line);\n return this;\n }\n \n public ItemBuilder setLoreLine(int index, String line) {\n this.lore.set(index, line);\n return this;\n }\n\n public ItemBuilder material(XMaterial material) {\n this.material = material;\n return this;\n }\n\n public ItemBuilder amount(int amount) {\n this.amount = amount;\n return this;\n }\n\n public ItemBuilder displayName(String displayName) {\n this.displayName = displayName;\n return this;\n }\n\n public ItemBuilder unbreakable(boolean unbreakable) {\n this.unbreakable = unbreakable;\n return this;\n }\n \n public ItemBuilder repairCost(int repairCost) {\n this.repairCost = repairCost;\n return this;\n }\n \n public ItemBuilder damage(int damage) {\n this.damage = damage;\n return this;\n }\n\n protected ItemMeta createItemMeta() {\n ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(this.material.parseMaterial());\n if (!attributes.isEmpty()) {\n this.attributes.forEach((attribute, modifier) -> itemMeta.addAttributeModifier(attribute, modifier));\n }\n\n if (!this.enchantments.isEmpty()) {\n this.enchantments.forEach((enchant, level) -> itemMeta.addEnchant(enchant, level, true));\n }\n\n if (itemFlags != null) {\n itemMeta.addItemFlags(this.itemFlags);\n }\n\n if (this.displayName != null) {\n itemMeta.setDisplayName(ColorUtils.color(this.displayName));\n }\n\n if (!this.lore.isEmpty()) {\n List<String> coloredLore = this.lore.stream().map(ColorUtils::color).collect(Collectors.toCollection(LinkedList::new));\n itemMeta.setLore(coloredLore);\n }\n \n if (itemMeta instanceof Repairable repairable) {\n repairable.setRepairCost(this.repairCost);\n }\n \n if (itemMeta instanceof Damageable damageable) {\n damageable.setDamage(this.damage);\n }\n \n itemMeta.setUnbreakable(unbreakable);\n return itemMeta;\n }\n \n public ItemStack build() {\n if (amount < 1) {\n amount = 1;\n }\n \n if (!material.parseMaterial().isItem()) {\n return null;\n }\n \n ItemStack itemStack = material.parseItem();\n itemStack.setAmount(amount);\n ItemMeta itemMeta = createItemMeta();\n itemStack.setItemMeta(itemMeta);\n return itemStack;\n }\n\n public ItemBuilder clone() {\n ItemBuilder clone = null;\n try {\n clone = (ItemBuilder) super.clone();\n } catch (CloneNotSupportedException e) {\n e.printStackTrace();\n }\n clone.amount = amount;\n clone.attributes.putAll(this.attributes);\n clone.enchantments.putAll(this.enchantments);\n clone.itemFlags = this.itemFlags;\n clone.displayName = this.displayName;\n clone.lore.addAll(this.lore);\n clone.unbreakable = this.unbreakable;\n clone.repairCost = this.repairCost;\n clone.damage = this.damage;\n return clone;\n }\n \n public static class Armor extends ArmorItemBuilder {\n public Armor(ArmorMaterial material, ArmorSlot slot) {\n super(XMaterial.valueOf(material.name() + \"_\" + slot.name()));\n }\n }\n \n public static class AxolotlBucket extends AxolotlItemBuilder {\n public AxolotlBucket(Axolotl.Variant variant) {\n variant(variant);\n }\n }\n \n public static class Banner extends BannerItemBuilder {\n public Banner(DyeColor dyeColor) {\n super(switch (dyeColor) {\n case WHITE -> XMaterial.WHITE_BANNER;\n case ORANGE -> XMaterial.ORANGE_BANNER;\n case MAGENTA -> XMaterial.MAGENTA_BANNER;\n case LIGHT_BLUE -> XMaterial.LIGHT_BLUE_BANNER;\n case YELLOW -> XMaterial.YELLOW_BANNER;\n case LIME -> XMaterial.LIME_BANNER;\n case PINK -> XMaterial.PINK_BANNER;\n case GRAY -> XMaterial.GRAY_BANNER;\n case LIGHT_GRAY -> XMaterial.LIGHT_GRAY_BANNER;\n case CYAN -> XMaterial.CYAN_BANNER;\n case PURPLE -> XMaterial.PURPLE_BANNER;\n case BLUE -> XMaterial.BLUE_BANNER;\n case BROWN -> XMaterial.BROWN_BANNER;\n case GREEN -> XMaterial.GREEN_BANNER;\n case RED -> XMaterial.RED_BANNER;\n case BLACK -> XMaterial.BLACK_BANNER;\n });\n }\n }\n \n public static class Book extends BookItemBuilder {\n public Book(BookType bookType, String title, String author) {\n super(XMaterial.valueOf(bookType.name() + \"_BOOK\"));\n title(title).author(author);\n }\n }\n\n public static class Compass extends CompassItemBuilder {\n public Compass() {}\n \n public Compass(Location lodestone) {\n super.lodestone(lodestone);\n }\n \n public Compass(Location lodestone, boolean tracked) {\n super.lodestone(lodestone).tracked(tracked);\n }\n }\n\n public static class Crossbow extends CrossbowItemBuilder {\n public Crossbow(ItemStack projectile) {\n addProjectile(projectile);\n }\n }\n\n public static class EnchantedBook extends EnchantedBookBuilder {\n public EnchantedBook(Enchantment enchantment, int level) {\n addEnchant(enchantment, level);\n }\n }\n\n public static class Firework extends FireworkItemBuilder {\n public Firework(FireworkEffect effect, int power) {\n super.addEffect(effect).power(power);\n }\n }\n\n public static class FireworkStar extends FireworkStarBuilder {\n public FireworkStar(FireworkEffect effect) {\n super.effect(effect);\n }\n }\n\n public static class FishBucket extends FishBucketBuilder {\n public FishBucket(DyeColor bodyColor, TropicalFish.Pattern pattern, DyeColor patternColor) {\n super.bodyColor(bodyColor).pattern(pattern).patternColor(patternColor);\n }\n }\n\n public static class GoatHorn extends GoatHornBuilder {\n public GoatHorn(MusicInstrument instrument) {\n super.instrument(instrument);\n }\n }\n\n public static class MapItem extends MapItemBuilder {\n public MapItem(MapView mapView) {\n super.mapView(mapView);\n }\n }\n\n public static class Skull extends SkullItemBuilder {\n public Skull(UUID owner) {\n super.owner(owner);\n }\n \n public Skull(PlayerProfile profile) {\n super.profile(profile);\n \n }\n }\n\n public static class Stew extends StewItemBuilder {\n \n }\n \n public static class Tool extends ItemBuilder {\n public Tool(ToolMaterial material, ToolType type) {\n Optional<XMaterial> xMaterial = XMaterial.matchXMaterial(material.name() + \"_\" + type.name());\n xMaterial.ifPresent(value -> this.material = value);\n }\n }\n \n private static ItemBuilder getSubClassFromMeta(ItemMeta itemMeta, String methodName, Class<?> paramClass, Object param) {\n Class<? extends ItemBuilder> itemBuilderClass = null;\n for (Map.Entry<Class<? extends ItemMeta>, Class<? extends ItemBuilder>> entry : META_TO_BUILDERS.entrySet()) {\n if (entry.getKey().isAssignableFrom(itemMeta.getClass())) {\n itemBuilderClass = entry.getValue();\n break;\n }\n }\n\n ItemBuilder itemBuilder;\n\n try {\n Method method = itemBuilderClass.getDeclaredMethod(methodName, paramClass);\n method.setAccessible(true);\n return (ItemBuilder) method.invoke(null, param);\n } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassCastException e) {\n Logger logger = Bukkit.getLogger();\n logger.log(Level.SEVERE, \"Error while parsing an ItemStack into an ItemBuilder\", e);\n return null;\n }\n }\n}"
}
] | import com.cryptomorin.xseries.XMaterial;
import com.stardevllc.starmclib.color.ColorUtils;
import com.stardevllc.starmclib.item.ItemBuilder;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.LinkedList;
import java.util.List; | 7,077 | package com.stardevllc.starmclib.item.material;
public class BookItemBuilder extends ItemBuilder {
private String author;
private List<BaseComponent[]> pages = new LinkedList<>();
private BookMeta.Generation generation = BookMeta.Generation.ORIGINAL;
private String title;
public BookItemBuilder(XMaterial material) {
super(material);
}
protected BookItemBuilder() {
}
protected static BookItemBuilder createFromItemStack(ItemStack itemStack) {
BookItemBuilder itemBuilder = new BookItemBuilder();
BookMeta itemMeta = (BookMeta) itemStack.getItemMeta();
itemBuilder.setPagesComponents(itemMeta.spigot().getPages()).author(itemMeta.getAuthor()).title(itemMeta.getTitle()).generation(itemMeta.getGeneration());
return itemBuilder;
}
protected static BookItemBuilder createFromConfig(ConfigurationSection section) {
BookItemBuilder builder = new BookItemBuilder();
builder.title(section.getString("title"));
builder.author(section.getString("author"));
builder.generation(BookMeta.Generation.valueOf(section.getString("generation")));
ConfigurationSection pagesSection = section.getConfigurationSection("pages");
if (pagesSection != null) {
for (String key : pagesSection.getKeys(false)) {
builder.addPage(ComponentSerializer.parse(pagesSection.getString(key)));
}
}
return builder;
}
@Override
public void saveToConfig(ConfigurationSection section) {
super.saveToConfig(section);
section.set("author", this.author);
section.set("title", this.title);
section.set("generation", this.generation.name());
for (int i = 0; i < pages.size(); i++) {
section.set("pages." + i, ComponentSerializer.toString(pages.get(i)));
}
}
public BookItemBuilder addPage(String page) { | package com.stardevllc.starmclib.item.material;
public class BookItemBuilder extends ItemBuilder {
private String author;
private List<BaseComponent[]> pages = new LinkedList<>();
private BookMeta.Generation generation = BookMeta.Generation.ORIGINAL;
private String title;
public BookItemBuilder(XMaterial material) {
super(material);
}
protected BookItemBuilder() {
}
protected static BookItemBuilder createFromItemStack(ItemStack itemStack) {
BookItemBuilder itemBuilder = new BookItemBuilder();
BookMeta itemMeta = (BookMeta) itemStack.getItemMeta();
itemBuilder.setPagesComponents(itemMeta.spigot().getPages()).author(itemMeta.getAuthor()).title(itemMeta.getTitle()).generation(itemMeta.getGeneration());
return itemBuilder;
}
protected static BookItemBuilder createFromConfig(ConfigurationSection section) {
BookItemBuilder builder = new BookItemBuilder();
builder.title(section.getString("title"));
builder.author(section.getString("author"));
builder.generation(BookMeta.Generation.valueOf(section.getString("generation")));
ConfigurationSection pagesSection = section.getConfigurationSection("pages");
if (pagesSection != null) {
for (String key : pagesSection.getKeys(false)) {
builder.addPage(ComponentSerializer.parse(pagesSection.getString(key)));
}
}
return builder;
}
@Override
public void saveToConfig(ConfigurationSection section) {
super.saveToConfig(section);
section.set("author", this.author);
section.set("title", this.title);
section.set("generation", this.generation.name());
for (int i = 0; i < pages.size(); i++) {
section.set("pages." + i, ComponentSerializer.toString(pages.get(i)));
}
}
public BookItemBuilder addPage(String page) { | this.pages.add(TextComponent.fromLegacyText(ColorUtils.color(page))); | 0 | 2023-10-31 12:53:19+00:00 | 8k |
Java-Game-Engine-Merger/Libgdx-Processing | framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/TMUIPlugin.java | [
{
"identifier": "TMModelManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/internal/model/TMModelManager.java",
"snippet": "public final class TMModelManager implements ITMModelManager{\n public static final TMModelManager INSTANCE=new TMModelManager();\n private final Map<IDocument,TMDocumentModel> models=new ConcurrentHashMap<>();\n private TMModelManager() {}\n @Override\n public TMDocumentModel connect(final IDocument document) {\n return models.computeIfAbsent(document,TMDocumentModel::new);\n }\n @Override\n public void disconnect(final IDocument document) {\n final var model=castNullable(models.remove(document));\n if(model!=null) {\n model.dispose();\n }\n }\n @Override\n public boolean isConnected(IDocument document) {\n return models.containsKey(document);\n }\n}"
},
{
"identifier": "SnippetManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/internal/snippets/SnippetManager.java",
"snippet": "public final class SnippetManager implements ISnippetManager{\n private static final ISnippet[] EMPTY_SNIPPETS= {};\n private static final String SNIPPET_ELT=\"snippet\";\n // \"snippets\" extension point\n private static final String EXTENSION_SNIPPETS=\"snippets\"; //$NON-NLS-1$\n @Nullable\n private static ISnippetManager INSTANCE;\n public static ISnippetManager getInstance() {\n if(INSTANCE!=null) {\n return INSTANCE;\n }\n INSTANCE=createInstance();\n return INSTANCE;\n }\n private static synchronized ISnippetManager createInstance() {\n if(INSTANCE!=null) {\n return INSTANCE;\n }\n final var manager=new SnippetManager();\n manager.load();\n return manager;\n }\n private final Map<String,@Nullable Collection<ISnippet>> snippets=new HashMap<>();\n private SnippetManager() {}\n private void load() {\n loadGrammarsFromExtensionPoints();\n }\n private void loadGrammarsFromExtensionPoints() {\n final IConfigurationElement[] cf=Platform.getExtensionRegistry().getConfigurationElementsFor(\n TMUIPlugin.PLUGIN_ID,EXTENSION_SNIPPETS);\n for(final IConfigurationElement ce:cf) {\n final String extensionName=ce.getName();\n if(SNIPPET_ELT.equals(extensionName)) {\n this.registerSnippet(new Snippet(ce));\n }\n }\n }\n private void registerSnippet(final Snippet snippet) {\n final String scopeName=snippet.getScopeName();\n Collection<ISnippet> snippets=this.snippets.get(scopeName);\n if(snippets==null) {\n snippets=new ArrayList<>();\n this.snippets.put(scopeName,snippets);\n }\n snippets.add(snippet);\n }\n @Override\n public ISnippet[] getSnippets(final String scopeName) {\n final Collection<ISnippet> snippets=this.snippets.get(scopeName);\n return snippets!=null?snippets.toArray(ISnippet[]::new):EMPTY_SNIPPETS;\n }\n}"
},
{
"identifier": "ThemeManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/internal/themes/ThemeManager.java",
"snippet": "public final class ThemeManager extends AbstractThemeManager{\n // \"themes\" extension point\n private static final String EXTENSION_THEMES=\"themes\"; //$NON-NLS-1$\n // \"theme\" declaration\n private static final String THEME_ELT=\"theme\"; //$NON-NLS-1$\n // \"themeAssociation\" declaration\n private static final String THEME_ASSOCIATION_ELT=\"themeAssociation\"; //$NON-NLS-1$\n @Nullable\n private static ThemeManager INSTANCE;\n public static ThemeManager getInstance() {\n if(INSTANCE!=null) {\n return INSTANCE;\n }\n INSTANCE=createInstance();\n return INSTANCE;\n }\n private static synchronized ThemeManager createInstance() {\n if(INSTANCE!=null) {\n return INSTANCE;\n }\n final var manager=new ThemeManager();\n manager.load();\n return manager;\n }\n private ThemeManager() {}\n private void load() {\n loadThemesFromExtensionPoints();\n loadThemesFromPreferences();\n }\n private void loadThemesFromExtensionPoints() {\n final var config=Platform.getExtensionRegistry().getConfigurationElementsFor(TMUIPlugin.PLUGIN_ID,\n EXTENSION_THEMES);\n for(final var configElement:config) {\n final String name=configElement.getName();\n switch(name) {\n case THEME_ELT:\n super.registerTheme(new Theme(configElement));\n break;\n case THEME_ASSOCIATION_ELT:\n super.registerThemeAssociation(new ThemeAssociation(configElement));\n break;\n }\n }\n }\n private void loadThemesFromPreferences() {\n // Load Theme definitions from the\n // \"${workspace_loc}/metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.tm4e.ui.prefs\"\n final var prefs=InstanceScope.INSTANCE.getNode(TMUIPlugin.PLUGIN_ID);\n String json=prefs.get(PreferenceConstants.THEMES,null);\n if(json!=null) {\n for(final var element:new Gson().fromJson(json,JsonObject[].class)) {\n final String name=element.get(\"id\").getAsString();\n super.registerTheme(new Theme(name,element.get(\"path\").getAsString(),name,\n element.get(\"dark\").getAsBoolean(),false));\n }\n }\n json=prefs.get(PreferenceConstants.THEME_ASSOCIATIONS,null);\n if(json!=null) {\n final var themeAssociations=PreferenceHelper.loadThemeAssociations(json);\n for(final IThemeAssociation association:themeAssociations) {\n super.registerThemeAssociation(association);\n }\n }\n }\n @Override\n public void save() throws BackingStoreException {\n final var prefs=InstanceScope.INSTANCE.getNode(TMUIPlugin.PLUGIN_ID);\n // Save Themes in the\n // \"${workspace_loc}/metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.tm4e.ui.prefs\"\n prefs.put(PreferenceConstants.THEMES,Arrays.stream(getThemes()) //\n .filter(t->t.getPluginId()==null) //\n .map(theme-> {\n final var json=new JsonObject();\n json.addProperty(\"id\",theme.getId());\n json.addProperty(\"path\",theme.getPath());\n json.addProperty(\"dark\",theme.isDark());\n return json;\n }).collect(JsonArray::new,(final JsonArray array,final JsonObject object)->array.add(object),\n (r,r1)-> {})\n .toString());\n // Save Theme associations in the\n // \"${workspace_loc}/metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.tm4e.ui.prefs\"\n final String json=PreferenceHelper.toJsonThemeAssociations(Arrays.stream(getAllThemeAssociations())\n .filter(t->t.getPluginId()==null).collect(Collectors.toList()));\n prefs.put(PreferenceConstants.THEME_ASSOCIATIONS,json);\n // Save preferences\n prefs.flush();\n }\n public void addPreferenceChangeListener(final IPreferenceChangeListener themeChangeListener) {\n // Observe change of Eclipse E4 Theme\n var preferences=PreferenceUtils.getE4PreferenceStore();\n if(preferences!=null) {\n preferences.addPreferenceChangeListener(themeChangeListener);\n }\n // Observe change of TextMate Theme association\n preferences=InstanceScope.INSTANCE.getNode(TMUIPlugin.PLUGIN_ID);\n if(preferences!=null) {\n preferences.addPreferenceChangeListener(themeChangeListener);\n }\n }\n public void removePreferenceChangeListener(final IPreferenceChangeListener themeChangeListener) {\n // Observe change of Eclipse E4 Theme\n var preferences=PreferenceUtils.getE4PreferenceStore();\n if(preferences!=null) {\n preferences.removePreferenceChangeListener(themeChangeListener);\n }\n // Observe change of TextMate Theme association\n preferences=InstanceScope.INSTANCE.getNode(TMUIPlugin.PLUGIN_ID);\n if(preferences!=null) {\n preferences.removePreferenceChangeListener(themeChangeListener);\n }\n }\n}"
},
{
"identifier": "ITMModelManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/model/ITMModelManager.java",
"snippet": "public interface ITMModelManager{\n ITMDocumentModel connect(IDocument document);\n void disconnect(IDocument document);\n boolean isConnected(IDocument document);\n}"
},
{
"identifier": "ISnippetManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/snippets/ISnippetManager.java",
"snippet": "public interface ISnippetManager{\n ISnippet[] getSnippets(String scopeName);\n}"
},
{
"identifier": "ColorManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/themes/ColorManager.java",
"snippet": "public final class ColorManager{\n private static final ColorManager INSTANCE=new ColorManager();\n public static ColorManager getInstance() {\n return INSTANCE;\n }\n private static Color rgbToColor(RGB rgb) {\n // return new Color(UI.getDisplay(),rgb.red,rgb.green,rgb.blue);\n return new Color(rgb.red/255f,rgb.green/255f,rgb.blue/255f,1);\n }\n private final Map<RGB,Color> fColorTable=new HashMap<>(10);\n private ColorManager() {}\n public Color getColor(final RGB rgb) {\n return fColorTable.computeIfAbsent(rgb,ColorManager::rgbToColor);\n }\n @Deprecated\n public void dispose() {\n // fColorTable.values().forEach(Color::dispose);\n }\n @Nullable\n @Deprecated\n public Color getPreferenceEditorColor(final String tokenId) {\n // final var prefStore=PreferenceUtils.getEditorsPreferenceStore();\n // if(prefStore==null) return null;\n // return getColor(stringToRGB(prefStore.get(tokenId,\"\")));\n return null;\n }\n @Deprecated\n public boolean isColorUserDefined(final String tokenId) {\n // final var prefStore=PreferenceUtils.getEditorsPreferenceStore();\n // if(prefStore==null) return false;\n // final String systemDefaultToken=getSystemDefaultToken(tokenId);\n // return \"\".equals(systemDefaultToken) // returns true if system default token doesn't exists\n // ||!prefStore.getBoolean(systemDefaultToken,true);\n return false;\n }\n @Nullable\n @Deprecated\n public Color getPriorityColor(@Nullable final Color themeColor,final String tokenId) {\n if(isColorUserDefined(tokenId)) {\n return getPreferenceEditorColor(tokenId);\n }\n // return themeColor!=null?themeColor:null;\n return themeColor!=null?themeColor:null;\n }\n // private String getSystemDefaultToken(final String tokenId) {\n // return switch(tokenId) {\n // case AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND->AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT;\n // case AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND->AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT;\n // case AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND->AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT;\n // case AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND->AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT;\n // default->\"\";\n // };\n // }\n // private RGB stringToRGB(final String value) {\n // final String[] rgbValues=StringUtils.splitToArray(value,',');\n // return rgbValues.length==3\n // ?new RGB(Integer.parseInt(rgbValues[0]),Integer.parseInt(rgbValues[1]),Integer.parseInt(rgbValues[2]))\n // :new RGB(255,255,255);\n // }\n}"
},
{
"identifier": "IThemeManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/themes/IThemeManager.java",
"snippet": "public interface IThemeManager{\n void registerTheme(ITheme theme);\n void unregisterTheme(ITheme theme);\n @Nullable\n ITheme getThemeById(String themeId);\n ITheme[] getThemes();\n ITheme getDefaultTheme();\n ITheme[] getThemes(boolean dark);\n ITheme getThemeForScope(String scopeName,boolean dark);\n ITheme getThemeForScope(String scopeName);\n void registerThemeAssociation(IThemeAssociation association);\n void unregisterThemeAssociation(IThemeAssociation association);\n IThemeAssociation[] getAllThemeAssociations();\n IThemeAssociation[] getThemeAssociationsForScope(String scopeName);\n void save() throws BackingStoreException;\n boolean isDarkEclipseTheme();\n boolean isDarkEclipseTheme(@Nullable String eclipseThemeId);\n ITheme getThemeForScope(String scopeName,Color background);\n}"
}
] | import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.tm4e.ui.internal.model.TMModelManager;
import org.eclipse.tm4e.ui.internal.snippets.SnippetManager;
import org.eclipse.tm4e.ui.internal.themes.ThemeManager;
import org.eclipse.tm4e.ui.model.ITMModelManager;
import org.eclipse.tm4e.ui.snippets.ISnippetManager;
import org.eclipse.tm4e.ui.themes.ColorManager;
import org.eclipse.tm4e.ui.themes.IThemeManager;
import org.osgi.framework.BundleContext;
import pama1234.gdx.textmate.annotation.DeprecatedJface; | 3,715 | package org.eclipse.tm4e.ui;
// import org.eclipse.ui.plugin.AbstractUIPlugin;
// @Deprecated("别动这个")
@DeprecatedJface
public class TMUIPlugin{
// extends AbstractUIPlugin{
// The plug-in ID
public static final String PLUGIN_ID="org.eclipse.tm4e.ui"; //$NON-NLS-1$
private static final String TRACE_ID=PLUGIN_ID+"/trace"; //$NON-NLS-1$
// The shared instance
@Nullable
private static volatile TMUIPlugin plugin;
public static void log(final IStatus status) {
final var p=plugin;
if(p!=null) {
// p.getLog().log(status);
}else {
System.out.println(status);
}
}
public static void logError(final Exception ex) {
log(new Status(IStatus.ERROR,PLUGIN_ID,ex.getMessage(),ex));
}
public static void logTrace(final String message) {
if(isLogTraceEnabled()) {
log(new Status(IStatus.INFO,PLUGIN_ID,message));
}
}
public static boolean isLogTraceEnabled() {
return Boolean.parseBoolean(Platform.getDebugOption(TRACE_ID));
}
// @Override
public void start(@Nullable final BundleContext context) throws Exception {
// super.start(context);
plugin=this;
if(isLogTraceEnabled()) {
// if the trace option is enabled publish all TM4E CORE JDK logging output to the Eclipse Error Log
final var tm4eCorePluginId="org.eclipse.tm4e.core";
final var tm4eCoreLogger=Logger.getLogger(tm4eCorePluginId);
tm4eCoreLogger.setLevel(Level.FINEST);
tm4eCoreLogger.addHandler(new Handler() {
@Override
public void publish(@Nullable final LogRecord entry) {
if(entry!=null) {
log(new Status(toSeverity(entry.getLevel()),tm4eCorePluginId,
entry.getParameters()==null||entry.getParameters().length==0
?entry.getMessage()
:java.text.MessageFormat.format(entry.getMessage(),entry.getParameters())));
}
}
private int toSeverity(final Level level) {
if(level.intValue()>=Level.SEVERE.intValue()) {
return IStatus.ERROR;
}
if(level.intValue()>=Level.WARNING.intValue()) {
return IStatus.WARNING;
}
return IStatus.INFO;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() throws SecurityException {
// nothing to do
}
});
}
}
// @Override
public void stop(@Nullable final BundleContext context) throws Exception {
ColorManager.getInstance().dispose();
plugin=null;
// super.stop(context);
}
@Nullable
public static TMUIPlugin getDefault() {
return plugin;
}
public static ITMModelManager getTMModelManager() {
return TMModelManager.INSTANCE;
}
public static IThemeManager getThemeManager() {
return ThemeManager.getInstance();
}
public static ISnippetManager getSnippetManager() { | package org.eclipse.tm4e.ui;
// import org.eclipse.ui.plugin.AbstractUIPlugin;
// @Deprecated("别动这个")
@DeprecatedJface
public class TMUIPlugin{
// extends AbstractUIPlugin{
// The plug-in ID
public static final String PLUGIN_ID="org.eclipse.tm4e.ui"; //$NON-NLS-1$
private static final String TRACE_ID=PLUGIN_ID+"/trace"; //$NON-NLS-1$
// The shared instance
@Nullable
private static volatile TMUIPlugin plugin;
public static void log(final IStatus status) {
final var p=plugin;
if(p!=null) {
// p.getLog().log(status);
}else {
System.out.println(status);
}
}
public static void logError(final Exception ex) {
log(new Status(IStatus.ERROR,PLUGIN_ID,ex.getMessage(),ex));
}
public static void logTrace(final String message) {
if(isLogTraceEnabled()) {
log(new Status(IStatus.INFO,PLUGIN_ID,message));
}
}
public static boolean isLogTraceEnabled() {
return Boolean.parseBoolean(Platform.getDebugOption(TRACE_ID));
}
// @Override
public void start(@Nullable final BundleContext context) throws Exception {
// super.start(context);
plugin=this;
if(isLogTraceEnabled()) {
// if the trace option is enabled publish all TM4E CORE JDK logging output to the Eclipse Error Log
final var tm4eCorePluginId="org.eclipse.tm4e.core";
final var tm4eCoreLogger=Logger.getLogger(tm4eCorePluginId);
tm4eCoreLogger.setLevel(Level.FINEST);
tm4eCoreLogger.addHandler(new Handler() {
@Override
public void publish(@Nullable final LogRecord entry) {
if(entry!=null) {
log(new Status(toSeverity(entry.getLevel()),tm4eCorePluginId,
entry.getParameters()==null||entry.getParameters().length==0
?entry.getMessage()
:java.text.MessageFormat.format(entry.getMessage(),entry.getParameters())));
}
}
private int toSeverity(final Level level) {
if(level.intValue()>=Level.SEVERE.intValue()) {
return IStatus.ERROR;
}
if(level.intValue()>=Level.WARNING.intValue()) {
return IStatus.WARNING;
}
return IStatus.INFO;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() throws SecurityException {
// nothing to do
}
});
}
}
// @Override
public void stop(@Nullable final BundleContext context) throws Exception {
ColorManager.getInstance().dispose();
plugin=null;
// super.stop(context);
}
@Nullable
public static TMUIPlugin getDefault() {
return plugin;
}
public static ITMModelManager getTMModelManager() {
return TMModelManager.INSTANCE;
}
public static IThemeManager getThemeManager() {
return ThemeManager.getInstance();
}
public static ISnippetManager getSnippetManager() { | return SnippetManager.getInstance(); | 1 | 2023-10-27 05:47:39+00:00 | 8k |
llllllxy/tinycloud | tinycloud-common/src/main/java/org/tinycloud/common/aspect/LimitAspect.java | [
{
"identifier": "LimitType",
"path": "tinycloud-common/src/main/java/org/tinycloud/common/consts/LimitType.java",
"snippet": "public enum LimitType {\n /**\n * 默认策略全局限流\n */\n DEFAULT,\n\n /**\n * 根据请求者IP进行限流\n */\n IP\n}"
},
{
"identifier": "IpUtils",
"path": "tinycloud-common/src/main/java/org/tinycloud/common/utils/IpUtils.java",
"snippet": "public class IpUtils {\n final static Logger log = LoggerFactory.getLogger(IpUtils.class);\n\n /**\n * 在Nginx等代理之后获取用户真实IP地址\n *\n * @param request\n * @return\n */\n public static String getIpAddr(HttpServletRequest request) {\n String ip = request.getHeader(\"X-Real-IP\");\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"x-forwarded-for\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"HTTP_CLIENT_IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"HTTP_X_FORWARDED_FOR\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n if (\"127.0.0.1\".equals(ip) || \"0:0:0:0:0:0:0:1\".equals(ip)) {\n // 根据网卡取本机配置的IP\n InetAddress inet = null;\n try {\n inet = InetAddress.getLocalHost();\n } catch (UnknownHostException e) {\n log.error(\"getIpAddress exception:\", e);\n }\n ip = inet.getHostAddress();\n }\n }\n return StringUtils.substringBefore(ip, \",\");\n }\n}"
},
{
"identifier": "ServletUtils",
"path": "tinycloud-common/src/main/java/org/tinycloud/common/utils/web/ServletUtils.java",
"snippet": "public class ServletUtils {\n public static final String DEFAULT_PARAMS_PARAM = \"params\"; // 登录扩展参数(JSON字符串)优先级高于扩展参数前缀\n public static final String DEFAULT_PARAM_PREFIX_PARAM = \"param_\"; // 扩展参数前缀\n\n // 定义静态文件后缀;静态文件排除URI地址\n private static String[] staticFiles;\n private static String[] staticFileExcludeUri;\n\n /**\n * 获取当前请求对象\n *\n */\n public static HttpServletRequest getRequest() {\n HttpServletRequest request = null;\n try {\n request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();\n return request;\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * 获取当前响应对象\n *\n */\n public static HttpServletResponse getResponse() {\n HttpServletResponse response = null;\n try {\n response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();\n return response;\n } catch (Exception e) {\n return null;\n }\n }\n\n\n /**\n * 获取session\n *\n */\n public static HttpSession getSession() {\n return getRequest().getSession();\n }\n\n\n /**\n * 是否是Ajax异步请求\n *\n * @param request\n */\n public static boolean isAjaxRequest(HttpServletRequest request) {\n String accept = request.getHeader(\"accept\");\n if (accept != null && accept.indexOf(\"application/json\") != -1) {\n return true;\n }\n\n String xRequestedWith = request.getHeader(\"X-Requested-With\");\n if (xRequestedWith != null && xRequestedWith.indexOf(\"XMLHttpRequest\") != -1) {\n return true;\n }\n\n String uri = request.getRequestURI();\n if (inStringIgnoreCase(uri, \".json\", \".xml\")) {\n return true;\n }\n\n String ajax = request.getParameter(\"__ajax\");\n if (inStringIgnoreCase(ajax, \"json\", \"xml\")) {\n return true;\n }\n\n return false;\n }\n\n\n /**\n * 返回结果JSON字符串(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @return JSON字符串:{result:'true',message:''}\n */\n public static String renderResult(String result, String message) {\n return renderResult(result, message, null);\n }\n\n\n /**\n * 返回结果JSON字符串(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @param data 消息数据\n * @return JSON字符串:{result:'true',message:'', if map then key:value,key2:value2... else data:{} }\n */\n @SuppressWarnings(\"unchecked\")\n public static String renderResult(String result, String message, Object data) {\n Map<String, Object> resultMap = new HashMap<>();\n resultMap.put(\"result\", result);\n resultMap.put(\"message\", message);\n if (data != null) {\n if (data instanceof Map) {\n resultMap.putAll((Map<String, Object>) data);\n } else {\n resultMap.put(\"data\", data);\n }\n }\n HttpServletRequest request = ServletUtils.getRequest();\n String uri = request.getRequestURI();\n String functionName = request.getParameter(\"__callback\");\n ObjectMapper objectMapper = new ObjectMapper();\n String returnStr = \"\";\n try {\n if (StringUtils.isNotBlank(functionName)) {\n returnStr = objectMapper.writeValueAsString(new JSONPObject(functionName, resultMap));\n } else {\n returnStr = objectMapper.writeValueAsString(resultMap);\n }\n } catch (IOException var3) {\n\n }\n\n return returnStr;\n }\n\n\n /**\n * 直接将结果JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象:{result:'true',message:'',data:{}}\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @return null\n */\n public static String renderResult(HttpServletResponse response, String result, String message) {\n return renderString(response, renderResult(result, message), null);\n }\n\n\n /**\n * 直接将结果JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象:{result:'true',message:'',data:{}}\n * @param result Global.TRUE or Globle.False\n * @param message 执行消息\n * @param data 消息数据\n * @return null\n */\n public static String renderResult(HttpServletResponse response, String result, String message, Object data) {\n return renderString(response, renderResult(result, message, data), null);\n }\n\n /**\n * 将对象转换为JSON字符串渲染到客户端(支持JsonP,请求参数加:__callback=回调函数名)\n *\n * @param response 渲染对象\n * @param object 待转换JSON并渲染的对象\n * @return null\n */\n public static String renderObject(HttpServletResponse response, Object object) {\n HttpServletRequest request = ServletUtils.getRequest();\n String uri = request.getRequestURI();\n String functionName = request.getParameter(\"__callback\");\n\n ObjectMapper objectMapper = new ObjectMapper();\n String returnStr = \"\";\n\n try {\n if (StringUtils.isNotBlank(functionName)) {\n returnStr = objectMapper.writeValueAsString(new JSONPObject(functionName, object));\n } else {\n returnStr = objectMapper.writeValueAsString(object);\n }\n } catch (IOException var3) {\n\n }\n return returnStr;\n }\n\n\n /**\n * 将字符串渲染到客户端\n *\n * @param response 渲染对象\n * @param string 待渲染的字符串\n * @return null\n */\n public static String renderString(HttpServletResponse response, String string) {\n return renderString(response, string, null);\n }\n\n\n /**\n * 将字符串渲染到客户端\n *\n * @param response 渲染对象\n * @param string 待渲染的字符串\n * @return null\n */\n public static String renderString(HttpServletResponse response, String string, String type) {\n try {\n//\t\t\tresponse.reset(); // 先注释掉,否则以前设置的Header会被清理掉,如ajax登录设置记住我Cookie\n response.setContentType(type == null ? \"application/json\" : type);\n response.setCharacterEncoding(\"utf-8\");\n response.getWriter().print(string);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n\n /**\n * 获得请求参数值\n */\n public static String getParameter(String name) {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return null;\n }\n return request.getParameter(name);\n }\n\n /**\n * 获得请求参数Map\n */\n public static Map<String, Object> getParameters() {\n return getParameters(getRequest());\n }\n\n /**\n * 获得请求参数Map\n */\n public static Map<String, Object> getParameters(ServletRequest request) {\n if (request == null) {\n return new HashMap<String, Object>();\n }\n return getParametersStartingWith(request, \"\");\n }\n\n /**\n * 取得带相同前缀的Request Parameters, copy from spring WebUtils.\n * 返回的结果的Parameter名已去除前缀.\n */\n @SuppressWarnings(\"rawtypes\")\n public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {\n Validate.notNull(request, \"Request must not be null\");\n Enumeration paramNames = request.getParameterNames();\n Map<String, Object> params = new TreeMap<String, Object>();\n String pre = prefix;\n if (pre == null) {\n pre = \"\";\n }\n while (paramNames != null && paramNames.hasMoreElements()) {\n String paramName = (String) paramNames.nextElement();\n if (\"\".equals(pre) || paramName.startsWith(pre)) {\n String unprefixed = paramName.substring(pre.length());\n String[] values = request.getParameterValues(paramName);\n if (values == null || values.length == 0) {\n values = new String[]{};\n // Do nothing, no values found at all.\n } else if (values.length > 1) {\n params.put(unprefixed, values);\n } else {\n params.put(unprefixed, values[0]);\n }\n }\n }\n return params;\n }\n\n\n /**\n * 组合Parameters生成Query String的Parameter部分,并在paramter name上加上prefix.\n */\n public static String encodeParameterStringWithPrefix(Map<String, Object> params, String prefix) {\n StringBuilder queryStringBuilder = new StringBuilder();\n String pre = prefix;\n if (pre == null) {\n pre = \"\";\n }\n Iterator<Entry<String, Object>> it = params.entrySet().iterator();\n while (it.hasNext()) {\n Entry<String, Object> entry = it.next();\n queryStringBuilder.append(pre).append(entry.getKey()).append(\"=\").append(entry.getValue());\n if (it.hasNext()) {\n queryStringBuilder.append(\"&\");\n }\n }\n return queryStringBuilder.toString();\n }\n\n\n /**\n * 从请求对象中扩展参数数据,格式:JSON 或 param_ 开头的参数\n *\n * @param request 请求对象\n * @return 返回Map对象\n */\n public static Map<String, Object> getExtParams(ServletRequest request) {\n Map<String, Object> paramMap = null;\n String params = StringUtils.trim(request.getParameter(DEFAULT_PARAMS_PARAM));\n if (StringUtils.isNotBlank(params) && StringUtils.startsWith(params, \"{\")) {\n ObjectMapper mapper = new ObjectMapper();\n try {\n paramMap = mapper.readValue(params, Map.class);\n } catch (Exception e) {\n paramMap = new HashMap<>();\n }\n\n } else {\n paramMap = getParametersStartingWith(ServletUtils.getRequest(), DEFAULT_PARAM_PREFIX_PARAM);\n }\n return paramMap;\n }\n\n\n /**\n * 设置客户端缓存过期时间 的Header.\n */\n public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {\n // Http 1.0 header, set a fix expires date.\n response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);\n // Http 1.1 header, set a time after now.\n response.setHeader(HttpHeaders.CACHE_CONTROL, \"private, max-age=\" + expiresSeconds);\n }\n\n\n /**\n * 设置禁止客户端缓存的Header.\n */\n public static void setNoCacheHeader(HttpServletResponse response) {\n // Http 1.0 header\n response.setDateHeader(HttpHeaders.EXPIRES, 1L);\n response.addHeader(HttpHeaders.PRAGMA, \"no-cache\");\n // Http 1.1 header\n response.setHeader(HttpHeaders.CACHE_CONTROL, \"no-cache, no-store, max-age=0\");\n }\n\n\n /**\n * 设置LastModified Header.\n */\n public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {\n response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);\n }\n\n /**\n * 设置Etag Header.\n */\n public static void setEtag(HttpServletResponse response, String etag) {\n response.setHeader(HttpHeaders.ETAG, etag);\n }\n\n /**\n * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.\n * 如果无修改, checkIfModify返回false ,设置304 not modify status.\n *\n * @param lastModified 内容的最后修改时间.\n */\n public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,\n long lastModified) {\n long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);\n if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {\n response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);\n return false;\n }\n return true;\n }\n\n\n /**\n * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.\n * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.\n *\n * @param etag 内容的ETag.\n */\n public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {\n String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);\n if (headerValue != null) {\n boolean conditionSatisfied = false;\n if (!\"*\".equals(headerValue)) {\n StringTokenizer commaTokenizer = new StringTokenizer(headerValue, \",\");\n\n while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {\n String currentToken = commaTokenizer.nextToken();\n if (currentToken.trim().equals(etag)) {\n conditionSatisfied = true;\n }\n }\n } else {\n conditionSatisfied = true;\n }\n\n if (conditionSatisfied) {\n response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);\n response.setHeader(HttpHeaders.ETAG, etag);\n return false;\n }\n }\n return true;\n }\n\n\n /**\n * 是否包含字符串\n *\n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs) {\n if (str != null && strs != null) {\n for (String s : strs) {\n if (str.equalsIgnoreCase(StringUtils.trim(s))) {\n return true;\n }\n }\n }\n return false;\n }\n}"
}
] | import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.tinycloud.common.annotation.Limit;
import org.tinycloud.common.consts.LimitType;
import org.tinycloud.common.utils.IpUtils;
import org.tinycloud.common.utils.web.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List; | 4,542 | package org.tinycloud.common.aspect;
/**
* 接口限流处理切面处理类
*
* @author liuxingyu01
* @since 2022-03-13-13:47
**/
@Aspect
@Component
public class LimitAspect {
final static Logger log = LoggerFactory.getLogger(LimitAspect.class);
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 前置通知,判断是否超出限流次数
*
* @param point
*/
@Before("@annotation(limit)")
public void doBefore(JoinPoint point, Limit limit) {
try {
// 拼接key
String key = getCombineKey(limit, point);
// 判断是否超出限流次数
if (!redisLimit(key, limit.count(), limit.time())) {
throw new RuntimeException("访问过于频繁,请稍候再试");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("接口限流异常,请稍候再试");
}
}
/**
* 根据限流类型拼接key
*/
public String getCombineKey(Limit limit, JoinPoint point) {
StringBuilder sb = new StringBuilder(limit.prefix() + ":");
// 按照IP限流
if (limit.type() == LimitType.IP) { | package org.tinycloud.common.aspect;
/**
* 接口限流处理切面处理类
*
* @author liuxingyu01
* @since 2022-03-13-13:47
**/
@Aspect
@Component
public class LimitAspect {
final static Logger log = LoggerFactory.getLogger(LimitAspect.class);
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 前置通知,判断是否超出限流次数
*
* @param point
*/
@Before("@annotation(limit)")
public void doBefore(JoinPoint point, Limit limit) {
try {
// 拼接key
String key = getCombineKey(limit, point);
// 判断是否超出限流次数
if (!redisLimit(key, limit.count(), limit.time())) {
throw new RuntimeException("访问过于频繁,请稍候再试");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("接口限流异常,请稍候再试");
}
}
/**
* 根据限流类型拼接key
*/
public String getCombineKey(Limit limit, JoinPoint point) {
StringBuilder sb = new StringBuilder(limit.prefix() + ":");
// 按照IP限流
if (limit.type() == LimitType.IP) { | sb.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append(":"); | 2 | 2023-10-28 02:05:15+00:00 | 8k |
Daudeuf/GLauncher | src/main/java/fr/glauncher/ui/Launcher.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": "Launch",
"path": "src/main/java/fr/glauncher/ui/panels/Launch.java",
"snippet": "public class Launch extends JPanel implements ActionListener, ChangeListener\n{\n\tprivate final Controller ctrl;\n\tprivate final JButton btnDisconnect;\n\tprivate final JButton btnPlay;\n\tprivate final JButton btnAdditional;\n\tprivate final JSpinner ramSelector;\n\tprivate final JProgressBar progressBar;\n\tprivate final JLabel lblRamInfo;\n\tprivate final JPanel panelBot;\n\tprivate final Image imgFond;\n\tprivate Image imgHead;\n\n\tpublic Launch( Controller ctrl )\n\t{\n\t\tthis.imgFond = getToolkit().getImage ( getClass().getResource(\"/background.png\") );\n\t\tthis.ctrl = ctrl;\n\n\t\tthis.setLayout( new BorderLayout() );\n\n\t\tSpinnerModel ramModel = new SpinnerNumberModel(4096, 1024, 16384, 256);\n\n\t\tlong memorySize = ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalMemorySize();\n\n\t\tthis.btnDisconnect = new JButton(\"Déconnexion\");\n\t\tthis.btnPlay = new JButton(\"Jouer\");\n\t\tthis.btnAdditional = new JButton(\"Mods supplémentaires\");\n\t\tthis.ramSelector = new JSpinner(ramModel);\n\t\tthis.progressBar = new JProgressBar(0, 10000);\n\t\tthis.lblRamInfo = new JLabel(String.format(\" Mémoire RAM disponible : %,d Mo \", memorySize / ( 1_024 * 1_024 )));\n\n\t\tthis.progressBar.setStringPainted(true);\n\t\tthis.progressBar.setValue(0);\n\n\t\tthis.btnPlay .addActionListener( this );\n\t\tthis.btnDisconnect.addActionListener( this );\n\t\tthis.btnAdditional.addActionListener( this );\n\n\t\tthis.ramSelector.setEditor(new JSpinner.NumberEditor(this.ramSelector, \"# Mo\"));\n\t\tthis.ramSelector.addChangeListener(this);\n\n\t\tBorder border = BorderFactory.createLineBorder(Color.darkGray, 2);\n\n\t\tthis.lblRamInfo.setBorder(border);\n\t\tthis.lblRamInfo.setBackground( Color.lightGray );\n\t\tthis.lblRamInfo.setOpaque(true);\n\n\t\tString ramValue = ctrl.getSaver().get(\"ram\");\n\t\tif (ramValue != null && ramValue.matches(\"\\\\d+\")) this.ramSelector.setValue( Integer.parseInt(ramValue) );\n\n\t\tJPanel panelTop = new JPanel();\n\t\tthis.panelBot = new JPanel();\n\n\t\tpanelTop.setOpaque( false );\n\t\tthis.panelBot.setOpaque( false );\n\n\t\tpanelTop.add( this.btnAdditional );\n\t\tpanelTop.add( this.btnDisconnect );\n\t\tpanelTop.add( this.btnPlay );\n\n\t\tthis.panelBot.add(this.ramSelector);\n\t\tthis.panelBot.add(this.lblRamInfo);\n\n\t\tthis.add(panelTop, BorderLayout.NORTH );\n\t\tthis.add( this.panelBot, BorderLayout.SOUTH );\n\t}\n\n\t@Override\n\tpublic void paintComponent(Graphics g)\n\t{\n\t\tsuper.paintComponent(g);\n\n\t\tg.drawImage ( this.imgFond, 0, 0, this );\n\n\t\tif (this.imgHead != null) g.drawImage ( this.imgHead, 50, 200, this );\n\t}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent e)\n\t{\n\t\tif ( e.getSource() == this.btnPlay )\n\t\t{\n\t\t\tthis.ctrl.getLogger().info(\"Preparing launch !\");\n\n\t\t\tnew Thread(() -> Setup.setup( this.ctrl, this ) ).start();\n\t\t}\n\t\telse if ( e.getSource() == this.btnAdditional )\n\t\t{\n\t\t\tnew AdditionalModList( this.ctrl );\n\t\t}\n\t\telse if ( e.getSource() == this.btnDisconnect )\n\t\t{\n\t\t\tthis.ctrl.getSaver().remove(\"msAccessToken\");\n\t\t\tthis.ctrl.getSaver().remove(\"msRefreshToken\");\n\t\t\tthis.ctrl.getSaver().save();\n\n\t\t\tthis.ctrl.switchLogin();\n\t\t}\n\t}\n\n\tpublic void setInLoading( boolean in )\n\t{\n\t\tthis.panelBot.removeAll();\n\n\t\tif (in)\n\t\t{\n\t\t\t//this.panelBot.add(this.ramSelector);\n\t\t\tthis.panelBot.add(this.progressBar);\n\n\t\t\tthis.btnPlay .setEnabled( false );\n\t\t\tthis.btnAdditional.setEnabled( false );\n\t\t\tthis.btnDisconnect.setEnabled( false );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.panelBot.add(this.ramSelector);\n\t\t\tthis.panelBot.add(this.lblRamInfo);\n\t\t\tthis.progressBar.setValue(0);\n\n\t\t\tthis.btnPlay .setEnabled( true );\n\t\t\tthis.btnAdditional.setEnabled( true );\n\t\t\tthis.btnDisconnect.setEnabled( true );\n\t\t}\n\n\t\tthis.repaint();\n\t\tthis.revalidate();\n\t}\n\n\tpublic void setLoadingProgress( int progress )\n\t{\n\t\tthis.progressBar.setValue( progress );\n\t}\n\n\tpublic void refreshHeadImg()\n\t{\n\t\tString name = this.ctrl.getAuth().getAuthInfos().getUsername();\n\n\t\ttry\n\t\t{\n\t\t\tURI url = new URI(String.format(\"https://mc-heads.net/avatar/%s/100.png\", name));\n\n\t\t\tthis.ctrl.getLogger().info(url.toURL().toString());\n\t\t\tthis.imgHead = new ImageIcon(url.toURL()).getImage();\n\t\t}\n\t\tcatch (URISyntaxException | MalformedURLException e)\n\t\t{\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void stateChanged(ChangeEvent e)\n\t{\n\t\tif (e.getSource() == this.ramSelector)\n\t\t{\n\t\t\tint value = (int) this.ramSelector.getValue();\n\n\t\t\tthis.ctrl.getSaver().set(\"ram\", String.valueOf(value));\n\t\t\tthis.ctrl.getSaver().save();\n\t\t}\n\t}\n}"
},
{
"identifier": "Login",
"path": "src/main/java/fr/glauncher/ui/panels/Login.java",
"snippet": "public class Login extends JPanel implements ActionListener\n{\n\tprivate final JCheckBox cb;\n\tprivate final JLabel lblUsername;\n\tprivate final JLabel lblMail;\n\tprivate final JLabel lblPassword;\n\tprivate final JPasswordField txtPassword;\n\tprivate final JTextField txtMail;\n\tprivate final JTextField txtUsername;\n\tprivate final JButton btnValid;\n\tprivate final Image imgFond;\n\n\tprivate final JPanel panelMid;\n\tprivate final JPanel panelBot;\n\n\tprivate final Controller ctrl;\n\n\tpublic Login( Controller ctrl )\n\t{\n\t\tthis.imgFond = getToolkit().getImage ( getClass().getResource(\"/background.png\") );\n\t\tthis.ctrl = ctrl;\n\n\t\tthis.cb = new JCheckBox(\"Mode Hors-Ligne\", false);\n\t\tthis.lblUsername = new JLabel(\"Nom d'Utilisateur\");\n\t\tthis.lblMail = new JLabel(\"Adresse Mail\");\n\t\tthis.lblPassword = new JLabel(\"Mot De Passe\");\n\t\tthis.txtUsername = new JTextField(24);\n\t\tthis.txtMail = new JTextField(48);\n\t\tthis.txtPassword = new JPasswordField(24);\n\t\tthis.btnValid = new JButton(\"Connexion\");\n\n\t\tthis.panelMid = new JPanel();\n\t\tthis.panelBot = new JPanel();\n\n\t\tthis.setLayout( new BorderLayout() );\n\n\t\tthis.btnValid.addActionListener( this );\n\t\tthis.cb .addActionListener( this );\n\n\t\tthis.cb .setOpaque( false );\n\t\tthis.panelMid.setOpaque( false );\n\t\tthis.panelBot.setOpaque( false );\n\n\t\tthis.add(this.panelMid, BorderLayout.CENTER);\n\t\tthis.add(this.panelBot, BorderLayout.SOUTH);\n\n\t\tthis.panelBot.add(this.cb);\n\n\t\tthis.panelMid.add(this.lblMail);\n\t\tthis.panelMid.add(this.txtMail);\n\t\tthis.panelMid.add(this.lblPassword);\n\t\tthis.panelMid.add(this.txtPassword);\n\n\t\tthis.panelBot.add(this.btnValid);\n\t}\n\n\t@Override\n\tpublic void paintComponent(Graphics g)\n\t{\n\t\tsuper.paintComponent(g);\n\n\t\tg.drawImage ( this.imgFond, 0, 0, this );\n\t}\n\n\t@Override\n\tpublic void actionPerformed(ActionEvent e)\n\t{\n\t\tif (e.getSource() == this.cb) // changer crack / pas crack\n\t\t{\n\t\t\tthis.panelMid.removeAll();\n\t\t\tthis.panelBot.removeAll();\n\t\t\t// this.removeAll();\n\n\t\t\tthis.ctrl.getLogger().info(this.cb.isSelected() ? \"Account Type : Offline\" : \"Account Type : Online\");\n\n\t\t\tif ( this.cb.isSelected() )\n\t\t\t{\n\t\t\t\tthis.txtUsername.setText( ctrl.getSaver().get(\"offline-username\") != null ? ctrl.getSaver().get(\"offline-username\") : \"\" );\n\n\t\t\t\tthis.panelBot.add( this.cb );\n\t\t\t\tthis.panelBot.add( this.btnValid );\n\n\t\t\t\tthis.panelMid.add(this.lblUsername );\n\t\t\t\tthis.panelMid.add(this.txtUsername );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthis.txtPassword.setText(\"\");\n\t\t\t\tthis.txtMail .setText(\"\");\n\n\t\t\t\tthis.panelBot.add( this.cb );\n\t\t\t\tthis.panelBot.add( this.btnValid );\n\n\t\t\t\tthis.panelMid.add(this.lblMail );\n\t\t\t\tthis.panelMid.add(this.txtMail );\n\t\t\t\tthis.panelMid.add(this.lblPassword );\n\t\t\t\tthis.panelMid.add(this.txtPassword );\n\t\t\t}\n\n\t\t\tthis.repaint();\n\t\t\tthis.revalidate();\n\t\t}\n\t\telse if (e.getSource() == this.btnValid)\n\t\t{\n\t\t\tString username = this.txtUsername.getText();\n\t\t\tString mail = this.txtMail .getText();\n\t\t\tchar[] password = this.txtPassword.getPassword();\n\n\t\t\tif (this.cb.isSelected() && !username.isEmpty()) this.loginOffline(username);\n\n\t\t\tif (!this.cb.isSelected() && !mail.isEmpty() && password.length >= 3)\n\t\t\t{\n\t\t\t\tthis.loginOnline(mail, password);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void loginOffline(String username)\n\t{\n\t\tthis.ctrl.getSaver().set(\"offline-username\", username);\n\t\tthis.ctrl.getSaver().save();\n\n\t\tif ( this.ctrl.getAuth().isAuth( false ) )\n\t\t{\n\t\t\tthis.ctrl.getLogger().info(\"Connection [ Account Type : Offline ] !\");\n\t\t\tthis.ctrl.getLogger().info(this.ctrl.getAuth().getAuthInfos().getUsername());\n\t\t\tthis.ctrl.switchLogin();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.ctrl.getLogger().err(\"Connection Error [ Account Type : Online ] !\");\n\t\t}\n\t}\n\n\tpublic void loginOnline(String mail, char[] password)\n\t{\n\t\tthis.ctrl.getAuth().auth(mail, password);\n\n\t\tif ( this.ctrl.getAuth().isAuth( true ) )\n\t\t{\n\t\t\tthis.ctrl.getLogger().info(\"Connection [ Account Type : Online ] !\");\n\t\t\tthis.ctrl.getLogger().info(this.ctrl.getAuth().getAuthInfos().getUsername());\n\t\t\tthis.ctrl.switchLogin();\n\n\t\t\tthis.txtPassword.setText(\"\");\n\t\t\tthis.txtMail .setText(\"\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.ctrl.getLogger().err(\"Connection Error [ Account Type : Online ] !\");\n\t\t}\n\t}\n\n\tpublic void checkOnline()\n\t{\n\t\t// lock\n\t\tthis.btnValid.setEnabled( false );\n\t\tthis.txtMail .setEnabled( false );\n\t\tthis.txtPassword.setEnabled( false );\n\t\tthis.txtUsername.setEnabled( false );\n\n\t\tif ( this.ctrl.getAuth().isAuth( true ) )\n\t\t{\n\t\t\tthis.ctrl.getLogger().info(\"Automatic Connection [ Account Type : Online !\");\n\t\t\tthis.ctrl.getLogger().info(this.ctrl.getAuth().getAuthInfos().getUsername());\n\t\t\tthis.ctrl.switchLogin();\n\n\t\t\tthis.txtPassword.setText(\"\");\n\t\t\tthis.txtMail .setText(\"\");\n\t\t}\n\n\t\t// unlock\n\t\tthis.btnValid .setEnabled( true );\n\t\tthis.txtMail .setEnabled( true );\n\t\tthis.txtPassword.setEnabled( true );\n\t\tthis.txtUsername.setEnabled( true );\n\t}\n}"
}
] | import fr.glauncher.Controller;
import fr.glauncher.ui.panels.Launch;
import fr.glauncher.ui.panels.Login;
import javax.swing.*;
import java.awt.*; | 3,726 | package fr.glauncher.ui;
public class Launcher extends JFrame
{
private final JPanel panelSwitch;
private final JPanel panelLaunch;
private final JPanel panelLogin;
private final CardLayout crdLyt;
public Launcher(Controller ctrl)
{
Image icon = getToolkit().getImage( getClass().getResource("/icon.png") );
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = ((int) screenSize.getWidth() - 1024) / 2;
int y = ((int) screenSize.getHeight() - 512) / 2;
this.setLocation(x, y);
this.setSize(1024, 512);
this.setTitle("G Launcher");
this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
this.setResizable( false );
this.setIconImage( icon );
this.crdLyt = new CardLayout();
this.panelSwitch = new JPanel ( this.crdLyt ); | package fr.glauncher.ui;
public class Launcher extends JFrame
{
private final JPanel panelSwitch;
private final JPanel panelLaunch;
private final JPanel panelLogin;
private final CardLayout crdLyt;
public Launcher(Controller ctrl)
{
Image icon = getToolkit().getImage( getClass().getResource("/icon.png") );
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = ((int) screenSize.getWidth() - 1024) / 2;
int y = ((int) screenSize.getHeight() - 512) / 2;
this.setLocation(x, y);
this.setSize(1024, 512);
this.setTitle("G Launcher");
this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
this.setResizable( false );
this.setIconImage( icon );
this.crdLyt = new CardLayout();
this.panelSwitch = new JPanel ( this.crdLyt ); | this.panelLaunch = new Launch (ctrl); | 1 | 2023-10-28 15:35:30+00:00 | 8k |
oehf/xds-registry-to-fhir | src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryVistorImpl.java | [
{
"identifier": "URI_URN",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java",
"snippet": "public static final String URI_URN = \"urn:ietf:rfc:3986\";"
},
{
"identifier": "assignDefaultVersioning",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static Consumer<? super XDSMetaClass> assignDefaultVersioning() {\n return meta -> {\n meta.setLogicalUuid(meta.getEntryUuid());\n meta.setVersion(DEFAULT_VERSION);\n };\n}"
},
{
"identifier": "buildIdentifierQuery",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static ICriterion<?> buildIdentifierQuery(GetByIdQuery query, TokenClientParam param) {\n var searchIdentifiers = new ArrayList<String>();\n if (query.getUniqueIds() != null) {\n searchIdentifiers.addAll(query.getUniqueIds());\n }\n if (query.getUuids() != null) {\n searchIdentifiers.addAll(query.getUuids());\n }\n return param.exactly().systemAndValues(URI_URN,\n searchIdentifiers.stream().map(MappingSupport::toUrnCoded).toList());\n}"
},
{
"identifier": "entryUuidFrom",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static String entryUuidFrom(IBaseResource resource) {\n List<Identifier> identifier;\n if (resource instanceof DocumentReference dResource) {\n identifier = dResource.getIdentifier();\n } else if (resource instanceof ListResource lResource) {\n identifier = lResource.getIdentifier();\n } else {\n return null;\n }\n return identifier.stream().filter(id -> Identifier.IdentifierUse.OFFICIAL.equals(id.getUse())).findFirst()\n .orElse(identifier.stream().findFirst().orElse(new Identifier())).getValue();\n}"
},
{
"identifier": "map",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static void map(TimeRange dateRange, DateClientParam date, IQuery<Bundle> fhirQuery) {\n if (dateRange != null) {\n if (dateRange.getFrom() != null) {\n fhirQuery.where(date.afterOrEquals().millis(Date.from(dateRange.getFrom().getDateTime().toInstant())));\n }\n if (dateRange.getTo() != null) {\n fhirQuery.where(date.before().millis(Date.from(dateRange.getTo().getDateTime().toInstant())));\n }\n }\n}"
},
{
"identifier": "mapPatientIdToQuery",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static void mapPatientIdToQuery(PatientIdBasedStoredQuery query, IQuery<Bundle> fhirQuery) {\n var patientId = query.getPatientId();\n\n var identifier = DocumentReference.PATIENT\n .hasChainedProperty(Patient.IDENTIFIER.exactly().systemAndIdentifier(\n OID_URN + patientId.getAssigningAuthority().getUniversalId(), patientId.getId()));\n fhirQuery.where(identifier);\n}"
},
{
"identifier": "mapStatus",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static void mapStatus(List<AvailabilityStatus> status, TokenClientParam param, IQuery<Bundle> fhirQuery) {\n List<String> fhirStatus = status.stream()\n .map(MappingSupport.STATUS_MAPPING_FROM_XDS::get)\n .filter(Objects::nonNull)\n .map(DocumentReferenceStatus::toCode)\n .toList();\n if (!fhirStatus.isEmpty())\n fhirQuery.where(param.exactly().codes(fhirStatus));\n}"
},
{
"identifier": "urnIdentifierList",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryMapper.java",
"snippet": "public static List<String> urnIdentifierList(GetFromDocumentQuery query) {\n List<String> searchIdentifiers = new ArrayList<>();\n if (query.getUniqueId() != null) {\n searchIdentifiers.add(query.getUniqueId());\n }\n if (query.getUuid() != null) {\n searchIdentifiers.add(query.getUuid());\n }\n searchIdentifiers = searchIdentifiers.stream().map(MappingSupport::toUrnCoded).toList();\n return searchIdentifiers;\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": "MhdFolder",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/fhir/MhdFolder.java",
"snippet": "@ResourceDef(name = \"List\", profile = MappingSupport.MHD_COMPREHENSIVE_FOLDER_PROFILE)\npublic class MhdFolder extends ListResource {\n private static final long serialVersionUID = 6730967324453182475L;\n\n public static final CodeableConcept FOLDER_CODEING = new CodeableConcept(\n new Coding(\"https://profiles.ihe.net/ITI/MHD/CodeSystem/MHDlistTypes\", \"folder\",\n \"Folder as a FHIR List\"));\n\n public MhdFolder() {\n super();\n setCode(FOLDER_CODEING);\n setStatus(ListStatus.CURRENT);\n setMode(ListMode.WORKING);\n }\n\n @Child(name = \"designationType\", type = {CodeableConcept.class}, order=1, min=1, max=Child.MAX_UNLIMITED, modifier=false, summary=false)\n @Extension(url = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/ihe-designationType\", definedLocally = false, isModifier = false)\n @Description(shortDefinition = \"Clinical code of the List\")\n @Getter @Setter\n private List<CodeableConcept> designationType;\n\n}"
},
{
"identifier": "MhdSubmissionSet",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/fhir/MhdSubmissionSet.java",
"snippet": "@ResourceDef(name = \"List\", profile = MappingSupport.MHD_COMPREHENSIVE_SUBMISSIONSET_PROFILE)\npublic class MhdSubmissionSet extends ListResource {\n private static final long serialVersionUID = 6730967324453182475L;\n\n public static final CodeableConcept SUBMISSIONSET_CODEING = new CodeableConcept(\n new Coding(\"https://profiles.ihe.net/ITI/MHD/CodeSystem/MHDlistTypes\", \"submissionset\",\n \"SubmissionSet as a FHIR List\"));\n\n public MhdSubmissionSet() {\n super();\n setCode(SUBMISSIONSET_CODEING);\n setStatus(ListStatus.CURRENT);\n setMode(ListMode.WORKING);\n }\n\n @Child(name = \"designationType\", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=false)\n @Extension(url = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/ihe-designationType\", definedLocally = false, isModifier = false)\n @Description(shortDefinition = \"Clinical code of the List\")\n @Getter @Setter\n private CodeableConcept designationType;\n\n @Child(name = \"sourceId\", type = {Identifier.class}, order=2, min=1, max=1, modifier=false, summary=false)\n @Extension(url = \"https://profiles.ihe.net/ITI/MHD/StructureDefinition/ihe-sourceId\", definedLocally = false, isModifier = false)\n @Description(shortDefinition=\"Publisher organization identity of the SubmissionSet\" )\n @Getter @Setter\n protected Identifier sourceId;\n\n\n}"
}
] | import static org.openehealth.app.xdstofhir.registry.common.MappingSupport.URI_URN;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.assignDefaultVersioning;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.buildIdentifierQuery;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.entryUuidFrom;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.map;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.mapPatientIdToQuery;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.mapStatus;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.urnIdentifierList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.StreamSupport;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.gclient.IQuery;
import ca.uhn.fhir.rest.gclient.TokenClientParam;
import ca.uhn.fhir.util.BundleUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.DocumentReference;
import org.hl7.fhir.r4.model.DomainResource;
import org.hl7.fhir.r4.model.ListResource;
import org.openehealth.app.xdstofhir.registry.common.MappingSupport;
import org.openehealth.app.xdstofhir.registry.common.fhir.MhdFolder;
import org.openehealth.app.xdstofhir.registry.common.fhir.MhdSubmissionSet;
import org.openehealth.ipf.commons.core.URN;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.Association;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.AssociationLabel;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.AssociationType;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.ObjectReference;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindFoldersQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindSubmissionSetsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetAllQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetAssociationsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsAndAssociationsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFolderAndContentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFoldersForDocumentQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFoldersQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetRelatedDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetSubmissionSetAndContentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetSubmissionSetsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.responses.ErrorCode;
import org.openehealth.ipf.commons.ihe.xds.core.responses.ErrorInfo;
import org.openehealth.ipf.commons.ihe.xds.core.responses.QueryResponse;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Severity;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Status; | 3,691 | package org.openehealth.app.xdstofhir.registry.query;
/**
* Implement ITI-18 queries using IPF visitor pattern.
*
* The XDS queries will be mapped to a FHIR query.
*
*
*/
@RequiredArgsConstructor
public class StoredQueryVistorImpl extends AbstractStoredQueryVisitor {
/*
* Hapi currently ignore "_list" parameter, workaround here with "_has" reverse chain search
* https://github.com/hapifhir/hapi-fhir/issues/3761
*/
private static final String HAS_LIST_ITEM_IDENTIFIER = "_has:List:item:identifier";
private final IGenericClient client;
private final StoredQueryProcessor queryProcessor;
private final boolean isObjectRefResult;
@Getter
private final QueryResponse response = new QueryResponse(Status.SUCCESS);
@Override
public void visit(FindDocumentsQuery query) {
IQuery<Bundle> documentFhirQuery = prepareQuery(query);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(GetDocumentsQuery query) {
var documentFhirQuery = initDocumentQuery();
var identifier = buildIdentifierQuery(query, DocumentReference.IDENTIFIER);
documentFhirQuery.where(identifier);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(FindFoldersQuery query) {
var folderFhirQuery = initFolderQuery();
mapPatientIdToQuery(query, folderFhirQuery); | package org.openehealth.app.xdstofhir.registry.query;
/**
* Implement ITI-18 queries using IPF visitor pattern.
*
* The XDS queries will be mapped to a FHIR query.
*
*
*/
@RequiredArgsConstructor
public class StoredQueryVistorImpl extends AbstractStoredQueryVisitor {
/*
* Hapi currently ignore "_list" parameter, workaround here with "_has" reverse chain search
* https://github.com/hapifhir/hapi-fhir/issues/3761
*/
private static final String HAS_LIST_ITEM_IDENTIFIER = "_has:List:item:identifier";
private final IGenericClient client;
private final StoredQueryProcessor queryProcessor;
private final boolean isObjectRefResult;
@Getter
private final QueryResponse response = new QueryResponse(Status.SUCCESS);
@Override
public void visit(FindDocumentsQuery query) {
IQuery<Bundle> documentFhirQuery = prepareQuery(query);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(GetDocumentsQuery query) {
var documentFhirQuery = initDocumentQuery();
var identifier = buildIdentifierQuery(query, DocumentReference.IDENTIFIER);
documentFhirQuery.where(identifier);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(FindFoldersQuery query) {
var folderFhirQuery = initFolderQuery();
mapPatientIdToQuery(query, folderFhirQuery); | map(query.getLastUpdateTime(), ListResource.DATE, folderFhirQuery); | 4 | 2023-10-30 18:58:31+00:00 | 8k |
danielbatres/orthodontic-dentistry-clinical-management | src/com/view/createAsistente/NewAsistenteInformation.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": "AsistenteModel",
"path": "src/com/model/AsistenteModel.java",
"snippet": "public class AsistenteModel extends Usuario {\r\n private String paletaPreferencia;\r\n private String especialidad;\r\n private String estadoActividad;\r\n\r\n /** \r\n * Creacion de nuevo Asistente\r\n */\r\n public AsistenteModel() {\r\n }\r\n\r\n public AsistenteModel(String paletaPreferencia, String especialidad, String estadoActividad, int id, int edad, int diaNacimiento, int mesNacimiento, int annioNacimiento, String nombres, String apellidos, String genero, String telefonoCasa, String telefonoCelular, String direccion, String departamento, String municipio, String foto, String correoElectronico, String contrasena, int diaCreacion, int mesCreacion, int annioCreacion, String horaCreacion, int diaModificacion, int mesModificacion, int annioModificacion, String horaModificacion) {\r\n super(id, edad, diaNacimiento, mesNacimiento, annioNacimiento, nombres, apellidos, genero, telefonoCasa, telefonoCelular, direccion, departamento, municipio, foto, correoElectronico, contrasena, diaCreacion, mesCreacion, annioCreacion, horaCreacion, diaModificacion, mesModificacion, annioModificacion, horaModificacion);\r\n this.paletaPreferencia = paletaPreferencia;\r\n this.especialidad = especialidad;\r\n this.estadoActividad = estadoActividad;\r\n }\r\n \r\n /*------------------ Getters and setters --------------------*/\r\n\r\n public String getEspecialidad() {\r\n return especialidad;\r\n }\r\n\r\n public void setEspecialidad(String especialidad) {\r\n this.especialidad = especialidad;\r\n }\r\n \r\n public String getPaletaPreferencia() {\r\n return paletaPreferencia;\r\n }\r\n\r\n public void setPaletaPreferencia(String paletaPreferencia) {\r\n this.paletaPreferencia = paletaPreferencia;\r\n }\r\n\r\n public String getEstadoActividad() {\r\n return estadoActividad;\r\n }\r\n\r\n public void setEstadoActividad(String estadoActividad) {\r\n this.estadoActividad = estadoActividad;\r\n }\r\n \r\n /*------------------ Getters and setters --------------------*/\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"
},
{
"identifier": "NewContext",
"path": "src/com/view/createPacient/NewContext.java",
"snippet": "public class NewContext extends Styles {\r\n public ArrayList<JTextField> camposTexto = new ArrayList<>();\r\n public ArrayList<KGradientPanel> containersTexto = new ArrayList<>();\r\n public ArrayList<JLabel> advertenciasTexto = new ArrayList<>();\r\n public static boolean isTratamientoOdontologico = false;\r\n public static boolean isTratamientoOrtodontico = false;\r\n public static PacienteModel paciente = new PacienteModel();\r\n public static LocalDateTime localTime = LocalDateTime.now();\r\n public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(\"a\");\r\n public static int emptyCounter = 0;\r\n public static int countedErrors = 0;\r\n \r\n /** \r\n * Este metodo validara todos los campos\r\n * @param camposTexto\r\n * @param advertencias\r\n * @param containers\r\n */\r\n public static void validarTodosLosCampos(ArrayList<JTextField> camposTexto, ArrayList<JLabel> advertencias, ArrayList<KGradientPanel> containers) {\r\n for (int i = 0; i < camposTexto.size(); i++) {\r\n validacionCampo(containers.get(i), camposTexto.get(i), advertencias.get(i), 3);\r\n }\r\n }\r\n \r\n /**\r\n * Este metodo validara campos de texto o numericos en una capa ligera\r\n * \r\n * @param container contenedor al que se pintara borde segun el estado\r\n * @param jTextField el campo de validacion\r\n * @param advertencia texto de advertencia que se desplegara\r\n * @param minLenght\r\n * @return isValidated \r\n */\r\n public static boolean validacionCampo(KGradientPanel container, JTextField jTextField, JLabel advertencia, int minLenght) {\r\n boolean isValidated;\r\n advertencia.setForeground(StateColors.getDanger());\r\n jTextField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger()));\r\n container.setkStartColor(StateColors.getDanger());\r\n container.setkEndColor(StateColors.getDanger());\r\n \r\n isValidated = true;\r\n countedErrors++;\r\n if (jTextField.getText().toLowerCase().contains(\"ingresa\")) {\r\n advertencia.setText(\"Informaci\\u00f3n invalida\");\r\n } else if (jTextField.getText().isEmpty()) {\r\n advertencia.setText(\"No puede ser vac\\u00edo\");\r\n } else if (jTextField.getText().length() < minLenght) {\r\n advertencia.setText(\"M\\u00ednimo \" + minLenght + \" caracteres\");\r\n } else if (jTextField.getText().length() > 75) {\r\n advertencia.setText(\"M\\u00e1ximo 75 caracteres\");\r\n } else {\r\n advertencia.setText(\"\");\r\n jTextField.setBorder(new MatteBorder(1, 0, 1, 0, ChoosedPalette.getGray()));\r\n container.setkStartColor(ChoosedPalette.getGray());\r\n container.setkEndColor(ChoosedPalette.getGray());\r\n \r\n isValidated = false;\r\n if (countedErrors > 0) countedErrors--;\r\n }\r\n \r\n container.repaint();\r\n return isValidated;\r\n }\r\n \r\n /**\r\n * Este metodo validara la fecha de nacimiento\r\n * \r\n * @param containers arreglo de contenedores que se pintaran\r\n * @param jTextFields arreglo de campos que validaremos\r\n * @param advertencia advertencia que se desplegara\r\n */\r\n public void validarFechaNacimiento(ArrayList<KGradientPanel> containers, ArrayList<JTextField> jTextFields, JLabel advertencia) {\r\n advertencia.setForeground(StateColors.getDanger());\r\n for (JTextField jTextField : jTextFields) {\r\n jTextField.setBorder(new MatteBorder(1, 0, 1, 0, StateColors.getDanger()));\r\n }\r\n \r\n for (KGradientPanel container : containers) {\r\n container.setkStartColor(StateColors.getDanger());\r\n container.setkEndColor(StateColors.getDanger());\r\n container.repaint();\r\n }\r\n \r\n countedErrors++;\r\n \r\n for (JTextField jTextField : jTextFields) {\r\n if (jTextField.getText().equals(\"dd\") || jTextField.getText().equals(\"mm\") || jTextField.getText().equals(\"aaaa\")) {\r\n advertencia.setText(\"Fecha inv\\u00e1lida\");\r\n } else if (String.valueOf(jTextField.getText()).trim().equals(\"\")) {\r\n advertencia.setText(\"Fecha inv\\u00e1lida\");\r\n } else {\r\n advertencia.setText(\"\");\r\n jTextField.setBorder(new MatteBorder(1, 0, 1, 0, ChoosedPalette.getGray()));\r\n containers.get(jTextFields.indexOf(jTextField)).setkStartColor(ChoosedPalette.getGray());\r\n containers.get(jTextFields.indexOf(jTextField)).setkEndColor(ChoosedPalette.getGray());\r\n if (countedErrors > 0) countedErrors--;\r\n }\r\n }\r\n }\r\n \r\n /**\r\n * Este metodo validara un combo box segun los parametros indicados\r\n *\r\n * @param comboBox comboBox a validar\r\n * @param advertencia la advertencia que se desplegara\r\n * @param invalidOption opcion invalida a validar\r\n */\r\n public void validacionCombo(JComboBox comboBox, JLabel advertencia, String invalidOption) {\r\n advertencia.setForeground(StateColors.getDanger());\r\n comboBox.setBorder(new LineBorder(StateColors.getDanger()));\r\n \r\n countedErrors++;\r\n if (comboBox.getSelectedItem().toString().equals(invalidOption)) {\r\n advertencia.setText(\"Opci\\u00f3n invalida\");\r\n } else {\r\n advertencia.setText(\"\");\r\n comboBox.setBorder(new LineBorder(ChoosedPalette.getGray()));\r\n if (countedErrors > 0) countedErrors--;\r\n }\r\n }\r\n \r\n public static String emptyMessage(String message) {\r\n if (message.toLowerCase().contains(\"ingresa\") || message.equals(\"\")) return \"No agregado\";\r\n return message;\r\n }\r\n \r\n public void verifyEmpty() {\r\n for (JTextField textField : TEXTFIELDS) {\r\n if (textField.getText().toLowerCase().contains(\"ingresa\") || textField.getText().toLowerCase().contains(\"no agregado\")) {\r\n NewContext.emptyCounter++;\r\n break;\r\n }\r\n }\r\n }\r\n}\r"
}
] | import com.context.ChoosedPalette;
import com.k33ptoo.components.KGradientPanel;
import com.model.AsistenteModel;
import com.utils.Tools;
import com.view.createPacient.NewContext;
import java.time.LocalDateTime;
import java.util.ArrayList;
import javax.swing.JTextField; | 6,462 | package com.view.createAsistente;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 23/09/22
*/
public class NewAsistenteInformation extends NewContext {
ArrayList<JTextField> deleteIngresa = new ArrayList<>();
ArrayList<JTextField> deleteDate = new ArrayList<>();
ArrayList<JTextField> dayAndMonth = new ArrayList<>();
ArrayList<KGradientPanel> contenedoresFechaNacimiento = new ArrayList<>();
ArrayList<JTextField> camposFechaNacimiento = new ArrayList<>();
/**
* Creates new form NewAsistenteInformation
*/
public NewAsistenteInformation() {
initComponents();
styleMyComponentBaby();
}
public AsistenteModel devolverDatos() {
AsistenteModel asistente = new AsistenteModel();
asistente.setEstadoActividad("activo");
asistente.setEspecialidad("asistente");
asistente.setEdad(Integer.parseInt(textField6.getText()));
asistente.setDiaNacimiento(Integer.parseInt(textField2.getText()));
asistente.setMesNacimiento(Integer.parseInt(textField3.getText()));
asistente.setAnnioNacimiento(Integer.parseInt(textField4.getText()));
asistente.setNombres(emptyMessage(textField1.getText()));
asistente.setApellidos(emptyMessage(textField5.getText()));
asistente.setGenero(generoCombo.getSelectedItem().toString());
asistente.setTelefonoCelular(emptyMessage(textField9.getText()));
asistente.setTelefonoCasa(emptyMessage(textField10.getText()));
asistente.setDireccion(emptyMessage(textField11.getText()));
asistente.setDepartamento(comboDepartamento.getSelectedItem().toString());
asistente.setMunicipio(emptyMessage(textField12.getText()));
asistente.setDiaCreacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesCreacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioCreacion(LocalDateTime.now().getYear());
asistente.setCorreoElectronico(textField7.getText());
asistente.setContrasena(textField8.getText());
asistente.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setDiaModificacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesModificacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioModificacion(LocalDateTime.now().getYear());
asistente.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setPaletaPreferencia("light");
return asistente;
}
@Override
public void addTitlesAndSubtitles() {
TITLES_AND_SUBTITLES.add(title1);
TITLES_AND_SUBTITLES.add(title2);
TITLES_AND_SUBTITLES.add(title3);
TITLES_AND_SUBTITLES.add(title4);
TITLES_AND_SUBTITLES.add(title5);
TITLES_AND_SUBTITLES.add(title6);
TITLES_AND_SUBTITLES.add(title7);
TITLES_AND_SUBTITLES.add(title9);
TITLES_AND_SUBTITLES.add(title10);
TITLES_AND_SUBTITLES.add(title11);
TITLES_AND_SUBTITLES.add(title12);
TITLES_AND_SUBTITLES.add(title13);
TITLES_AND_SUBTITLES.add(title14);
TITLES_AND_SUBTITLES.add(title15);
}
@Override
public void addPlainText() {
PLAIN_TEXT.add(text1);
}
@Override
public void addContainers() {
CONTAINERS.add(container1);
CONTAINERS.add(container2);
CONTAINERS.add(container4);
CONTAINERS.add(container5);
CONTAINERS.add(container6);
CONTAINERS.add(container7);
CONTAINERS.add(container8);
CONTAINERS.add(container9);
CONTAINERS.add(container10);
CONTAINERS.add(container11);
CONTAINERS.add(container12);
CONTAINERS.add(container13);
}
@Override
public void addTextFields() {
TEXTFIELDS.add(textField1);
TEXTFIELDS.add(textField2);
TEXTFIELDS.add(textField3);
TEXTFIELDS.add(textField4);
TEXTFIELDS.add(textField5);
TEXTFIELDS.add(textField6);
TEXTFIELDS.add(textField7);
TEXTFIELDS.add(textField8);
TEXTFIELDS.add(textField9);
TEXTFIELDS.add(textField10);
TEXTFIELDS.add(textField11);
TEXTFIELDS.add(textField12);
}
@Override
public void initStyles() {
styles();
camposFechaNacimiento.add(textField2);
camposFechaNacimiento.add(textField3);
camposFechaNacimiento.add(textField4);
contenedoresFechaNacimiento.add(container2);
contenedoresFechaNacimiento.add(container4);
contenedoresFechaNacimiento.add(container5);
camposTexto.add(textField1);
camposTexto.add(textField5);
camposTexto.add(textField7);
camposTexto.add(textField8);
containersTexto.add(container1);
containersTexto.add(container7);
containersTexto.add(container9);
containersTexto.add(container6);
advertenciasTexto.add(advertenciaNombre);
advertenciasTexto.add(advertenciaApellidos);
advertenciasTexto.add(advertenciaCorreo);
advertenciasTexto.add(advertenciaContrasena);
addItemsDepartamento();
}
private void styles() {
informationIcon.setSize(50, 50);
direccionIcon.setSize(50, 50); | package com.view.createAsistente;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 23/09/22
*/
public class NewAsistenteInformation extends NewContext {
ArrayList<JTextField> deleteIngresa = new ArrayList<>();
ArrayList<JTextField> deleteDate = new ArrayList<>();
ArrayList<JTextField> dayAndMonth = new ArrayList<>();
ArrayList<KGradientPanel> contenedoresFechaNacimiento = new ArrayList<>();
ArrayList<JTextField> camposFechaNacimiento = new ArrayList<>();
/**
* Creates new form NewAsistenteInformation
*/
public NewAsistenteInformation() {
initComponents();
styleMyComponentBaby();
}
public AsistenteModel devolverDatos() {
AsistenteModel asistente = new AsistenteModel();
asistente.setEstadoActividad("activo");
asistente.setEspecialidad("asistente");
asistente.setEdad(Integer.parseInt(textField6.getText()));
asistente.setDiaNacimiento(Integer.parseInt(textField2.getText()));
asistente.setMesNacimiento(Integer.parseInt(textField3.getText()));
asistente.setAnnioNacimiento(Integer.parseInt(textField4.getText()));
asistente.setNombres(emptyMessage(textField1.getText()));
asistente.setApellidos(emptyMessage(textField5.getText()));
asistente.setGenero(generoCombo.getSelectedItem().toString());
asistente.setTelefonoCelular(emptyMessage(textField9.getText()));
asistente.setTelefonoCasa(emptyMessage(textField10.getText()));
asistente.setDireccion(emptyMessage(textField11.getText()));
asistente.setDepartamento(comboDepartamento.getSelectedItem().toString());
asistente.setMunicipio(emptyMessage(textField12.getText()));
asistente.setDiaCreacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesCreacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioCreacion(LocalDateTime.now().getYear());
asistente.setCorreoElectronico(textField7.getText());
asistente.setContrasena(textField8.getText());
asistente.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setDiaModificacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesModificacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioModificacion(LocalDateTime.now().getYear());
asistente.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setPaletaPreferencia("light");
return asistente;
}
@Override
public void addTitlesAndSubtitles() {
TITLES_AND_SUBTITLES.add(title1);
TITLES_AND_SUBTITLES.add(title2);
TITLES_AND_SUBTITLES.add(title3);
TITLES_AND_SUBTITLES.add(title4);
TITLES_AND_SUBTITLES.add(title5);
TITLES_AND_SUBTITLES.add(title6);
TITLES_AND_SUBTITLES.add(title7);
TITLES_AND_SUBTITLES.add(title9);
TITLES_AND_SUBTITLES.add(title10);
TITLES_AND_SUBTITLES.add(title11);
TITLES_AND_SUBTITLES.add(title12);
TITLES_AND_SUBTITLES.add(title13);
TITLES_AND_SUBTITLES.add(title14);
TITLES_AND_SUBTITLES.add(title15);
}
@Override
public void addPlainText() {
PLAIN_TEXT.add(text1);
}
@Override
public void addContainers() {
CONTAINERS.add(container1);
CONTAINERS.add(container2);
CONTAINERS.add(container4);
CONTAINERS.add(container5);
CONTAINERS.add(container6);
CONTAINERS.add(container7);
CONTAINERS.add(container8);
CONTAINERS.add(container9);
CONTAINERS.add(container10);
CONTAINERS.add(container11);
CONTAINERS.add(container12);
CONTAINERS.add(container13);
}
@Override
public void addTextFields() {
TEXTFIELDS.add(textField1);
TEXTFIELDS.add(textField2);
TEXTFIELDS.add(textField3);
TEXTFIELDS.add(textField4);
TEXTFIELDS.add(textField5);
TEXTFIELDS.add(textField6);
TEXTFIELDS.add(textField7);
TEXTFIELDS.add(textField8);
TEXTFIELDS.add(textField9);
TEXTFIELDS.add(textField10);
TEXTFIELDS.add(textField11);
TEXTFIELDS.add(textField12);
}
@Override
public void initStyles() {
styles();
camposFechaNacimiento.add(textField2);
camposFechaNacimiento.add(textField3);
camposFechaNacimiento.add(textField4);
contenedoresFechaNacimiento.add(container2);
contenedoresFechaNacimiento.add(container4);
contenedoresFechaNacimiento.add(container5);
camposTexto.add(textField1);
camposTexto.add(textField5);
camposTexto.add(textField7);
camposTexto.add(textField8);
containersTexto.add(container1);
containersTexto.add(container7);
containersTexto.add(container9);
containersTexto.add(container6);
advertenciasTexto.add(advertenciaNombre);
advertenciasTexto.add(advertenciaApellidos);
advertenciasTexto.add(advertenciaCorreo);
advertenciasTexto.add(advertenciaContrasena);
addItemsDepartamento();
}
private void styles() {
informationIcon.setSize(50, 50);
direccionIcon.setSize(50, 50); | Tools.setImageLabel(informationIcon, "src/com/assets/usuario.png", 30, 30, ChoosedPalette.getWhite()); | 2 | 2023-10-26 19:35:40+00:00 | 8k |
ddoubest/mini-spring | src/com/minis/web/AnnotationConfigWebApplicationContext.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": "AbstractApplicationContext",
"path": "src/com/minis/context/AbstractApplicationContext.java",
"snippet": "public abstract class AbstractApplicationContext implements ApplicationContext {\n private Environment environment;\n private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();\n private long startupDate;\n private final AtomicBoolean active = new AtomicBoolean();\n private ApplicationEventPublisher applicationEventPublisher;\n\n public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {\n return beanFactoryPostProcessors;\n }\n\n public void refresh() {\n postProcessBeanFactory(getBeanFactory());\n registerBeanPostProcessors(getBeanFactory());\n initApplicationEventPublisher();\n onRefresh();\n registerListeners();\n finishRefresh();\n }\n\n protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {\n beanFactoryPostProcessors.forEach(beanFactoryPostProcessor -> {\n try {\n beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);\n } catch (BeansException e) {\n throw new RuntimeException(e);\n }\n });\n };\n\n protected abstract void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory);\n\n protected abstract void initApplicationEventPublisher();\n\n protected abstract void onRefresh();\n\n protected abstract void registerListeners();\n\n protected abstract void finishRefresh();\n\n @Override\n public String getApplicationName() {\n return \"\";\n }\n\n @Override\n public long getStartupDate() {\n return startupDate;\n }\n\n @Override\n public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {\n beanFactoryPostProcessors.add(postProcessor);\n }\n\n @Override\n public boolean isActive() {\n return active.get();\n }\n\n @Override\n public void close() {\n active.set(false);\n }\n\n public ApplicationEventPublisher getApplicationEventPublisher() {\n return applicationEventPublisher;\n }\n\n public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {\n this.applicationEventPublisher = applicationEventPublisher;\n }\n\n @Override\n public Environment getEnvironment() {\n return environment;\n }\n\n @Override\n public void setEnvironment(Environment environment) {\n this.environment = environment;\n }\n\n @Override\n public void publishEvent(ApplicationEvent event) {\n getApplicationEventPublisher().publishEvent(event);\n }\n\n @Override\n public void addApplicationListener(ApplicationListener listener) {\n getApplicationEventPublisher().addApplicationListener(listener);\n }\n\n @Override\n public Object getBean(String beanName) throws BeansException {\n return getBeanFactory().getBean(beanName);\n }\n\n @Override\n public Boolean containsBean(String beanName) {\n return getBeanFactory().containsBean(beanName);\n }\n\n @Override\n public void registerBean(String beanName, Object obj) {\n getBeanFactory().registerBean(beanName, obj);\n }\n\n @Override\n public boolean isSingleton(String name) {\n return getBeanFactory().isSingleton(name);\n }\n\n @Override\n public boolean isPrototype(String name) {\n return getBeanFactory().isPrototype(name);\n }\n\n @Override\n public Class<?> getType(String name) {\n return getBeanFactory().getType(name);\n }\n\n @Override\n public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {\n getBeanFactory().addBeanPostProcessor(beanPostProcessor);\n }\n\n @Override\n public int getBeanPostProcessorCount() {\n return getBeanFactory().getBeanPostProcessorCount();\n }\n\n @Override\n public List<BeanPostProcessor> getBeanPostProcessors() {\n return getBeanFactory().getBeanPostProcessors();\n }\n\n @Override\n public void registerDependentBean(String beanName, String dependentBeanName) {\n getBeanFactory().registerDependentBean(beanName, dependentBeanName);\n }\n\n @Override\n public String[] getDependentBeans(String beanName) {\n return getBeanFactory().getDependentBeans(beanName);\n }\n\n @Override\n public boolean containsBeanDefinition(String beanName) {\n return getBeanFactory().containsBeanDefinition(beanName);\n }\n\n @Override\n public int getBeanDefinitionCount() {\n return getBeanFactory().getBeanDefinitionCount();\n }\n\n @Override\n public String[] getBeanDefinitionNames() {\n return getBeanFactory().getBeanDefinitionNames();\n }\n\n @Override\n public String[] getBeanNamesForType(Class<?> clazz) {\n return getBeanFactory().getBeanNamesForType(clazz);\n }\n\n @Override\n public <T> Map<String, T> getBeansOfTypes(Class<T> clazz) {\n return getBeanFactory().getBeansOfTypes(clazz);\n }\n\n @Override\n public void registerSingleton(String beanName, Object singletonObject) {\n getBeanFactory().registerSingleton(beanName, singletonObject);\n }\n\n @Override\n public Object getSingleton(String beanName) {\n return getBeanFactory().getSingleton(beanName);\n }\n\n @Override\n public Boolean contatinsSingleton(String beanName) {\n return getBeanFactory().contatinsSingleton(beanName);\n }\n\n @Override\n public String[] getSingletonNames() {\n return getBeanFactory().getSingletonNames();\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": "BeansException",
"path": "src/com/minis/exceptions/BeansException.java",
"snippet": "public class BeansException extends Exception {\n public BeansException(String message) {\n super(message);\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.context.AbstractApplicationContext;
import com.minis.event.ApplicationListener;
import com.minis.event.ContextRefreshEvent;
import com.minis.event.SimpleApplicationEventPublisher;
import com.minis.exceptions.BeansException;
import com.minis.utils.ScanComponentHelper;
import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List; | 3,779 | package com.minis.web;
public class AnnotationConfigWebApplicationContext extends AbstractApplicationContext implements WebApplicationContext {
private final DefaultListableBeanFactory beanFactory;
private ServletContext servletContext;
private WebApplicationContext parentWebApplicationContext;
public AnnotationConfigWebApplicationContext(String fileName) {
this(fileName, null);
}
public AnnotationConfigWebApplicationContext(String fileName, WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.servletContext = parentWebApplicationContext.getServletContext();
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
URL xmlPath;
try {
xmlPath = getServletContext().getResource(fileName);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
List<String> packageNames = XmlScanComponentHelper.getNodeValue(xmlPath);
List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames);
ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames);
refresh();
}
@Override
public Object getBean(String beanName) throws BeansException {
Object result = super.getBean(beanName);
if (result == null) {
result = parentWebApplicationContext.getBean(beanName);
}
return result;
}
public WebApplicationContext getParentWebApplicationContext() {
return parentWebApplicationContext;
}
public void setParentWebApplicationContext(WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public WebApplicationContext getParent() {
return parentWebApplicationContext;
}
@Override
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return beanFactory;
}
@Override
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { | package com.minis.web;
public class AnnotationConfigWebApplicationContext extends AbstractApplicationContext implements WebApplicationContext {
private final DefaultListableBeanFactory beanFactory;
private ServletContext servletContext;
private WebApplicationContext parentWebApplicationContext;
public AnnotationConfigWebApplicationContext(String fileName) {
this(fileName, null);
}
public AnnotationConfigWebApplicationContext(String fileName, WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.servletContext = parentWebApplicationContext.getServletContext();
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
URL xmlPath;
try {
xmlPath = getServletContext().getResource(fileName);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
List<String> packageNames = XmlScanComponentHelper.getNodeValue(xmlPath);
List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames);
ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames);
refresh();
}
@Override
public Object getBean(String beanName) throws BeansException {
Object result = super.getBean(beanName);
if (result == null) {
result = parentWebApplicationContext.getBean(beanName);
}
return result;
}
public WebApplicationContext getParentWebApplicationContext() {
return parentWebApplicationContext;
}
public void setParentWebApplicationContext(WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public WebApplicationContext getParent() {
return parentWebApplicationContext;
}
@Override
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return beanFactory;
}
@Override
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { | beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(this)); | 2 | 2023-10-30 12:36:32+00:00 | 8k |
xingduansuzhao-MC/ModTest | src/main/java/com/xdsz/test/util/RegistryHandler.java | [
{
"identifier": "Test",
"path": "src/main/java/com/xdsz/test/Test.java",
"snippet": "@Mod(\"test\")\npublic class Test\n{\n // Directly reference a log4j logger.\n public static final Logger LOGGER = LogManager.getLogger();//p15的private改为public,控制台能查看调试\n public static final String MOD_ID = \"test\";\n\n public Test() {\n // Register the setup method for mod loading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n\n RegistryHandler.init();\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n private void setup(final FMLCommonSetupEvent event) {\n DeferredWorkQueue.runLater(() -> {\n GlobalEntityTypeAttributes.put(RegistryHandler.TEST_BEAR.get(), TestBearEntity.testBearAttributes().create());\n });\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_FLUID.get(), RenderType.getTranslucent());\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_BLOCK.get(), RenderType.getTranslucent());\n RenderTypeLookup.setRenderLayer(TestFluids.HONEYTEST_FLOWING.get(), RenderType.getTranslucent());\n\n TestKeybinds.register(event);\n }\n\n public static final ItemGroup TAB = new ItemGroup(\"testTab\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(RegistryHandler.SAPPHIRE.get());\n }\n };\n\n}"
},
{
"identifier": "ModArmorMaterial",
"path": "src/main/java/com/xdsz/test/armor/ModArmorMaterial.java",
"snippet": "public enum ModArmorMaterial implements IArmorMaterial {\n\n SAPPHIRE(Test.MOD_ID + \":sapphire\", 40, new int[] { 2, 5, 6, 2 },\n 18 , SoundEvents.ITEM_ARMOR_EQUIP_GENERIC,\n 99999999999999999.0F,\n () -> { return Ingredient.fromItems(RegistryHandler.SAPPHIRE.get());},\n 0);\n\n private static final int[] MAX_DAMAGE_ARRAY = new int[] { 11, 16, 15, 13 };\n private final String name;\n private final int maxDamageFactor;\n private final int[] damageReductionAmountArray;\n private final int enchantability;\n private final SoundEvent soundEvent;\n private final float toughness;\n private final Supplier<Ingredient> repairMaterial;\n private final float knockbackResistance;\n\n ModArmorMaterial(String name,int maxDamageFactor,int[] damageReductionAmountArray\n ,int enchantability,SoundEvent soundEvent,float toughness,\n Supplier<Ingredient> repairMaterial,float knockbackResistance) {\n this.name = name;\n this.maxDamageFactor = maxDamageFactor;\n this.damageReductionAmountArray = damageReductionAmountArray;\n this.enchantability = enchantability;\n this.soundEvent = soundEvent;\n this.toughness = toughness;\n this.repairMaterial = repairMaterial;\n this.knockbackResistance = knockbackResistance;\n }\n\n @Override\n public int getDurability(EquipmentSlotType equipmentSlotType) {\n return MAX_DAMAGE_ARRAY[equipmentSlotType.getIndex()] * this.maxDamageFactor;\n }\n\n @Override\n public int getDamageReductionAmount(EquipmentSlotType equipmentSlotType) {\n return this.damageReductionAmountArray[equipmentSlotType.getIndex()];\n }\n\n @Override\n public int getEnchantability() {\n return this.enchantability;\n }\n\n @Override\n public SoundEvent getSoundEvent() {\n return this.soundEvent;\n }\n\n @Override\n public Ingredient getRepairMaterial() {\n return this.repairMaterial.get();\n }\n\n @OnlyIn(Dist.CLIENT)\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public float getToughness() {\n return this.toughness;\n }\n\n\n //注意 func_230304_f_替换为getKnockbackResistance\n @Override\n public float getKnockbackResistance() {\n return this.knockbackResistance;\n }\n}"
},
{
"identifier": "BlockItemBase",
"path": "src/main/java/com/xdsz/test/blocks/BlockItemBase.java",
"snippet": "public class BlockItemBase extends BlockItem {\n public BlockItemBase(Block block) {\n super(block, new Item.Properties().group(Test.TAB));\n }\n}"
},
{
"identifier": "SapphireOre",
"path": "src/main/java/com/xdsz/test/blocks/SapphireOre.java",
"snippet": "public class SapphireOre extends OreBlock {\n public SapphireOre() {\n super(AbstractBlock.Properties.create(Material.IRON)\n .hardnessAndResistance(3.0f,4.0f)\n .sound(SoundType.STONE)\n .harvestTool(ToolType.PICKAXE)\n .harvestLevel(2)\n /*.setRequiresTool()*/ );\n }\n\n @Override\n public int getExpDrop(BlockState state, IWorldReader reader, BlockPos pos, int fortune, int silktouch){\n return 1;\n }\n}"
},
{
"identifier": "TestBearEntity",
"path": "src/main/java/com/xdsz/test/entities/TestBearEntity.java",
"snippet": "public class TestBearEntity extends PolarBearEntity {\n public TestBearEntity(EntityType<? extends PolarBearEntity> type, World world) {super(type, world);}\n\n public static AttributeModifierMap.MutableAttribute testBearAttributes(){\n return MobEntity.func_233666_p_()\n .createMutableAttribute(Attributes.MAX_HEALTH, 30.00)\n .createMutableAttribute(Attributes.MOVEMENT_SPEED, 0.25D);\n }\n}"
},
{
"identifier": "TestFluids",
"path": "src/main/java/com/xdsz/test/fluids/TestFluids.java",
"snippet": "public class TestFluids {\n\n public static final ResourceLocation WATER_STILL_RL = new ResourceLocation(\"block/water_still\");\n public static final ResourceLocation WATER_FLOWING_RL = new ResourceLocation(\"block/water_flow\");\n public static final ResourceLocation WATER_OVERLAY_RL = new ResourceLocation(\"block/water_overlay\");\n\n public static final RegistryObject<FlowingFluid> HONEYTEST_FLUID = FLUIDS.register(\"honeytest_fluid\",\n () -> new ForgeFlowingFluid.Source(TestFluids.HONEYTEST_PROPERTIES));\n\n public static final RegistryObject<FlowingFluid> HONEYTEST_FLOWING = FLUIDS.register(\"honeytest_flowing\",\n () -> new ForgeFlowingFluid.Flowing(TestFluids.HONEYTEST_PROPERTIES));\n\n public static final ForgeFlowingFluid.Properties HONEYTEST_PROPERTIES = new ForgeFlowingFluid.Properties(\n () -> HONEYTEST_FLUID.get(), () -> HONEYTEST_FLOWING.get(),\n FluidAttributes.builder(WATER_STILL_RL, WATER_FLOWING_RL)\n .sound(SoundEvents.ITEM_HONEY_BOTTLE_DRINK).overlay(WATER_OVERLAY_RL)\n .color(0xffffd247)).slopeFindDistance(9).levelDecreasePerBlock(2)\n .block(()->TestFluids.HONEYTEST_BLOCK.get()).bucket(()-> RegistryHandler.HONEYTEST_BUCKET.get());\n\n public static final RegistryObject<FlowingFluidBlock> HONEYTEST_BLOCK = RegistryHandler.BLOCKS.register(\"honeytest\",\n () -> new FlowingFluidBlock(()->TestFluids.HONEYTEST_FLUID.get(), AbstractBlock.Properties.create(Material.WATER)\n .hardnessAndResistance(0f)));\n\n public static void register(IEventBus eventBus){FLUIDS.register(eventBus);}\n}"
},
{
"identifier": "ItemBase",
"path": "src/main/java/com/xdsz/test/items/ItemBase.java",
"snippet": "public class ItemBase extends Item {\n public ItemBase() {\n super(new Item.Properties().group(Test.TAB));\n }\n}"
},
{
"identifier": "PoisonApple",
"path": "src/main/java/com/xdsz/test/items/PoisonApple.java",
"snippet": "public class PoisonApple extends Item {\n public PoisonApple() {\n super(new Item.Properties()\n .group(Test.TAB)\n .food(new Food.Builder()\n .hunger(10)\n .saturation(1.2f)\n .effect(new EffectInstance(Effects.NAUSEA, 300, 1), 1)\n .effect(new EffectInstance(Effects.POISON, 300, 1), 1)\n .effect(new EffectInstance(Effects.HUNGER, 300, 1), 0.3f)\n .meat()\n .setAlwaysEdible()\n .build())\n\n\n\n\n\n );\n }\n}"
},
{
"identifier": "SapphireBlock",
"path": "src/main/java/com/xdsz/test/blocks/SapphireBlock.java",
"snippet": "public class SapphireBlock extends Block {\n public SapphireBlock() {\n super(AbstractBlock.Properties.create(Material.IRON)\n .hardnessAndResistance(5.0f,6.0f)\n .sound(SoundType.METAL)\n .harvestTool(ToolType.PICKAXE)\n .harvestLevel(2)\n /*.setRequiresTool()\n .setLightLevel(value -> 15)*/ );\n }\n}"
},
{
"identifier": "TestSpawnEgg",
"path": "src/main/java/com/xdsz/test/items/TestSpawnEgg.java",
"snippet": "public class TestSpawnEgg extends SpawnEggItem {\n\n protected static final List<TestSpawnEgg> UNADDED_EGGS = new ArrayList<>();\n private final Lazy<? extends EntityType<?>> entityTypeSupplier;\n\n public TestSpawnEgg(final RegistryObject<? extends EntityType<?>> entityTypeSupplier, int p_i48465_2_, int p_i48465_3_, Properties p_i48465_4_) {\n super(null, p_i48465_2_, p_i48465_3_, p_i48465_4_);\n this.entityTypeSupplier = Lazy.of(entityTypeSupplier::get);\n UNADDED_EGGS.add(this);\n }\n\n public static void initSpawnEggs(){\n final Map<EntityType<?>, SpawnEggItem> EGGS = ObfuscationReflectionHelper.getPrivateValue(SpawnEggItem.class, null, \"field_195987_b\");\n for (final SpawnEggItem spawnEgg : UNADDED_EGGS){\n EGGS.put(spawnEgg.getType(null), spawnEgg);\n }\n }\n\n @Override\n public EntityType<?> getType(CompoundNBT nbt) {\n return this.entityTypeSupplier.get();\n }\n}"
},
{
"identifier": "ModItemTier",
"path": "src/main/java/com/xdsz/test/tools/ModItemTier.java",
"snippet": "public enum ModItemTier implements IItemTier {\n\n SAPPHIRE(4, 2000, 20.0F, 3.0F, 16 ,\n () -> {return Ingredient.fromItems(RegistryHandler.SAPPHIRE.get());});\n\n\n private final int harvestLevel;\n private final int maxUses;\n private final float efficiency;\n private final float attackDamage;\n private final int enchantability;\n private final Supplier<Ingredient> repairMaterial;\n\n ModItemTier(int harvestLevel,int maxUses,float efficiency,float attackDamage,\n int enchantability,Supplier<Ingredient> repairMaterial) {\n this.harvestLevel = harvestLevel;\n this.efficiency = efficiency;\n this.enchantability = enchantability;\n this.attackDamage = attackDamage;\n this.maxUses = maxUses;\n this.repairMaterial = repairMaterial;\n }\n\n @Override\n public int getMaxUses() {return maxUses;}\n\n @Override\n public float getEfficiency() {\n return efficiency;\n }\n\n @Override\n public float getAttackDamage() {\n return attackDamage;\n }\n\n @Override\n public int getHarvestLevel() {\n return harvestLevel;\n }\n\n @Override\n public int getEnchantability() {\n return enchantability;\n }\n\n @Override\n public Ingredient getRepairMaterial() {\n return repairMaterial.get();\n }\n}"
}
] | import com.xdsz.test.Test;
import com.xdsz.test.armor.ModArmorMaterial;
import com.xdsz.test.blocks.BlockItemBase;
import com.xdsz.test.blocks.SapphireOre;
import com.xdsz.test.entities.TestBearEntity;
import com.xdsz.test.fluids.TestFluids;
import com.xdsz.test.items.ItemBase;
import com.xdsz.test.items.PoisonApple;
import com.xdsz.test.blocks.SapphireBlock;
import com.xdsz.test.items.TestSpawnEgg;
import com.xdsz.test.tools.ModItemTier;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType;
import net.minecraft.fluid.Fluid;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries; | 4,179 | package com.xdsz.test.util;
public class RegistryHandler {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Test.MOD_ID);
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Test.MOD_ID);
public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Test.MOD_ID);
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, Test.MOD_ID);
public static void init(){
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
TestFluids.register(FMLJavaModLoadingContext.get().getModEventBus());
SOUND_EVENTS.register(FMLJavaModLoadingContext.get().getModEventBus());
ENTITY_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus());
}
//物品
public static final RegistryObject<Item> SAPPHIRE = ITEMS.register("sapphire",ItemBase::new);
//方块(手持)
public static final RegistryObject<Block> SAPPHIRE_BLOCK = BLOCKS.register("sapphire_block",SapphireBlock::new);
public static final RegistryObject<Block> SAPPHIRE_ORE = BLOCKS.register("sapphire_ore", SapphireOre::new);
//方块(着地)
public static final RegistryObject<Item> SAPPHIRE_BLOCK_ITEM = ITEMS.register("sapphire_block",
() -> new BlockItemBase(SAPPHIRE_BLOCK.get()));
public static final RegistryObject<Item> SAPPHIRE_ORE_ITEM = ITEMS.register("sapphire_ore",
() -> new BlockItemBase(SAPPHIRE_ORE.get()));
//工具
public static final RegistryObject<SwordItem> SAPPHIRE_SWORD = ITEMS.register("sapphire_sword",
() -> new SwordItem(ModItemTier.SAPPHIRE, 50, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<AxeItem> SAPPHIRE_AXE = ITEMS.register("sapphire_axe",
() -> new AxeItem(ModItemTier.SAPPHIRE, 100,20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ShovelItem> SAPPHIRE_SHOVEL = ITEMS.register("sapphire_shovel",
() -> new ShovelItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<HoeItem> SAPPHIRE_HOE = ITEMS.register("sapphire_hoe",
() -> new HoeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<PickaxeItem> SAPPHIRE_PICKAXE = ITEMS.register("sapphire_pickaxe",
() -> new PickaxeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
//盔甲
public static final RegistryObject<ArmorItem> SAPPHIRE_HELMET = ITEMS.register("sapphire_helmet",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.HEAD, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_CHESTPLATE = ITEMS.register("sapphire_chestplate",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.CHEST, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_LEGS = ITEMS.register("sapphire_leggings",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.LEGS, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_BOOTS = ITEMS.register("sapphire_boots",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.FEET, new Item.Properties().group(Test.TAB)));
//毒苹果
public static final RegistryObject<PoisonApple> POISON_APPLE = ITEMS.register("poison_apple", PoisonApple::new);
//流体(桶)
public static final RegistryObject<Item> HONEYTEST_BUCKET = ITEMS.register("honeytest_bucket",
()->new BucketItem(()->TestFluids.HONEYTEST_FLUID.get(), new Item.Properties().maxStackSize(1).group(Test.TAB)));
//音乐
public static final RegistryObject<SoundEvent> CAI_XUKUN = SOUND_EVENTS.register("cai_xukun",
()->new SoundEvent(new ResourceLocation(Test.MOD_ID, "cai_xukun")));
public static final RegistryObject<Item> KUN_DISC = ITEMS.register("kun_disc",
()->new MusicDiscItem(1, () -> CAI_XUKUN.get(), new Item.Properties().maxStackSize(16).group(Test.TAB)));
//实体 | package com.xdsz.test.util;
public class RegistryHandler {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Test.MOD_ID);
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Test.MOD_ID);
public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Test.MOD_ID);
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, Test.MOD_ID);
public static void init(){
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
TestFluids.register(FMLJavaModLoadingContext.get().getModEventBus());
SOUND_EVENTS.register(FMLJavaModLoadingContext.get().getModEventBus());
ENTITY_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus());
}
//物品
public static final RegistryObject<Item> SAPPHIRE = ITEMS.register("sapphire",ItemBase::new);
//方块(手持)
public static final RegistryObject<Block> SAPPHIRE_BLOCK = BLOCKS.register("sapphire_block",SapphireBlock::new);
public static final RegistryObject<Block> SAPPHIRE_ORE = BLOCKS.register("sapphire_ore", SapphireOre::new);
//方块(着地)
public static final RegistryObject<Item> SAPPHIRE_BLOCK_ITEM = ITEMS.register("sapphire_block",
() -> new BlockItemBase(SAPPHIRE_BLOCK.get()));
public static final RegistryObject<Item> SAPPHIRE_ORE_ITEM = ITEMS.register("sapphire_ore",
() -> new BlockItemBase(SAPPHIRE_ORE.get()));
//工具
public static final RegistryObject<SwordItem> SAPPHIRE_SWORD = ITEMS.register("sapphire_sword",
() -> new SwordItem(ModItemTier.SAPPHIRE, 50, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<AxeItem> SAPPHIRE_AXE = ITEMS.register("sapphire_axe",
() -> new AxeItem(ModItemTier.SAPPHIRE, 100,20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ShovelItem> SAPPHIRE_SHOVEL = ITEMS.register("sapphire_shovel",
() -> new ShovelItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<HoeItem> SAPPHIRE_HOE = ITEMS.register("sapphire_hoe",
() -> new HoeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<PickaxeItem> SAPPHIRE_PICKAXE = ITEMS.register("sapphire_pickaxe",
() -> new PickaxeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
//盔甲
public static final RegistryObject<ArmorItem> SAPPHIRE_HELMET = ITEMS.register("sapphire_helmet",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.HEAD, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_CHESTPLATE = ITEMS.register("sapphire_chestplate",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.CHEST, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_LEGS = ITEMS.register("sapphire_leggings",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.LEGS, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_BOOTS = ITEMS.register("sapphire_boots",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.FEET, new Item.Properties().group(Test.TAB)));
//毒苹果
public static final RegistryObject<PoisonApple> POISON_APPLE = ITEMS.register("poison_apple", PoisonApple::new);
//流体(桶)
public static final RegistryObject<Item> HONEYTEST_BUCKET = ITEMS.register("honeytest_bucket",
()->new BucketItem(()->TestFluids.HONEYTEST_FLUID.get(), new Item.Properties().maxStackSize(1).group(Test.TAB)));
//音乐
public static final RegistryObject<SoundEvent> CAI_XUKUN = SOUND_EVENTS.register("cai_xukun",
()->new SoundEvent(new ResourceLocation(Test.MOD_ID, "cai_xukun")));
public static final RegistryObject<Item> KUN_DISC = ITEMS.register("kun_disc",
()->new MusicDiscItem(1, () -> CAI_XUKUN.get(), new Item.Properties().maxStackSize(16).group(Test.TAB)));
//实体 | public static final RegistryObject<EntityType<TestBearEntity>> TEST_BEAR = ENTITY_TYPES.register("test_bear", | 4 | 2023-10-28 05:14:07+00:00 | 8k |
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,681 | 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");
} else {
setLatitudeLongitudeUsingCity(cityName);
}
}
private void getDataUsingNetwork() {
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
//check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
} else {
client.getLastLocation().addOnSuccessListener(location -> {
setLongitudeLatitude(location);
city = getCityNameUsingNetwork(this, location);
getTodayWeatherInfo(city);
});
}
}
private void setLatitudeLongitudeUsingCity(String cityName) { | 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");
} else {
setLatitudeLongitudeUsingCity(cityName);
}
}
private void getDataUsingNetwork() {
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
//check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
} else {
client.getLastLocation().addOnSuccessListener(location -> {
setLongitudeLatitude(location);
city = getCityNameUsingNetwork(this, location);
getTodayWeatherInfo(city);
});
}
}
private void setLatitudeLongitudeUsingCity(String cityName) { | URL.setCity_url(cityName); | 7 | 2023-10-25 21:15:57+00:00 | 8k |
dawex/sigourney | trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataproduct/DataProductVerifiableCredentialTest.java | [
{
"identifier": "FormatProvider",
"path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java",
"snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\t *\n\t * @param formatName the format name, used in {@link JsonLdProperty#formatName}\n\t */\n\tOptional<String> getFormat(String formatName);\n}"
},
{
"identifier": "DefaultFormatProvider",
"path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/shared/DefaultFormatProvider.java",
"snippet": "public class DefaultFormatProvider implements FormatProvider {\n\n\tprivate final Map<String, Supplier<String>> formats = new HashMap<>();\n\n\t@Override\n\tpublic Optional<String> getFormat(String formatName) {\n\t\tif (!formats.containsKey(formatName)) {\n\t\t\treturn Optional.empty();\n\t\t}\n\t\treturn Optional.ofNullable(formats.get(formatName).get());\n\t}\n\n\t/**\n\t * Sets the specified format.\n\t *\n\t * @param formatName is the name used in {@link JsonLdProperty#formatName}\n\t * @param format is the format, following the {@link java.util.Formatter} syntax, where the argument is replaced by the attribute value\n\t */\n\tpublic void setFormat(String formatName, String format) {\n\t\tformats.put(formatName, () -> format);\n\t}\n\n\t/**\n\t * Sets the specified format.\n\t *\n\t * @param formatName is the name used in {@link JsonLdProperty#formatName}\n\t * @param formatSupplier supplies the format, that follows the {@link java.util.Formatter} syntax, where the argument is replaced by the attribute value\n\t */\n\tpublic void setFormat(String formatName, Supplier<String> formatSupplier) {\n\t\tformats.put(formatName, formatSupplier);\n\t}\n}"
},
{
"identifier": "Format",
"path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/serialization/Format.java",
"snippet": "public class Format {\n\tpublic static final String DATA_PRODUCT_AGGREGATION_OF = \"DATA_PRODUCT_AGGREGATION_OF\";\n\n\tpublic static final String DATA_PRODUCT_CREDENTIAL_SUBJECT = \"DATA_PRODUCT_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String DATA_PRODUCT_ISSUER = \"DATA_PRODUCT_ISSUER\";\n\n\tpublic static final String DATA_PRODUCT_PROVIDED_BY = \"DATA_PRODUCT_PROVIDED_BY\";\n\n\tpublic static final String DATA_PRODUCT_TERMS_AND_CONDITIONS_URI = \"DATA_PRODUCT_TERMS_AND_CONDITIONS_URI\";\n\n\tpublic static final String DATA_PRODUCT_VERIFIABLE_CREDENTIAL = \"DATA_PRODUCT_VERIFIABLE_CREDENTIAL\";\n\n\tpublic static final String DATA_RESOURCE_CREDENTIAL_SUBJECT = \"DATA_RESOURCE_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String DATA_RESOURCE_COPYRIGHT_OWNED_BY = \"DATA_RESOURCE_COPYRIGHT_OWNED_BY\";\n\n\tpublic static final String DATA_RESOURCE_EXPOSED_THROUGH = \"DATA_RESOURCE_EXPOSED_THROUGH\";\n\n\tpublic static final String DATA_RESOURCE_ISSUER = \"DATA_RESOURCE_ISSUER\";\n\n\tpublic static final String DATA_RESOURCE_PRODUCED_BY = \"DATA_RESOURCE_PRODUCED_BY\";\n\n\tpublic static final String DATA_RESOURCE_VERIFIABLE_CREDENTIAL = \"DATA_RESOURCE_VERIFIABLE_CREDENTIAL\";\n\n\tpublic static final String ORGANISATION_CREDENTIAL_SUBJECT = \"ORGANISATION_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String ORGANISATION_ISSUER = \"ORGANISATION_ISSUER\";\n\n\tpublic static final String ORGANISATION_VERIFIABLE_CREDENTIAL = \"ORGANISATION_VERIFIABLE_CREDENTIAL\";\n\n\tpublic static final String TERMS_AND_CONDITIONS_CREDENTIAL_SUBJECT = \"TERMS_AND_CONDITIONS_CREDENTIAL_SUBJECT\";\n\n\tpublic static final String TERMS_AND_CONDITIONS_ISSUER = \"TERMS_AND_CONDITIONS_ISSUER\";\n\n\tpublic static final String TERMS_AND_CONDITIONS_VERIFIABLE_CREDENTIAL = \"TERMS_AND_CONDITIONS_VERIFIABLE_CREDENTIAL\";\n\n\tprivate Format() {\n\t\t// no instance allowed\n\t}\n}"
},
{
"identifier": "JacksonModuleFactory",
"path": "trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2210/serialization/JacksonModuleFactory.java",
"snippet": "public class JacksonModuleFactory {\n\n\t/**\n\t * Create a configured Jackson module for serializing organisation verifiable credentials\n\t */\n\tpublic static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) {\n\t\tfinal List<Class> domainClasses = List.of(Address.class,\n\t\t\t\tOrganisationCredentialSubject.class,\n\t\t\t\tOrganisationLegalRegistrationNumber.class,\n\t\t\t\tOrganisationVerifiableCredential.class);\n\t\treturn createVerifiableCredentialSerializationModule(formatProvider, baseIriSupplier, domainClasses);\n\t}\n\n\t/**\n\t * Create a configured Jackson module for serializing data product verifiable credentials\n\t */\n\tpublic static Module dataProductSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) {\n\t\tfinal List<Class> domainClasses = List.of(AggregationOf.class,\n\t\t\t\tDataAccountExport.class,\n\t\t\t\tDataProductCredentialSubject.class,\n\t\t\t\tDataProductVerifiableCredential.class,\n\t\t\t\tLocation.class,\n\t\t\t\tProvidedBy.class,\n\t\t\t\tTermsAndConditionURI.class);\n\t\treturn createVerifiableCredentialSerializationModule(formatProvider, baseIriSupplier, domainClasses);\n\t}\n\n\t/**\n\t * Create a configured Jackson module for serializing terms & conditions verifiable credentials\n\t */\n\tpublic static Module dataResourcesSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) {\n\t\tfinal List<Class> domainClasses = List.of(DataResourceCredentialSubject.class, DataResourceVerifiableCredential.class,\n\t\t\t\tDistribution.class, ExposedThrough.class, Location.class, ProducedBy.class);\n\t\treturn createVerifiableCredentialSerializationModule(formatProvider, baseIriSupplier, domainClasses);\n\t}\n\n\t/**\n\t * Create a configured Jackson module for serializing terms & conditions verifiable credentials\n\t */\n\tpublic static Module termsAndConditionsSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) {\n\t\tfinal List<Class> domainClasses = List.of(TermsAndConditionsVerifiableCredential.class, TermsAndConditionsCredentialSubject.class);\n\t\treturn createVerifiableCredentialSerializationModule(formatProvider, baseIriSupplier, domainClasses);\n\t}\n\n\tprivate static SimpleModule createVerifiableCredentialSerializationModule(FormatProvider formatProvider,\n\t\t\tSupplier<String> baseIriSupplier, List<Class> domainClasses) {\n\t\tfinal SimpleModule module = new SimpleModule();\n\n\t\tdomainClasses.forEach(clazz -> module.addSerializer(clazz, new JsonLdSerializer<>(clazz, formatProvider)));\n\n\t\tmodule.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier));\n\t\tmodule.addSerializer(Proof.class, new JsonLdSerializer<>(Proof.class, formatProvider));\n\t\tmodule.addSerializer(SignedObject.class, new SignedObjectJsonLdSerializer(formatProvider));\n\t\tmodule.addSerializer(VerifiablePresentation.class, new JsonLdSerializer<>(VerifiablePresentation.class, formatProvider));\n\n\t\treturn module;\n\t}\n\n\t/**\n\t * Create a configured Jackson module for serializing public keys\n\t */\n\tpublic static Module sharedSerializationModule(Supplier<String> baseIriSupplier) {\n\t\tfinal SimpleModule module = new SimpleModule();\n\t\tmodule.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier));\n\t\tmodule.addSerializer(Did.class, new JsonLdSerializer<>(Did.class));\n\t\tmodule.addSerializer(JsonWebKey2020.class, new JsonLdSerializer<>(JsonWebKey2020.class));\n\t\treturn module;\n\t}\n\n\tprivate JacksonModuleFactory() {\n\t\t// no instance allowed\n\t}\n}"
},
{
"identifier": "AbstractVerifiableCredentialTest",
"path": "trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/v2210/AbstractVerifiableCredentialTest.java",
"snippet": "public abstract class AbstractVerifiableCredentialTest {\n\n\tprivate static final JwkSetUtils.CreatedKeys CREATED_KEYS = JwkSetUtils.createKeysWithSelfSignedCertificate(null, \"Test\", 12);\n\n\tprivate final static com.nimbusds.jose.jwk.JWK JWK = CREATED_KEYS.jwkSet().getKeys().stream().findFirst().orElseThrow();\n\n\tprivate static final String PROOF_VERIFICATION_METHOD = \"did:web:dawex.com:api:credentials#ded0da80-ef24-41ea-8824-34d082fb5dfb\";\n\n\tprivate final ObjectMapper objectMapper = getObjectMapper();\n\n\tprotected abstract ObjectMapper getObjectMapper();\n\n\tprotected String serializeVc(Object verifiableCredential) throws JsonProcessingException {\n\t\tfinal var proof = ProofGenerator.generateProof(\n\t\t\t\tobjectMapper.writeValueAsString(verifiableCredential),\n\t\t\t\tPROOF_VERIFICATION_METHOD,\n\t\t\t\tJWK);\n\t\tfinal var signedVc = new SignedObject<>(verifiableCredential, proof);\n\t\treturn objectMapper.writeValueAsString(signedVc);\n\t}\n\n\tprotected void assertThatProofIsValid(String serializedVc) {\n\t\tassertThatJsonStringValue(\"$['proof']['type']\", serializedVc).isEqualTo(\"JsonWebSignature2020\");\n\t\tassertThat(JsonPath.compile(\"$['proof']['created']\")).isNotNull();\n\t\tassertThatJsonStringValue(\"$['proof']['proofPurpose']\", serializedVc).isEqualTo(\"assertionMethod\");\n\t\tassertThatJsonStringValue(\"$['proof']['verificationMethod']\", serializedVc).isEqualTo(PROOF_VERIFICATION_METHOD);\n\t\tnew ProofSignatureExpectationsHelper(CREATED_KEYS.jwkSet(), CREATED_KEYS.certificates()).assertSignatureIsValid(serializedVc);\n\t}\n}"
},
{
"identifier": "assertThatJsonListValue",
"path": "trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/utils/TestUtils.java",
"snippet": "public static AbstractListAssert<?, List<?>, Object, ObjectAssert<Object>> assertThatJsonListValue(String jsonPath, String json) {\n\treturn assertThat((Object) JsonPath.compile(jsonPath).read(json)).asList();\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.jsonld.serialization.FormatProvider;
import com.dawex.sigourney.trustframework.vc.model.shared.DefaultFormatProvider;
import com.dawex.sigourney.trustframework.vc.model.v2210.serialization.Format;
import com.dawex.sigourney.trustframework.vc.model.v2210.serialization.JacksonModuleFactory;
import com.dawex.sigourney.trustframework.vc.model.v2210.AbstractVerifiableCredentialTest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneOffset;
import java.util.List;
import static com.dawex.sigourney.trustframework.vc.model.utils.TestUtils.assertThatJsonListValue;
import static com.dawex.sigourney.trustframework.vc.model.utils.TestUtils.assertThatJsonStringValue; | 3,985 | package com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct;
class DataProductVerifiableCredentialTest extends AbstractVerifiableCredentialTest {
@Test
void shouldGenerateValidVerifiableCredentialForDataProduct() throws JsonProcessingException {
// given
final var verifiableCredential = getDataProductVerifiableCredential();
// when
final String serializedVc = serializeVc(verifiableCredential);
// then
assertThatProofIsValid(serializedVc);
assertThatJsonListValue("$['@context']", serializedVc).hasSize(4);
assertThatJsonStringValue("$['@context'][0]['@base']", serializedVc).isEqualTo("https://dawex.com");
assertThatJsonStringValue("$['@context'][0]['dct']", serializedVc).isEqualTo("http://purl.org/dc/terms/");
assertThatJsonStringValue("$['@context'][1]", serializedVc).isEqualTo("https://www.w3.org/2018/credentials/v1");
assertThatJsonStringValue("$['@context'][2]", serializedVc).isEqualTo("https://w3id.org/security/suites/jws-2020/v1");
assertThatJsonStringValue("$['@context'][3]", serializedVc).isEqualTo(
"https://registry.lab.gaia-x.eu/development/api/trusted-shape-registry/v1/shapes/jsonld/trustframework#");
assertThatJsonStringValue("$['type']", serializedVc).isEqualTo("VerifiableCredential");
assertThatJsonStringValue("$['id']", serializedVc)
.isEqualTo(
"./api/secure/participant/organisations/62b570acb33e417edcb345ee/dataOfferings/62bab5ae84fd784b1541e8f3/verifiableCredential");
assertThatJsonStringValue("$['issuer']", serializedVc).isEqualTo("./organisations/62b570acb33e417ed-issuer");
assertThatJsonStringValue("$['issuanceDate']", serializedVc).isEqualTo("2022-08-04T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['id']", serializedVc)
.isEqualTo("./dataOfferings/62bab5ae84fd784-dataproduct");
assertThatJsonStringValue("$['credentialSubject']['type']", serializedVc)
.isEqualTo("gx:ServiceOffering");
assertThatJsonStringValue("$['credentialSubject']['dct:title']", serializedVc)
.isEqualTo("Statistics of road accidents in France");
assertThatJsonStringValue("$['credentialSubject']['dct:description']", serializedVc)
.isEqualTo("This publication provides data on road accidents in France.");
assertThatJsonStringValue("$['credentialSubject']['dct:issued']", serializedVc).isEqualTo("2022-01-18T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['gx:providedBy']['id']", serializedVc)
.isEqualTo("./organisations/62b570acb33e417-provider");
assertThatJsonListValue("$['credentialSubject']['gx:termsAndConditions']", serializedVc)
.hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:URL']", serializedVc)
.isEqualTo("./termsAndConditions/https://dawex.com/termsAndConditions");
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:hash']", serializedVc)
.isEqualTo("d8402a23de560f5ab34b22d1a142feb9e13b3143");
assertThatJsonListValue("$['credentialSubject']['gx:policy']", serializedVc)
.hasSize(1)
.first()
.isEqualTo("policy");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:requestType']", serializedVc)
.isEqualTo("DataAccountExport.requestType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:accessType']", serializedVc)
.isEqualTo("DataAccountExport.accessType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:formatType']", serializedVc)
.isEqualTo("DataAccountExport.formatType");
assertThatJsonListValue("$['credentialSubject']['gx:aggregationOf']", serializedVc).hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:aggregationOf'][0]['id']", serializedVc)
.isEqualTo("./dataResource/62bac14584fd784b1541e9cb");
}
private static DataProductVerifiableCredential getDataProductVerifiableCredential() {
return DataProductVerifiableCredential.builder()
.id(new DataProductVerifiableCredential.Id("62bab5ae84fd784b1541e8f3", "62b570acb33e417edcb345ee"))
.issuer("62b570acb33e417ed-issuer")
.issuanceDate(LocalDate.of(2022, Month.AUGUST, 4).atStartOfDay(ZoneOffset.UTC))
.credentialSubject(DataProductCredentialSubject.builder()
.id("62bab5ae84fd784-dataproduct")
.title("Statistics of road accidents in France")
.description("This publication provides data on road accidents in France.")
.issued(LocalDate.of(2022, Month.JANUARY, 18).atStartOfDay(ZoneOffset.UTC))
.providedBy(ProvidedBy.builder().id("62b570acb33e417-provider").build())
.termsAndConditions(List.of(TermsAndConditionURI.builder()
.url("https://dawex.com/termsAndConditions")
.hash("d8402a23de560f5ab34b22d1a142feb9e13b3143")
.build()))
.policy(List.of("policy"))
.dataAccountExport(DataAccountExport.builder()
.requestType("DataAccountExport.requestType")
.accessType("DataAccountExport.accessType")
.formatType("DataAccountExport.formatType")
.build())
.aggregationOf(List.of(
AggregationOf.builder()
.id("62bac14584fd784b1541e9cb")
.build()
))
.build())
.build();
}
@Override
protected ObjectMapper getObjectMapper() {
final var objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.registerModule(JacksonModuleFactory.dataProductSerializationModule(getFormatProvider(), () -> "https://dawex.com"));
return objectMapper;
}
private static FormatProvider getFormatProvider() { | package com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct;
class DataProductVerifiableCredentialTest extends AbstractVerifiableCredentialTest {
@Test
void shouldGenerateValidVerifiableCredentialForDataProduct() throws JsonProcessingException {
// given
final var verifiableCredential = getDataProductVerifiableCredential();
// when
final String serializedVc = serializeVc(verifiableCredential);
// then
assertThatProofIsValid(serializedVc);
assertThatJsonListValue("$['@context']", serializedVc).hasSize(4);
assertThatJsonStringValue("$['@context'][0]['@base']", serializedVc).isEqualTo("https://dawex.com");
assertThatJsonStringValue("$['@context'][0]['dct']", serializedVc).isEqualTo("http://purl.org/dc/terms/");
assertThatJsonStringValue("$['@context'][1]", serializedVc).isEqualTo("https://www.w3.org/2018/credentials/v1");
assertThatJsonStringValue("$['@context'][2]", serializedVc).isEqualTo("https://w3id.org/security/suites/jws-2020/v1");
assertThatJsonStringValue("$['@context'][3]", serializedVc).isEqualTo(
"https://registry.lab.gaia-x.eu/development/api/trusted-shape-registry/v1/shapes/jsonld/trustframework#");
assertThatJsonStringValue("$['type']", serializedVc).isEqualTo("VerifiableCredential");
assertThatJsonStringValue("$['id']", serializedVc)
.isEqualTo(
"./api/secure/participant/organisations/62b570acb33e417edcb345ee/dataOfferings/62bab5ae84fd784b1541e8f3/verifiableCredential");
assertThatJsonStringValue("$['issuer']", serializedVc).isEqualTo("./organisations/62b570acb33e417ed-issuer");
assertThatJsonStringValue("$['issuanceDate']", serializedVc).isEqualTo("2022-08-04T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['id']", serializedVc)
.isEqualTo("./dataOfferings/62bab5ae84fd784-dataproduct");
assertThatJsonStringValue("$['credentialSubject']['type']", serializedVc)
.isEqualTo("gx:ServiceOffering");
assertThatJsonStringValue("$['credentialSubject']['dct:title']", serializedVc)
.isEqualTo("Statistics of road accidents in France");
assertThatJsonStringValue("$['credentialSubject']['dct:description']", serializedVc)
.isEqualTo("This publication provides data on road accidents in France.");
assertThatJsonStringValue("$['credentialSubject']['dct:issued']", serializedVc).isEqualTo("2022-01-18T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['gx:providedBy']['id']", serializedVc)
.isEqualTo("./organisations/62b570acb33e417-provider");
assertThatJsonListValue("$['credentialSubject']['gx:termsAndConditions']", serializedVc)
.hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:URL']", serializedVc)
.isEqualTo("./termsAndConditions/https://dawex.com/termsAndConditions");
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:hash']", serializedVc)
.isEqualTo("d8402a23de560f5ab34b22d1a142feb9e13b3143");
assertThatJsonListValue("$['credentialSubject']['gx:policy']", serializedVc)
.hasSize(1)
.first()
.isEqualTo("policy");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:requestType']", serializedVc)
.isEqualTo("DataAccountExport.requestType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:accessType']", serializedVc)
.isEqualTo("DataAccountExport.accessType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:formatType']", serializedVc)
.isEqualTo("DataAccountExport.formatType");
assertThatJsonListValue("$['credentialSubject']['gx:aggregationOf']", serializedVc).hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:aggregationOf'][0]['id']", serializedVc)
.isEqualTo("./dataResource/62bac14584fd784b1541e9cb");
}
private static DataProductVerifiableCredential getDataProductVerifiableCredential() {
return DataProductVerifiableCredential.builder()
.id(new DataProductVerifiableCredential.Id("62bab5ae84fd784b1541e8f3", "62b570acb33e417edcb345ee"))
.issuer("62b570acb33e417ed-issuer")
.issuanceDate(LocalDate.of(2022, Month.AUGUST, 4).atStartOfDay(ZoneOffset.UTC))
.credentialSubject(DataProductCredentialSubject.builder()
.id("62bab5ae84fd784-dataproduct")
.title("Statistics of road accidents in France")
.description("This publication provides data on road accidents in France.")
.issued(LocalDate.of(2022, Month.JANUARY, 18).atStartOfDay(ZoneOffset.UTC))
.providedBy(ProvidedBy.builder().id("62b570acb33e417-provider").build())
.termsAndConditions(List.of(TermsAndConditionURI.builder()
.url("https://dawex.com/termsAndConditions")
.hash("d8402a23de560f5ab34b22d1a142feb9e13b3143")
.build()))
.policy(List.of("policy"))
.dataAccountExport(DataAccountExport.builder()
.requestType("DataAccountExport.requestType")
.accessType("DataAccountExport.accessType")
.formatType("DataAccountExport.formatType")
.build())
.aggregationOf(List.of(
AggregationOf.builder()
.id("62bac14584fd784b1541e9cb")
.build()
))
.build())
.build();
}
@Override
protected ObjectMapper getObjectMapper() {
final var objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.registerModule(JacksonModuleFactory.dataProductSerializationModule(getFormatProvider(), () -> "https://dawex.com"));
return objectMapper;
}
private static FormatProvider getFormatProvider() { | final DefaultFormatProvider formatProvider = new DefaultFormatProvider(); | 1 | 2023-10-25 16:10:40+00:00 | 8k |
mcxiaoxiao/library-back | src/main/java/com/main/reader/ReaderServiceImpl.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": "HistoryEntity",
"path": "src/main/java/com/main/schema/HistoryEntity.java",
"snippet": "@Entity\n@Table(name = \"history\", schema = \"public\", catalog = \"library\")\npublic class HistoryEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"hisid\")\n private int hisid;\n @Basic\n @Column(name = \"bookid\")\n private Integer bookid;\n @Basic\n @Column(name = \"readerid\")\n private Integer readerid;\n @Basic\n @Column(name = \"type\")\n private String type;\n @Basic\n @Column(name = \"bookname\")\n private String bookname;\n @Basic\n @Column(name = \"readername\")\n private String readername;\n @Basic\n @Column(name = \"time\")\n private Date time;\n\n public int getHisid() {\n return hisid;\n }\n\n public void setHisid(int hisid) {\n this.hisid = hisid;\n }\n\n public Integer getBookid() {\n return bookid;\n }\n\n public void setBookid(Integer bookid) {\n this.bookid = bookid;\n }\n\n public Integer getReaderid() {\n return readerid;\n }\n\n public void setReaderid(Integer readerid) {\n this.readerid = readerid;\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 getBookname() {\n return bookname;\n }\n\n public void setBookname(String bookname) {\n this.bookname = bookname;\n }\n\n public String getReadername() {\n return readername;\n }\n\n public void setReadername(String readername) {\n this.readername = readername;\n }\n\n public Date getTime() {\n return time;\n }\n\n public void setTime(Date time) {\n this.time = time;\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\n HistoryEntity that = (HistoryEntity) o;\n\n if (hisid != that.hisid) return false;\n if (bookid != null ? !bookid.equals(that.bookid) : that.bookid != null) return false;\n if (readerid != null ? !readerid.equals(that.readerid) : that.readerid != null) return false;\n if (type != null ? !type.equals(that.type) : that.type != null) return false;\n if (bookname != null ? !bookname.equals(that.bookname) : that.bookname != null) return false;\n if (readername != null ? !readername.equals(that.readername) : that.readername != null) return false;\n if (time != null ? !time.equals(that.time) : that.time != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = hisid;\n result = 31 * result + (bookid != null ? bookid.hashCode() : 0);\n result = 31 * result + (readerid != null ? readerid.hashCode() : 0);\n result = 31 * result + (type != null ? type.hashCode() : 0);\n result = 31 * result + (bookname != null ? bookname.hashCode() : 0);\n result = 31 * result + (readername != null ? readername.hashCode() : 0);\n result = 31 * result + (time != null ? time.hashCode() : 0);\n return result;\n }\n}"
},
{
"identifier": "ReaderEntity",
"path": "src/main/java/com/main/schema/ReaderEntity.java",
"snippet": "@Entity\n@Table(name = \"reader\", schema = \"public\", catalog = \"library\")\npublic class ReaderEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"userid\")\n private int userid;\n @Basic\n @Column(name = \"email\")\n private String email;\n @Basic\n @Column(name = \"readername\")\n private String readername;\n @Basic\n @Column(name = \"readersex\")\n private String readersex;\n @Basic\n @Column(name = \"readertype\")\n private String readertype;\n @Basic\n @Column(name = \"admin\")\n private String admin;\n @Basic\n @Column(name = \"password\")\n private String password;\n @Basic\n @Column(name = \"role\")\n private Integer role;\n\n public int getUserid() {\n return userid;\n }\n\n public void setUserid(int userid) {\n this.userid = userid;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getReadername() {\n return readername;\n }\n\n public void setReadername(String readername) {\n this.readername = readername;\n }\n\n public String getReadersex() {\n return readersex;\n }\n\n public void setReadersex(String readersex) {\n this.readersex = readersex;\n }\n\n public String getReadertype() {\n return readertype;\n }\n\n public void setReadertype(String readertype) {\n this.readertype = readertype;\n }\n\n public String getAdmin() {\n return admin;\n }\n\n public void setAdmin(String admin) {\n this.admin = admin;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Integer getRole() {\n return role;\n }\n\n public void setRole(Integer role) {\n this.role = role;\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\n ReaderEntity that = (ReaderEntity) o;\n\n if (userid != that.userid) return false;\n if (email != null ? !email.equals(that.email) : that.email != null) return false;\n if (readername != null ? !readername.equals(that.readername) : that.readername != null) return false;\n if (readersex != null ? !readersex.equals(that.readersex) : that.readersex != null) return false;\n if (readertype != null ? !readertype.equals(that.readertype) : that.readertype != null) return false;\n if (admin != null ? !admin.equals(that.admin) : that.admin != null) return false;\n if (password != null ? !password.equals(that.password) : that.password != null) return false;\n if (role != null ? !role.equals(that.role) : that.role != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = userid;\n result = 31 * result + (email != null ? email.hashCode() : 0);\n result = 31 * result + (readername != null ? readername.hashCode() : 0);\n result = 31 * result + (readersex != null ? readersex.hashCode() : 0);\n result = 31 * result + (readertype != null ? readertype.hashCode() : 0);\n result = 31 * result + (admin != null ? admin.hashCode() : 0);\n result = 31 * result + (password != null ? password.hashCode() : 0);\n result = 31 * result + (role != null ? role.hashCode() : 0);\n return result;\n }\n}"
},
{
"identifier": "TakeEntity",
"path": "src/main/java/com/main/schema/TakeEntity.java",
"snippet": "@Entity\n@Table(name = \"take\", schema = \"public\", catalog = \"library\")\npublic class TakeEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"takeid\")\n private int takeid;\n @Basic\n @Column(name = \"bookid\")\n private Integer bookid;\n @Basic\n @Column(name = \"borroweddate\")\n private Date borroweddate;\n @Basic\n @Column(name = \"borrowedddl\")\n private Date borrowedddl;\n @Basic\n @Column(name = \"borrowedtime\")\n private Integer borrowedtime;\n @Basic\n @Column(name = \"readerid\")\n private Integer readerid;\n @Basic\n @Column(name = \"isreturned\")\n private Boolean isreturned;\n @Basic\n @Column(name = \"bookname\")\n private String bookname;\n\n public int getTakeid() {\n return takeid;\n }\n\n public void setTakeid(int takeid) {\n this.takeid = takeid;\n }\n\n public Integer getBookid() {\n return bookid;\n }\n\n public void setBookid(Integer bookid) {\n this.bookid = bookid;\n }\n\n public Date getBorroweddate() {\n return borroweddate;\n }\n\n public void setBorroweddate(Date borroweddate) {\n this.borroweddate = borroweddate;\n }\n\n public Date getBorrowedddl() {\n return borrowedddl;\n }\n\n public void setBorrowedddl(Date borrowedddl) {\n this.borrowedddl = borrowedddl;\n }\n\n public Integer getBorrowedtime() {\n return borrowedtime;\n }\n\n public void setBorrowedtime(Integer borrowedtime) {\n this.borrowedtime = borrowedtime;\n }\n\n public Integer getReaderid() {\n return readerid;\n }\n\n public void setReaderid(Integer readerid) {\n this.readerid = readerid;\n }\n\n public Boolean getIsreturned() {\n return isreturned;\n }\n\n public void setIsreturned(Boolean isreturned) {\n this.isreturned = isreturned;\n }\n\n public String getBookname() {\n return bookname;\n }\n\n public void setBookname(String bookname) {\n this.bookname = bookname;\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\n TakeEntity that = (TakeEntity) o;\n\n if (takeid != that.takeid) return false;\n if (bookid != null ? !bookid.equals(that.bookid) : that.bookid != null) return false;\n if (borroweddate != null ? !borroweddate.equals(that.borroweddate) : that.borroweddate != null) return false;\n if (borrowedddl != null ? !borrowedddl.equals(that.borrowedddl) : that.borrowedddl != null) return false;\n if (borrowedtime != null ? !borrowedtime.equals(that.borrowedtime) : that.borrowedtime != null) return false;\n if (readerid != null ? !readerid.equals(that.readerid) : that.readerid != null) return false;\n if (isreturned != null ? !isreturned.equals(that.isreturned) : that.isreturned != null) return false;\n if (bookname != null ? !bookname.equals(that.bookname) : that.bookname != null) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = takeid;\n result = 31 * result + (bookid != null ? bookid.hashCode() : 0);\n result = 31 * result + (borroweddate != null ? borroweddate.hashCode() : 0);\n result = 31 * result + (borrowedddl != null ? borrowedddl.hashCode() : 0);\n result = 31 * result + (borrowedtime != null ? borrowedtime.hashCode() : 0);\n result = 31 * result + (readerid != null ? readerid.hashCode() : 0);\n result = 31 * result + (isreturned != null ? isreturned.hashCode() : 0);\n result = 31 * result + (bookname != null ? bookname.hashCode() : 0);\n return result;\n }\n}"
}
] | import com.main.schema.BookEntity;
import com.main.schema.HistoryEntity;
import com.main.schema.ReaderEntity;
import com.main.schema.TakeEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List; | 4,545 | package com.main.reader;
@Service
public class ReaderServiceImpl implements ReaderService {
@Resource
private ReaderRepository readerRepository;
public ReaderServiceImpl(ReaderRepository readerRepository)
{
this.readerRepository=readerRepository;
}
@Override | package com.main.reader;
@Service
public class ReaderServiceImpl implements ReaderService {
@Resource
private ReaderRepository readerRepository;
public ReaderServiceImpl(ReaderRepository readerRepository)
{
this.readerRepository=readerRepository;
}
@Override | public Page<ReaderEntity> findReaderAll(int pageNumber, int pageSize) | 2 | 2023-10-30 14:38:00+00:00 | 8k |
kdetard/koki | app/src/main/java/io/github/kdetard/koki/feature/settings/SettingsLogoutController.java | [
{
"identifier": "NetworkModule",
"path": "app/src/main/java/io/github/kdetard/koki/di/NetworkModule.java",
"snippet": "@Module\n@InstallIn(SingletonComponent.class)\npublic abstract class NetworkModule {\n public static final String BASE_URL = \"https://uiot.ixxc.dev\";\n public static final String COOKIE_STORE_NAME = \"kookies\"; // get it? ;D\n\n @Provides\n @Singleton\n public static CookieJar provideCookieJar() {\n return new MMKVCookieJar(COOKIE_STORE_NAME);\n }\n\n @Provides\n @Singleton\n public static HttpLoggingInterceptor provideHttpLoggingInterceptor() {\n return new HttpLoggingInterceptor()\n .setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);\n }\n\n @Provides\n @Singleton\n public static Cache provideCache(final @ApplicationContext Context context) {\n return new Cache(new File(context.getCacheDir(), \"http_cache\"), 50L * 1024L * 1024L); // 10 MiB\n }\n\n @Provides\n @Singleton\n public static OkHttpClient provideOkHttpClient(\n final Cache cache,\n final CookieJar cookieJar,\n final HttpLoggingInterceptor logging,\n final Authenticator laxAuthenticator,\n final @StrictAuthenticator Interceptor strictAuthenticator,\n final @CacheInterceptor Interceptor cacheInterceptor\n ) {\n return new OkHttpClient.Builder()\n .cache(cache)\n .cookieJar(cookieJar)\n .addInterceptor(logging)\n .authenticator(laxAuthenticator)\n .addInterceptor(strictAuthenticator)\n .addInterceptor(cacheInterceptor)\n .build();\n }\n\n @Provides\n @Singleton\n public static Authenticator provideLaxAuthenticator(\n final JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter,\n final RxDataStore<Settings> settings\n ) {\n return (route, response) ->\n NetworkUtils.commonAuthenticator(\n keycloakTokenJsonAdapter,\n settings,\n route == null ? null : route.address().url().host(),\n response.request(),\n response\n );\n }\n\n @Provides\n @Singleton\n @StrictAuthenticator\n public static Interceptor provideStrictAuthenticator(\n final JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter,\n final RxDataStore<Settings> settings\n ) {\n return chain -> chain.proceed(\n Objects.requireNonNull(NetworkUtils.commonAuthenticator(\n keycloakTokenJsonAdapter,\n settings,\n chain.request().url().host(),\n chain.request(),\n null\n ))\n );\n }\n\n @Provides\n @Singleton\n @CacheInterceptor\n public static Interceptor provideCacheInterceptor(final @ApplicationContext Context context) {\n return chain -> {\n // Get the request from the chain.\n var request = chain.request();\n\n /*\n * Leveraging the advantage of using Kotlin,\n * we initialize the request and change its header depending on whether\n * the device is connected to Internet or not.\n */\n if (NetworkUtils.hasNetwork(context)) {\n /*\n * If there is Internet, get the cache that was stored 5 seconds ago.\n * If the cache is older than 5 seconds, then discard it,\n * and indicate an error in fetching the response.\n * The 'max-age' attribute is responsible for this behavior.\n */\n request = request.newBuilder().header(\"Cache-Control\", \"public, max-age=\" + 5).build();\n } else\n /*\n * If there is no Internet, get the cache that was stored 7 days ago.\n * If the cache is older than 7 days, then discard it,\n * and indicate an error in fetching the response.\n * The 'max-stale' attribute is responsible for this behavior.\n * The 'only-if-cached' attribute indicates to not retrieve new data; fetch the cache only instead.\n */ {\n request = request.newBuilder().header(\"Cache-Control\", \"public, only-if-cached, max-stale=\" + 60 * 60 * 24 * 7).build();\n }\n // End of if-else statement\n\n // Add the modified request to the chain.\n return chain.proceed(request);\n };\n }\n\n @Provides\n @Singleton\n public static Retrofit provideRetrofit(final OkHttpClient okHttpClient, final Moshi moshi) {\n return new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .client(okHttpClient)\n .addConverterFactory(MoshiConverterFactory.create(moshi))\n .addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io()))\n .build();\n }\n\n @Provides\n @Singleton\n public static KeycloakApiService provideKeycloakApiService(final Retrofit retrofit) {\n return retrofit.create(KeycloakApiService.class);\n }\n\n @Provides\n @Singleton\n public static OpenRemoteService provideOpenRemoteService(final Retrofit retrofit) {\n return retrofit.create(OpenRemoteService.class);\n }\n\n @Provides\n @Singleton\n public static OpenMeteoService provideOpenMeteoService(final Retrofit retrofit) {\n return retrofit.create(OpenMeteoService.class);\n }\n\n @Provides\n @Singleton\n public static AqicnService provideAqicnService(final Retrofit retrofit) {\n return retrofit.create(AqicnService.class);\n }\n}"
},
{
"identifier": "BaseController",
"path": "app/src/main/java/io/github/kdetard/koki/feature/base/BaseController.java",
"snippet": "public abstract class BaseController extends Controller implements ActivityLayoutProvider, OnConfigurationChangeListener {\n private final int layoutRes;\n\n public BaseController(int layoutRes) {\n this(layoutRes, null);\n }\n\n public BaseController(int layoutRes, @Nullable Bundle args) {\n super(args);\n this.layoutRes = layoutRes;\n ControllerUtils.watchForLeaks(this);\n addLifecycleListener(new LifecycleListener() {\n @Override\n public void postCreateView(@NonNull Controller controller, @NonNull View view) {\n super.postCreateView(controller, view);\n onViewCreated(view);\n }\n });\n }\n\n public int getLayoutRes() {\n return layoutRes;\n }\n\n public LifecycleScopeProvider<ControllerEvent> getScopeProvider() { return ControllerScopeProvider.from(this); }\n\n public View getRoot() {\n final var provider = ((ActivityLayoutProvider)getActivity());\n if (provider != null) {\n return provider.getRoot();\n }\n return null;\n }\n\n public Toolbar getToolbar() {\n final var provider = ((ActivityLayoutProvider)getActivity());\n if (provider != null) {\n return provider.getToolbar();\n }\n return null;\n }\n\n public ExpandedAppBarLayout getAppBarLayout() {\n final var provider = ((ActivityLayoutProvider)getActivity());\n if (provider != null) {\n return provider.getAppBarLayout();\n }\n return null;\n }\n\n public NavigationBarView getNavBar() {\n final var provider = ((ActivityLayoutProvider)getActivity());\n if (provider != null) {\n return provider.getNavBar();\n }\n return null;\n }\n\n protected String title = null;\n\n @NonNull\n public View onCreateView(@NonNull LayoutInflater inflater,\n @NonNull ViewGroup container,\n Bundle savedViewState) {\n return inflater.inflate(layoutRes, container, false);\n }\n\n public void onViewCreated(View view) {}\n\n @Override\n public void onChangeStarted(@NonNull ControllerChangeHandler changeHandler, @NonNull ControllerChangeType changeType) {\n super.onChangeStarted(changeHandler, changeType);\n\n if (changeType.isEnter) {\n if (getToolbar() != null) {\n configureMenu(getToolbar());\n }\n }\n }\n\n public FragmentManager getSupportFragmentManager() {\n return ((FragmentActivity) Objects.requireNonNull(getActivity())).getSupportFragmentManager();\n }\n\n public void configureToolbar(Toolbar toolbar) {\n if (title == null) {\n return;\n }\n\n var parentController = getParentController();\n while (parentController != null) {\n if (parentController instanceof BaseController && ((BaseController) parentController).title != null) {\n return;\n }\n parentController = parentController.getParentController();\n }\n\n toolbar.setTitle(title);\n }\n\n public void configureMenu(Toolbar toolbar) {\n toolbar.getMenu().clear();\n }\n\n @Override\n public void onConfigurationChange(@NonNull Configuration newConfig) {\n final boolean isLandscape = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;\n final int orientationInsetType = isLandscape ? InsetUtils.LandscapeInsetType : InsetUtils.OutOfBoundInsetType;\n\n Insetter.builder()\n .paddingLeft(orientationInsetType, false)\n .paddingRight(orientationInsetType, false)\n .applyToView(getRoot());\n }\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": "RxRestKeycloak",
"path": "app/src/main/java/io/github/kdetard/koki/keycloak/RxRestKeycloak.java",
"snippet": "public class RxRestKeycloak extends RxKeycloak {\n public static @NonNull Single<KeycloakToken> newSession(\n final KeycloakApiService service,\n final KeycloakConfig config,\n final String username,\n final String password\n ) {\n return buildRequest(config)\n .flatMap(authRequest -> service.newSession(\n authRequest.configuration.tokenEndpoint.toString(),\n authRequest.clientId,\n username,\n password,\n KeycloakGrantType.PASSWORD\n ))\n .onErrorResumeNext(e -> {\n Timber.w(e, \"Error occurred while signing in\");\n return Single.error(e);\n });\n }\n\n public static @NonNull Single<SignUpResult> createUser(\n final KeycloakApiService service,\n final KeycloakConfig config,\n final String username,\n final String email,\n final String password,\n final String confirmPassword\n ) {\n return buildRequest(config)\n\n // Step on sign in page\n .flatMap(authRequest ->\n service.stepOnSignInPage(\n // uiot.ixxc.dev/auth/..../auth?client_id=...\n Objects.requireNonNull(authRequest.configuration.authorizationEndpoint).toString(),\n config.client(),\n config.redirectUri(),\n \"code\"\n ))\n\n // Extract signup link without session code from sign in form\n .flatMap(r -> extractLinkFromElement(config, r, \"(//a)[1]\", \"href\"))\n\n .doOnSuccess(r -> Timber.d(\"Sign up link (no session code): %s\", r))\n\n // Step on signup page\n .flatMap(service::stepOnSignUpPage)\n\n // Extract signup link with session code from sign up form\n .flatMap(r -> extractLinkFromElement(config, r, \"//form\", \"action\"))\n\n .doOnSuccess(r -> Timber.d(\"Sign up link (with session code): %s\", r))\n\n // Create new user from the signup link with session code above\n .flatMap(r -> service.createUser(r, username, email, password, confirmPassword, \"\"))\n\n .onErrorResumeNext(e -> {\n Timber.w(e, \"Error occurred while creating user\");\n return Single.error(e);\n })\n\n // check sign up result\n .flatMap(r -> {\n var result = SignUpResult.UNKNOWN;\n\n try (var rawBody = r.body()) {\n if (rawBody == null) {\n result = SignUpResult.NULL;\n }\n else {\n final var body = rawBody.string();\n if (body.isEmpty()) {\n result = SignUpResult.EMPTY;\n }\n if (body.contains(\"Invalid\")) {\n result = SignUpResult.INVALID;\n }\n if (body.contains(\"specify\")) {\n result = SignUpResult.SPECIFY;\n }\n if (body.contains(\"timed out\")) {\n result = SignUpResult.TIMEOUT;\n }\n if (body.contains(\"Username already\")) {\n result = SignUpResult.USERNAME_EXISTS;\n }\n if (body.contains(\"Email already\")) {\n result = SignUpResult.EMAIL_EXISTS;\n }\n if (body.contains(\"/manager/\")) {\n result = SignUpResult.SUCCESS;\n }\n }\n }\n\n return Single.just(result);\n });\n }\n\n public static @NonNull Single<ResetPasswordResult> resetPassword(\n final KeycloakApiService service,\n final KeycloakConfig config,\n final String usernameOrEmail\n ) {\n return buildRequest(config)\n\n // Step on sign in page\n .flatMap(authRequest ->\n service.stepOnSignInPage(\n // uiot.ixxc.dev/auth/..../auth?client_id=...\n Objects.requireNonNull(authRequest.configuration.authorizationEndpoint).toString(),\n config.client(),\n config.redirectUri(),\n \"code\"\n ))\n\n // Extract password reset link without session code from sign in form\n .flatMap(r -> extractLinkFromElement(config, r, \"(//a)[2]\", \"href\"))\n\n .doOnSuccess(r -> Timber.d(\"Reset password link (no session code): %s\", r))\n\n // Step on signup page\n .flatMap(service::stepOnSignUpPage)\n\n // Extract password reset link with session code from password reset form\n .flatMap(r -> extractLinkFromElement(config, r, \"//form\", \"action\"))\n\n .doOnSuccess(r -> Timber.d(\"Reset password link (with session code): %s\", r))\n\n // Reset password from the password reset link with session code above\n .flatMap(r -> service.resetPassword(r, usernameOrEmail, \"\"))\n\n .onErrorResumeNext(e -> {\n Timber.w(e, \"Error occurred while resetting password\");\n return Single.error(e);\n })\n\n // check sign up result\n .flatMap(r -> {\n var result = ResetPasswordResult.UNKNOWN;\n\n try (var rawBody = r.body()) {\n if (rawBody == null) {\n result = ResetPasswordResult.NULL;\n }\n else {\n final var body = rawBody.string();\n if (body.isEmpty()) {\n result = ResetPasswordResult.EMPTY;\n }\n if (body.contains(\"Failed to send mail\")) {\n result = ResetPasswordResult.FAILED_TO_SEND_MAIL;\n }\n if (body.contains(\"specify\")) {\n result = ResetPasswordResult.SPECIFY;\n }\n if (body.contains(\"timed out\")) {\n result = ResetPasswordResult.TIMEOUT;\n }\n if (body.contains(\"should receive\")) {\n result = ResetPasswordResult.SUCCESS;\n }\n }\n }\n\n return Single.just(result);\n });\n }\n\n public static @NonNull Single<String> extractLinkFromElement(\n final KeycloakConfig config,\n final ResponseBody resp,\n final @NonNull String xPath,\n final @NonNull String attr\n ) {\n try {\n final var redirectUri = Uri.parse(config.authServerUrl());\n final var baseUri = String.format(\"%s://%s\", redirectUri.getScheme(), redirectUri.getHost());\n final var document = Jsoup.parse(resp.string(), baseUri);\n final var linkSelector = document.selectXpath(String.format(\"%s[@%s]\", xPath, attr)).get(0);\n final var signupUrl = linkSelector.attr(String.format(\"abs:%s\", attr));\n return Single.just(signupUrl);\n } catch (IndexOutOfBoundsException e) {\n return Single.error(new Error(\"Cannot find link in request\"));\n } catch (IOException e) {\n return Single.error(new Error(\"Invalid request\"));\n } catch (Exception e) {\n Timber.w(e, \"Unknown error occurred while extracting link\");\n return Single.error(e);\n }\n }\n\n public static @NonNull Completable endSession(\n final KeycloakApiService service,\n final KeycloakConfig config,\n final String refreshToken\n ) {\n return buildRequest(config)\n .flatMapCompletable(authRequest -> service.endSession(\n Objects.requireNonNull(authRequest.configuration.endSessionEndpoint).toString(),\n authRequest.clientId,\n refreshToken\n ));\n }\n\n public static @NonNull Single<KeycloakToken> refreshSession(\n final KeycloakApiService service,\n final KeycloakConfig config\n ) {\n return buildRequest(config)\n .flatMap(authRequest -> service.refreshSession(\n authRequest.configuration.tokenEndpoint.toString(),\n authRequest.clientId,\n MMKV.defaultMMKV().getString(\"refreshToken\", \"\"),\n KeycloakGrantType.REFRESH_TOKEN\n ));\n }\n}"
}
] | import static autodispose2.AutoDispose.autoDisposable;
import android.view.View;
import androidx.datastore.rxjava3.RxDataStore;
import com.maxkeppeler.sheets.core.SheetStyle;
import com.maxkeppeler.sheets.info.InfoSheet;
import com.squareup.moshi.JsonAdapter;
import com.tencent.mmkv.MMKV;
import java.util.Objects;
import dagger.hilt.EntryPoint;
import dagger.hilt.InstallIn;
import dagger.hilt.android.EntryPointAccessors;
import dagger.hilt.components.SingletonComponent;
import io.github.kdetard.koki.R;
import io.github.kdetard.koki.Settings;
import io.github.kdetard.koki.di.NetworkModule;
import io.github.kdetard.koki.feature.base.BaseController;
import io.github.kdetard.koki.keycloak.KeycloakApiService;
import io.github.kdetard.koki.keycloak.RxRestKeycloak;
import io.github.kdetard.koki.keycloak.models.KeycloakConfig;
import io.github.kdetard.koki.keycloak.models.KeycloakToken;
import io.reactivex.rxjava3.core.Single;
import kotlin.Unit; | 4,977 | package io.github.kdetard.koki.feature.settings;
public class SettingsLogoutController extends BaseController {
@EntryPoint
@InstallIn(SingletonComponent.class)
interface SettingsLogoutEntryPoint {
RxDataStore<Settings> settings();
KeycloakApiService keycloakApiService();
JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter();
}
SettingsLogoutEntryPoint entryPoint;
KeycloakConfig mKeycloakConfig;
public SettingsLogoutController() { super(R.layout.controller_settings_dialog); }
@Override
public void onViewCreated(View view) {
super.onViewCreated(view);
entryPoint = EntryPointAccessors.fromApplication(Objects.requireNonNull(getApplicationContext()), SettingsLogoutEntryPoint.class);
mKeycloakConfig = KeycloakConfig.getDefaultConfig(getApplicationContext());
new InfoSheet().show(Objects.requireNonNull(getActivity()), null, sheet -> {
sheet.style(SheetStyle.DIALOG);
sheet.setShowsDialog(true);
sheet.title(R.string.logout);
sheet.content(R.string.confirm_logout);
sheet.onCancel(this::cancelLogout);
sheet.onNegative(R.string.decline_logout, this::cancelLogout);
sheet.onPositive(R.string.accept_logout, this::confirmLogout);
return null;
});
}
private Unit cancelLogout() {
getRouter().popController(this);
return null;
}
private Unit confirmLogout() {
entryPoint.settings()
.data()
.firstOrError()
.map(Settings::getKeycloakTokenJson)
.map(entryPoint.keycloakTokenJsonAdapter()::fromJson)
.map(KeycloakToken::refreshToken)
.flatMapCompletable(refreshToken -> | package io.github.kdetard.koki.feature.settings;
public class SettingsLogoutController extends BaseController {
@EntryPoint
@InstallIn(SingletonComponent.class)
interface SettingsLogoutEntryPoint {
RxDataStore<Settings> settings();
KeycloakApiService keycloakApiService();
JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter();
}
SettingsLogoutEntryPoint entryPoint;
KeycloakConfig mKeycloakConfig;
public SettingsLogoutController() { super(R.layout.controller_settings_dialog); }
@Override
public void onViewCreated(View view) {
super.onViewCreated(view);
entryPoint = EntryPointAccessors.fromApplication(Objects.requireNonNull(getApplicationContext()), SettingsLogoutEntryPoint.class);
mKeycloakConfig = KeycloakConfig.getDefaultConfig(getApplicationContext());
new InfoSheet().show(Objects.requireNonNull(getActivity()), null, sheet -> {
sheet.style(SheetStyle.DIALOG);
sheet.setShowsDialog(true);
sheet.title(R.string.logout);
sheet.content(R.string.confirm_logout);
sheet.onCancel(this::cancelLogout);
sheet.onNegative(R.string.decline_logout, this::cancelLogout);
sheet.onPositive(R.string.accept_logout, this::confirmLogout);
return null;
});
}
private Unit cancelLogout() {
getRouter().popController(this);
return null;
}
private Unit confirmLogout() {
entryPoint.settings()
.data()
.firstOrError()
.map(Settings::getKeycloakTokenJson)
.map(entryPoint.keycloakTokenJsonAdapter()::fromJson)
.map(KeycloakToken::refreshToken)
.flatMapCompletable(refreshToken -> | RxRestKeycloak.endSession(entryPoint.keycloakApiService(), mKeycloakConfig, refreshToken)) | 3 | 2023-10-30 00:44:59+00:00 | 8k |
HiNinoJay/easyUsePoi | src/main/java/top/nino/easyUsePoi/word/module/DocumentTool.java | [
{
"identifier": "ModuleTypeEnum",
"path": "src/main/java/top/nino/easyUsePoi/word/constant/ModuleTypeEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ModuleTypeEnum {\n\n PARAGRAPH(\"paragraph\"),\n TABLE(\"table\"),\n BAR_CHART(\"barChart\"),\n Pi_CHART(\"piChart\");\n\n private final String name;\n\n}"
},
{
"identifier": "ColorEnum",
"path": "src/main/java/top/nino/easyUsePoi/word/constant/text/ColorEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ColorEnum {\n\n BLACK(\"黑色\", \"000000\"),\n WHITE(\"白色\", \"FFFFFF\"),\n CUSTOM_COLOR(\"青蓝色\", \"08abac\");\n\n private final String name;\n private final String hexCode;\n\n}"
},
{
"identifier": "FontSizeEnum",
"path": "src/main/java/top/nino/easyUsePoi/word/constant/text/FontSizeEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum FontSizeEnum {\n\n SMALL_PRIMARY(\"小初\", 36, 12.70),\n ONE(\"一号\", 26, 9.17),\n SMALL_ONE(\"小一\", 24, 8.47),\n TWO(\"二号\", 22, 7.76),\n SMALL_TWO(\"小二\", 18, 6.35),\n THREE(\"三号\", 16, 5.64),\n SMALL_THREE(\"小三\", 15, 5.29),\n FOUR(\"四号\", 14, 4.94),\n SMALL_FOUR(\"小四\", 12, 4.32),\n SMALL_FIVE(\"小五\", 9, 3.18);\n\n /**\n * 字号\n */\n private final String name;\n /**\n * 字体磅\n */\n private final Integer sizeInPoints;\n\n /**\n * 毫米数\n */\n private final Double sizeInMillimeters;\n\n}"
},
{
"identifier": "BarChartTool",
"path": "src/main/java/top/nino/easyUsePoi/word/module/chart/BarChartTool.java",
"snippet": "@Component\npublic class BarChartTool {\n /*\n * @Description:重载创建柱状图方法\n * @Param: XWPFDocument docxDocument\n * String chartTile : 图标名称,\n * String xAxisName : x轴名称,\n * String[] xAxisData : x轴数据,\n * String yAxisName, Integer[] yAxisData : xy轴数据,\n * String titleName,\n * PresetColor color : 柱状图的颜色\n * LegendPosition location:图例位置(上下左右)\n * AxisPosition valueAxis : 值轴\n * AxisPosition classificationAxis : 分类轴\n * AxisCrossBetween axisCrossBetween : 图柱位置 eg:居中\n * BarDirection barDirection : 柱状图方向\n * @Return:\n * @DateTime: 15:30 2023/10/30\n * @author: dingchy\n */\n public void drawBarChart(XWPFDocument docxDocument, String chartTile, String xAxisName, String[] xAxisData, String yAxisName, Integer[] yAxisData, String titleName, PresetColor color,\n LegendPosition location, AxisPosition classificationAxis, AxisPosition valueAxis, AxisCrossBetween axisCrossBetween, BarDirection barDirection) {\n // 1、创建chart图表对象,抛出异常\n\n XWPFChart chart = null;\n try {\n chart = docxDocument.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);\n } catch (InvalidFormatException | IOException e) {\n throw new RuntimeException(e);\n }\n // 2、图表相关设置\n\n chart.setTitleText(chartTile); // 图表标题\n\n // 3、图例设置\n\n XDDFChartLegend legend = chart.getOrAddLegend();\n legend.setPosition(location); // 图例位置:上下左右\n\n // 4、X轴(分类轴)相关设置\n\n XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); // 创建X轴,并且指定位置\n xAxis.setTitle(xAxisName); // x轴标题\n XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置X轴数据\n\n // 5、Y轴(值轴)相关设置\n\n XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT); // 创建Y轴,指定位置\n yAxis.setTitle(yAxisName); // Y轴标题\n yAxis.setCrossBetween(AxisCrossBetween.BETWEEN); // 设置图柱的位置:BETWEEN居中\n XDDFNumericalDataSource<Integer> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置Y轴数据\n\n // 6、创建柱状图对象\n\n XDDFBarChartData barChart = (XDDFBarChartData) chart.createData(ChartTypes.BAR, xAxis, yAxis);\n barChart.setBarDirection(BarDirection.COL); // 设置柱状图的方向:BAR横向,COL竖向,默认是BAR\n\n // 7、加载柱状图数据集\n\n XDDFBarChartData.Series barSeries = (XDDFBarChartData.Series) barChart.addSeries(xAxisSource, yAxisSource);\n barSeries.setTitle(titleName, null); // 图例标题\n barSeries.setFillProperties(new XDDFSolidFillProperties(XDDFColor.from(color)));\n\n // 8、绘制柱状图\n\n chart.plot(barChart);\n }\n\n\n /*\n * @Description:重载创建柱状图方法\n * @Param: XWPFDocument docxDocument, String chartTile : 图标名称, String xAxisName : x轴名称, String[] xAxisData : x轴数据, String yAxisName, Integer[] yAxisData, String titleName, PresetColor color : 柱状图的颜色\n * @Return:\n * @DateTime: 19:30 2023/10/27\n * @author: dingchy\n */\n public void drawDefaultBarChart(XWPFDocument docxDocument, String chartTile, String xAxisName, String[] xAxisData, String yAxisName, Integer[] yAxisData, String titleName, PresetColor color) {\n //默认柱状图\n drawBarChart(docxDocument, chartTile, xAxisName, xAxisData, yAxisName, yAxisData, titleName, PresetColor.BLUE, LegendPosition.TOP, AxisPosition.BOTTOM, AxisPosition.LEFT, AxisCrossBetween.BETWEEN, BarDirection.COL);\n }\n\n public void drawBarChart(XWPFDocument xwpfDocument, WordModule wordModule) {\n }\n}"
},
{
"identifier": "PiChartTool",
"path": "src/main/java/top/nino/easyUsePoi/word/module/chart/PiChartTool.java",
"snippet": "@Component\npublic class PiChartTool {\n\n /*\n * @Description:diy饼状图,与模板设计稍有出入,但是关键数据展示成功\n * @Param: XWPFDocument docxDocument, String titleText : 饼状图名称, String xAxisName : x轴名称, String[] xAxisData : x轴数据, String yAxisName, Integer[] yAxisData, String titleName, PresetColor color : 柱状图的颜色\n * @Return:\n * @DateTime: 11:28 2023/10/30\n * @author: dingchy\n */\n public void drawPieChart(XWPFDocument docxDocument, String charTitle, String[] xAxisData, Integer[] yAxisData) {\n XWPFChart chart = null;\n try {\n chart = docxDocument.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);\n } catch (InvalidFormatException e) {\n throw new RuntimeException(e);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n chart.setTitleText(charTitle);\n chart.setTitleOverlay(false);\n XDDFChartLegend orAddLegend = chart.getOrAddLegend();\n orAddLegend.setPosition(LegendPosition.TOP_RIGHT);\n\n XDDFCategoryDataSource xAxisSource = XDDFDataSourcesFactory.fromArray(xAxisData); // 设置分类数据\n XDDFNumericalDataSource<Integer> yAxisSource = XDDFDataSourcesFactory.fromArray(yAxisData); // 设置值数据\n\n // 7、创建饼图对象,饼状图不需要X,Y轴,只需要数据集即可\n XDDFPieChartData pieChart = (XDDFPieChartData) chart.createData(ChartTypes.PIE, null, null);\n\n // 8、加载饼图数据集\n XDDFPieChartData.Series pieSeries = (XDDFPieChartData.Series) pieChart.addSeries(xAxisSource, yAxisSource);\n// pieSeries.setTitle(\"粉丝数\", null); // 系列提示标题\n // 9、绘制饼图\n chart.plot(pieChart);\n\n CTDLbls dLbls = chart.getCTChart().getPlotArea().getPieChartArray(0).getSerArray(0).addNewDLbls();\n dLbls.addNewShowVal().setVal(false);//不显示值\n dLbls.addNewShowLegendKey().setVal(false);\n dLbls.addNewShowCatName().setVal(true);//类别名称\n dLbls.addNewShowSerName().setVal(false);//不显示系列名称\n dLbls.addNewShowPercent().setVal(true);//显示百分比\n dLbls.addNewShowLeaderLines().setVal(true); //显示引导线\n }\n\n public void drawPieChart(XWPFDocument xwpfDocument, WordModule wordModule) {\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}"
},
{
"identifier": "WordModule",
"path": "src/main/java/top/nino/easyUsePoi/word/module/data/WordModule.java",
"snippet": "@Data\npublic class WordModule {\n\n /**\n * word 组件 的类型:paragraph | table | barChart | piChart\n */\n private String type;\n\n /**\n * 对齐位置:left | center | right\n */\n private String align;\n\n /**\n * 首行缩进\n */\n private String firstLineIndet;\n\n /**\n * 行间距\n */\n private String spacingBetween;\n\n /**\n * 是否分页\n */\n private Boolean pageBreak;\n\n /**\n * 段落里的文本\n */\n private List<WordText> textList;\n\n /**\n * 表格\n */\n private Integer rows;\n private Integer cols;\n private List<List<String>> tableContent;\n\n /**\n * 图\n */\n private String chartTitle;\n private List<String> chartFieldName;\n\n}"
},
{
"identifier": "WordText",
"path": "src/main/java/top/nino/easyUsePoi/word/module/data/WordText.java",
"snippet": "@Data\npublic class WordText {\n private String fontFamily;\n private String fontSize;\n private String boldFlag;\n private String color;\n private List<String> content;\n}"
},
{
"identifier": "ParagraphTool",
"path": "src/main/java/top/nino/easyUsePoi/word/module/paragraph/ParagraphTool.java",
"snippet": "@Component\n@Slf4j\npublic class ParagraphTool {\n\n\n @Autowired\n private PictureTool pictureTool;\n\n @Autowired\n private TextTool textTool;\n\n\n /**\n * 创建一个 段落 并设置该段落的 样式\n *\n * @param xwpfDocument 该 word 文件\n * @param paragraphAlignment 该段落的 对齐方向,如 居中 ParagraphAlignment.CENTER\n * @param firstLineIndent 首行缩进 如400\n * @param spacingBetween 行间距 如1.5\n */\n public XWPFParagraph drawParagraph(XWPFDocument xwpfDocument,\n ParagraphAlignment paragraphAlignment,\n Integer firstLineIndent, Double spacingBetween) {\n // 创建段落\n XWPFParagraph paragraph = xwpfDocument.createParagraph();\n // 对齐方式\n paragraph.setAlignment(paragraphAlignment);\n // 首行缩进 400 即是0.71cm 2字符\n paragraph.setFirstLineIndent(firstLineIndent);\n // 行间距1.5\n paragraph.setSpacingBetween(spacingBetween);\n // paragraphX.setSpacingLineRule(LineSpacingRule.AT_LEAST);\n return paragraph;\n }\n\n /**\n * 返回一个正文的默认段落 靠左,首行缩进为0,行间距为1.5\n * @param xwpfDocument\n * @return\n */\n public XWPFParagraph drawDefaultMainBodyParagraph(XWPFDocument xwpfDocument) {\n return drawParagraph(xwpfDocument, ParagraphDefaultSetting.DEFAULT_MAIN_BODY_ALIGN,\n ParagraphDefaultSetting.DEFAULT_FIRST_LINE_INDENT, ParagraphDefaultSetting.DEFAULT_SPACING_BETWEEN);\n }\n\n /**\n * 返回一个公告标题的默认段落 居中,首行缩进为0,行间距为1.5\n * @param xwpfDocument\n * @return\n */\n public XWPFParagraph drawDefaultAnnouncementParagraph(XWPFDocument xwpfDocument) {\n return drawParagraph(xwpfDocument, ParagraphDefaultSetting.DEFAULT_ANNOUNCEMENT_ALIGN,\n ParagraphDefaultSetting.DEFAULT_FIRST_LINE_INDENT, ParagraphDefaultSetting.DEFAULT_SPACING_BETWEEN);\n }\n\n /**\n * 给段落 增加一张图片\n *\n * @param paragraph\n * @param pictureUrl\n */\n public void drawDefaultPngPicture(XWPFParagraph paragraph, String pictureUrl) {\n pictureTool.drawDefaultPngPicture(paragraph, pictureUrl);\n }\n\n /**\n * 默认 正文 文本格式: 宋体,四号字体大小,黑色,不加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultMainBodyText(XWPFParagraph paragraph, String text) {\n textTool.drawDefaultMainBodyText(paragraph, text);\n }\n\n /**\n * 默认 小标题 文本格式: 黑体,三号字体大小,黑色,加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultTitleText(XWPFParagraph paragraph, String text) {\n textTool.drawDefaultTitleText(paragraph, text);\n }\n\n /**\n * 默认 居中公告标题 文本格式: 黑体,三号字体大小,黑色,加粗,默认一个回车,结束不分页\n * @param paragraph\n * @param text\n */\n public void drawDefaultAnnouncementText(XWPFParagraph paragraph, String text) {\n textTool.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 textTool.drawAnnouncementTextColorAndSize(paragraph, text, colorHex, fontSize, boldFlag);\n }\n\n /**\n * 通过 wordModule 生成 一个 段落\n * @param xwpfDocument\n * @param wordModule\n * @return\n */\n public XWPFParagraph drawParagraph(XWPFDocument xwpfDocument, WordModule wordModule) {\n return drawParagraph(xwpfDocument, ParagraphDefaultSetting.getAlignByString(wordModule.getAlign()),\n Integer.parseInt(wordModule.getFirstLineIndet()), Double.parseDouble(wordModule.getSpacingBetween()));\n }\n\n /**\n * 在 段落 中 添加多段文字\n * @param paragraph\n * @param preData\n */\n public void drawText(XWPFParagraph paragraph, WordText textPo, HashMap<String, String> preData) {\n textTool.drawText(paragraph, textPo, preData);\n }\n}"
},
{
"identifier": "TableTool",
"path": "src/main/java/top/nino/easyUsePoi/word/module/table/TableTool.java",
"snippet": "@Component\n@Slf4j\npublic class TableTool {\n\n /**\n * 表格的默认 宽\n */\n private final static String TABLE_DEFAULT_WIDTH = \"4381\";\n\n /**\n * 表格的默认 高\n */\n private final static int TABLE_DEFAULT_HEIGHT = 547;\n\n public void drawTable(XWPFDocument xwpfDocument, int rows, int cols, List<List<String>> text) {\n if (CollectionUtils.isEmpty(text)) {\n return;\n }\n\n XWPFTable table = xwpfDocument.createTable(rows, cols);\n int dataRows = text.size();\n\n for (int i = 0; i < dataRows; i++) {\n // 得到第i行\n List<String> rowTextList = text.get(i);\n if(CollectionUtils.isEmpty(rowTextList)) {\n continue;\n }\n XWPFTableRow row = table.getRow(i);\n row.setHeight(TABLE_DEFAULT_HEIGHT);\n for (int j = 0; j < text.get(i).size(); j++) {\n // 得到第i行,第j个单元格\n String cellText = rowTextList.get(j);\n row.getCell(j).setWidth(TABLE_DEFAULT_WIDTH);\n row.getCell(j).setText(cellText);\n row.getCell(j).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);\n }\n }\n }\n\n\n public void drawTable(XWPFDocument xwpfDocument, WordModule wordModule) {\n drawTable(xwpfDocument, wordModule.getRows(), wordModule.getCols(), wordModule.getTableContent());\n }\n}"
}
] | import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xddf.usermodel.PresetColor;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.nino.easyUsePoi.word.constant.ModuleTypeEnum;
import top.nino.easyUsePoi.word.constant.text.ColorEnum;
import top.nino.easyUsePoi.word.constant.text.FontSizeEnum;
import top.nino.easyUsePoi.word.module.chart.BarChartTool;
import top.nino.easyUsePoi.word.module.chart.PiChartTool;
import top.nino.easyUsePoi.word.module.data.WordJsonVo;
import top.nino.easyUsePoi.word.module.data.WordModule;
import top.nino.easyUsePoi.word.module.data.WordText;
import top.nino.easyUsePoi.word.module.paragraph.ParagraphTool;
import top.nino.easyUsePoi.word.module.table.TableTool;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List; | 4,972 | package top.nino.easyUsePoi.word.module;
/**
* @Author:zengzhj
* @Date:2023/10/30 13:02
*/
@Component
@Slf4j
public class DocumentTool {
/**
* A4纸张 的 宽
*/
private final static long A4_WIDTH = 12242L;
/**
* A4纸张 的 高
*/
private final static long A4_HEIGHT = 15842L;
@Autowired | package top.nino.easyUsePoi.word.module;
/**
* @Author:zengzhj
* @Date:2023/10/30 13:02
*/
@Component
@Slf4j
public class DocumentTool {
/**
* A4纸张 的 宽
*/
private final static long A4_WIDTH = 12242L;
/**
* A4纸张 的 高
*/
private final static long A4_HEIGHT = 15842L;
@Autowired | private ParagraphTool paragraphTool; | 8 | 2023-10-31 19:43:22+00:00 | 8k |
inceptive-tech/ENTSOEDataRetrieval | src/test/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/TestUnavailabilityDocCSVTransformer.java | [
{
"identifier": "UnavailabilityMarketDocument",
"path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/UnavailabilityMarketDocument.java",
"snippet": "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"Unavailability_MarketDocument\", propOrder = {\n \"mrid\",\n \"revisionNumber\",\n \"type\",\n \"processProcessType\",\n \"createdDateTime\",\n \"senderMarketParticipantMRID\",\n \"senderMarketParticipantMarketRoleType\",\n \"receiverMarketParticipantMRID\",\n \"receiverMarketParticipantMarketRoleType\",\n \"unavailabilityTimePeriodTimeInterval\",\n \"docStatus\",\n \"timeSeries\",\n \"reason\"\n})\n@XmlRootElement(name = \"Unavailability_MarketDocument\")\npublic class UnavailabilityMarketDocument {\n\n @XmlElement(name = \"mRID\", required = true)\n protected String mrid;\n @XmlElement(required = true)\n protected String revisionNumber;\n @XmlElement(required = true)\n protected String type;\n @XmlElement(name = \"process.processType\", required = true)\n protected String processProcessType;\n @XmlElement(required = true)\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar createdDateTime;\n @XmlElement(name = \"sender_MarketParticipant.mRID\", required = true)\n protected PartyIDString senderMarketParticipantMRID;\n @XmlElement(name = \"sender_MarketParticipant.marketRole.type\", required = true)\n protected String senderMarketParticipantMarketRoleType;\n @XmlElement(name = \"receiver_MarketParticipant.mRID\", required = true)\n protected PartyIDString receiverMarketParticipantMRID;\n @XmlElement(name = \"receiver_MarketParticipant.marketRole.type\", required = true)\n protected String receiverMarketParticipantMarketRoleType;\n @XmlElement(name = \"unavailability_Time_Period.timeInterval\", required = true)\n protected ESMPDateTimeInterval unavailabilityTimePeriodTimeInterval;\n protected ActionStatus docStatus;\n @XmlElement(name = \"TimeSeries\")\n protected List<TimeSeries> timeSeries;\n @XmlElement(name = \"Reason\", required = true)\n protected List<Reason> reason;\n\n /**\n * Gets the value of the mrid property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMRID() {\n return mrid;\n }\n\n /**\n * Sets the value of the mrid property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMRID(String value) {\n this.mrid = value;\n }\n\n /**\n * Gets the value of the revisionNumber property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getRevisionNumber() {\n return revisionNumber;\n }\n\n /**\n * Sets the value of the revisionNumber property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setRevisionNumber(String value) {\n this.revisionNumber = value;\n }\n\n /**\n * Gets the value of the type property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setType(String value) {\n this.type = value;\n }\n\n /**\n * Gets the value of the processProcessType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getProcessProcessType() {\n return processProcessType;\n }\n\n /**\n * Sets the value of the processProcessType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setProcessProcessType(String value) {\n this.processProcessType = value;\n }\n\n /**\n * Gets the value of the createdDateTime property.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getCreatedDateTime() {\n return createdDateTime;\n }\n\n /**\n * Sets the value of the createdDateTime property.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setCreatedDateTime(XMLGregorianCalendar value) {\n this.createdDateTime = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getSenderMarketParticipantMRID() {\n return senderMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setSenderMarketParticipantMRID(PartyIDString value) {\n this.senderMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getSenderMarketParticipantMarketRoleType() {\n return senderMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the senderMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setSenderMarketParticipantMarketRoleType(String value) {\n this.senderMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMRID property.\n * \n * @return\n * possible object is\n * {@link PartyIDString }\n * \n */\n public PartyIDString getReceiverMarketParticipantMRID() {\n return receiverMarketParticipantMRID;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMRID property.\n * \n * @param value\n * allowed object is\n * {@link PartyIDString }\n * \n */\n public void setReceiverMarketParticipantMRID(PartyIDString value) {\n this.receiverMarketParticipantMRID = value;\n }\n\n /**\n * Gets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getReceiverMarketParticipantMarketRoleType() {\n return receiverMarketParticipantMarketRoleType;\n }\n\n /**\n * Sets the value of the receiverMarketParticipantMarketRoleType property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setReceiverMarketParticipantMarketRoleType(String value) {\n this.receiverMarketParticipantMarketRoleType = value;\n }\n\n /**\n * Gets the value of the unavailabilityTimePeriodTimeInterval property.\n * \n * @return\n * possible object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public ESMPDateTimeInterval getUnavailabilityTimePeriodTimeInterval() {\n return unavailabilityTimePeriodTimeInterval;\n }\n\n /**\n * Sets the value of the unavailabilityTimePeriodTimeInterval property.\n * \n * @param value\n * allowed object is\n * {@link ESMPDateTimeInterval }\n * \n */\n public void setUnavailabilityTimePeriodTimeInterval(ESMPDateTimeInterval value) {\n this.unavailabilityTimePeriodTimeInterval = value;\n }\n\n /**\n * Gets the value of the docStatus property.\n * \n * @return\n * possible object is\n * {@link ActionStatus }\n * \n */\n public ActionStatus getDocStatus() {\n return docStatus;\n }\n\n /**\n * Sets the value of the docStatus property.\n * \n * @param value\n * allowed object is\n * {@link ActionStatus }\n * \n */\n public void setDocStatus(ActionStatus value) {\n this.docStatus = value;\n }\n\n /**\n * Gets the value of the timeSeries property.\n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the timeSeries property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getTimeSeries().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link TimeSeries }\n * \n * \n */\n public List<TimeSeries> getTimeSeries() {\n if (timeSeries == null) {\n timeSeries = new ArrayList<TimeSeries>();\n }\n return this.timeSeries;\n }\n\n /**\n * Gets the value of the reason property.\n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the reason property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getReason().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link Reason }\n * \n * \n */\n public List<Reason> getReason() {\n if (reason == null) {\n reason = new ArrayList<Reason>();\n }\n return this.reason;\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.BufferedWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.mockito.Mockito.*;
import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition;
import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.custom.JAXBDeserializerHelper; | 5,019 | /*
* 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.csv.transformers;
/**
*
* @author Andres Bel Alonso
*/
public class TestUnavailabilityDocCSVTransformer {
private static final Logger LOGGER = LogManager.getLogger(TestUnavailabilityDocCSVTransformer.class);
@Test
public void testWriteNextEntry() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryOutOfBondsBefore() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2018, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryOutOfBondsAfter() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryStartPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 7, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryEndPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 19, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNewEntryDifferentSepator() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1");
}
@Test
public void testWriteNewEntryNonScheduled() throws IOException {
// this document contains an outage non scheduled
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMeUnscheduled.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 4, 10, 4, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;0");
}
@Test
public void testWriteNewEntryGenerationOutage() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2023, 3, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1;114.0");
}
@Test
public void testComputeColumnDefTransmission() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "10T-ME-RS-00001G",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "10T-ME-RS-00001G",
colDef.get(1).colName());
}
@Test
public void testComputeColumnDefGeneration() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(3, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.GENERATION_UNAVAILABILITY_BASE_NAME + "21W00000000PIVA9",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "21W00000000PIVA9",
colDef.get(1).colName());
assertEquals("ME_" + UnavailabilityDocCSVTransformer.NOMINAL_OUTAGE_POWER + "21W00000000PIVA9",
colDef.get(2).colName());
}
@Test
public void testComputeColumnDefTransmissionMissingAsset() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutagaeGridUnknow.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "Unknown_asset_IT-CS_ME",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "Unknown_asset_IT-CS_ME",
colDef.get(1).colName());
}
private UnavailabilityMarketDocument readUnavailabilityDoc(String xmlFilename) throws IOException {
try { | /*
* 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.csv.transformers;
/**
*
* @author Andres Bel Alonso
*/
public class TestUnavailabilityDocCSVTransformer {
private static final Logger LOGGER = LogManager.getLogger(TestUnavailabilityDocCSVTransformer.class);
@Test
public void testWriteNextEntry() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryOutOfBondsBefore() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2018, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryOutOfBondsAfter() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryStartPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 7, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryEndPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 19, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNewEntryDifferentSepator() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1");
}
@Test
public void testWriteNewEntryNonScheduled() throws IOException {
// this document contains an outage non scheduled
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMeUnscheduled.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 4, 10, 4, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;0");
}
@Test
public void testWriteNewEntryGenerationOutage() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2023, 3, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1;114.0");
}
@Test
public void testComputeColumnDefTransmission() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "10T-ME-RS-00001G",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "10T-ME-RS-00001G",
colDef.get(1).colName());
}
@Test
public void testComputeColumnDefGeneration() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(3, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.GENERATION_UNAVAILABILITY_BASE_NAME + "21W00000000PIVA9",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "21W00000000PIVA9",
colDef.get(1).colName());
assertEquals("ME_" + UnavailabilityDocCSVTransformer.NOMINAL_OUTAGE_POWER + "21W00000000PIVA9",
colDef.get(2).colName());
}
@Test
public void testComputeColumnDefTransmissionMissingAsset() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutagaeGridUnknow.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "Unknown_asset_IT-CS_ME",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "Unknown_asset_IT-CS_ME",
colDef.get(1).colName());
}
private UnavailabilityMarketDocument readUnavailabilityDoc(String xmlFilename) throws IOException {
try { | return JAXBDeserializerHelper.doJAXBUnmarshall( | 1 | 2023-10-30 09:09:53+00:00 | 8k |
EricFan2002/SC2002 | src/app/entity/report/EnquiryReport.java | [
{
"identifier": "Camp",
"path": "src/app/entity/camp/Camp.java",
"snippet": "public class Camp extends CampDetails implements ITaggedItem {\n\n protected Staff staffInCharge;\n protected Set<Student> attendees;\n protected Set<Student> committees;\n protected Set<Student> registeredStudents;\n private ArrayList<Suggestion> suggestionList;\n private ArrayList<Enquiry> enquiryList;\n\n public static final int MAX_COMMITTEE = 10;\n\n /**\n * Constructs a new Camp instance with specified details.\n * \n * @param ID Unique identifier for the camp.\n * @param name Name of the camp.\n * @param description Description of the camp.\n * @param visibility Visibility status of the camp.\n * @param startDate Start date of the camp.\n * @param endDate End date of the camp.\n * @param closeRegistrationDate Closing date for registration.\n * @param school School associated with the camp.\n * @param location Location of the camp.\n * @param staffInCharge Staff member in charge of the camp.\n * @param totalSlots Total number of slots available in the camp.\n * @param totalCommitteeSlots Total number of committee slots available in the camp.\n */\n public Camp(String ID, String name, String description, Boolean visibility, Date startDate, Date endDate,\n Date closeRegistrationDate,\n String school, String location, Staff staffInCharge, int totalSlots, int totalCommitteeSlots) {\n super(ID, name, description, visibility, startDate, endDate, closeRegistrationDate, school, location,\n totalSlots, totalCommitteeSlots);\n this.staffInCharge = staffInCharge;\n this.attendees = new HashSet<Student>();\n this.committees = new HashSet<Student>();\n this.registeredStudents = new HashSet<Student>();\n this.suggestionList = new ArrayList<Suggestion>();\n this.enquiryList = new ArrayList<Enquiry>();\n }\n\n // Example for one getter and one setter\n /**\n * Retrieves the staff member in charge of the camp.\n * \n * @return Staff The staff member in charge.\n */\n public Staff getStaffInCharge() {\n return staffInCharge;\n }\n\n public Set<Student> getAttendees() {\n return attendees;\n }\n\n public Set<Student> getAttendeesAndCommittees(){\n Set<Student> res = new HashSet<>();\n res.addAll(attendees);\n res.addAll(committees);\n return res;\n }\n\n public Set<Student> getCommittees() {\n return committees;\n }\n\n /**\n * Sets the staff member in charge of the camp.\n * \n * @param staffInCharge The staff member to be set as in charge.\n */\n public void setStaffInCharge(Staff staffInCharge) {\n this.staffInCharge = staffInCharge;\n }\n\n public void setAttendees(Set<Student> attendees) {\n this.attendees = attendees;\n }\n\n public void setCommittees(Set<Student> committees) {\n this.committees = committees;\n }\n\n /**\n * Adds a student as an attendee of the camp.\n * \n * @param attendee The student to be added as an attendee.\n * @return boolean True if the student is successfully added.\n */\n public boolean addAttendee(Student attendee) {\n if (this.attendees.size() >= this.totalSlots - MAX_COMMITTEE) {\n return false;\n }\n attendees.add(attendee);\n registeredStudents.add(attendee);\n return true;\n }\n\n /**\n * Adds a student as a committee member of the camp.\n *\n * @param committee The student to be added as a committee member.\n * @return boolean True if the student is successfully added.\n */\n public boolean addCommittee(Student committee) {\n if (this.committees.size() >= MAX_COMMITTEE) {\n return false;\n }\n committees.add(committee);\n registeredStudents.add(committee);\n return true;\n }\n\n /**\n * Removes a student from the list of attendees.\n *\n * @param attendee The student to be removed.\n * @return boolean True if the student is successfully removed.\n */\n public boolean removeAttendee(Student attendee) {\n return attendees.remove(attendee);\n }\n\n public boolean removeCommittee(Student committee) {\n return committees.remove(committee);\n }\n\n /**\n * Creates a suggestion plan based on the current state of the camp.\n * This plan can be used to suggest modifications or improvements to the camp.\n * \n * @return CampDetails A new {@code CampDetails} object representing the\n * suggestion plan.\n */\n public CampDetails createSuggestionPlan() {\n CampDetails suggestionPlan = new CampDetails();\n suggestionPlan.setID(this.ID);\n return suggestionPlan;\n }\n\n /**\n * Retrieves the list of suggestions for the camp.\n *\n * @return The list of suggestions.\n */\n public ArrayList<Suggestion> getSuggestionList() {\n return suggestionList;\n }\n\n /**\n * Retrieves the list of enquiries for the camp.\n *\n * @return The list of enquiries.\n */\n public ArrayList<Enquiry> getEnquiryList() {\n return enquiryList;\n }\n\n /**\n * Adds a suggestion to the list of suggestions.\n *\n * @param suggestion The suggestion to be added.\n */\n public void addSuggestion(Suggestion suggestion) {\n suggestionList.add(suggestion);\n }\n\n /**\n * Adds an enquiry to the list of enquiries.\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 a suggestion from the list of suggestions.\n *\n * @param suggestion The suggestion to be removed.\n */\n public void removeSuggestion(Suggestion suggestion) {\n suggestionList.remove(suggestion);\n }\n\n /**\n * Removes an enquiry from the list of enquiries.\n *\n * @param enquiry The enquiry to be removed.\n */\n public void removeEnquiry(Enquiry enquiry) {\n enquiryList.remove(enquiry);\n }\n\n /**\n * Checks if a student is registered in the camp.\n *\n * @param student The student to check for registration.\n * @return True if the student is registered, false otherwise.\n */\n public boolean isStudentRegistered(Student student) {\n return registeredStudents.contains(student);\n }\n\n /**\n * Adds a student to the list of registered students (used for deserialize\n * only).\n *\n * @param student The student to be added.\n */\n public void addRegisteredStudent(Student student) {\n registeredStudents.add(student);\n }\n\n /**\n * Retrieves the list of previously registered students.\n */\n public Set<Student> getRegisteredStudents() {\n return registeredStudents;\n }\n}"
},
{
"identifier": "CampList",
"path": "src/app/entity/camp/CampList.java",
"snippet": "public class CampList extends RepositoryList<Camp> implements IFilterableByID<Camp>, IFilterableByDateRange<Camp>,\n IFilterableBySchool<Camp>, IFilterableByVisibility<Camp>, ISortableByEndDate<Camp>, ISortableByID<Camp>,\n ISortableByLocation<Camp>, ISortableByName<Camp>, ISortableByRegistrationCloseDate<Camp>,\n ISortableByStartingDate<Camp>, IFilterableByAttendee<Camp>, IFilterableByCampCommittee<Camp>,\n IFilterableByStudent<Camp> {\n /**\n * Constructs a new CampList with the specified list of camps.\n *\n * @param all A list of Camp objects to be managed.\n */\n public CampList(List<Camp> all) {\n super(all);\n }\n\n /**\n * Constructs an empty CampList.\n */\n public CampList() {\n super();\n }\n\n /**\n * Filters the list of camps by the specified ID.\n *\n * @param id The ID to filter by.\n * @return A new CampList containing camps that match the given ID.\n */\n public CampList filterByID(String id) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getID().equals(id)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by the specified school.\n *\n * @param school The school to filter by.\n * @return A new CampList containing camps associated with the given school.\n */\n public CampList filterBySchool(String school) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getSchool().equals(school)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by their visibility status.\n *\n * @param visible The visibility status to filter by.\n * @return A new CampList containing camps with the specified visibility status.\n */\n public CampList filterByVisibility(boolean visible) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.isVisible() == visible) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps within a specific date range.\n *\n * @param startDate The start date of the range.\n * @param endDate The end date of the range.\n * @return A new CampList containing camps within the specified date range.\n */\n public CampList filterByDateRange(Date startDate, Date endDate) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getStartDate().compareTo(startDate) >= 0 && camp.getEndDate().compareTo(endDate) <= 0) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by registration date.\n *\n * @param currentDate The date to compare registration dates against.\n * @return A new CampList containing camps whose registration date is on or\n * after the specified date.\n */\n public CampList filterByRegistrationDate(Date currentDate) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getCloseRegistrationDate().compareTo(currentDate) >= 0) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by a specific student attendee.\n *\n * @param student The student to filter by.\n * @return A new CampList containing camps that the given student is attending.\n */\n public CampList filterByStudent(Student student) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getAttendees().contains(student)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Filters the list of camps by a specific staff member in charge.\n *\n * @param staff The staff member to filter\n * by.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffsssssssssssssssssssssssssssssssssssssssssssss\n * @return A new CampList containing camps managed by the given staff member.\n */\n public CampList filterByStaff(Staff staff) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getStaffInCharge().equals(staff)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n public CampList filterByCampCommittee(Student student) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getCommittees().contains(student)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n public CampList filterByAttendee(Student attendee) {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n if (camp.getAttendees().contains(attendee)) {\n result.add(camp);\n }\n }\n return result;\n }\n\n /**\n * Sorts the list of camps by their names.\n *\n * @return A new CampList sorted by camp names.\n */\n public CampList sortByName() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getName().compareTo(o2.getName());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their registration close dates.\n *\n * @return A new CampList sorted by camp registration close dates.\n */\n public CampList sortByRegistrationCloseDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getCloseRegistrationDate().compareTo(o2.getCloseRegistrationDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their starting dates.\n *\n * @return A new CampList sorted by camp starting dates.\n */\n public CampList sortByStartingDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getStartDate().compareTo(o2.getStartDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their end dates.\n *\n * @return A new CampList sorted by camp end dates.\n */\n public CampList sortByEndDate() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getEndDate().compareTo(o2.getEndDate());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their locations.\n *\n * @return A new CampList sorted by camp locations.\n */\n public CampList sortByLocation() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getLocation().compareTo(o2.getLocation());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Sorts the list of camps by their IDs.\n *\n * @return A new CampList sorted by camp IDs.\n */\n public CampList sortByID() {\n CampList result = new CampList();\n for (Camp camp : super.all) {\n result.add(camp);\n }\n Comparator<Camp> comparator = new Comparator<Camp>() {\n @Override\n public int compare(Camp o1, Camp o2) {\n return o1.getID().compareTo(o2.getID());\n }\n };\n result.all.sort(comparator);\n\n return result;\n }\n\n /**\n * Returns all camps in the list.\n *\n * @return This CampList.\n */\n public CampList getAll() {\n return this;\n }\n\n /**\n * Converts the CampList to an array of Camp objects.\n *\n * @return An array of Camp objects.\n */\n public Camp[] toArray() {\n return super.all.toArray(new Camp[super.all.size()]);\n }\n\n public ArrayList<ArrayList<String>> serialize() {\n\n ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();\n super.all.forEach(campRaw -> {\n Camp camp = (Camp) campRaw;\n // id, name, desc, visibility (0/1), startDate, endDate, closeRegDate, school,\n ArrayList<String> record = new ArrayList<String>();\n String visibility = (camp.isVisible()) ? \"1\" : \"0\";\n String startDate = Long.toString(camp.getStartDate().getTime());\n String endDate = Long.toString(camp.getEndDate().getTime());\n String closeRegDate = Long.toString(camp.getCloseRegistrationDate().getTime());\n\n String staffID = camp.getStaffInCharge().getID();\n\n List<String> attendeeIDsTemp = new ArrayList<String>();\n for (Student attendee : camp.getAttendees()) {\n attendeeIDsTemp.add(attendee.getID());\n }\n String attendeeIDs = String.join(\";\", attendeeIDsTemp);\n\n List<String> committeeIDsTemp = new ArrayList<String>();\n for (Student committee : camp.getCommittees()) {\n committeeIDsTemp.add(committee.getID());\n }\n String committeeIDs = String.join(\";\", committeeIDsTemp);\n\n List<String> registeredIDsTemp = new ArrayList<String>();\n for (Student registered : camp.getRegisteredStudents()) {\n registeredIDsTemp.add(registered.getID());\n }\n String registeredIDs = String.join(\";\", registeredIDsTemp);\n\n record.add(camp.getID());\n record.add(camp.getName());\n record.add(camp.getDescription());\n record.add(visibility);\n record.add(startDate);\n record.add(endDate);\n record.add(closeRegDate);\n record.add(camp.getSchool());\n record.add(camp.getLocation());\n record.add(staffID);\n record.add(attendeeIDs);\n record.add(committeeIDs);\n record.add(registeredIDs);\n record.add(Integer.toString(camp.getTotalSlots()));\n record.add(Integer.toString(camp.getTotalCommitteeSlots()));\n\n result.add(record);\n\n });\n\n return result;\n }\n\n}"
},
{
"identifier": "Enquiry",
"path": "src/app/entity/enquiry/Enquiry.java",
"snippet": "public class Enquiry implements ITaggedItem {\n protected String ID;\n protected Student sender;\n protected String question;\n protected String answer;\n protected Camp camp;\n protected User answeredBy;\n\n /**\n * Constructs a new Enquiry with the provided ID, sender, question, and associated camp.\n * Initially, the enquiry is not answered.\n *\n * @param ID Unique identifier for the enquiry.\n * @param sender The student who sent the enquiry.\n * @param question The question asked in the enquiry.\n * @param camp The camp related to the enquiry.\n */\n public Enquiry(String ID, Student sender, String question, Camp camp) {\n this.ID = ID;\n this.sender = sender;\n this.question = question;\n this.camp = camp;\n this.answeredBy = null; // assume not yet answered if it is null\n this.answer = null;\n }\n\n /**\n * Constructs a new Enquiry with the provided details including an answer and the responder.\n *\n * @param ID Unique identifier for the enquiry.\n * @param sender The student who sent the enquiry.\n * @param question The question asked in the enquiry.\n * @param answer The answer to the enquiry.\n * @param camp The camp related to the enquiry.\n * @param answeredBy The user who answered the enquiry.\n */\n public Enquiry(String ID, Student sender, String question, String answer, Camp camp, User answeredBy) {\n this.ID = ID;\n this.sender = sender;\n this.question = question;\n this.answer = answer;\n this.camp = camp;\n this.answeredBy = answeredBy; // assume not yet answered if it is null\n }\n\n /**\n * Returns the ID of the enquiry.\n *\n * @return The unique identifier of the enquiry.\n */\n public String getID() {\n return ID;\n }\n\n /**\n * Returns the sender of the enquiry.\n *\n * @return The student who sent the enquiry.\n */\n public Student getSender() {\n return sender;\n }\n\n /**\n * Returns the question of the enquiry.\n *\n * @return The question asked in the enquiry.\n */\n public String getQuestion() {\n return question;\n }\n\n /**\n * Returns the answer to the enquiry.\n *\n * @return The answer to the enquiry.\n */\n public String getAnswer() {\n return answer;\n }\n\n /**\n * Returns the camp related to the enquiry.\n *\n * @return The camp related to the enquiry.\n */\n public Camp getCamp() {\n return camp;\n }\n\n /**\n * Returns the user who answered the enquiry.\n *\n * @return The user who answered the enquiry.\n */\n public User getAnsweredBy() {\n return answeredBy;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param answer The answer to the enquiry.\n * @param answeredBy The user who answered the enquiry.\n */\n public void setAnswer(String answer, User answeredBy) {\n this.answer = answer;\n this.answeredBy = answeredBy;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param ID The unique identifier of the enquiry.\n */\n public void setID(String ID) {\n this.ID = ID;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param sender The student who sent the enquiry.\n */\n public void setSender(Student sender) {\n this.sender = sender;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param question The question asked in the enquiry.\n */\n public void setQuestion(String question) {\n this.question = question;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param camp The camp related to the enquiry.\n */\n public void setCamp(Camp camp) {\n this.camp = camp;\n }\n\n /**\n * Returns whether the enquiry has been answered.\n *\n * @param answeredBy The user who answered the enquiry.\n */\n public void setAnsweredBy(Student answeredBy) {\n this.answeredBy = answeredBy;\n }\n}"
}
] | import java.util.ArrayList;
import java.util.Arrays;
import app.entity.camp.Camp;
import app.entity.camp.CampList;
import app.entity.enquiry.Enquiry; | 6,017 | package app.entity.report;
/**
* The {@code EnquiryReport} class represents a report on camp enquiries, including details about questions and answers.
* It extends the {@code Report} class and implements the {@code ISerializeable} interface.
*/
public class EnquiryReport extends Report {
/**
* The fields included in the report.
*/
private static String[] fields = { "Camp ID", "Camp Name", "Sender ID", "Sender Name", "Question",
"Answered by Name", "Answered by ID", "Answer" };
/**
* The list of camps to be included in the report.
*/
private CampList camp;
/**
* Constructs an EnquiryReport object with the specified camp list.
*
* @param camp The list of camps to be included in the report.
*/
public EnquiryReport(CampList camp) {
super();
this.camp = new CampList();
camp.forEach((curCamp) -> {
this.camp.add(curCamp);
});
}
/**
* Constructs an EnquiryReport object with the specified camp.
*
* @param camp The camp to be included in the report.
*/
public EnquiryReport(Camp camp) {
super();
this.camp = new CampList();
this.camp.add(camp);
}
/**
* Serializes the enquiry report and represents its data as an ArrayList of ArrayList of Strings.
*
* @return An {@code ArrayList<ArrayList<String>>} representing the serialized data of the enquiry report.
*/
public final ArrayList<ArrayList<String>> serialize() {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> header = new ArrayList<String>(Arrays.asList(fields));
data.add(header);
for (Camp camp : this.camp) { | package app.entity.report;
/**
* The {@code EnquiryReport} class represents a report on camp enquiries, including details about questions and answers.
* It extends the {@code Report} class and implements the {@code ISerializeable} interface.
*/
public class EnquiryReport extends Report {
/**
* The fields included in the report.
*/
private static String[] fields = { "Camp ID", "Camp Name", "Sender ID", "Sender Name", "Question",
"Answered by Name", "Answered by ID", "Answer" };
/**
* The list of camps to be included in the report.
*/
private CampList camp;
/**
* Constructs an EnquiryReport object with the specified camp list.
*
* @param camp The list of camps to be included in the report.
*/
public EnquiryReport(CampList camp) {
super();
this.camp = new CampList();
camp.forEach((curCamp) -> {
this.camp.add(curCamp);
});
}
/**
* Constructs an EnquiryReport object with the specified camp.
*
* @param camp The camp to be included in the report.
*/
public EnquiryReport(Camp camp) {
super();
this.camp = new CampList();
this.camp.add(camp);
}
/**
* Serializes the enquiry report and represents its data as an ArrayList of ArrayList of Strings.
*
* @return An {@code ArrayList<ArrayList<String>>} representing the serialized data of the enquiry report.
*/
public final ArrayList<ArrayList<String>> serialize() {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> header = new ArrayList<String>(Arrays.asList(fields));
data.add(header);
for (Camp camp : this.camp) { | ArrayList<Enquiry> enquiries = camp.getEnquiryList(); | 2 | 2023-11-01 05:18:29+00:00 | 8k |
LLNL/response | src/main/java/gov/llnl/gnem/response/NDCUnitsParser.java | [
{
"identifier": "ResponseUnits",
"path": "src/main/java/com/isti/jevalresp/ResponseUnits.java",
"snippet": "public class ResponseUnits implements Serializable {\r\n\r\n private static final long serialVersionUID = 6244556146016308579L;\r\n\r\n private final Unit<? extends Quantity<?>> inputUnits;\r\n private final UnitImpl unitObj;\r\n private final UnitsStatus unitsStatus;\r\n\r\n public final static Unit<Angle> DEGREE = RADIAN.divide(Math.PI).multiply(180.0).asType(Angle.class);\r\n\r\n public final static Unit<Information> BIT = new AlternateUnit(ONE, \"bit\");\r\n public final static ProductUnit<InformationRate> BITS_PER_SECOND = new ProductUnit<>(BIT.divide(SECOND));\r\n public final static Unit<Information> BYTE = BIT.multiply(8);\r\n\r\n public final static Unit<Speed> MILLIMETER_PER_HOUR = METRE_PER_SECOND.multiply(1000 * 3600);\r\n\r\n public final static Unit<Speed> INCH_PER_SECOND = METRE_PER_SECOND.divide(39.3701);\r\n public final static Unit<Speed> MILE_PER_HOUR = METRE_PER_SECOND.multiply(0.44704);\r\n\r\n public final static Unit<?> WATT_PER_SQUARE_METRE = WATT.divide(METRE.pow(2));\r\n\r\n public final static Unit<Speed> NANOMETER_PER_SECOND = MetricPrefix.NANO(METRE_PER_SECOND);\r\n public final static Unit<?> NANOMETER_PER_SQUARE_SECOND = MetricPrefix.NANO(METRE_PER_SQUARE_SECOND);\r\n\r\n public final static Unit<Length> NANOMETER = MetricPrefix.NANO(METRE);\r\n public final static Unit<Dimensionless> COUNT = new AlternateUnit(ONE, \"count\");\r\n public final static Unit<Dimensionless> CYCLE = new AlternateUnit(ONE, \"cycle\");\r\n public final static Unit<Dimensionless> NUMBER = new AlternateUnit(ONE, \"number\");\r\n public final static Unit<Dimensionless> REBOOT_COUNT = new AlternateUnit(ONE, \"reboot\");\r\n public final static Unit<Dimensionless> STRAIN = new AlternateUnit(ONE, \"strain\");\r\n public final static Unit<Dimensionless> VOLUMETRIC_STRAIN = new AlternateUnit(ONE, \"vstrain\");\r\n public final static Unit<Dimensionless> MICRO_STRAIN = MetricPrefix.MICRO(ResponseUnits.STRAIN);\r\n public final static Unit<Pressure> BAR = MetricPrefix.KILO(MetricPrefix.HECTO(PASCAL));\r\n public final static Unit<Pressure> MILLIBAR = MetricPrefix.HECTO(PASCAL);\r\n\r\n public final static Unit<Dimensionless> GAPS = new AlternateUnit(ONE, \"gaps\");\r\n public final static Unit<Dimensionless> HITS = new AlternateUnit(ONE, \"hits\");\r\n public final static Unit<?> HAIL_INTENSITY = HITS.divide(METRE.pow(2)).divide(SECOND);\r\n public final static Unit<Dimensionless> DEFAULT = new AlternateUnit(ONE, \"default\");\r\n\r\n public final static Unit<Length> MICRON = MetricPrefix.MICRO(METRE);\r\n public final static Unit<Length> PICO_METRE = MetricPrefix.PICO(METRE);\r\n\r\n private static final ArrayList<SimpleEntry<String, String>> UNITS_DESCRIPTION = new ArrayList<>();\r\n\r\n public static ArrayList<SimpleEntry<String, String>> getUnitsDescription() {\r\n return new ArrayList<>(UNITS_DESCRIPTION);\r\n }\r\n\r\n static {\r\n SimpleUnitFormat.getInstance().label(STRAIN, \"strain\");\r\n SimpleUnitFormat.getInstance().label(VOLUMETRIC_STRAIN, \"vstrain\");\r\n SimpleUnitFormat.getInstance().label(REBOOT_COUNT, \"reboot\");\r\n SimpleUnitFormat.getInstance().label(NUMBER, \"number\");\r\n SimpleUnitFormat.getInstance().label(CYCLE, \"cycle\");\r\n SimpleUnitFormat.getInstance().label(COUNT, \"count\");\r\n SimpleUnitFormat.getInstance().label(BIT, \"bit\");\r\n SimpleUnitFormat.getInstance().label(BYTE, \"byte\");\r\n SimpleUnitFormat.getInstance().label(GAPS, \"gaps\");\r\n SimpleUnitFormat.getInstance().label(HITS, \"hits\");\r\n SimpleUnitFormat.getInstance().label(DEFAULT, \"default\");\r\n SimpleUnitFormat.getInstance().label(DEGREE, \"degree\");\r\n SimpleUnitFormat.getInstance().label(MILE_PER_HOUR, \"mph\");\r\n SimpleUnitFormat.getInstance().label(INCH_PER_SECOND, \"ips\");\r\n SimpleUnitFormat.getInstance().label(MILLIMETER_PER_HOUR, \"mm/h\");\r\n SimpleUnitFormat.getInstance().label(NANOMETER_PER_SECOND, \"nm/s\");\r\n SimpleUnitFormat.getInstance().label(NANOMETER_PER_SQUARE_SECOND, \"nm/s^2\");\r\n SimpleUnitFormat.getInstance().label(NANOMETER, \"nm\");\r\n SimpleUnitFormat.getInstance().label(MICRO_STRAIN, \"microstrain\");\r\n SimpleUnitFormat.getInstance().label(MICRON, \"micron\");\r\n SimpleUnitFormat.getInstance().label(PICO_METRE, \"pm\");\r\n SimpleUnitFormat.getInstance().label(CELSIUS, \"degC\");\r\n SimpleUnitFormat.getInstance().label(METRE_PER_SQUARE_SECOND, \"m/s^2\");\r\n SimpleUnitFormat.getInstance().label(WATT_PER_SQUARE_METRE, \"W/m^2\");\r\n SimpleUnitFormat.getInstance().label(MetricPrefix.CENTI(METRE).divide(SECOND.pow(2)), \"cm/s^2\");\r\n SimpleUnitFormat.getInstance().label(HAIL_INTENSITY.multiply(0.36), \"H/cm^2/hr\");\r\n SimpleUnitFormat.getInstance().label(HAIL_INTENSITY, \"hail\");\r\n\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"default\", \"No units requested\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"strain\", \"Strain e.g. meters per meter\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"vstrain\", \"Volumetric strain e.g. m^3 / m^3\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"bit/s\", \"Information rate in bits per second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"byte\", \"Digital Size in Digital bytes\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"degC\", \"temperature in degrees Celsius\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"cm/s^2\", \"acceleration in centimeters per seconds squared\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"count\", \"Digital Counts\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"cPa\", \"Pressure in centiPascal\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"cycle\", \"Cycles\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"degree\", \"Direction in Degrees\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"hail\", \"hail intensity in hits per meters squared sec\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"kPa\", \"Pressure in kilo-Pascals\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"m\", \"Displacement in Meters\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"m/s^2\", \"ACCELERATION in Meters per square second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"mrad\", \"Angle in Microradians\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"microstrain\", \"Microstrain\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"micron\", \"length in units of 10^-6 METRE\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"pm\", \"length in units of 10^-12 METRE\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"hPa\", \"Pressure in hectoPascals or millibars\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"mm/h\", \"Velocity in millimeters per hour\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"ips\", \"Velocity in inches per second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"mPa\", \"Pressure in milliPascals\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"mph\", \"Velocity in miles per hour\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"nm/s\", \"Velocity in nanometers per second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"number\", \"Dimensionless number\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"nT\", \"Magnetic field in nanoTeslas\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"Pa\", \"Pressure in Pascals\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"%\", \"Percentage 0-100\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"rad/s\", \"Angular velocity in radians per second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"reboot\", \"Reboot count\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"s\", \"Time in Seconds\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"T\", \"Magnetic field in Teslas\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"rad\", \"Angular rotation in radians\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"ns\", \"Time in nanoseconds\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"V\", \"EMF in Volts\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"V/m\", \"Electric field in Volts per meter\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"A\", \"Electric Current in Amperes\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"gaps\", \"Gap count\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"m/s\", \"VELOCITY in Meters Per Second\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"mV\", \"EMF in millivolts\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"nm\", \"DISPLACEMENT IN NANOMETERS\"));\r\n UNITS_DESCRIPTION.add(new SimpleEntry<>(\"W/m^2\", \"Watts Per Square Meter\"));\r\n\r\n }\r\n\r\n private static Unit<?>[] allUnits = { ResponseUnits.STRAIN, //\r\n ResponseUnits.VOLUMETRIC_STRAIN, //\r\n ResponseUnits.BITS_PER_SECOND, //\r\n ResponseUnits.BYTE, //\r\n CELSIUS, //\r\n MetricPrefix.CENTI(METRE).divide(SECOND.pow(2)), //\r\n ResponseUnits.COUNT, //\r\n MetricPrefix.CENTI(PASCAL), //\r\n ResponseUnits.CYCLE, //\r\n ResponseUnits.DEGREE, //\r\n ResponseUnits.HAIL_INTENSITY.multiply(0.36), //\r\n ResponseUnits.HAIL_INTENSITY, //\r\n MetricPrefix.HECTO(PASCAL), //\r\n MetricPrefix.KILO(PASCAL), METRE, //\r\n METRE_PER_SQUARE_SECOND, //\r\n MetricPrefix.MILLI(RADIAN), //\r\n MICRO_STRAIN, MICRON, //\r\n PICO_METRE, //\r\n ResponseUnits.MILLIBAR, ResponseUnits.MILLIMETER_PER_HOUR, //\r\n MetricPrefix.MILLI(PASCAL), //\r\n MILE_PER_HOUR, //\r\n NANOMETER_PER_SECOND, //\r\n ResponseUnits.NUMBER, //\r\n MetricPrefix.NANO(TESLA), //\r\n PASCAL, //\r\n PERCENT, //\r\n RADIAN.divide(SECOND), //\r\n ResponseUnits.REBOOT_COUNT, //\r\n SECOND, //\r\n TESLA, //\r\n RADIAN, //\r\n MetricPrefix.NANO(SECOND), //\r\n VOLT, //\r\n VOLT.divide(METRE), //\r\n AMPERE, //\r\n ResponseUnits.GAPS, //\r\n METRE_PER_SECOND, //\r\n ResponseUnits.MILLIBAR, //\r\n MetricPrefix.MILLI(VOLT), //\r\n MetricPrefix.NANO(METRE), //\r\n WATT.divide(METRE.pow(2)) };//\r\n\r\n public ResponseUnits(Unit<?> inputUnits, UnitImpl unitObj, UnitsStatus unitsStatus) {\r\n this.inputUnits = inputUnits;\r\n this.unitObj = unitObj;\r\n this.unitsStatus = unitsStatus;\r\n }\r\n\r\n public ResponseUnits() {\r\n unitsStatus = UnitsStatus.UNDETERMINED;\r\n unitObj = UnitImpl.UNKNOWN;\r\n inputUnits = new AlternateUnit(ONE, \"unknown\");\r\n }\r\n\r\n public ResponseUnits(UnitsStatus unitsStatus) {\r\n this.unitsStatus = unitsStatus;\r\n unitObj = UnitImpl.UNKNOWN;\r\n inputUnits = new AlternateUnit(ONE, \"unknown\");\r\n }\r\n\r\n ResponseUnits(ResponseUnits units) {\r\n unitsStatus = units.unitsStatus;\r\n unitObj = units.unitObj;\r\n inputUnits = units.inputUnits;\r\n }\r\n\r\n public Unit<? extends Quantity<?>> getInputUnits() {\r\n return inputUnits;\r\n }\r\n\r\n public UnitImpl getUnitObj() {\r\n return unitObj;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n int hash = 7;\r\n hash = 59 * hash + Objects.hashCode(this.inputUnits);\r\n hash = 59 * hash + Objects.hashCode(this.unitObj);\r\n hash = 59 * hash + Objects.hashCode(this.unitsStatus);\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 ResponseUnits other = (ResponseUnits) obj;\r\n if (!Objects.equals(this.inputUnits, other.inputUnits)) {\r\n return false;\r\n }\r\n if (!Objects.equals(this.unitObj, other.unitObj)) {\r\n return false;\r\n }\r\n if (this.unitsStatus != other.unitsStatus) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n public UnitsStatus getUnitsStatus() {\r\n return unitsStatus;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"ResponseUnits{\" + \"inputUnits=\" + inputUnits + \", unitObj=\" + unitObj + \", unitsStatus=\" + unitsStatus + '}';\r\n }\r\n\r\n public static void main(String[] args) {\r\n String tmp = \"m/s\";\r\n Unit<?> likelyUnits = ResponseUnits.parse(tmp);\r\n System.out.println(likelyUnits);\r\n }\r\n\r\n public static double getScaleFactor(Unit<?> inUnit, Unit<?> outUnit) {\r\n\r\n if (!inUnit.isCompatible(outUnit)) {\r\n throw new IllegalArgumentException(String.format(\"The input units (%s) are incompatible with the output units(%s)\", inUnit.toString(), outUnit.toString()));\r\n }\r\n if (inUnit.isCompatible(METRE)) {\r\n UnitConverter converter = inUnit.asType(Length.class).getConverterTo(outUnit.asType(Length.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(METRE_PER_SECOND)) {\r\n UnitConverter converter = inUnit.asType(Speed.class).getConverterTo(outUnit.asType(Speed.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(METRE_PER_SQUARE_SECOND)) {\r\n UnitConverter converter = inUnit.asType(Acceleration.class).getConverterTo(outUnit.asType(Acceleration.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(PASCAL)) {\r\n UnitConverter converter = inUnit.asType(Pressure.class).getConverterTo(outUnit.asType(Pressure.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(RADIAN)) {\r\n UnitConverter converter = inUnit.asType(Angle.class).getConverterTo(outUnit.asType(Angle.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(SECOND)) {\r\n UnitConverter converter = inUnit.asType(Time.class).getConverterTo(outUnit.asType(Time.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(AMPERE)) {\r\n UnitConverter converter = inUnit.asType(ElectricCurrent.class).getConverterTo(outUnit.asType(ElectricCurrent.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(CELSIUS)) {\r\n UnitConverter converter = inUnit.asType(Temperature.class).getConverterTo(outUnit.asType(Temperature.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(PERCENT)) {\r\n UnitConverter converter = inUnit.asType(Dimensionless.class).getConverterTo(outUnit.asType(Dimensionless.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(TESLA)) {\r\n UnitConverter converter = inUnit.asType(MagneticFluxDensity.class).getConverterTo(outUnit.asType(MagneticFluxDensity.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(VOLT)) {\r\n UnitConverter converter = inUnit.asType(ElectricPotential.class).getConverterTo(outUnit.asType(ElectricPotential.class));\r\n return converter.convert(1.0);\r\n } else if (inUnit.isCompatible(WATT)) {\r\n UnitConverter converter = inUnit.asType(Power.class).getConverterTo(outUnit.asType(Power.class));\r\n return converter.convert(1.0);\r\n } else {\r\n throw new IllegalArgumentException(String.format(\"Unhandled units: %s\", inUnit));\r\n }\r\n }\r\n\r\n public static Unit<?> parse(String unitString) {\r\n return SimpleUnitFormat.getInstance().parse(unitString);\r\n }\r\n\r\n public static void listUnits(PrintStream pw) {\r\n\r\n for (SimpleEntry<String, String> SimpleEntry : UNITS_DESCRIPTION) {\r\n String tmp = String.format(\"Use code \\\"%s\\\" for %s\", SimpleEntry.getKey(), SimpleEntry.getValue());\r\n pw.println(tmp);\r\n }\r\n }\r\n\r\n public boolean isGroundMotionType() {\r\n return inputUnits.isCompatible(METRE) || inputUnits.isCompatible(METRE_PER_SECOND) || inputUnits.isCompatible(METRE_PER_SQUARE_SECOND);\r\n }\r\n\r\n public static boolean areUnitsEquivalent(Unit<?> unit1, Unit<?> unit2) {\r\n if (unit1 == null && unit2 == null) {\r\n return true;\r\n }\r\n if (unit1 == null && unit2 != null) {\r\n return false;\r\n }\r\n if (unit2 == null && unit1 != null) {\r\n return false;\r\n }\r\n\r\n if (unit1.isCompatible(unit2)) {\r\n return SimpleUnitFormat.getInstance().parse(unit1.toString()).equals(SimpleUnitFormat.getInstance().parse(unit2.toString()));\r\n }\r\n return false;\r\n }\r\n\r\n private void writeObject(ObjectOutputStream s) throws IOException {\r\n s.writeObject(inputUnits.toString());\r\n s.writeObject(unitObj.toString());\r\n s.writeObject(unitsStatus.toString());\r\n }\r\n\r\n private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {\r\n Class type = ResponseUnits.class;\r\n String tmp = (String) s.readObject();\r\n try {\r\n Field field = type.getDeclaredField(\"inputUnits\");\r\n // make the field non final\r\n field.setAccessible(true);\r\n field.set(this, ResponseUnits.parse(tmp));\r\n\r\n // make the field final again\r\n field.setAccessible(false);\r\n\r\n tmp = (String) s.readObject();\r\n field = type.getDeclaredField(\"unitObj\");\r\n // make the field non final\r\n field.setAccessible(true);\r\n field.set(this, UnitImpl.getUnitFromString(tmp));\r\n\r\n // make the field final again\r\n field.setAccessible(false);\r\n\r\n tmp = (String) s.readObject();\r\n field = type.getDeclaredField(\"unitsStatus\");\r\n // make the field non final\r\n field.setAccessible(true);\r\n field.set(this, UnitsStatus.valueOf(tmp));\r\n\r\n // make the field final again\r\n field.setAccessible(false);\r\n\r\n } catch (NoSuchFieldException ex) {\r\n Logger.getLogger(ResponseUnits.class.getName()).log(Level.SEVERE, null, ex);\r\n } catch (SecurityException ex) {\r\n Logger.getLogger(ResponseUnits.class.getName()).log(Level.SEVERE, null, ex);\r\n } catch (IllegalArgumentException ex) {\r\n Logger.getLogger(ResponseUnits.class.getName()).log(Level.SEVERE, null, ex);\r\n } catch (IllegalAccessException ex) {\r\n Logger.getLogger(ResponseUnits.class.getName()).log(Level.SEVERE, null, ex);\r\n }\r\n }\r\n}\r"
},
{
"identifier": "UnitsStatus",
"path": "src/main/java/com/isti/jevalresp/UnitsStatus.java",
"snippet": "public enum UnitsStatus {\r\n UNDETERMINED, QUANTITY_ONLY, QUANTITY_AND_UNITS, FORCED_VALUE\r\n}\r"
}
] | import tec.units.ri.unit.MetricPrefix;
import static tec.units.ri.unit.Units.METRE;
import static tec.units.ri.unit.Units.METRE_PER_SECOND;
import static tec.units.ri.unit.Units.METRE_PER_SQUARE_SECOND;
import static tec.units.ri.unit.Units.PASCAL;
import edu.iris.Fissures.model.UnitImpl;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import com.isti.jevalresp.ResponseUnits;
import com.isti.jevalresp.UnitsStatus;
| 5,025 | /*-
* #%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 NDCUnitsParser {
public ResponseUnits getResponseUnits(File file) throws FileNotFoundException {
ResponseUnits quantity = new ResponseUnits();
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.trim().startsWith("#")) {
String tmp = line.toLowerCase();
if (tmp.contains("nm/s/s")) {
| /*-
* #%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 NDCUnitsParser {
public ResponseUnits getResponseUnits(File file) throws FileNotFoundException {
ResponseUnits quantity = new ResponseUnits();
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.trim().startsWith("#")) {
String tmp = line.toLowerCase();
if (tmp.contains("nm/s/s")) {
| return new ResponseUnits(MetricPrefix.NANO(METRE_PER_SQUARE_SECOND), UnitImpl.NANOMETER_PER_SECOND_PER_SECOND, UnitsStatus.QUANTITY_AND_UNITS);
| 1 | 2023-10-30 21:06:43+00:00 | 8k |
NUMS-half/OnlineOA | src/main/java/cn/edu/neu/onlineoa/controller/ApplyExportServlet.java | [
{
"identifier": "Apply",
"path": "src/main/java/cn/edu/neu/onlineoa/bean/Apply.java",
"snippet": "public class Apply {\n private int aid;\n private int status = -1;\n private String studentId;\n private String studentName;\n private String courseId;\n private String courseName;\n private String applyReason;\n private String reasonFilePath;\n private String applyTime;\n private String firstTeacherId;\n private String firstApproveTeaId;\n private String firstApproveTime;\n private String secondTeacherId;\n private String secondApproveTeaId;\n private String secondApproveTime;\n private String rejectReason;\n private boolean confirm;\n\n public Apply() {}\n\n public Apply(int aid, int status, String studentId, String studentName, String courseId, String courseName, String applyReason) {\n this.aid = aid;\n this.status = status;\n this.studentId = studentId;\n this.studentName = studentName;\n this.courseId = courseId;\n this.courseName = courseName;\n this.applyReason = applyReason;\n }\n\n public Apply(int aid, int status, String studentId, String studentName, String courseId, String courseName, String applyReason, String firstTeacherId, String secondTeacherId, String rejectReason, boolean confirm) {\n this.aid = aid;\n this.status = status;\n this.studentId = studentId;\n this.studentName = studentName;\n this.courseId = courseId;\n this.courseName = courseName;\n this.applyReason = applyReason;\n this.firstTeacherId = firstTeacherId;\n this.secondTeacherId = secondTeacherId;\n this.rejectReason = rejectReason;\n this.confirm = confirm;\n }\n\n public Apply(int aid, int status, String studentId, String studentName, String courseId, String courseName, String applyReason, String applyTime, String firstTeacherId, String firstApproveTime, String secondTeacherId, String secondApproveTime, String rejectReason, boolean confirm) {\n this.aid = aid;\n this.status = status;\n this.studentId = studentId;\n this.studentName = studentName;\n this.courseId = courseId;\n this.courseName = courseName;\n this.applyReason = applyReason;\n this.applyTime = applyTime;\n this.firstTeacherId = firstTeacherId;\n this.firstApproveTime = firstApproveTime;\n this.secondTeacherId = secondTeacherId;\n this.secondApproveTime = secondApproveTime;\n this.rejectReason = rejectReason;\n this.confirm = confirm;\n }\n\n public int getAid() {\n return aid;\n }\n\n public void setAid(int aid) {\n this.aid = aid;\n }\n\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n\n public String getStudentId() {\n return studentId;\n }\n\n public void setStudentId(String studentId) {\n this.studentId = studentId;\n }\n\n public String getStudentName() {\n return studentName;\n }\n\n public void setStudentName(String studentName) {\n this.studentName = studentName;\n }\n\n public String getCourseId() {\n return courseId;\n }\n\n public void setCourseId(String courseId) {\n this.courseId = courseId;\n }\n\n public String getCourseName() {\n return courseName;\n }\n\n public void setCourseName(String courseName) {\n this.courseName = courseName;\n }\n\n public String getApplyReason() {\n return applyReason;\n }\n\n public void setApplyReason(String applyReason) {\n this.applyReason = applyReason;\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\n public String getRejectReason() {\n return rejectReason;\n }\n\n public void setRejectReason(String rejectReason) {\n this.rejectReason = rejectReason;\n }\n\n public boolean isConfirm() {\n return confirm;\n }\n\n public void setConfirm(boolean confirm) {\n this.confirm = confirm;\n }\n\n public String getApplyTime() {\n return applyTime;\n }\n\n public void setApplyTime(String applyTime) {\n this.applyTime = applyTime;\n }\n\n public String getFirstApproveTeaId() {\n return firstApproveTeaId;\n }\n\n public void setFirstApproveTeaId(String firstApproveTeaId) {\n this.firstApproveTeaId = firstApproveTeaId;\n }\n\n public String getFirstApproveTime() {\n return firstApproveTime;\n }\n\n public void setFirstApproveTime(String firstApproveTime) {\n this.firstApproveTime = firstApproveTime;\n }\n\n public String getSecondApproveTeaId() {\n return secondApproveTeaId;\n }\n\n public void setSecondApproveTeaId(String secondApproveTeaId) {\n this.secondApproveTeaId = secondApproveTeaId;\n }\n\n public String getSecondApproveTime() {\n return secondApproveTime;\n }\n\n public void setSecondApproveTime(String secondApproveTime) {\n this.secondApproveTime = secondApproveTime;\n }\n\n public String getReasonFilePath() {\n return reasonFilePath;\n }\n\n public void setReasonFilePath(String reasonFilePath) {\n this.reasonFilePath = reasonFilePath;\n }\n\n @Override\n public String toString() {\n return \"Apply{\" +\n \"aid=\" + aid +\n \", status=\" + status +\n \", studentId='\" + studentId + '\\'' +\n \", studentName='\" + studentName + '\\'' +\n \", courseId='\" + courseId + '\\'' +\n \", courseName='\" + courseName + '\\'' +\n \", applyReason='\" + applyReason + '\\'' +\n \", reasonFilePath='\" + reasonFilePath + '\\'' +\n \", applyTime='\" + applyTime + '\\'' +\n \", firstTeacherId='\" + firstTeacherId + '\\'' +\n \", firstApproveTeaId='\" + firstApproveTeaId + '\\'' +\n \", firstApproveTime='\" + firstApproveTime + '\\'' +\n \", secondTeacherId='\" + secondTeacherId + '\\'' +\n \", secondApproveTeaId='\" + secondApproveTeaId + '\\'' +\n \", secondApproveTime='\" + secondApproveTime + '\\'' +\n \", rejectReason='\" + rejectReason + '\\'' +\n \", confirm=\" + confirm +\n '}';\n }\n}"
},
{
"identifier": "ApplyStatus",
"path": "src/main/java/cn/edu/neu/onlineoa/bean/ApplyStatus.java",
"snippet": "public enum ApplyStatus {\n SUBMITTED(\"申请已提交\", 0), //0:申请已提交\n TEACHER_APPROVING(\"课程主讲教师审批中\", 1), //1:课程主讲教师审批中\n HEAD_APPROVING(\"主管教师审批中\", 2), //2:主管教师审批中\n SUCCESS(\"申请成功\", 3), //3:申请成功\n REJECT(\"申请被驳回\", 4); //4:申请被驳回\n\n private String name;\n private int id;\n\n ApplyStatus(String name, int id) {\n this.name = name;\n this.id = id;\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 int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public static String getNameByIndex(int id){\n ApplyStatus[] statuses = ApplyStatus.values();\n for ( ApplyStatus s : statuses) {\n if( s.getId() == id )\n return s.name;\n }\n return null;\n }\n}"
},
{
"identifier": "ApplyService",
"path": "src/main/java/cn/edu/neu/onlineoa/service/ApplyService.java",
"snippet": "public class ApplyService {\n\n SqlSessionFactory sqlSessionFactory = MybatisUtils.getSessionFactoryInstance();\n\n public List<Apply> findAllApply() {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findAllApply();\n }\n }\n\n public List<Apply> findAllConfirmedApply(String studentId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findAllConfirmedApply(studentId);\n }\n }\n\n public List<Apply> findAllPassedApply() {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findAllPassedApply();\n }\n }\n\n public Apply findApplyByAid(int aid) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyByAid(aid);\n }\n }\n\n public List<Apply> findApplyByStuId(String studentId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyByStuId(studentId);\n }\n }\n\n public List<Apply> findApplyByTea1Id(String teacherId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyByTea1Id(teacherId);\n }\n }\n\n public List<Apply> findApplyByTea2Id(String teacherId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyByTea2Id(teacherId);\n }\n }\n\n public List<Apply> findApplyToApproveByTea1Id(String teacherId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyToApproveByTea1Id(teacherId);\n }\n }\n\n public List<Apply> findApplyToApproveByTea2Id(String teacherId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyToApproveByTea2Id(teacherId);\n }\n }\n\n public int deleteApplyByAid(int aid) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.deleteApplyByAid(aid);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public int addApply(Apply apply) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.addApply(apply);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public int updateApply(Apply apply) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession(true) ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.updateApply(apply);\n } catch ( Exception e ) {\n return 0;\n }\n }\n\n public List<Apply> findConfirmedApplyWithMultiCondition(Apply apply, String studentId) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findConfirmedApplyWithMultiCondition(apply, studentId);\n }\n }\n\n public List<Apply> findApplyWithMultiCondition(Apply apply, String teacherId1, String teacherId2) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyWithMultiCondition(apply, teacherId1, teacherId2);\n }\n }\n\n public List<Apply> findApplyHistory( String uid, int identity, Apply apply) {\n try ( SqlSession sqlSession = sqlSessionFactory.openSession() ) {\n ApplyDao applyDao = sqlSession.getMapper(ApplyDao.class);\n return applyDao.findApplyHistory(uid, identity, apply);\n }\n }\n}"
},
{
"identifier": "DateUtils",
"path": "src/main/java/cn/edu/neu/onlineoa/utils/DateUtils.java",
"snippet": "public class DateUtils {\n /**\n * return the LocalDateTime with certain format\n * @param format\n * @return now.format(formatter)\n */\n public static String getLocalDateTime(String format) {\n LocalDateTime now = LocalDateTime.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);\n return now.format(formatter);\n }\n}"
}
] | import cn.edu.neu.onlineoa.bean.Apply;
import cn.edu.neu.onlineoa.bean.ApplyStatus;
import cn.edu.neu.onlineoa.service.ApplyService;
import cn.edu.neu.onlineoa.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List; | 3,929 | package cn.edu.neu.onlineoa.controller;
@WebServlet(name = "ApplyExportServlet", urlPatterns = "/applyExport")
public class ApplyExportServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置文件类型与文件名
String filename = "申请审批信息导出_" + DateUtils.getLocalDateTime("yyyyMMdd_HH-mm-ss");
String encodedFileName = URLEncoder.encode(filename, "UTF-8");
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName + ".xls");
// 创建Excel工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("已通过的申请");
// 获取要导出的数据
ApplyService applyService = new ApplyService();
List<Apply> applyList = applyService.findAllPassedApply();
// 创建表头行
Row headerRow = sheet.createRow(0);
// 添加表头列
headerRow.createCell(0).setCellValue("申请ID");
headerRow.createCell(1).setCellValue("申请状态");
headerRow.createCell(2).setCellValue("学生ID");
headerRow.createCell(3).setCellValue("学生姓名");
headerRow.createCell(4).setCellValue("课程ID");
headerRow.createCell(5).setCellValue("课程名称");
headerRow.createCell(6).setCellValue("申请原因");
headerRow.createCell(7).setCellValue("申请提交时间");
headerRow.createCell(8).setCellValue("第一审批人ID");
headerRow.createCell(9).setCellValue("第一次审批时间");
headerRow.createCell(10).setCellValue("第二审批人ID");
headerRow.createCell(11).setCellValue("第二次审批时间");
headerRow.createCell(12).setCellValue("学生是否确认");
// 填充数据行
int rowNum = 1;
for ( Apply apply : applyList ) {
Row dataRow = sheet.createRow(rowNum++);
dataRow.createCell(0).setCellValue(apply.getAid()); | package cn.edu.neu.onlineoa.controller;
@WebServlet(name = "ApplyExportServlet", urlPatterns = "/applyExport")
public class ApplyExportServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置文件类型与文件名
String filename = "申请审批信息导出_" + DateUtils.getLocalDateTime("yyyyMMdd_HH-mm-ss");
String encodedFileName = URLEncoder.encode(filename, "UTF-8");
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName + ".xls");
// 创建Excel工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("已通过的申请");
// 获取要导出的数据
ApplyService applyService = new ApplyService();
List<Apply> applyList = applyService.findAllPassedApply();
// 创建表头行
Row headerRow = sheet.createRow(0);
// 添加表头列
headerRow.createCell(0).setCellValue("申请ID");
headerRow.createCell(1).setCellValue("申请状态");
headerRow.createCell(2).setCellValue("学生ID");
headerRow.createCell(3).setCellValue("学生姓名");
headerRow.createCell(4).setCellValue("课程ID");
headerRow.createCell(5).setCellValue("课程名称");
headerRow.createCell(6).setCellValue("申请原因");
headerRow.createCell(7).setCellValue("申请提交时间");
headerRow.createCell(8).setCellValue("第一审批人ID");
headerRow.createCell(9).setCellValue("第一次审批时间");
headerRow.createCell(10).setCellValue("第二审批人ID");
headerRow.createCell(11).setCellValue("第二次审批时间");
headerRow.createCell(12).setCellValue("学生是否确认");
// 填充数据行
int rowNum = 1;
for ( Apply apply : applyList ) {
Row dataRow = sheet.createRow(rowNum++);
dataRow.createCell(0).setCellValue(apply.getAid()); | dataRow.createCell(1).setCellValue(ApplyStatus.getNameByIndex(apply.getStatus())); | 1 | 2023-10-31 04:50:21+00:00 | 8k |
TNO/PPS | plugins/nl.esi.pps.tmsc.analysis.ui/xtend-gen/nl/esi/pps/tmsc/analysis/ui/dataanalysis/TimeBoundOutlierDataAnalysisItemContentProvider.java | [
{
"identifier": "Dependency",
"path": "plugins/nl.esi.pps.tmsc/src-gen/nl/esi/pps/tmsc/Dependency.java",
"snippet": "public interface Dependency extends PropertiesContainer, ITimeRange {\n\t/**\n\t * Returns the value of the '<em><b>Tmsc</b></em>' container reference.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.FullScopeTMSC#getDependencies <em>Dependencies</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Tmsc</em>' container reference.\n\t * @see #setTmsc(FullScopeTMSC)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Tmsc()\n\t * @see nl.esi.pps.tmsc.FullScopeTMSC#getDependencies\n\t * @model opposite=\"dependencies\" required=\"true\" transient=\"false\"\n\t * @generated\n\t */\n\tFullScopeTMSC getTmsc();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#getTmsc <em>Tmsc</em>}' container reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Tmsc</em>' container reference.\n\t * @see #getTmsc()\n\t * @generated\n\t */\n\tvoid setTmsc(FullScopeTMSC value);\n\n\t/**\n\t * Returns the value of the '<em><b>Source</b></em>' reference.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.Event#getFullScopeOutgoingDependencies <em>Full Scope Outgoing Dependencies</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Source</em>' reference.\n\t * @see #setSource(Event)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Source()\n\t * @see nl.esi.pps.tmsc.Event#getFullScopeOutgoingDependencies\n\t * @model opposite=\"fullScopeOutgoingDependencies\" resolveProxies=\"false\" required=\"true\" transient=\"true\"\n\t * @generated\n\t */\n\tEvent getSource();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#getSource <em>Source</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Source</em>' reference.\n\t * @see #getSource()\n\t * @generated\n\t */\n\tvoid setSource(Event value);\n\n\t/**\n\t * Returns the value of the '<em><b>Target</b></em>' reference.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.Event#getFullScopeIncomingDependencies <em>Full Scope Incoming Dependencies</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Target</em>' reference.\n\t * @see #setTarget(Event)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Target()\n\t * @see nl.esi.pps.tmsc.Event#getFullScopeIncomingDependencies\n\t * @model opposite=\"fullScopeIncomingDependencies\" resolveProxies=\"false\" required=\"true\" transient=\"true\"\n\t * @generated\n\t */\n\tEvent getTarget();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#getTarget <em>Target</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Target</em>' reference.\n\t * @see #getTarget()\n\t * @generated\n\t */\n\tvoid setTarget(Event value);\n\n\t/**\n\t * Returns the value of the '<em><b>Scopes</b></em>' reference list.\n\t * The list contents are of type {@link nl.esi.pps.tmsc.ScopedTMSC}.\n\t * It is bidirectional and its opposite is '{@link nl.esi.pps.tmsc.ScopedTMSC#getDependencies <em>Dependencies</em>}'.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * <!-- begin-model-doc -->\n\t * All dependencies of a child-scope ScopedTMSC should be contained by its parent-scope TMSC.\n\t * \n\t * Note that this is a derived 'many' relation. Though the return type 'EList' provides methods to alter the content, no altering method should be used and will throw an UnsupportedOperationException upon usage.\n\t * <!-- end-model-doc -->\n\t * @return the value of the '<em>Scopes</em>' reference list.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Scopes()\n\t * @see nl.esi.pps.tmsc.ScopedTMSC#getDependencies\n\t * @model opposite=\"dependencies\" resolveProxies=\"false\" transient=\"true\" ordered=\"false\"\n\t * @generated\n\t */\n\tEList<ScopedTMSC> getScopes();\n\n\t/**\n\t * Returns the value of the '<em><b>Start Time</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Start Time</em>' attribute.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_StartTime()\n\t * @model dataType=\"nl.esi.pps.tmsc.ETimestamp\" required=\"true\" transient=\"true\" changeable=\"false\" volatile=\"true\" derived=\"true\"\n\t * @generated\n\t */\n\tLong getStartTime();\n\n\t/**\n\t * Returns the value of the '<em><b>End Time</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>End Time</em>' attribute.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_EndTime()\n\t * @model dataType=\"nl.esi.pps.tmsc.ETimestamp\" required=\"true\" transient=\"true\" changeable=\"false\" volatile=\"true\" derived=\"true\"\n\t * @generated\n\t */\n\tLong getEndTime();\n\n\t/**\n\t * Returns the value of the '<em><b>Duration</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @return the value of the '<em>Duration</em>' attribute.\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Duration()\n\t * @model dataType=\"nl.esi.pps.tmsc.EDuration\" required=\"true\" transient=\"true\" changeable=\"false\" volatile=\"true\" derived=\"true\"\n\t * @generated\n\t */\n\tLong getDuration();\n\n\t/**\n\t * Returns the value of the '<em><b>Time Bound</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * <!-- begin-model-doc -->\n\t * The time-bound specifies the lowerbound for the duration of this dependency. This analysis attribute is used in e.g. critical-path and slack analysis.\n\t * <!-- end-model-doc -->\n\t * @return the value of the '<em>Time Bound</em>' attribute.\n\t * @see #setTimeBound(Long)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_TimeBound()\n\t * @model dataType=\"nl.esi.pps.tmsc.EDuration\"\n\t * @generated\n\t */\n\tLong getTimeBound();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#getTimeBound <em>Time Bound</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Time Bound</em>' attribute.\n\t * @see #getTimeBound()\n\t * @generated\n\t */\n\tvoid setTimeBound(Long value);\n\n\t/**\n\t * Returns the value of the '<em><b>Scheduled</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * <!-- begin-model-doc -->\n\t * If true, this dependency was induced by the (software) platform as result of scheduling. \n\t * If false, this dependency reflects a control or data dependency as programmed in code.\n\t * By default Executions and LifelineSegments-without-activeExecution are considered to be scheduled dependencies, see TmscRefinements#refineWithCallStacks(Lifeline).\n\t * <!-- end-model-doc -->\n\t * @return the value of the '<em>Scheduled</em>' attribute.\n\t * @see #setScheduled(Boolean)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Scheduled()\n\t * @model\n\t * @generated\n\t */\n\tBoolean getScheduled();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#getScheduled <em>Scheduled</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Scheduled</em>' attribute.\n\t * @see #getScheduled()\n\t * @generated\n\t */\n\tvoid setScheduled(Boolean value);\n\n\t/**\n\t * Returns the value of the '<em><b>Projection</b></em>' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * <!-- begin-model-doc -->\n\t * If true, this dependency was not originally part of the TMSC, but is an effect of projection, see nl.esi.pps.tmsc.util.TmscProjection class.\n\t * Projections should typically not be visible to the user, unless they provide additional information.\n\t * <!-- end-model-doc -->\n\t * @return the value of the '<em>Projection</em>' attribute.\n\t * @see #setProjection(boolean)\n\t * @see nl.esi.pps.tmsc.TmscPackage#getDependency_Projection()\n\t * @model\n\t * @generated\n\t */\n\tboolean isProjection();\n\n\t/**\n\t * Sets the value of the '{@link nl.esi.pps.tmsc.Dependency#isProjection <em>Projection</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @param value the new value of the '<em>Projection</em>' attribute.\n\t * @see #isProjection()\n\t * @generated\n\t */\n\tvoid setProjection(boolean value);\n\n\t/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @model kind=\"operation\"\n\t * @generated\n\t */\n\tboolean isEpochTime();\n\n} // Dependency"
},
{
"identifier": "TimeBoundOutlierAnalysis",
"path": "plugins/nl.esi.pps.tmsc.analysis/xtend-gen/nl/esi/pps/tmsc/analysis/TimeBoundOutlierAnalysis.java",
"snippet": "@SuppressWarnings(\"all\")\npublic class TimeBoundOutlierAnalysis {\n private static final double IQR_FACTOR = 3.0;\n \n private TimeBoundOutlierAnalysis() {\n }\n \n public static Iterable<Dependency> analyseTimeBoundOutliers(final TMSC tmsc) {\n final Function1<Dependency, Boolean> _function = (Dependency it) -> {\n return Boolean.valueOf(TimeBoundOutlierAnalysis.isTimeBoundOutlier(it));\n };\n return IterableExtensions.<Dependency>filter(tmsc.getDependencies(), _function);\n }\n \n public static boolean isTimeBoundOutlier(final Dependency dependency) {\n Long _timeBound = dependency.getTimeBound();\n boolean _tripleEquals = (_timeBound == null);\n if (_tripleEquals) {\n return false;\n }\n final Long timeBoundOutlierThreshold = TimeBoundOutlierAnalysis.analyseTimeBoundOutlierThreshold(dependency, false);\n if ((timeBoundOutlierThreshold == null)) {\n return false;\n }\n Long _timeBound_1 = dependency.getTimeBound();\n return (_timeBound_1.compareTo(timeBoundOutlierThreshold) > 0);\n }\n \n public static Long analyseTimeBoundOutlierThreshold(final Dependency dependency, final boolean refresh) {\n if ((TimeBoundOutlierAnalysis.isSetTimeBoundOutlierThreshold(dependency) && (!refresh))) {\n return TimeBoundOutlierAnalysis.getTimeBoundOutlierThreshold(dependency);\n }\n if (((!TimeBoundOutlierAnalysis.isSetTimeBoundSamples(dependency)) || TimeBoundOutlierAnalysis.getTimeBoundSamples(dependency).isEmpty())) {\n return null;\n }\n final Pair<Double, Double> iqr = TimeBoundOutlierAnalysis.getInterquartileRange(TimeBoundOutlierAnalysis.getTimeBoundSamples(dependency));\n final Double Q1 = iqr.getKey();\n final Double Q3 = iqr.getValue();\n double _minus = DoubleExtensions.operator_minus(Q3, Q1);\n double _multiply = (_minus * TimeBoundOutlierAnalysis.IQR_FACTOR);\n double _plus = ((Q3).doubleValue() + _multiply);\n TimeBoundOutlierAnalysis.setTimeBoundOutlierThreshold(dependency, Long.valueOf(Double.valueOf(Math.ceil(_plus)).longValue()));\n return TimeBoundOutlierAnalysis.getTimeBoundOutlierThreshold(dependency);\n }\n \n /**\n * @see https://en.wikipedia.org/wiki/Interquartile_range\n */\n private static Pair<Double, Double> getInterquartileRange(final Iterable<Long> values) {\n Pair<Double, Double> _switchResult = null;\n List<Long> _sort = IterableExtensions.<Long>sort(values);\n final List<Long> sortedValues = _sort;\n boolean _matched = false;\n boolean _isEmpty = sortedValues.isEmpty();\n if (_isEmpty) {\n _matched=true;\n _switchResult = null;\n }\n if (!_matched) {\n int _size = sortedValues.size();\n boolean _equals = (_size == 1);\n if (_equals) {\n _matched=true;\n _switchResult = Pair.<Double, Double>of(Double.valueOf(IterableExtensions.<Long>head(sortedValues).doubleValue()), Double.valueOf(IterableExtensions.<Long>head(sortedValues).doubleValue()));\n }\n }\n if (!_matched) {\n int _size_1 = sortedValues.size();\n int _divide = (_size_1 / 2);\n int _modulo = (_divide % 2);\n boolean _equals_1 = (_modulo == 0);\n if (_equals_1) {\n _matched=true;\n Pair<Double, Double> _xblockexpression = null;\n {\n int _size_2 = sortedValues.size();\n final int highIndexQ1 = (_size_2 / 4);\n Long _at = TimeBoundOutlierAnalysis.<Long>at(sortedValues, (highIndexQ1 - 1));\n Long _at_1 = TimeBoundOutlierAnalysis.<Long>at(sortedValues, highIndexQ1);\n long _plus = ((_at).longValue() + (_at_1).longValue());\n double _divide_1 = (_plus / 2.0);\n Long _at_2 = TimeBoundOutlierAnalysis.<Long>at(sortedValues, ((-highIndexQ1) + 1));\n Long _at_3 = TimeBoundOutlierAnalysis.<Long>at(sortedValues, (-highIndexQ1));\n long _plus_1 = ((_at_2).longValue() + (_at_3).longValue());\n double _divide_2 = (_plus_1 / 2.0);\n _xblockexpression = Pair.<Double, Double>of(Double.valueOf(_divide_1), Double.valueOf(_divide_2));\n }\n _switchResult = _xblockexpression;\n }\n }\n if (!_matched) {\n Pair<Double, Double> _xblockexpression_1 = null;\n {\n int _size_2 = sortedValues.size();\n final int indexQ1 = (_size_2 / 4);\n _xblockexpression_1 = Pair.<Double, Double>of(Double.valueOf(TimeBoundOutlierAnalysis.<Long>at(sortedValues, indexQ1).doubleValue()), Double.valueOf(TimeBoundOutlierAnalysis.<Long>at(sortedValues, (-indexQ1)).doubleValue()));\n }\n _switchResult = _xblockexpression_1;\n }\n return _switchResult;\n }\n \n private static <T extends Object> T at(final List<T> values, final int position) {\n T _xifexpression = null;\n if ((position < 0)) {\n int _size = values.size();\n int _minus = (_size - 1);\n int _plus = (_minus + position);\n _xifexpression = values.get(_plus);\n } else {\n _xifexpression = values.get(position);\n }\n return _xifexpression;\n }\n \n public static Long getTimeBoundOutlierThreshold(final Dependency container) {\n final String key = \"timeBoundOutlierThreshold\";\n final Object value = container.getProperties().get(key);\n return (Long) value;\n }\n \n public static void setTimeBoundOutlierThreshold(final Dependency container, final Long value) {\n final String key = \"timeBoundOutlierThreshold\";\n container.getProperties().put(key, value);\n }\n \n /**\n * Returns whether the value of the '{@link nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis#getTimeBoundOutlierThreshold <em>timeBoundOutlierThreshold</em>}' property is set on {@code container}.\n */\n public static boolean isSetTimeBoundOutlierThreshold(final Dependency container) {\n final String key = \"timeBoundOutlierThreshold\";\n return container.getProperties().containsKey(key);\n }\n \n /**\n * Unsets the value of the '{@link nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis#getTimeBoundOutlierThreshold <em>timeBoundOutlierThreshold</em>}' property on {@code container}.\n */\n public static void unsetTimeBoundOutlierThreshold(final Dependency container) {\n final String key = \"timeBoundOutlierThreshold\";\n container.getProperties().remove(key);\n }\n \n /**\n * Creates initial value for persisted {@code timeBoundSamples} property on Dependency\n */\n private static final ArrayList<Long> _getInitial_Dependency_TimeBoundSamples() {\n ArrayList<Long> _newArrayList = CollectionLiterals.<Long>newArrayList();\n return _newArrayList;\n }\n \n public static ArrayList<Long> getTimeBoundSamples(final Dependency container) {\n final String key = \"timeBoundSamples\";\n final Object value = container.getProperties().map().computeIfAbsent(key, k -> _getInitial_Dependency_TimeBoundSamples());\n return (ArrayList<Long>) value;\n }\n \n public static void setTimeBoundSamples(final Dependency container, final ArrayList<Long> value) {\n final String key = \"timeBoundSamples\";\n container.getProperties().put(key, value);\n }\n \n /**\n * Returns whether the value of the '{@link nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis#getTimeBoundSamples <em>timeBoundSamples</em>}' property is set on {@code container}.\n */\n public static boolean isSetTimeBoundSamples(final Dependency container) {\n final String key = \"timeBoundSamples\";\n return container.getProperties().containsKey(key);\n }\n \n /**\n * Unsets the value of the '{@link nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis#getTimeBoundSamples <em>timeBoundSamples</em>}' property on {@code container}.\n */\n public static void unsetTimeBoundSamples(final Dependency container) {\n final String key = \"timeBoundSamples\";\n container.getProperties().remove(key);\n }\n}"
},
{
"identifier": "IDataAnalysisItemContentProvider",
"path": "plugins/nl.esi.pps.tmsc.edit/src/nl/esi/pps/tmsc/provider/dataanalysis/IDataAnalysisItemContentProvider.java",
"snippet": "public interface IDataAnalysisItemContentProvider {\n\t/**\n\t * The default configuration for data analysis. If your data analysis only\n\t * supports a single configuration, its is recommended to use this\n\t * configuration.\n\t */\n\tstatic final String DEFAULT_CONFIGURATION = \"Default\";\n\n\t/**\n\t * Returns the supported data analysis configurations for {@code object}.\n\t */\n\tSet<String> getConfigurations(Object object);\n\n\t/**\n\t * Returns the title of the data analysis for {@code object} in the selected\n\t * {@code configuration}.\n\t */\n\tString getTitle(Object object, String configuration);\n\n\t/**\n\t * Returns the budget of the data analysis for {@code object} in the selected\n\t * {@code configuration}, or {@code null} if the budget is not applicable.\n\t */\n\tdefault Long getBudget(Object object, String configuration) {\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the siblings of {@code object} for the selected\n\t * {@code configuration}.\n\t */\n\tIterable<?> getSiblings(Object object, String configuration);\n\n\t/**\n\t * Returns the duration of {@code sibling} in the selected\n\t * {@code configuration}. Please note that {@code sibling} can be any of the\n\t * elements as returned by {@link #getSiblings(Object, String)} or the\n\t * {@code object} itself.\n\t */\n\tLong getDuration(Object object, Object sibling, String configuration);\n\n\t/**\n\t * @return (@code true} if the bars in the time-series viewer should be colored\n\t * based on a {@link #getCategory(Object, Object, String) category}.\n\t */\n\tdefault boolean isCategorized(Object object, String configuration) {\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return the category for the {@code sibling} in the time-series viewer.\n\t */\n\tdefault String getCategory(Object object, Object sibling, String configuration) {\n\t\treturn DEFAULT_CONFIGURATION;\n\t}\n}"
}
] | import java.util.Collections;
import java.util.Set;
import nl.esi.pps.tmsc.Dependency;
import nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis;
import nl.esi.pps.tmsc.provider.dataanalysis.IDataAnalysisItemContentProvider;
import org.eclipse.lsat.common.xtend.Queries; | 5,395 | /**
* Copyright (c) 2018-2023 TNO and Contributors to the GitHub community
*
* This program and the accompanying materials are made available
* under the terms of the MIT License which is available at
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*/
package nl.esi.pps.tmsc.analysis.ui.dataanalysis;
@SuppressWarnings("all")
public class TimeBoundOutlierDataAnalysisItemContentProvider implements IDataAnalysisItemContentProvider {
@Override
public Set<String> getConfigurations(final Object object) {
final Dependency dependency = ((Dependency) object);
Set<String> _xifexpression = null; | /**
* Copyright (c) 2018-2023 TNO and Contributors to the GitHub community
*
* This program and the accompanying materials are made available
* under the terms of the MIT License which is available at
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*/
package nl.esi.pps.tmsc.analysis.ui.dataanalysis;
@SuppressWarnings("all")
public class TimeBoundOutlierDataAnalysisItemContentProvider implements IDataAnalysisItemContentProvider {
@Override
public Set<String> getConfigurations(final Object object) {
final Dependency dependency = ((Dependency) object);
Set<String> _xifexpression = null; | boolean _isSetTimeBoundSamples = TimeBoundOutlierAnalysis.isSetTimeBoundSamples(dependency); | 1 | 2023-10-30 16:00:25+00:00 | 8k |
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE | src/main/java/com/cerbon/bosses_of_mass_destruction/projectile/PetalBladeProjectile.java | [
{
"identifier": "BMDEntities",
"path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/BMDEntities.java",
"snippet": "public class BMDEntities {\n public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig();\n\n public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =\n DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, BMDConstants.MOD_ID);\n\n public static final RegistryObject<EntityType<LichEntity>> LICH = ENTITY_TYPES.register(\"lich\",\n () -> EntityType.Builder.<LichEntity>of((entityType, level) -> new LichEntity(entityType, level, mobConfig.lichConfig), MobCategory.MONSTER)\n .sized(1.8f, 3.0f)\n .updateInterval(1)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"lich\").toString()));\n\n public static final RegistryObject<EntityType<MagicMissileProjectile>> MAGIC_MISSILE = ENTITY_TYPES.register(\"blue_fireball\",\n () -> EntityType.Builder.<MagicMissileProjectile>of(MagicMissileProjectile::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"blue_fireball\").toString()));\n\n public static final RegistryObject<EntityType<CometProjectile>> COMET = ENTITY_TYPES.register(\"comet\",\n () -> EntityType.Builder.<CometProjectile>of(CometProjectile::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"comet\").toString()));\n\n public static final RegistryObject<EntityType<SoulStarEntity>> SOUL_STAR = ENTITY_TYPES.register(\"soul_star\",\n () -> EntityType.Builder.<SoulStarEntity>of(SoulStarEntity::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"soul_star\").toString()));\n\n public static final RegistryObject<EntityType<ChargedEnderPearlEntity>> CHARGED_ENDER_PEARL = ENTITY_TYPES.register(\"charged_ender_pearl\",\n () -> EntityType.Builder.of(ChargedEnderPearlEntity::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"charged_ender_pearl\").toString()));\n\n public static final RegistryObject<EntityType<ObsidilithEntity>> OBSIDILITH = ENTITY_TYPES.register(\"obsidilith\",\n () -> EntityType.Builder.<ObsidilithEntity>of((entityType, level) -> new ObsidilithEntity(entityType, level, mobConfig.obsidilithConfig), MobCategory.MONSTER)\n .sized(2.0f, 4.4f)\n .fireImmune()\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"obsidilith\").toString()));\n\n public static final RegistryObject<EntityType<GauntletEntity>> GAUNTLET = ENTITY_TYPES.register(\"gauntlet\",\n () -> EntityType.Builder.<GauntletEntity>of((entityType, level) -> new GauntletEntity(entityType, level, mobConfig.gauntletConfig) , MobCategory.MONSTER)\n .sized(5.0f, 4.0f)\n .fireImmune()\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"gauntlet\").toString()));\n\n public static final RegistryObject<EntityType<VoidBlossomEntity>> VOID_BLOSSOM = ENTITY_TYPES.register(\"void_blossom\",\n () -> EntityType.Builder.<VoidBlossomEntity>of((entityType, level) -> new VoidBlossomEntity(entityType, level, mobConfig.voidBlossomConfig), MobCategory.MONSTER)\n .sized(8.0f, 10.0f)\n .fireImmune()\n .setTrackingRange(3)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"void_blossom\").toString()));\n\n public static final RegistryObject<EntityType<SporeBallProjectile>> SPORE_BALL = ENTITY_TYPES.register(\"spore_ball\",\n () -> EntityType.Builder.<SporeBallProjectile>of(SporeBallProjectile::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"spore_ball\").toString()));\n\n public static final RegistryObject<EntityType<PetalBladeProjectile>> PETAL_BLADE = ENTITY_TYPES.register(\"petal_blade\",\n () -> EntityType.Builder.<PetalBladeProjectile>of(PetalBladeProjectile::new, MobCategory.MISC)\n .sized(0.25f, 0.25f)\n .build(new ResourceLocation(BMDConstants.MOD_ID, \"petal_blade\").toString()));\n\n public static final LichKillCounter killCounter = new LichKillCounter(mobConfig.lichConfig.summonMechanic);\n\n public static void createAttributes(EntityAttributeCreationEvent event){\n event.put(BMDEntities.LICH.get(), Mob.createMobAttributes()\n .add(Attributes.FLYING_SPEED, 5.0)\n .add(Attributes.MAX_HEALTH, BMDEntities.mobConfig.lichConfig.health)\n .add(Attributes.FOLLOW_RANGE, 64)\n .add(Attributes.ATTACK_DAMAGE, BMDEntities.mobConfig.lichConfig.missile.damage)\n .build());\n\n event.put(BMDEntities.OBSIDILITH.get(), Mob.createMobAttributes()\n .add(Attributes.MAX_HEALTH, mobConfig.obsidilithConfig.health)\n .add(Attributes.FOLLOW_RANGE, 32)\n .add(Attributes.ATTACK_DAMAGE, mobConfig.obsidilithConfig.attack)\n .add(Attributes.KNOCKBACK_RESISTANCE, 10)\n .add(Attributes.ARMOR, mobConfig.obsidilithConfig.armor)\n .build());\n\n event.put(BMDEntities.GAUNTLET.get(), Mob.createMobAttributes()\n .add(Attributes.FLYING_SPEED, 4.0)\n .add(Attributes.FOLLOW_RANGE, 48.0)\n .add(Attributes.MAX_HEALTH, mobConfig.gauntletConfig.health)\n .add(Attributes.KNOCKBACK_RESISTANCE, 10)\n .add(Attributes.ATTACK_DAMAGE, mobConfig.gauntletConfig.attack)\n .add(Attributes.ARMOR, mobConfig.gauntletConfig.armor)\n .build());\n\n event.put(BMDEntities.VOID_BLOSSOM.get(), Mob.createMobAttributes()\n .add(Attributes.MAX_HEALTH, mobConfig.voidBlossomConfig.health)\n .add(Attributes.FOLLOW_RANGE, 32)\n .add(Attributes.ATTACK_DAMAGE, mobConfig.voidBlossomConfig.attack)\n .add(Attributes.KNOCKBACK_RESISTANCE, 10.0)\n .add(Attributes.ARMOR, mobConfig.voidBlossomConfig.armor)\n .build());\n }\n\n @OnlyIn(Dist.CLIENT)\n public static void initClient(){\n PauseAnimationTimer pauseSecondTimer = new PauseAnimationTimer(Blaze3D::getTime, () -> Minecraft.getInstance().isPaused());\n\n EntityRenderers.register(LICH.get(), context -> {\n ResourceLocation texture = new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/lich.png\");\n return new SimpleLivingGeoRenderer<>(\n context,\n new GeoModel<>(\n lichEntity -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/lich.geo.json\"),\n entity -> texture,\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/lich.animation.json\"),\n new LichCodeAnimations(),\n RenderType::entityCutoutNoCull\n ),\n new BoundedLighting<>(5),\n new LichBoneLight(),\n new EternalNightRenderer(),\n null,\n null,\n true\n );\n });\n\n EntityRenderers.register(OBSIDILITH.get(), context -> {\n ObsidilithBoneLight runeColorHandler = new ObsidilithBoneLight();\n GeoModel<ObsidilithEntity> modelProvider = new GeoModel<>(\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/obsidilith.geo.json\"),\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/obsidilith.png\"),\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/obsidilith.animation.json\"),\n (animatable, data, geoModel) -> {},\n RenderType::entityCutout\n );\n ObsidilithArmorRenderer armorRenderer = new ObsidilithArmorRenderer(modelProvider, context);\n return new SimpleLivingGeoRenderer<>(\n context,\n modelProvider,\n null,\n runeColorHandler,\n new CompositeRenderer<>(armorRenderer, runeColorHandler),\n armorRenderer,\n null,\n false\n );\n });\n\n EntityRenderers.register(COMET.get(), context ->\n new SimpleLivingGeoRenderer<>(\n context,\n new GeoModel<>(\n geoAnimatable -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/comet.geo.json\"),\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/comet.png\"),\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/comet.animation.json\"),\n new CometCodeAnimations(),\n RenderType::entityCutout\n ),\n new FullRenderLight<>(),\n null,\n new ConditionalRenderer<>(\n new WeakHashPredicate<>(() -> new FrameLimiter(60f, pauseSecondTimer)::canDoFrame),\n new LerpedPosRenderer<>(vec3 -> ParticleFactories.cometTrail().build(vec3.add(RandomUtils.randVec().scale(0.5)), Vec3.ZERO))\n ),\n null,\n null,\n true\n ));\n\n EntityRenderers.register(SOUL_STAR.get(), context ->\n new ThrownItemRenderer<>(context, 1.0f, true));\n\n EntityRenderers.register(CHARGED_ENDER_PEARL.get(), ThrownItemRenderer::new);\n\n ResourceLocation missileTexture = new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/blue_magic_missile.png\");\n RenderType magicMissileRenderType = RenderType.entityCutoutNoCull(missileTexture);\n EntityRenderers.register(MAGIC_MISSILE.get(), context ->\n new SimpleEntityRenderer<>(context,\n new CompositeRenderer<>(\n new BillboardRenderer<>(context.getEntityRenderDispatcher(), magicMissileRenderType, f -> 0.5f),\n new ConditionalRenderer<>(\n new WeakHashPredicate<>(() -> new FrameLimiter(20f, pauseSecondTimer)::canDoFrame),\n new LerpedPosRenderer<>(vec3 -> ParticleFactories.soulFlame().build(vec3.add(RandomUtils.randVec().scale(0.25)), Vec3.ZERO)))),\n entity -> missileTexture,\n new FullRenderLight<>()\n ));\n\n EntityRenderers.register(GAUNTLET.get(), context -> {\n GeoModel<GauntletEntity> modelProvider = new GeoModel<>(\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/gauntlet.geo.json\"),\n new GauntletTextureProvider(),\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/gauntlet.animation.json\"),\n new GauntletCodeAnimations(),\n RenderType::entityCutout\n );\n GauntletEnergyRenderer energyRenderer = new GauntletEnergyRenderer(modelProvider, context);\n GauntletOverlay overlayOverride = new GauntletOverlay();\n return new SimpleLivingGeoRenderer<>(\n context,\n modelProvider,\n null,\n null,\n new CompositeRenderer<>(\n new GauntletLaserRenderer(),\n new ConditionalRenderer<>(\n new WeakHashPredicate<>(() -> new FrameLimiter(20f, pauseSecondTimer)::canDoFrame),\n new LaserParticleRenderer()\n ),\n energyRenderer,\n overlayOverride\n ),\n energyRenderer,\n overlayOverride,\n false\n );\n });\n\n EntityRenderers.register(VOID_BLOSSOM.get(), context -> {\n ResourceLocation texture = new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/void_blossom.png\");\n GeoModel<VoidBlossomEntity> modelProvider = new GeoModel<>(\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/void_blossom.geo.json\"),\n entity -> texture,\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/void_blossom.animation.json\"),\n new VoidBlossomCodeAnimations(),\n RenderType::entityCutout\n );\n VoidBlossomBoneLight boneLight = new VoidBlossomBoneLight();\n NoRedOnDeathOverlay overlay = new NoRedOnDeathOverlay();\n return new SimpleLivingGeoRenderer<>(\n context,\n modelProvider,\n null,\n boneLight,\n new CompositeRenderer<>(new VoidBlossomSpikeRenderer(), boneLight, overlay),\n null,\n overlay,\n false\n );\n });\n\n EntityRenderers.register(SPORE_BALL.get(), context -> {\n SporeBallOverlay explosionFlasher = new SporeBallOverlay();\n return new SimpleLivingGeoRenderer<>(\n context,\n new GeoModel<>(\n geoAnimatable -> new ResourceLocation(BMDConstants.MOD_ID, \"geo/comet.geo.json\"),\n entity -> new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/spore.png\"),\n new ResourceLocation(BMDConstants.MOD_ID, \"animations/comet.animation.json\"),\n new SporeCodeAnimations(),\n RenderType::entityCutout),\n new FullRenderLight<>(),\n null,\n new CompositeRenderer<>(\n new ConditionalRenderer<>(\n new WeakHashPredicate<>(() -> new FrameLimiter(60f, pauseSecondTimer)::canDoFrame),\n new LerpedPosRenderer<>(vec3 -> {\n ClientParticleBuilder projectileParticles = new ClientParticleBuilder(BMDParticles.OBSIDILITH_BURST.get())\n .color(Vec3Colors.GREEN)\n .colorVariation(0.4)\n .scale(0.5f)\n .brightness(BMDParticles.FULL_BRIGHT);\n projectileParticles.build(vec3.add(RandomUtils.randVec().scale(0.25)), VecUtils.yAxis.scale(0.1));\n })),\n explosionFlasher,\n new SporeBallSizeRenderer()),\n null,\n explosionFlasher,\n true);\n });\n\n ResourceLocation petalTexture = new ResourceLocation(BMDConstants.MOD_ID, \"textures/entity/petal_blade.png\");\n RenderType petalBladeRenderType = RenderType.entityCutoutNoCull(petalTexture);\n EntityRenderers.register(PETAL_BLADE.get(), context ->\n new SimpleEntityRenderer<>(context,\n new CompositeRenderer<>(\n new PetalBladeRenderer(context.getEntityRenderDispatcher(), petalBladeRenderType),\n new ConditionalRenderer<>(\n new WeakHashPredicate<>(() -> new FrameLimiter(30f, pauseSecondTimer)::canDoFrame),\n new PetalBladeParticleRenderer<>()\n )),\n entity -> petalTexture,\n new FullRenderLight<>()));\n }\n\n public static void register(IEventBus eventBus){\n ENTITY_TYPES.register(eventBus);\n }\n}"
},
{
"identifier": "GauntletEntity",
"path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/custom/gauntlet/GauntletEntity.java",
"snippet": "public class GauntletEntity extends BaseEntity implements MultipartAwareEntity {\n public final GauntletHitboxes hitboxHelper = new GauntletHitboxes(this);\n public final GauntletClientLaserHandler laserHandler = new GauntletClientLaserHandler(this, postTickEvents);\n public final GauntletClientEnergyShieldHandler energyShieldHandler = new GauntletClientEnergyShieldHandler(this, postTickEvents);\n public final GauntletBlindnessIndicatorParticles clientBlindnessHandler = new GauntletBlindnessIndicatorParticles(this, preTickEvents);\n public final DamageMemory damageMemory = new DamageMemory(5, this);\n\n private final AnimationHolder animationHandler;\n\n public static final EntityDataAccessor<Integer> laserTarget = SynchedEntityData.defineId(GauntletEntity.class, EntityDataSerializers.INT);\n public static final EntityDataAccessor<Boolean> isEnergized = SynchedEntityData.defineId(GauntletEntity.class, EntityDataSerializers.BOOLEAN);\n\n public GauntletEntity(EntityType<? extends PathfinderMob> entityType, Level level, GauntletConfig mobConfig) {\n super(entityType, level);\n\n GauntletGoalHandler gauntletGoalHandler = new GauntletGoalHandler(this, goalSelector, targetSelector, postTickEvents, mobConfig);\n animationHandler = new AnimationHolder(\n this, Map.of(\n GauntletAttacks.punchAttack, new AnimationHolder.Animation(\"punch_start\", \"punch_loop\"),\n GauntletAttacks.stopPunchAnimation, new AnimationHolder.Animation(\"punch_stop\", \"idle\"),\n GauntletAttacks.stopPoundAnimation, new AnimationHolder.Animation(\"pound_stop\", \"idle\"),\n GauntletAttacks.laserAttack, new AnimationHolder.Animation(\"laser_eye_start\", \"laser_eye_loop\"),\n GauntletAttacks.laserAttackStop, new AnimationHolder.Animation(\"laser_eye_stop\", \"idle\"),\n GauntletAttacks.swirlPunchAttack, new AnimationHolder.Animation(\"swirl_punch\", \"idle\"),\n GauntletAttacks.blindnessAttack, new AnimationHolder.Animation(\"cast\", \"idle\"),\n (byte) 3, new AnimationHolder.Animation(\"death\", \"idle\")\n ), GauntletAttacks.stopAttackAnimation, 5);\n\n noCulling = true;\n laserHandler.initDataTracker();\n energyShieldHandler.initDataTracker();\n damageHandler = new CompositeDamageHandler(hitboxHelper, gauntletGoalHandler, damageMemory);\n entityEventHandler = new CompositeEntityEventHandler(animationHandler, laserHandler, clientBlindnessHandler);\n dataAccessorHandler = new CompositeDataAccessorHandler(laserHandler, energyShieldHandler);\n clientTick = laserHandler;\n serverTick = serverLevel -> {if (getTarget() == null) heal(mobConfig.idleHealingPerTick);};\n bossBar = new ServerBossEvent(getDisplayName(), BossEvent.BossBarColor.RED, BossEvent.BossBarOverlay.NOTCHED_6);\n mobEffectHandler = new EffectsImmunity(MobEffects.WITHER, MobEffects.POISON);\n moveHandler = gauntletGoalHandler;\n nbtHandler = gauntletGoalHandler;\n deathClientTick = new ClientGauntletDeathHandler(this);\n deathServerTick = new ServerGauntletDeathHandler(this, CerbonsApiCapabilities.getLevelEventScheduler(level), mobConfig);\n }\n\n @Override\n public void registerControllers(AnimatableManager.ControllerRegistrar data) {\n animationHandler.registerControllers(data);\n }\n\n @Override\n protected void checkFallDamage(double y, boolean onGround, @NotNull BlockState state, @NotNull BlockPos pos) {}\n\n @Override\n public void travel(@NotNull Vec3 travelVector) {\n VanillaCopiesServer.travel(travelVector, this, 0.85f);\n }\n\n @Override\n public void setNextDamagedPart(@Nullable String part) {\n hitboxHelper.setNextDamagedPart(part);\n }\n\n @Override\n public void onSetPos(double x, double y, double z) {\n if (hitboxHelper != null) hitboxHelper.updatePosition();\n }\n\n @Override\n public boolean onClimbable() {\n return false;\n }\n\n @Override\n public boolean causeFallDamage(float fallDistance, float multiplier, @NotNull DamageSource source) {\n return false;\n }\n\n @Override\n public int getMaxHeadXRot() {\n return 90;\n }\n\n @Override\n public CompoundOrientedBox getCompoundBoundingBox(AABB bounds) {\n return hitboxHelper.getHitbox().getBox(bounds);\n }\n\n @Override\n public EntityBounds getBounds() {\n return hitboxHelper.getHitbox();\n }\n\n @Override\n protected float getStandingEyeHeight(@NotNull Pose pose, EntityDimensions dimensions) {\n return dimensions.height * 0.4f;\n }\n\n @Override\n public boolean isInWall() {\n return false;\n }\n\n @Override\n public int getArmorValue() {\n return getTarget() != null ? super.getArmorValue() : 24;\n }\n\n @Nullable\n @Override\n protected SoundEvent getAmbientSound() {\n return BMDSounds.GAUNTLET_IDLE.get();\n }\n\n @Nullable\n @Override\n protected SoundEvent getHurtSound(@NotNull DamageSource damageSource) {\n return BMDSounds.GAUNTLET_HURT.get();\n }\n\n @Nullable\n @Override\n protected SoundEvent getDeathSound() {\n return BMDSounds.GAUNTLET_DEATH.get();\n }\n\n @Override\n protected float getSoundVolume() {\n return 2.0f;\n }\n\n @Override\n public void checkDespawn() {\n MobUtils.preventDespawnExceptPeaceful(this, level());\n }\n}"
},
{
"identifier": "ExemptEntities",
"path": "src/main/java/com/cerbon/bosses_of_mass_destruction/projectile/util/ExemptEntities.java",
"snippet": "public class ExemptEntities implements Predicate<EntityHitResult> {\n final List<EntityType<?>> exemptEntities;\n\n public ExemptEntities(List<EntityType<?>> exemptEntities){\n this.exemptEntities = exemptEntities;\n }\n\n @Override\n public boolean test(EntityHitResult t) {\n return !exemptEntities.contains(t.getEntity().getType());\n }\n}"
}
] | import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities;
import com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet.GauntletEntity;
import com.cerbon.bosses_of_mass_destruction.projectile.util.ExemptEntities;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.projectile.ThrowableItemProjectile;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.Consumer; | 5,306 | package com.cerbon.bosses_of_mass_destruction.projectile;
public class PetalBladeProjectile extends BaseThrownItemProjectile{
private Consumer<LivingEntity> entityHit;
| package com.cerbon.bosses_of_mass_destruction.projectile;
public class PetalBladeProjectile extends BaseThrownItemProjectile{
private Consumer<LivingEntity> entityHit;
| public static final EntityDataAccessor<Float> renderRotation = SynchedEntityData.defineId(GauntletEntity.class, EntityDataSerializers.FLOAT); | 1 | 2023-10-25 16:28:17+00:00 | 8k |
SmartGecko44/Spigot-Admin-Toys | src/main/java/org/gecko/wauh/listeners/BarrierListener.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.Player;
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.*; | 5,003 | dist = (int) clickedLocation.distance(block.getLocation()) + 1;
if (dist > radiusLimit - 3) {
limitReached = true;
limitReachedThisIteration = true;
}
if ((dist - 1) > highestDist) {
if (dist > 1) {
int progressPercentage = (int) ((double) highestDist / (realRadiusLimit - 2) * 100);
highestDist = dist - 1;
// Send a message to the player only when the dist value rises
if (highestDist < realRadiusLimit - 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.RED + progressPercentage + "% " + ChatColor.GREEN + "(" + ChatColor.RED + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else if (!limitReachedThisIteration) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + progressPercentage + "% (" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
}
}
// Check if the block is grass or dirt
if (block.getType() == Material.GRASS) {
grassRemovedCount++;
} else if (block.getType() == Material.DIRT) {
dirtRemovedCount++;
} else if (block.getType() == Material.BARRIER) {
barrierRemovedCount++;
}
if (!Main.getPlugin(Main.class).getShowRemoval()) {
markedBlocks.add(block);
} else {
block.setType(Material.AIR);
}
// Iterate through neighboring blocks and add them to the next set
// Iterate through neighboring blocks and add them to the next set
for (int i = -1; i <= 1; i++) {
if (i == 0) continue; // Skip the current block
addIfValid(block.getRelative(i, 0, 0), nextSet);
addIfValid(block.getRelative(0, i, 0), nextSet);
addIfValid(block.getRelative(0, 0, i), nextSet);
}
processedBlocks.add(block);
}
blocksToProcess = nextSet;
if (limitReachedThisIteration) {
barriuhFin();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
if (dist > 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
displaySummary();
}
}
private void barriuhFin() {
// Check if there are more blocks to process
if (limitReached) {
displaySummary();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
displaySummary();
}
}
public void displaySummary() {
Player player = currentRemovingPlayer;
// Display the block removal summary to the player
if (grassRemovedCount + dirtRemovedCount + barrierRemovedCount > 1) {
if (barrierRemovedCount == 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount == 0 && dirtRemovedCount == 0 && grassRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks.");
} else if (barrierRemovedCount == 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount == 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
}
// Display the block removal summary in the console
Bukkit.getConsoleSender().sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.GREEN + " removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
if (!Main.getPlugin(Main.class).getShowRemoval()) {
removeMarkedBlocks();
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
}
private void removeMarkedBlocks() { | package org.gecko.wauh.listeners;
public class BarrierListener implements Listener {
private final Set<Block> markedBlocks = new HashSet<>();
private final Set<Block> processedBlocks = new HashSet<>();
private final Set<Block> removedBlocks = new HashSet<>();
public Player currentRemovingPlayer;
public boolean stopBlockRemoval = false;
public boolean blockRemovalActive = false;
private int grassRemovedCount;
private int dirtRemovedCount;
private int barrierRemovedCount;
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 static final Set<Material> IMMUTABLE_MATERIALS = EnumSet.of(Material.GRASS, Material.DIRT, Material.BARRIER, Material.STRUCTURE_VOID);
private void addIfValid(Block block, Set<Block> nextSet) {
if (IMMUTABLE_MATERIALS.contains(block.getType())) {
nextSet.add(block);
}
}
@EventHandler
public void barrierBreakEventHandler(BlockBreakEvent event) {
if (!event.getPlayer().isOp() || event.getPlayer().getInventory().getItemInMainHand() == null || event.getPlayer().getInventory().getItemInMainHand().getAmount() == 0 || event.getPlayer().getInventory().getItemInMainHand().getType() == Material.AIR) {
return;
}
ConfigurationManager configManager;
FileConfiguration config;
configManager = new ConfigurationManager(Main.getPlugin(Main.class));
config = configManager.getConfig();
if (config.getInt("Barrier enabled") == 0) {
return;
}
BucketListener bucketListener = Main.getPlugin(Main.class).getBucketListener();
BedrockListener bedrockListener = Main.getPlugin(Main.class).getBedrockListener();
WaterBucketListener waterBucketListener = Main.getPlugin(Main.class).getWaterBucketListener();
NBTItem nbtItem = new NBTItem(event.getPlayer().getInventory().getItemInMainHand());
String identifier = nbtItem.getString("Ident");
radiusLimit = Main.getPlugin(Main.class).getRadiusLimit();
realRadiusLimit = radiusLimit - 2;
if (realRadiusLimit > 1) {
if (!bucketListener.wauhRemovalActive && !blockRemovalActive && !bedrockListener.allRemovalActive && !waterBucketListener.tsunamiActive) {
Player player = event.getPlayer();
if (IMMUTABLE_MATERIALS.contains(event.getBlock().getType())) {
// Check if the bucket is filling with water
if (player.getInventory().getItemInMainHand().getType() == Material.BARRIER && identifier.equalsIgnoreCase("Custom Barrier")) {
blockRemovalActive = true;
limitReached = false;
clickedLocation = event.getBlock().getLocation();
// Reset the water removal counts and initialize the set of blocks to process
grassRemovedCount = 0;
dirtRemovedCount = 0;
barrierRemovedCount = 0;
highestDist = 0;
blocksToProcess.clear();
currentRemovingPlayer = player;
// Add the clicked block to the set of blocks to process
blocksToProcess.add(clickedLocation.getBlock());
// Start the water removal process
processBlockRemoval();
}
}
}
}
}
private void processBlockRemoval() {
if (stopBlockRemoval) {
stopBlockRemoval = false;
displaySummary();
return;
}
Set<Block> nextSet = new HashSet<>();
boolean limitReachedThisIteration = false; // Variable to track whether the limit was reached this iteration
for (Block block : blocksToProcess) {
if (processedBlocks.contains(block)) {
continue;
}
dist = (int) clickedLocation.distance(block.getLocation()) + 1;
if (dist > radiusLimit - 3) {
limitReached = true;
limitReachedThisIteration = true;
}
if ((dist - 1) > highestDist) {
if (dist > 1) {
int progressPercentage = (int) ((double) highestDist / (realRadiusLimit - 2) * 100);
highestDist = dist - 1;
// Send a message to the player only when the dist value rises
if (highestDist < realRadiusLimit - 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.RED + progressPercentage + "% " + ChatColor.GREEN + "(" + ChatColor.RED + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else if (!limitReachedThisIteration) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + progressPercentage + "% (" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
}
}
// Check if the block is grass or dirt
if (block.getType() == Material.GRASS) {
grassRemovedCount++;
} else if (block.getType() == Material.DIRT) {
dirtRemovedCount++;
} else if (block.getType() == Material.BARRIER) {
barrierRemovedCount++;
}
if (!Main.getPlugin(Main.class).getShowRemoval()) {
markedBlocks.add(block);
} else {
block.setType(Material.AIR);
}
// Iterate through neighboring blocks and add them to the next set
// Iterate through neighboring blocks and add them to the next set
for (int i = -1; i <= 1; i++) {
if (i == 0) continue; // Skip the current block
addIfValid(block.getRelative(i, 0, 0), nextSet);
addIfValid(block.getRelative(0, i, 0), nextSet);
addIfValid(block.getRelative(0, 0, i), nextSet);
}
processedBlocks.add(block);
}
blocksToProcess = nextSet;
if (limitReachedThisIteration) {
barriuhFin();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
if (dist > 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
displaySummary();
}
}
private void barriuhFin() {
// Check if there are more blocks to process
if (limitReached) {
displaySummary();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
displaySummary();
}
}
public void displaySummary() {
Player player = currentRemovingPlayer;
// Display the block removal summary to the player
if (grassRemovedCount + dirtRemovedCount + barrierRemovedCount > 1) {
if (barrierRemovedCount == 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount == 0 && dirtRemovedCount == 0 && grassRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks.");
} else if (barrierRemovedCount == 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount == 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
}
// Display the block removal summary in the console
Bukkit.getConsoleSender().sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.GREEN + " removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
if (!Main.getPlugin(Main.class).getShowRemoval()) {
removeMarkedBlocks();
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
}
private void removeMarkedBlocks() { | Scale scale; | 2 | 2023-10-28 11:26:45+00:00 | 8k |
sinch/sinch-sdk-java | client/src/test/java/com/sinch/sdk/domains/numbers/adapters/converters/AvailableNumberDtoConverterTest.java | [
{
"identifier": "AvailableNumber",
"path": "client/src/main/com/sinch/sdk/domains/numbers/models/AvailableNumber.java",
"snippet": "public class AvailableNumber {\n private final String phoneNumber;\n\n private final String regionCode;\n\n private final NumberType type;\n\n private final Collection<Capability> capability;\n\n private final Money setupPrice;\n\n private final Money monthlyPrice;\n\n private final Integer paymentIntervalMonths;\n\n private final Boolean supportingDocumentationRequired;\n\n /**\n * @param phoneNumber The phone number in E.164 format with leading +. Example +12025550134.\n * @param regionCode ISO 3166-1 alpha-2 country code of the phone number. Example: US, UK or SE.\n * @param type The number type.\n * @param capability The capability of the number.\n * @param setupPrice An object giving details on currency code and the amount charged.\n * @param monthlyPrice An object giving details on currency code and the amount charged.\n * @param paymentIntervalMonths How often the recurring price is charged in months.\n * @param supportingDocumentationRequired Whether or not supplementary documentation will be\n * required to complete the number rental.\n */\n public AvailableNumber(\n String phoneNumber,\n String regionCode,\n NumberType type,\n Collection<Capability> capability,\n Money setupPrice,\n Money monthlyPrice,\n Integer paymentIntervalMonths,\n Boolean supportingDocumentationRequired) {\n this.phoneNumber = phoneNumber;\n this.regionCode = regionCode;\n this.type = type;\n this.capability = capability;\n this.setupPrice = setupPrice;\n this.monthlyPrice = monthlyPrice;\n this.paymentIntervalMonths = paymentIntervalMonths;\n this.supportingDocumentationRequired = supportingDocumentationRequired;\n }\n\n public String getPhoneNumber() {\n return phoneNumber;\n }\n\n public String getRegionCode() {\n return regionCode;\n }\n\n public NumberType getType() {\n return type;\n }\n\n public Collection<Capability> getCapability() {\n return capability;\n }\n\n public Money getSetupPrice() {\n return setupPrice;\n }\n\n public Money getMonthlyPrice() {\n return monthlyPrice;\n }\n\n public Integer getPaymentIntervalMonths() {\n return paymentIntervalMonths;\n }\n\n public Boolean getSupportingDocumentationRequired() {\n return supportingDocumentationRequired;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n public String toString() {\n return \"AvailableNumber{\"\n + \"phoneNumber='\"\n + phoneNumber\n + '\\''\n + \", regionCode='\"\n + regionCode\n + '\\''\n + \", type='\"\n + type\n + '\\''\n + \", capability=\"\n + capability\n + \", setupPrice=\"\n + setupPrice\n + \", monthlyPrice=\"\n + monthlyPrice\n + \", paymentIntervalMonths=\"\n + paymentIntervalMonths\n + \", supportingDocumentationRequired=\"\n + supportingDocumentationRequired\n + '}';\n }\n\n public static class Builder {\n private String phoneNumber;\n\n private String regionCode;\n\n private NumberType type;\n\n private Collection<Capability> capability;\n\n private Money setupPrice;\n\n private Money monthlyPrice;\n\n private Integer paymentIntervalMonths;\n\n private Boolean supportingDocumentationRequired;\n\n private Builder() {}\n\n public AvailableNumber build() {\n return new AvailableNumber(\n phoneNumber,\n regionCode,\n type,\n capability,\n setupPrice,\n monthlyPrice,\n paymentIntervalMonths,\n supportingDocumentationRequired);\n }\n\n public Builder setPhoneNumber(String phoneNumber) {\n this.phoneNumber = phoneNumber;\n return this;\n }\n\n public Builder setRegionCode(String regionCode) {\n this.regionCode = regionCode;\n return this;\n }\n\n public Builder setType(NumberType type) {\n this.type = type;\n return this;\n }\n\n public Builder setCapability(Collection<Capability> capability) {\n this.capability = capability;\n return this;\n }\n\n public Builder setSetupPrice(Money setupPrice) {\n this.setupPrice = setupPrice;\n return this;\n }\n\n public Builder setMonthlyPrice(Money monthlyPrice) {\n this.monthlyPrice = monthlyPrice;\n return this;\n }\n\n public Builder setPaymentIntervalMonths(Integer paymentIntervalMonths) {\n this.paymentIntervalMonths = paymentIntervalMonths;\n return this;\n }\n\n public Builder setSupportingDocumentationRequired(Boolean supportingDocumentationRequired) {\n this.supportingDocumentationRequired = supportingDocumentationRequired;\n return this;\n }\n }\n}"
},
{
"identifier": "Capability",
"path": "client/src/main/com/sinch/sdk/domains/numbers/models/Capability.java",
"snippet": "public final class Capability extends EnumDynamic<String, Capability> {\n /** The SMS product can use the number. */\n public static final Capability SMS = new Capability(\"SMS\");\n\n /** The Voice product can use the number. */\n public static final Capability VOICE = new Capability(\"VOICE\");\n\n private static final EnumSupportDynamic<String, Capability> ENUM_SUPPORT =\n new EnumSupportDynamic<>(Capability.class, Capability::new, Arrays.asList(SMS, VOICE));\n\n private Capability(String value) {\n super(value);\n }\n\n public static Stream<Capability> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static Capability from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(Capability e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}"
},
{
"identifier": "NumberType",
"path": "client/src/main/com/sinch/sdk/domains/numbers/models/NumberType.java",
"snippet": "public final class NumberType extends EnumDynamic<String, NumberType> {\n\n /** Numbers that belong to a specific range. */\n public static final NumberType MOBILE = new NumberType(\"MOBILE\");\n\n /** Numbers that are assigned to a specific geographic region. */\n public static final NumberType LOCAL = new NumberType(\"LOCAL\");\n\n /** Numbers that are free of charge for the calling party but billed for all arriving calls. */\n public static final NumberType TOLL_FREE = new NumberType(\"TOLL_FREE\");\n\n private static final EnumSupportDynamic<String, NumberType> ENUM_SUPPORT =\n new EnumSupportDynamic<>(\n NumberType.class, NumberType::new, Arrays.asList(MOBILE, LOCAL, TOLL_FREE));\n\n private NumberType(String value) {\n super(value);\n }\n\n public static Stream<NumberType> values() {\n return ENUM_SUPPORT.values();\n }\n\n public static NumberType from(String value) {\n return ENUM_SUPPORT.from(value);\n }\n\n public static String valueOf(NumberType e) {\n return ENUM_SUPPORT.valueOf(e);\n }\n}"
},
{
"identifier": "AvailableNumberDto",
"path": "openapi-contracts/src/main/com/sinch/sdk/domains/numbers/models/dto/v1/AvailableNumberDto.java",
"snippet": "@JsonPropertyOrder({\n AvailableNumberDto.JSON_PROPERTY_PHONE_NUMBER,\n AvailableNumberDto.JSON_PROPERTY_REGION_CODE,\n AvailableNumberDto.JSON_PROPERTY_TYPE,\n AvailableNumberDto.JSON_PROPERTY_CAPABILITY,\n AvailableNumberDto.JSON_PROPERTY_SETUP_PRICE,\n AvailableNumberDto.JSON_PROPERTY_MONTHLY_PRICE,\n AvailableNumberDto.JSON_PROPERTY_PAYMENT_INTERVAL_MONTHS,\n AvailableNumberDto.JSON_PROPERTY_SUPPORTING_DOCUMENTATION_REQUIRED\n})\n@JsonFilter(\"uninitializedFilter\")\n@JsonInclude(value = JsonInclude.Include.CUSTOM)\npublic class AvailableNumberDto {\n public static final String JSON_PROPERTY_PHONE_NUMBER = \"phoneNumber\";\n private String phoneNumber;\n private boolean phoneNumberDefined = false;\n\n public static final String JSON_PROPERTY_REGION_CODE = \"regionCode\";\n private String regionCode;\n private boolean regionCodeDefined = false;\n\n public static final String JSON_PROPERTY_TYPE = \"type\";\n private String type;\n private boolean typeDefined = false;\n\n public static final String JSON_PROPERTY_CAPABILITY = \"capability\";\n private List<String> capability;\n private boolean capabilityDefined = false;\n\n public static final String JSON_PROPERTY_SETUP_PRICE = \"setupPrice\";\n private MoneyDto setupPrice;\n private boolean setupPriceDefined = false;\n\n public static final String JSON_PROPERTY_MONTHLY_PRICE = \"monthlyPrice\";\n private MoneyDto monthlyPrice;\n private boolean monthlyPriceDefined = false;\n\n public static final String JSON_PROPERTY_PAYMENT_INTERVAL_MONTHS = \"paymentIntervalMonths\";\n private Integer paymentIntervalMonths;\n private boolean paymentIntervalMonthsDefined = false;\n\n public static final String JSON_PROPERTY_SUPPORTING_DOCUMENTATION_REQUIRED =\n \"supportingDocumentationRequired\";\n private Boolean supportingDocumentationRequired;\n private boolean supportingDocumentationRequiredDefined = false;\n\n public AvailableNumberDto() {}\n\n @JsonCreator\n public AvailableNumberDto(\n @JsonProperty(JSON_PROPERTY_PHONE_NUMBER) String phoneNumber,\n @JsonProperty(JSON_PROPERTY_REGION_CODE) String regionCode,\n @JsonProperty(JSON_PROPERTY_PAYMENT_INTERVAL_MONTHS) Integer paymentIntervalMonths,\n @JsonProperty(JSON_PROPERTY_SUPPORTING_DOCUMENTATION_REQUIRED)\n Boolean supportingDocumentationRequired) {\n this();\n this.phoneNumber = phoneNumber;\n this.phoneNumberDefined = true;\n this.regionCode = regionCode;\n this.regionCodeDefined = true;\n this.paymentIntervalMonths = paymentIntervalMonths;\n this.paymentIntervalMonthsDefined = true;\n this.supportingDocumentationRequired = supportingDocumentationRequired;\n this.supportingDocumentationRequiredDefined = true;\n }\n\n /**\n * The phone number in <a\n * href=\\"https://community.sinch.com/t5/Glossary/E-164/ta-p/7537\\"\n * target=\\"_blank\\">E.164</a> format with leading `+`. Example\n * `+12025550134`.\n *\n * @return phoneNumber\n */\n @JsonProperty(JSON_PROPERTY_PHONE_NUMBER)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public String getPhoneNumber() {\n return phoneNumber;\n }\n\n @JsonIgnore\n public boolean getPhoneNumberDefined() {\n return phoneNumberDefined;\n }\n\n /**\n * ISO 3166-1 alpha-2 country code of the phone number. Example: `US`, `GB` or\n * `SE`.\n *\n * @return regionCode\n */\n @JsonProperty(JSON_PROPERTY_REGION_CODE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public String getRegionCode() {\n return regionCode;\n }\n\n @JsonIgnore\n public boolean getRegionCodeDefined() {\n return regionCodeDefined;\n }\n\n public AvailableNumberDto type(String type) {\n this.type = type;\n this.typeDefined = true;\n return this;\n }\n\n /**\n * The number type.\n *\n * @return type\n */\n @JsonProperty(JSON_PROPERTY_TYPE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public String getType() {\n return type;\n }\n\n @JsonIgnore\n public boolean getTypeDefined() {\n return typeDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_TYPE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setType(String type) {\n this.type = type;\n this.typeDefined = true;\n }\n\n public AvailableNumberDto capability(List<String> capability) {\n this.capability = capability;\n this.capabilityDefined = true;\n return this;\n }\n\n public AvailableNumberDto addCapabilityItem(String capabilityItem) {\n if (this.capability == null) {\n this.capability = new ArrayList<>();\n }\n this.capabilityDefined = true;\n this.capability.add(capabilityItem);\n return this;\n }\n\n /**\n * The capability of the number.\n *\n * @return capability\n */\n @JsonProperty(JSON_PROPERTY_CAPABILITY)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public List<String> getCapability() {\n return capability;\n }\n\n @JsonIgnore\n public boolean getCapabilityDefined() {\n return capabilityDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_CAPABILITY)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCapability(List<String> capability) {\n this.capability = capability;\n this.capabilityDefined = true;\n }\n\n public AvailableNumberDto setupPrice(MoneyDto setupPrice) {\n this.setupPrice = setupPrice;\n this.setupPriceDefined = true;\n return this;\n }\n\n /**\n * Get setupPrice\n *\n * @return setupPrice\n */\n @JsonProperty(JSON_PROPERTY_SETUP_PRICE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public MoneyDto getSetupPrice() {\n return setupPrice;\n }\n\n @JsonIgnore\n public boolean getSetupPriceDefined() {\n return setupPriceDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_SETUP_PRICE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setSetupPrice(MoneyDto setupPrice) {\n this.setupPrice = setupPrice;\n this.setupPriceDefined = true;\n }\n\n public AvailableNumberDto monthlyPrice(MoneyDto monthlyPrice) {\n this.monthlyPrice = monthlyPrice;\n this.monthlyPriceDefined = true;\n return this;\n }\n\n /**\n * Get monthlyPrice\n *\n * @return monthlyPrice\n */\n @JsonProperty(JSON_PROPERTY_MONTHLY_PRICE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public MoneyDto getMonthlyPrice() {\n return monthlyPrice;\n }\n\n @JsonIgnore\n public boolean getMonthlyPriceDefined() {\n return monthlyPriceDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_MONTHLY_PRICE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setMonthlyPrice(MoneyDto monthlyPrice) {\n this.monthlyPrice = monthlyPrice;\n this.monthlyPriceDefined = true;\n }\n\n /**\n * How often the recurring price is charged in months.\n *\n * @return paymentIntervalMonths\n */\n @JsonProperty(JSON_PROPERTY_PAYMENT_INTERVAL_MONTHS)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public Integer getPaymentIntervalMonths() {\n return paymentIntervalMonths;\n }\n\n @JsonIgnore\n public boolean getPaymentIntervalMonthsDefined() {\n return paymentIntervalMonthsDefined;\n }\n\n /**\n * Whether or not supplementary documentation will be required to complete the number rental.\n *\n * @return supportingDocumentationRequired\n */\n @JsonProperty(JSON_PROPERTY_SUPPORTING_DOCUMENTATION_REQUIRED)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public Boolean getSupportingDocumentationRequired() {\n return supportingDocumentationRequired;\n }\n\n @JsonIgnore\n public boolean getSupportingDocumentationRequiredDefined() {\n return supportingDocumentationRequiredDefined;\n }\n\n /** Return true if this AvailableNumber object is equal to o. */\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 AvailableNumberDto availableNumber = (AvailableNumberDto) o;\n return Objects.equals(this.phoneNumber, availableNumber.phoneNumber)\n && Objects.equals(this.regionCode, availableNumber.regionCode)\n && Objects.equals(this.type, availableNumber.type)\n && Objects.equals(this.capability, availableNumber.capability)\n && Objects.equals(this.setupPrice, availableNumber.setupPrice)\n && Objects.equals(this.monthlyPrice, availableNumber.monthlyPrice)\n && Objects.equals(this.paymentIntervalMonths, availableNumber.paymentIntervalMonths)\n && Objects.equals(\n this.supportingDocumentationRequired, availableNumber.supportingDocumentationRequired);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n phoneNumber,\n regionCode,\n type,\n capability,\n setupPrice,\n monthlyPrice,\n paymentIntervalMonths,\n supportingDocumentationRequired);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class AvailableNumberDto {\\n\");\n sb.append(\" phoneNumber: \").append(toIndentedString(phoneNumber)).append(\"\\n\");\n sb.append(\" regionCode: \").append(toIndentedString(regionCode)).append(\"\\n\");\n sb.append(\" type: \").append(toIndentedString(type)).append(\"\\n\");\n sb.append(\" capability: \").append(toIndentedString(capability)).append(\"\\n\");\n sb.append(\" setupPrice: \").append(toIndentedString(setupPrice)).append(\"\\n\");\n sb.append(\" monthlyPrice: \").append(toIndentedString(monthlyPrice)).append(\"\\n\");\n sb.append(\" paymentIntervalMonths: \")\n .append(toIndentedString(paymentIntervalMonths))\n .append(\"\\n\");\n sb.append(\" supportingDocumentationRequired: \")\n .append(toIndentedString(supportingDocumentationRequired))\n .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 (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": "AvailableNumbersResponseDto",
"path": "openapi-contracts/src/main/com/sinch/sdk/domains/numbers/models/dto/v1/AvailableNumbersResponseDto.java",
"snippet": "@JsonPropertyOrder({AvailableNumbersResponseDto.JSON_PROPERTY_AVAILABLE_NUMBERS})\n@JsonFilter(\"uninitializedFilter\")\n@JsonInclude(value = JsonInclude.Include.CUSTOM)\npublic class AvailableNumbersResponseDto {\n public static final String JSON_PROPERTY_AVAILABLE_NUMBERS = \"availableNumbers\";\n private List<AvailableNumberDto> availableNumbers;\n private boolean availableNumbersDefined = false;\n\n public AvailableNumbersResponseDto() {}\n\n public AvailableNumbersResponseDto availableNumbers(List<AvailableNumberDto> availableNumbers) {\n this.availableNumbers = availableNumbers;\n this.availableNumbersDefined = true;\n return this;\n }\n\n public AvailableNumbersResponseDto addAvailableNumbersItem(\n AvailableNumberDto availableNumbersItem) {\n if (this.availableNumbers == null) {\n this.availableNumbers = new ArrayList<>();\n }\n this.availableNumbersDefined = true;\n this.availableNumbers.add(availableNumbersItem);\n return this;\n }\n\n /**\n * List of available phone numbers.\n *\n * @return availableNumbers\n */\n @JsonProperty(JSON_PROPERTY_AVAILABLE_NUMBERS)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public List<AvailableNumberDto> getAvailableNumbers() {\n return availableNumbers;\n }\n\n @JsonIgnore\n public boolean getAvailableNumbersDefined() {\n return availableNumbersDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_AVAILABLE_NUMBERS)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setAvailableNumbers(List<AvailableNumberDto> availableNumbers) {\n this.availableNumbers = availableNumbers;\n this.availableNumbersDefined = true;\n }\n\n /** Return true if this AvailableNumbersResponse object is equal to o. */\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 AvailableNumbersResponseDto availableNumbersResponse = (AvailableNumbersResponseDto) o;\n return Objects.equals(this.availableNumbers, availableNumbersResponse.availableNumbers);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(availableNumbers);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class AvailableNumbersResponseDto {\\n\");\n sb.append(\" availableNumbers: \").append(toIndentedString(availableNumbers)).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 (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": "MoneyDto",
"path": "openapi-contracts/src/main/com/sinch/sdk/domains/numbers/models/dto/v1/MoneyDto.java",
"snippet": "@JsonPropertyOrder({MoneyDto.JSON_PROPERTY_CURRENCY_CODE, MoneyDto.JSON_PROPERTY_AMOUNT})\n@JsonFilter(\"uninitializedFilter\")\n@JsonInclude(value = JsonInclude.Include.CUSTOM)\npublic class MoneyDto {\n public static final String JSON_PROPERTY_CURRENCY_CODE = \"currencyCode\";\n private String currencyCode;\n private boolean currencyCodeDefined = false;\n\n public static final String JSON_PROPERTY_AMOUNT = \"amount\";\n private String amount;\n private boolean amountDefined = false;\n\n public MoneyDto() {}\n\n public MoneyDto currencyCode(String currencyCode) {\n this.currencyCode = currencyCode;\n this.currencyCodeDefined = true;\n return this;\n }\n\n /**\n * The 3-letter currency code defined in <a\n * href=\\"https://www.iso.org/iso-4217-currency-codes.html\\"\n * target=\\"_blank\\">ISO 4217</a>.\n *\n * @return currencyCode\n */\n @JsonProperty(JSON_PROPERTY_CURRENCY_CODE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public String getCurrencyCode() {\n return currencyCode;\n }\n\n @JsonIgnore\n public boolean getCurrencyCodeDefined() {\n return currencyCodeDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_CURRENCY_CODE)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setCurrencyCode(String currencyCode) {\n this.currencyCode = currencyCode;\n this.currencyCodeDefined = true;\n }\n\n public MoneyDto amount(String amount) {\n this.amount = amount;\n this.amountDefined = true;\n return this;\n }\n\n /**\n * The amount in decimal form. For example `2.00`. There are no guarantees on the\n * precision unless documented by the message origin. The amount cannot be updated and is\n * read-only.\n *\n * @return amount\n */\n @JsonProperty(JSON_PROPERTY_AMOUNT)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public String getAmount() {\n return amount;\n }\n\n @JsonIgnore\n public boolean getAmountDefined() {\n return amountDefined;\n }\n\n @JsonProperty(JSON_PROPERTY_AMOUNT)\n @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n public void setAmount(String amount) {\n this.amount = amount;\n this.amountDefined = true;\n }\n\n /** Return true if this Money object is equal to o. */\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 MoneyDto money = (MoneyDto) o;\n return Objects.equals(this.currencyCode, money.currencyCode)\n && Objects.equals(this.amount, money.amount);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(currencyCode, amount);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class MoneyDto {\\n\");\n sb.append(\" currencyCode: \").append(toIndentedString(currencyCode)).append(\"\\n\");\n sb.append(\" amount: \").append(toIndentedString(amount)).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 (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 static org.junit.jupiter.api.Assertions.assertEquals;
import com.sinch.sdk.domains.numbers.models.AvailableNumber;
import com.sinch.sdk.domains.numbers.models.Capability;
import com.sinch.sdk.domains.numbers.models.NumberType;
import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumberDto;
import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumbersResponseDto;
import com.sinch.sdk.domains.numbers.models.dto.v1.MoneyDto;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | 6,450 | package com.sinch.sdk.domains.numbers.adapters.converters;
class AvailableNumberDtoConverterTest {
AvailableNumberDto dtoItem;
public static void compareWithDto(AvailableNumber client, AvailableNumberDto dto) {
assertEquals(dto.getPhoneNumber(), client.getPhoneNumber());
assertEquals(dto.getRegionCode(), client.getRegionCode());
assertEquals(dto.getType(), NumberType.valueOf(client.getType()));
assertEquals(
null == dto.getCapability() ? null : dto.getCapability(),
null == client.getCapability()
? null
: client.getCapability().stream()
.map(Capability::valueOf)
.collect(Collectors.toList()));
MoneyDtoConverterTest.compareWithDto(client.getSetupPrice(), dto.getSetupPrice());
MoneyDtoConverterTest.compareWithDto(client.getMonthlyPrice(), dto.getMonthlyPrice());
assertEquals(dto.getPaymentIntervalMonths(), client.getPaymentIntervalMonths());
assertEquals(
dto.getSupportingDocumentationRequired(), client.getSupportingDocumentationRequired());
}
@Test
void convertAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
dto.setAvailableNumbers(Collections.singletonList(dtoItem));
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(dto.getAvailableNumbers().size(), converted.size());
}
@Test
void convertEmptyAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(converted.size(), 0);
}
@Test
void convertAvailableNumberDto() {
AvailableNumberDto dto = dtoItem;
AvailableNumber converted = AvailableNumberDtoConverter.convert(dtoItem);
compareWithDto(converted, dto);
}
@Test
void convertAvailableNumberDtoWithUnknownType() {
dtoItem =
new AvailableNumberDto("phoneNumber", "regionCode", 4, true)
.type("foo")
.addCapabilityItem(Capability.SMS.value())
.addCapabilityItem(Capability.VOICE.value()) | package com.sinch.sdk.domains.numbers.adapters.converters;
class AvailableNumberDtoConverterTest {
AvailableNumberDto dtoItem;
public static void compareWithDto(AvailableNumber client, AvailableNumberDto dto) {
assertEquals(dto.getPhoneNumber(), client.getPhoneNumber());
assertEquals(dto.getRegionCode(), client.getRegionCode());
assertEquals(dto.getType(), NumberType.valueOf(client.getType()));
assertEquals(
null == dto.getCapability() ? null : dto.getCapability(),
null == client.getCapability()
? null
: client.getCapability().stream()
.map(Capability::valueOf)
.collect(Collectors.toList()));
MoneyDtoConverterTest.compareWithDto(client.getSetupPrice(), dto.getSetupPrice());
MoneyDtoConverterTest.compareWithDto(client.getMonthlyPrice(), dto.getMonthlyPrice());
assertEquals(dto.getPaymentIntervalMonths(), client.getPaymentIntervalMonths());
assertEquals(
dto.getSupportingDocumentationRequired(), client.getSupportingDocumentationRequired());
}
@Test
void convertAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
dto.setAvailableNumbers(Collections.singletonList(dtoItem));
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(dto.getAvailableNumbers().size(), converted.size());
}
@Test
void convertEmptyAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(converted.size(), 0);
}
@Test
void convertAvailableNumberDto() {
AvailableNumberDto dto = dtoItem;
AvailableNumber converted = AvailableNumberDtoConverter.convert(dtoItem);
compareWithDto(converted, dto);
}
@Test
void convertAvailableNumberDtoWithUnknownType() {
dtoItem =
new AvailableNumberDto("phoneNumber", "regionCode", 4, true)
.type("foo")
.addCapabilityItem(Capability.SMS.value())
.addCapabilityItem(Capability.VOICE.value()) | .setupPrice(new MoneyDto().currencyCode("EU").amount(".8")) | 5 | 2023-10-31 08:32:59+00:00 | 8k |
SpCoGov/SpCoBot | src/main/java/top/spco/service/command/Command.java | [
{
"identifier": "Message",
"path": "src/main/java/top/spco/api/message/Message.java",
"snippet": "public interface Message extends Codable{\n /**\n * 转为接近官方格式的字符串, 即 \"内容\". 如 At(member) + \"test\" 将转为 \"@QQ test\"\n *\n * @return 转化后的文本\n */\n String toMessageContext();\n}"
},
{
"identifier": "CommandEvents",
"path": "src/main/java/top/spco/events/CommandEvents.java",
"snippet": "public class CommandEvents {\n /**\n * Called when a command is received.\n */\n public static final Event<Command> COMMAND = EventFactory.createArrayBacked(Command.class, callbacks -> (bot, from, sender, message, time, command, label, args, meta) -> {\n for (Command event : callbacks) {\n event.onCommand(bot, from, sender, message, time, command, label, args, meta);\n }\n });\n\n @FunctionalInterface\n public interface Command {\n /**\n * 假如用户发送了命令 \"/command a b c\"\n *\n * @param bot 收到命令的机器人\n * @param from 收到命令的来源\n * @param sender 命令的发送者\n * @param message 原始消息\n * @param time 命令发送的时间\n * @param command 命令的原始文本 (如 {@code \"/command a b c\"} )\n * @param label 命令的类型 (如 {@code \"command\"} )\n * @param args 命令的参数 (如 {@code [\"a\", \"b\", \"c\"]) }\n * @param meta 命令的元数据\n */\n void onCommand(Bot bot, Interactive from, User sender, Message message, int time, String command, String label, String[] args, CommandMeta meta);\n }\n\n /**\n * Called when a friend command is received.\n */\n public static final Event<FriendCommand> FRIEND_COMMAND = EventFactory.createArrayBacked(FriendCommand.class, callbacks -> (bot, interactor, message, time, command, label, args, meta) -> {\n for (FriendCommand event : callbacks) {\n event.onFriendCommand(bot, interactor, message, time, command, label, args, meta);\n }\n });\n\n @FunctionalInterface\n public interface FriendCommand {\n /**\n * 假如好友发送了命令 \"/command a b c\"\n *\n * @param bot 收到命令的机器人\n * @param interactor 命令的发送者\n * @param message 原始消息\n * @param time 命令发送的时间\n * @param command 命令的原始文本 (如 {@code \"/command a b c\"} )\n * @param label 命令的类型 (如 {@code \"command\"} )\n * @param args 命令的参数 (如 {@code [\"a\", \"b\", \"c\"]) }\n * @param meta 命令的元数据\n */\n void onFriendCommand(Bot bot, Friend interactor, Message message, int time, String command, String label, String[] args, CommandMeta meta);\n }\n\n /**\n * Called when a group command is received.\n */\n public static final Event<GroupCommand> GROUP_COMMAND = EventFactory.createArrayBacked(GroupCommand.class, callbacks -> (bot, from, sender, message, time, command, label, args, meta) -> {\n for (GroupCommand event : callbacks) {\n event.onGroupCommand(bot, from, sender, message, time, command, label, args, meta);\n }\n });\n\n @FunctionalInterface\n public interface GroupCommand {\n /**\n * 假如好友发送了命令 \"/command a b c\"\n *\n * @param bot 收到命令的机器人\n * @param from 收到命令的来源\n * @param sender 命令的发送者\n * @param time 命令发送的时间\n * @param message 原始消息\n * @param command 命令的原始文本 (如 {@code \"/command a b c\"} )\n * @param label 命令的类型 (如 {@code \"command\"} )\n * @param args 命令的参数 (如 {@code [\"a\", \"b\", \"c\"]) }\n * @param meta 命令的元数据\n */\n void onGroupCommand(Bot bot, Group from, Member sender, Message message, int time, String command, String label, String[] args, CommandMeta meta);\n }\n\n /**\n * Called when a group-temp command is received.\n */\n public static final Event<GroupTempCommand> GROUP_TEMP_COMMAND = EventFactory.createArrayBacked(GroupTempCommand.class, callbacks -> (bot, interactor, message, time, command, label, args, meta) -> {\n for (GroupTempCommand event : callbacks) {\n event.onGroupTempCommand(bot, interactor, message, time, command, label, args, meta);\n }\n });\n\n @FunctionalInterface\n public interface GroupTempCommand {\n /**\n * 假如好友发送了命令 \"/command a b c\"\n *\n * @param bot 收到命令的机器人\n * @param interactor 命令的发送者\n * @param time 命令发送的时间\n * @param message 原始消息\n * @param command 命令的原始文本 (如 {@code \"/command a b c\"} )\n * @param label 命令的类型 (如 {@code \"command\"} )\n * @param args 命令的参数 (如 {@code [\"a\", \"b\", \"c\"]) }\n * @param meta 命令的元数据\n */\n void onGroupTempCommand(Bot bot, Member interactor, Message message, int time, String command, String label, String[] args, CommandMeta meta);\n }\n}"
},
{
"identifier": "Chat",
"path": "src/main/java/top/spco/service/chat/Chat.java",
"snippet": "public class Chat {\n private final ChatType type;\n private volatile boolean frozen = false;\n private List<Stage> stages = new ArrayList<>();\n private int currentStageIndex = 0;\n private final Interactive target;\n private boolean stopped;\n\n /**\n * 获取对话的类型。\n *\n * @return 对话的类型\n */\n public ChatType getType() {\n return type;\n }\n\n /**\n * 获取对话的目标交互对象。\n *\n * @return 目标交互对象\n */\n public Interactive getTarget() {\n return target;\n }\n\n /**\n * 构造一个新的对话实例。\n *\n * @param type 对话的类型\n * @param target 对话的目标交互对象\n */\n public Chat(ChatType type, Interactive target) {\n this.type = type;\n this.target = target;\n }\n\n /**\n * 向对话中添加一个交互阶段。\n *\n * @param stage 要添加的交互阶段\n * @throws IllegalStateException 如果对话已被冻结,无法添加阶段\n */\n public void addStage(Stage stage) {\n if (frozen) {\n throw new IllegalStateException(\"Cannot add stages after the pre-initialization phase!\");\n }\n stages.add(stage);\n }\n\n /**\n * 冻结对话,防止添加更多阶段。\n */\n public void freeze() {\n frozen = true;\n }\n\n /**\n * 运行当前阶段的交互。\n */\n public void runStage() {\n if (stopped) {\n return;\n }\n target.sendMessage(getCurrentStage().startMessage.get());\n }\n\n /**\n * 处理收到的消息。\n *\n * @param bot 机器人对象\n * @param source 消息的源交互对象\n * @param sender 消息的发送者交互对象\n * @param message 收到的消息\n * @param time 时间戳\n */\n public void handleMessage(Bot bot, Interactive source, Interactive sender, Message message, int time) {\n if (stopped) {\n return;\n }\n getCurrentStage().stageExecuter.onMessage(this, bot, source, sender, message, time);\n }\n\n /**\n * 启动对话,运行第一个交互阶段。\n */\n public void start() {\n toStage(0);\n }\n\n /**\n * 停止对话,释放资源。\n */\n public void stop() {\n this.stages = null;\n this.stopped = true;\n SpCoBot.getInstance().chatDispatcher.stopChat(target, type);\n }\n\n private Stage getCurrentStage() {\n return this.stages.get(this.currentStageIndex);\n }\n\n /**\n * 重新运行当前阶段的交互。\n */\n public void replay() {\n runStage();\n }\n\n /**\n * 跳转到指定索引的交互阶段。\n *\n * @param index 要跳转到的阶段索引\n */\n public void toStage(int index) {\n this.currentStageIndex = index;\n runStage();\n }\n\n /**\n * 进入下一个交互阶段,如果已经是最后一个阶段,则停止对话。\n */\n public void next() {\n this.currentStageIndex += 1;\n if (this.currentStageIndex == this.stages.size()) {\n this.stop();\n }\n runStage();\n }\n}"
},
{
"identifier": "Stage",
"path": "src/main/java/top/spco/service/chat/Stage.java",
"snippet": "public class Stage {\n public final Supplier<String> startMessage;\n public final StageExecuter stageExecuter;\n\n public Stage(Supplier<String> startMessage, StageExecuter executer) {\n this.startMessage = startMessage;\n this.stageExecuter = executer;\n }\n\n public interface StageExecuter {\n void onMessage(Chat chat, Bot bot, Interactive source, Interactive sender, Message message, int time);\n }\n}"
},
{
"identifier": "HelpCommand",
"path": "src/main/java/top/spco/service/command/commands/HelpCommand.java",
"snippet": "public final class HelpCommand extends AbstractCommand {\n @Override\n public String[] getLabels() {\n return new String[]{\"help\", \"?\"};\n }\n\n @Override\n public String getDescriptions() {\n return \"获取帮助信息\";\n }\n\n @Override\n public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) {\n StringBuilder sb = new StringBuilder();\n for (String help : SpCoBot.getInstance().getCommandDispatcher().getHelpList()) {\n sb.append(help).append(\"\\n\");\n }\n from.quoteReply(message, sb.toString());\n }\n}"
},
{
"identifier": "BotUser",
"path": "src/main/java/top/spco/user/BotUser.java",
"snippet": "public class BotUser {\n private final long id;\n private UserPermission permission;\n private int smfCoin;\n private String sign;\n private int premium;\n\n BotUser(long id, UserPermission permission, int smfCoin, String sign, int premium) {\n this.id = id;\n this.permission = permission;\n this.smfCoin = smfCoin;\n this.sign = sign;\n this.premium = premium;\n }\n\n public long getId() {\n return id;\n }\n\n public UserPermission getPermission() {\n return permission;\n }\n\n /**\n * 设置用户权限\n *\n * @throws UserOperationException 解封用户失败时抛出此异常\n */\n public void setPermission(UserPermission permission) throws UserOperationException {\n this.permission = permission;\n try {\n SpCoBot.getInstance().getDataBase().update(\"update user set permission=? where id=?\", permission.getLevel(), id);\n } catch (SQLException e) {\n throw new UserOperationException(\"An error occurred while saving data.\", e);\n }\n }\n\n public int getSMFCoin() {\n return smfCoin;\n }\n\n public void setSign(String sign) {\n this.sign = sign;\n }\n\n public String getSign() {\n return sign;\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 BotUser user = (BotUser) o;\n return id == user.id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n\n /**\n * 签到\n *\n * @return 成功时返回签到获得的海绵山币数量, 已签到返回-1\n * @throws UserOperationException 签到失败时抛出此异常\n */\n public int sign() throws UserOperationException {\n try {\n LocalDate today = DateUtils.today();\n String signDate = SpCoBot.getInstance().getDataBase().selectString(\"user\", \"sign\", \"id\", id);\n if (signDate.equals(today.toString())) {\n return -1;\n }\n SpCoBot.getInstance().getDataBase().update(\"update user set sign=? where id=?\", today, id);\n int randomNumber = ThreadLocalRandom.current().nextInt(10, 101);\n this.smfCoin += randomNumber;\n SpCoBot.getInstance().getDataBase().update(\"update user set smf_coin=? where id=?\", this.smfCoin, this.id);\n return randomNumber;\n } catch (SQLException e) {\n throw new UserOperationException(\"An error occurred while reading or saving data.\", e);\n }\n }\n\n /**\n * 解封此用户\n *\n * @throws UserOperationException 解封用户失败时抛出此异常\n */\n public void pardon() throws UserOperationException {\n if (!isBanned()) {\n throw new UserOperationException(\"User(\" + id + \") is not banned.\");\n } else {\n setPermission(UserPermission.NORMAL);\n }\n }\n\n /**\n * 封禁此用户\n *\n * @throws UserOperationException 封禁用户失败时抛出此异常\n */\n public void ban() throws UserOperationException {\n if (isBanned()) {\n throw new UserOperationException(\"User(\" + id + \") has been banned.\");\n } else {\n setPermission(UserPermission.BANNED);\n }\n }\n\n /**\n * 将此用户设置为管理员\n *\n * @throws UserOperationException 提权失败时抛出此异常\n */\n public void promote() throws UserOperationException {\n if (isBanned()) {\n throw new UserOperationException(\"User(\" + id + \") has been banned. Please lift the ban before proceeding with any operations.\");\n } else if (permission.isOperator()) {\n throw new UserOperationException(\"User(\" + id + \") already has operator privileges.\");\n } else {\n setPermission(UserPermission.ADMINISTRATOR);\n }\n }\n\n /**\n * 将管理员用户设置为普通用户\n *\n * @throws UserOperationException 限权失败时抛出此异常\n */\n public void demote() throws UserOperationException {\n if (isBanned()) {\n throw new UserOperationException(\"User(\" + id + \") has been banned. Please lift the ban before proceeding with any operations.\");\n } else if (!permission.isOperator()) {\n throw new UserOperationException(\"User(\" + id + \") does not have operator privileges.\");\n } else {\n setPermission(UserPermission.NORMAL);\n }\n }\n\n /**\n * 检查用户是否被封禁\n *\n * @return 已被封禁时返回 {@code true}\n */\n public boolean isBanned() {\n return permission.isBanned();\n }\n\n /**\n * 判断用户是否为Premium会员。\n *\n * @return 如果用户是Premium会员,返回 true;否则返回 false。\n */\n public boolean isPremium() {\n return premium == 1;\n }\n\n /**\n * 将用户权限转换为 {@link UserPermission}。\n *\n * @return 对应的用户权限\n * @deprecated 请使用 {@link #getPermission()} 替代\n */\n @Deprecated\n public UserPermission toUserPermission() {\n return getPermission();\n }\n\n @Override\n public String toString() {\n return \"QQ: \" + this.id + \"\\n海绵山币: \" + smfCoin + \"\\n会员信息: \" + (isPremium() ? \"Premium会员\" : \"普通会员\") + \"\\n权限信息: \" + permission;\n }\n}"
},
{
"identifier": "UserPermission",
"path": "src/main/java/top/spco/user/UserPermission.java",
"snippet": "public enum UserPermission implements Comparable<UserPermission> {\n /**\n * 被封禁用户<p>ordinal = 0\n */\n BANNED,\n\n /**\n * 普通用户<p>ordinal = 1\n */\n NORMAL,\n\n /**\n * 管理员<p>ordinal = 2\n */\n ADMINISTRATOR,\n\n /**\n * 机器人主人<p>ordinal = 3\n */\n OWNER;\n\n /**\n * 权限等级. {@link #OWNER} 为 3, {@link #ADMINISTRATOR} 为 2, {@link #NORMAL} 为 1, {@link #BANNED} 为 0\n */\n public int getLevel() {\n return ordinal();\n }\n\n /**\n * 判断权限是否为机器人主人\n */\n public boolean isOwner() {\n return this == OWNER;\n }\n\n /**\n * 判断权限是否为管理员\n */\n public boolean isAdministrator() {\n return this == ADMINISTRATOR;\n }\n\n /**\n * 判断权限是否为管理员或机器人主人\n */\n public boolean isOperator() {\n return isAdministrator() || isOwner();\n }\n\n /**\n * 判断权限是否为已被封禁\n */\n public boolean isBanned() {\n return this == BANNED;\n }\n\n public static UserPermission byLevel(int level) {\n switch (level) {\n case 0 -> {\n return BANNED;\n }\n case 1 -> {\n return NORMAL;\n }\n case 2 -> {\n return ADMINISTRATOR;\n }\n case 3 -> {\n return OWNER;\n }\n default -> {\n return null;\n }\n }\n }\n\n @Override\n public String toString() {\n switch (this) {\n case OWNER -> {\n return \"机器人主人\";\n }\n case BANNED -> {\n return \"已封禁用户\";\n }\n case NORMAL -> {\n return \"普通用户\";\n }\n case ADMINISTRATOR -> {\n return \"机器人管理员\";\n }\n }\n return \"其它用户\";\n }\n}"
}
] | import top.spco.api.*;
import top.spco.api.message.Message;
import top.spco.events.CommandEvents;
import top.spco.service.chat.Chat;
import top.spco.service.chat.Stage;
import top.spco.service.command.commands.HelpCommand;
import top.spco.user.BotUser;
import top.spco.user.UserPermission;
import java.sql.SQLException;
import java.util.List; | 5,796 | /*
* Copyright 2023 SpCo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.spco.service.command;
/**
* {@link Command 命令}是一种用户与机器人交互的方式。与{@link Chat 对话}可能有以下不同:
* <ul>
* <li>{@link Chat 对话}传递参数时可以有明确的引导</li>
* <li>{@link Chat 对话}适合传递内容较大的参数</li>
* <li>{@link Chat 对话}每次传递参数都可以对参数进行校验</li>
* <li>{@link Chat 对话}支持传入的参数数量或类型取决于{@link Stage 阶段}的处理流程,而{@link Command 命令}支持传入不限量个参数(至多{@link Integer#MAX_VALUE 2<sup>31</sup>-1}个)</li>
* </ul>
* 这个接口代表一个命令的定义,用于处理用户输入的命令。每个命令都包括{@link #getLabels 标签}、{@link #getDescriptions 描述}、{@link #getScope 作用域}、{@link #needPermission 所需权限}等信息,
* 并提供{@link #init 初始化}和{@link #onCommand 执行命令}的方法。<p>
* <b>不建议命令实现此接口,而是继承 {@link AbstractCommand}类</b>
*
* @author SpCo
* @version 1.1.0
* @see AbstractCommand
* @since 0.1.0
*/
public interface Command {
/**
* 命令的标签(或名称)<p>
* 如命令 {@code "/command arg"} 中,{@code "command"} 就是该命令的标签。<p>
* 命令的标签是一个数组。数组的第一个元素是主标签,其余都是别称。<p>
* 在使用 {@link HelpCommand} 时,会将别称的描述重定向到主标签。<p>
* 如:
* <pre>
* help - 显示帮助信息
* ? -> help
* </pre>
*/
String[] getLabels();
List<CommandUsage> getUsages();
/**
* 命令的描述
*
* @return 命令的描述
*/
String getDescriptions();
/**
* 命令的作用域
*
* @return 命令的作用域
* @see CommandScope
*/
CommandScope getScope();
/**
* 使用命令所需的最低权限等级<p>
* 注意:这里的最低权限指的是{@link BotUser 机器人用户}的{@link UserPermission 用户权限},而不是群聊中{@link Member 群成员}的{@link MemberPermission 成员权限}。
*
* @return 使用命令所需的最低权限等级
* @see UserPermission
*/ | /*
* Copyright 2023 SpCo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.spco.service.command;
/**
* {@link Command 命令}是一种用户与机器人交互的方式。与{@link Chat 对话}可能有以下不同:
* <ul>
* <li>{@link Chat 对话}传递参数时可以有明确的引导</li>
* <li>{@link Chat 对话}适合传递内容较大的参数</li>
* <li>{@link Chat 对话}每次传递参数都可以对参数进行校验</li>
* <li>{@link Chat 对话}支持传入的参数数量或类型取决于{@link Stage 阶段}的处理流程,而{@link Command 命令}支持传入不限量个参数(至多{@link Integer#MAX_VALUE 2<sup>31</sup>-1}个)</li>
* </ul>
* 这个接口代表一个命令的定义,用于处理用户输入的命令。每个命令都包括{@link #getLabels 标签}、{@link #getDescriptions 描述}、{@link #getScope 作用域}、{@link #needPermission 所需权限}等信息,
* 并提供{@link #init 初始化}和{@link #onCommand 执行命令}的方法。<p>
* <b>不建议命令实现此接口,而是继承 {@link AbstractCommand}类</b>
*
* @author SpCo
* @version 1.1.0
* @see AbstractCommand
* @since 0.1.0
*/
public interface Command {
/**
* 命令的标签(或名称)<p>
* 如命令 {@code "/command arg"} 中,{@code "command"} 就是该命令的标签。<p>
* 命令的标签是一个数组。数组的第一个元素是主标签,其余都是别称。<p>
* 在使用 {@link HelpCommand} 时,会将别称的描述重定向到主标签。<p>
* 如:
* <pre>
* help - 显示帮助信息
* ? -> help
* </pre>
*/
String[] getLabels();
List<CommandUsage> getUsages();
/**
* 命令的描述
*
* @return 命令的描述
*/
String getDescriptions();
/**
* 命令的作用域
*
* @return 命令的作用域
* @see CommandScope
*/
CommandScope getScope();
/**
* 使用命令所需的最低权限等级<p>
* 注意:这里的最低权限指的是{@link BotUser 机器人用户}的{@link UserPermission 用户权限},而不是群聊中{@link Member 群成员}的{@link MemberPermission 成员权限}。
*
* @return 使用命令所需的最低权限等级
* @see UserPermission
*/ | UserPermission needPermission(); | 6 | 2023-10-26 10:27:47+00:00 | 8k |
cty1928/GreenTravel | src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/navi/NaviRouteActivity.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": "BaseActivity",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/BaseActivity.java",
"snippet": "public class BaseActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n\n //透明状态栏\n getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n //透明导航栏\n //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n\n// //去掉标题栏\n// this.requestWindowFeature(Window.FEATURE_NO_TITLE);\n// //去掉信息栏\n// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);\n\n super.onCreate(savedInstanceState);\n\n// toggleHideyBar();\n }\n\n public void toggleHideyBar() {\n\n // BEGIN_INCLUDE (get_current_ui_flags)\n // The UI options currently enabled are represented by a bitfield.\n // getSystemUiVisibility() gives us that bitfield.\n int uiOptions = getWindow().getDecorView().getSystemUiVisibility();\n int newUiOptions = uiOptions;\n // END_INCLUDE (get_current_ui_flags)\n // BEGIN_INCLUDE (toggle_ui_flags)\n boolean isImmersiveModeEnabled =\n ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);\n\n // Navigation bar hiding: Backwards compatible to ICS.\n if (Build.VERSION.SDK_INT >= 14) {\n newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;\n }\n\n // Status bar hiding: Backwards compatible to Jellybean\n if (Build.VERSION.SDK_INT >= 16) {\n newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;\n }\n\n // Immersive mode: Backward compatible to KitKat.\n // Note that this flag doesn't do anything by itself, it only augments the behavior\n // of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample\n // all three flags are being toggled together.\n // Note that there are two immersive mode UI flags, one of which is referred to as \"sticky\".\n // Sticky immersive mode differs in that it makes the navigation and status bars\n // semi-transparent, and the UI flag does not get cleared when the user interacts with\n // the screen.\n if (Build.VERSION.SDK_INT >= 18) {\n newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n }\n\n getWindow().getDecorView().setSystemUiVisibility(newUiOptions);\n //END_INCLUDE (set_ui_flags)\n }\n}"
},
{
"identifier": "AnimEndListener",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/anim/AnimEndListener.java",
"snippet": "public interface AnimEndListener {\n\n public void onAnimEnd();\n}"
},
{
"identifier": "ViewAnimUtils",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/anim/ViewAnimUtils.java",
"snippet": "public class ViewAnimUtils {\n\n public static void pushOutWithInterpolator(View view, final AnimEndListener listener) {\n Animation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);\n animation.setDuration(300);\n Interpolator interpolator = AnimationUtils.loadInterpolator(view.getContext().getApplicationContext(), android.R.anim.accelerate_interpolator);\n\n animation.setInterpolator(interpolator);\n if (listener != null) {\n animation.setAnimationListener(new Animation.AnimationListener() {\n @Override\n public void onAnimationStart(Animation animation) {\n\n }\n\n @Override\n public void onAnimationEnd(Animation animation) {\n listener.onAnimEnd();\n }\n\n @Override\n public void onAnimationRepeat(Animation animation) {\n\n }\n });\n }\n view.startAnimation(animation);\n }\n\n public static void dropDownWithInterpolator(View view, final AnimEndListener listener) {\n Animation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);\n animation.setDuration(300);\n Interpolator interpolator = AnimationUtils.loadInterpolator(view.getContext().getApplicationContext(), android.R.anim.accelerate_decelerate_interpolator);\n\n animation.setInterpolator(interpolator);\n if (listener != null) {\n animation.setAnimationListener(new Animation.AnimationListener() {\n @Override\n public void onAnimationStart(Animation animation) {\n\n }\n\n @Override\n public void onAnimationEnd(Animation animation) {\n listener.onAnimEnd();\n }\n\n @Override\n public void onAnimationRepeat(Animation animation) {\n\n }\n });\n }\n view.startAnimation(animation);\n }\n\n\n public static void popupinWithInterpolator(View view, final AnimEndListener listener) {\n Animation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);\n animation.setDuration(300);\n Interpolator interpolator = AnimationUtils.loadInterpolator(view.getContext().getApplicationContext(), android.R.anim.accelerate_decelerate_interpolator);\n\n animation.setInterpolator(interpolator);\n if (listener != null) {\n animation.setAnimationListener(new Animation.AnimationListener() {\n @Override\n public void onAnimationStart(Animation animation) {\n\n }\n\n @Override\n public void onAnimationEnd(Animation animation) {\n listener.onAnimEnd();\n }\n\n @Override\n public void onAnimationRepeat(Animation animation) {\n\n }\n });\n }\n view.startAnimation(animation);\n }\n\n public static void popupoutWithInterpolator(View view, final AnimEndListener listener) {\n Animation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);\n animation.setDuration(300);\n Interpolator interpolator = AnimationUtils.loadInterpolator(view.getContext().getApplicationContext(), android.R.anim.accelerate_interpolator);\n animation.setInterpolator(interpolator);\n if (listener != null){\n animation.setAnimationListener(new Animation.AnimationListener() {\n @Override\n public void onAnimationStart(Animation animation) {\n\n }\n\n @Override\n public void onAnimationEnd(Animation animation) {\n listener.onAnimEnd();\n }\n\n @Override\n public void onAnimationRepeat(Animation animation) {\n\n }\n });\n }\n\n view.startAnimation(animation);\n }\n\n}"
},
{
"identifier": "MapsMainActivity",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/maps/MapsMainActivity.java",
"snippet": "public class MapsMainActivity extends BaseActivity implements MapsFragment.OnFragmentInteractionListener,\n LeftDrawerFragment.OnFragmentInteractionListener {\n\n private DrawerLayout mDrawerLayout;\n private DrawerStateListener mDrawerStateListener;\n private boolean mIsDrawerClicked = false;\n private int mDrawerClickedId = -1;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_maps_drawer);\n\n mDrawerStateListener = getMapsFragment();\n\n mDrawerLayout = (DrawerLayout) findViewById(R.id.maps_drawer_layout);\n\n mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {\n @Override\n public void onDrawerSlide(View drawerView, float slideOffset) {\n if (mDrawerStateListener != null) {\n mDrawerStateListener.onDrawerSlide(drawerView, slideOffset);\n }\n }\n\n @Override\n public void onDrawerOpened(View drawerView) {\n if (mDrawerStateListener != null) {\n mDrawerStateListener.onDrawerOpened(drawerView);\n }\n }\n\n @Override\n public void onDrawerClosed(View drawerView) {\n if (mIsDrawerClicked){\n if (mDrawerClickedId == R.id.leftDrawerOfflineBtn){\n Intent intent = new Intent(MapsMainActivity.this, OfflineMapActivity.class);\n startActivity(intent);\n\n } else if (mDrawerClickedId == R.id.left_drawer_setting){\n Intent intent = new Intent(MapsMainActivity.this, SettingActivity.class);\n startActivity(intent);\n } else if (mDrawerClickedId == R.id.leftDrawerAbout){\n Intent intent = new Intent(MapsMainActivity.this, AboutActivity.class);\n startActivity(intent);\n } else{\n getMapsFragment().onLeftDrawerViewClick(mDrawerClickedId);\n }\n mDrawerClickedId = -1;\n mIsDrawerClicked = false;\n }else {\n if (mDrawerStateListener != null) {\n mDrawerStateListener.onDrawerClosed(drawerView);\n }\n }\n }\n\n @Override\n public void onDrawerStateChanged(int newState) {\n if (mDrawerStateListener != null) {\n mDrawerStateListener.onDrawerStateChanged(newState);\n }\n }\n });\n\n\n if (savedInstanceState == null) {\n FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n ft.replace(R.id.center_frame_layout, getMapsFragment(), MapsFragment.class.getName());\n ft.replace(R.id.left_drawer_layout, getLeftDrawerFragment(), LeftDrawerFragment.class.getName());\n ft.commit();\n }\n\n }\n\n public void openLeftDrawer() {\n mDrawerLayout.openDrawer(Gravity.LEFT);\n }\n\n public void closeLeftDrawer() {\n mDrawerLayout.closeDrawer(Gravity.RIGHT);\n }\n\n private MapsFragment getMapsFragment() {\n MapsFragment mapsFragment = (MapsFragment) getSupportFragmentManager().findFragmentByTag(MapsFragment.class.getName());\n if (mapsFragment == null) {\n mapsFragment = new MapsFragment();\n }\n return mapsFragment;\n }\n\n private LeftDrawerFragment getLeftDrawerFragment() {\n LeftDrawerFragment leftDrawerFragment = (LeftDrawerFragment) getSupportFragmentManager().findFragmentByTag(LeftDrawerFragment.class.getName());\n if (leftDrawerFragment == null) {\n leftDrawerFragment = new LeftDrawerFragment();\n }\n return leftDrawerFragment;\n }\n\n\n @Override\n public void onBackPressed() {\n if (getMapsFragment().isInSearch()) {\n getMapsFragment().exitSearch();\n } else {\n super.onBackPressed();\n }\n }\n\n @Override\n public void onFragmentInteraction(int id) {\n mIsDrawerClicked = true;\n mDrawerClickedId = id;\n mDrawerLayout.closeDrawer(GravityCompat.START);\n }\n\n @Override\n public void onFragmentInteraction(Uri uri) {\n\n }\n}"
},
{
"identifier": "TTSController",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/module/TTSController.java",
"snippet": "public class TTSController implements SynthesizerListener, AMapNaviListener {\n\n\tpublic static TTSController ttsManager;\n\tprivate Context mContext;\n\t// 合成对象.\n\tprivate SpeechSynthesizer mSpeechSynthesizer;\n\n\tTTSController(Context context) {\n\t\tmContext = context;\n\t}\n\n\tpublic static TTSController getInstance(Context context) {\n\t\tif (ttsManager == null) {\n\t\t\tttsManager = new TTSController(context);\n\t\t}\n\t\treturn ttsManager;\n\t}\n\n\tpublic void init() {\n//\t\tSpeechUser.getUser().login(mContext, null, null,\n//\t\t\t\t\"appid=\" + mContext.getString(R.string.app_id), listener);\n\t\tSpeechUtility.createUtility(mContext, SpeechConstant.APPID + \"=55bc62c7\");\n\n\t\t// 初始化合成对象.\n\t\tmSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext, null);\n\t\tinitSpeechSynthesizer();\n\t}\n\n\t/**\n\t * 使用SpeechSynthesizer合成语音,不弹出合成Dialog.\n\t * \n\t * @param\n\t */\n\tpublic void playText(String playText) {\n\t\tif (!isfinish) {\n\t\t\treturn;\n\t\t}\n\t\tif (null == mSpeechSynthesizer) {\n\t\t\t// 创建合成对象.\n\t\t\tmSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext, null);\n\t\t\tinitSpeechSynthesizer();\n\t\t}\n\t\t// 进行语音合成.\n\t\tmSpeechSynthesizer.startSpeaking(playText, this);\n\n\t}\n\n\tpublic void stopSpeaking() {\n\t\tif (mSpeechSynthesizer != null)\n\t\t\tmSpeechSynthesizer.stopSpeaking();\n\t}\n\tpublic void startSpeaking() {\n\t\t isfinish=true;\n\t}\n\n\tprivate void initSpeechSynthesizer() {\n\t\t// 设置发音人\n\t\tmSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME,\n\t\t\t\tmContext.getString(R.string.preference_default_tts_role));\n\t\t// 设置语速\n\t\tmSpeechSynthesizer.setParameter(SpeechConstant.SPEED,\n\t\t\t\t\"\" + mContext.getString(R.string.preference_key_tts_speed));\n\t\t// 设置音量\n\t\tmSpeechSynthesizer.setParameter(SpeechConstant.VOLUME,\n\t\t\t\t\"\" + mContext.getString(R.string.preference_key_tts_volume));\n\t\t// 设置语调\n\t\tmSpeechSynthesizer.setParameter(SpeechConstant.PITCH,\n\t\t\t\t\"\" + mContext.getString(R.string.preference_key_tts_pitch));\n\n\t}\n\n\t/**\n\t * 用户登录回调监听器.\n\t */\n\tprivate SpeechListener listener = new SpeechListener() {\n\n\t\t@Override\n\t\tpublic void onCompleted(SpeechError error) {\n\t\t\tif (error != null) {\n\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onEvent(int arg0, Bundle arg1) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void onBufferReceived(byte[] bytes) {\n\n\t\t}\n\t};\n\n\t@Override\n\tpublic void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onEvent(int i, int i1, int i2, Bundle bundle) {\n\n\t}\n\n\t@Override\n\tpublic void onSpeakBegin() {\n\t\t// TODO Auto-generated method stub\n\t\tisfinish = false;\n\n\t}\n\n\t@Override\n\tpublic void onSpeakPaused() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onSpeakProgress(int arg0, int arg1, int arg2) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tboolean isfinish = true;\n\t@Override\n\tpublic void onCompleted(SpeechError speechError) {\n\t\tisfinish = true;\n\t}\n\n\t@Override\n\tpublic void onSpeakResumed() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tpublic void destroy() {\n\t\tif (mSpeechSynthesizer != null) {\n\t\t\tmSpeechSynthesizer.stopSpeaking();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onArriveDestination() {\n\t\t// TODO Auto-generated method stub\n\t\tthis.playText(\"到达目的地\");\n\t}\n\n\t@Override\n\tpublic void onArrivedWayPoint(int arg0) {\n\t\t// TODO Auto-generated method stub\n\t}\n\n\t@Override\n\tpublic void onCalculateRouteFailure(int arg0) {\n\t\t this.playText(\"路径计算失败,请检查网络或输入参数\");\n\t}\n\n\t@Override\n\tpublic void onCalculateRouteSuccess() {\n\t\tString calculateResult = \"路径计算就绪\";\n\n\t\tthis.playText(calculateResult);\n\t}\n\n\t@Override\n\tpublic void onEndEmulatorNavi() {\n\t\tthis.playText(\"导航结束\");\n\n\t}\n\n\t@Override\n\tpublic void onGetNavigationText(int arg0, String arg1) {\n\t\t// TODO Auto-generated method stub\n\t\tthis.playText(arg1);\n\t}\n\n\t@Override\n\tpublic void onInitNaviFailure() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onInitNaviSuccess() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onLocationChange(AMapNaviLocation arg0) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onReCalculateRouteForTrafficJam() {\n\t\t// TODO Auto-generated method stub\n\t\tthis.playText(\"前方路线拥堵,路线重新规划\");\n\t}\n\n\t@Override\n\tpublic void onReCalculateRouteForYaw() {\n\n\t\tthis.playText(\"您已偏航\");\n\t}\n\n\t@Override\n\tpublic void onStartNavi(int arg0) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onTrafficStatusUpdate() {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onGpsOpenStatus(boolean arg0) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\t@Override\n\tpublic void onNaviInfoUpdated(AMapNaviInfo arg0) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic void onNaviInfoUpdate(NaviInfo arg0) {\n\t\t \n\t\t// TODO Auto-generated method stub \n\t\t\n\t}\n}"
},
{
"identifier": "MarkerInteractor",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/presenters/MarkerInteractor.java",
"snippet": "public interface MarkerInteractor {\n\n interface OnMarkerCreatedListener {\n void onMarkerCreated(ArrayList<MarkerOptions> markerOptions);\n }\n\n\n interface OnReadCamerasListener {\n void onReadCameras(ArrayList<BJCamera> cameraBeans);\n }\n\n void createMarkers(OnMarkerCreatedListener listener);\n\n void readCameras(OnReadCamerasListener listener);\n\n}"
},
{
"identifier": "MarkerInteractorImpl",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/presenters/MarkerInteractorImpl.java",
"snippet": "public class MarkerInteractorImpl implements MarkerInteractor {\n\n private BitmapDescriptor mMarkerDesc = BitmapDescriptorFactory.fromResource(R.drawable.icon_camera_location);\n @Override\n public void createMarkers(OnMarkerCreatedListener listener) {\n if (null != listener){\n listener.onMarkerCreated(createMarkerOptions());\n }\n }\n\n @Override\n public void readCameras(OnReadCamerasListener listener) {\n if (listener != null) {\n listener.onReadCameras(readCameras());\n }\n }\n\n private ArrayList<MarkerOptions> createMarkerOptions(){\n ArrayList<MarkerOptions> markerOptions = new ArrayList<>();\n ArrayList<BJCamera> cameraBeans = readCameras();\n for (BJCamera cameraBean : cameraBeans) {\n LatLng latLng = new LatLng(cameraBean.getLatitude(), cameraBean.getLongtitude());\n MarkerOptions mo = new MarkerOptions().position(latLng).draggable(true).icon(mMarkerDesc);\n markerOptions.add(mo);\n }\n return markerOptions;\n }\n\n private ArrayList<BJCamera> readCameras(){\n return (ArrayList<BJCamera>) MapsApplication.getDaoSession().loadAll(BJCamera.class);\n }\n\n}"
},
{
"identifier": "SettingUtils",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/utils/SettingUtils.java",
"snippet": "public class SettingUtils {\n\n private static final String MYLOCATION_KEY = \"location_mode\";\n private static final String MAPS_STYLE_KEY = \"maps_style_key\";\n private static final String JING_CAMERA = \"jing_camera\";\n public static int SWITCH_ON = 1;\n public static int SWITCH_OFF = 0;\n\n public static int readCurrentMyLocationMode() {\n return FileUtils.readIntFromSharedPreference(MYLOCATION_KEY, AMap.LOCATION_TYPE_MAP_FOLLOW);\n }\n\n public static void writeCurrentMyLocationMode(int mode) {\n FileUtils.writeIntToSharedPreference(MYLOCATION_KEY, mode);\n }\n\n public static int readCurrentMapsStyle() {\n return FileUtils.readIntFromSharedPreference(MAPS_STYLE_KEY, AMap.MAP_TYPE_NORMAL);\n }\n\n public static void writeCurrentMapsStyle(int style) {\n FileUtils.writeIntToSharedPreference(MAPS_STYLE_KEY, style);\n }\n\n public static int readCurrentCameraState() {\n return FileUtils.readIntFromSharedPreference(JING_CAMERA, SWITCH_OFF);\n }\n\n public static void writeCurrentCameraState(int state) {\n FileUtils.writeIntToSharedPreference(JING_CAMERA, state);\n }\n\n\n private static SharedPreferences sPref = MapsApplication.getAppContext().getSharedPreferences(MapsApplication.getAppContext().getPackageName() + \"_preferences\", Context.MODE_PRIVATE);\n public static final String SETTING_PREF_JING_CAMERA = \"setting_pref_jing_camera\";\n public static final String SETTING_PREF_JING_CAMERA_ALERT = \"setting_pref_jing_camera_alert\";\n\n public static boolean isEnableBeijingCamera(){\n return sPref.getBoolean(SETTING_PREF_JING_CAMERA, true);\n }\n\n public static boolean isEnableBeijingCameraAlert(){\n return sPref.getBoolean(SETTING_PREF_JING_CAMERA_ALERT, true);\n }\n\n\n}"
},
{
"identifier": "Utils",
"path": "src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/utils/Utils.java",
"snippet": "public class Utils {\npublic static final String DAY_NIGHT_MODE=\"daynightmode\";\npublic static final String DEVIATION=\"deviationrecalculation\";\npublic static final String JAM=\"jamrecalculation\";\npublic static final String TRAFFIC=\"trafficbroadcast\";\npublic static final String CAMERA=\"camerabroadcast\";\npublic static final String SCREEN=\"screenon\";\npublic static final String THEME=\"theme\";\npublic static final String ISEMULATOR=\"isemulator\";\n\n\npublic static final String ACTIVITYINDEX=\"activityindex\";\n\npublic static final int SIMPLEHUDNAVIE=0;\npublic static final int EMULATORNAVI=1;\npublic static final int SIMPLEGPSNAVI=2;\npublic static final int SIMPLEROUTENAVI=3;\n\n\npublic static final boolean DAY_MODE=false;\npublic static final boolean NIGHT_MODE=true;\npublic static final boolean YES_MODE=true;\npublic static final boolean NO_MODE=false;\npublic static final boolean OPEN_MODE=true;\npublic static final boolean CLOSE_MODE=false;\n\n\n\n\n}"
}
] | import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import org.zarroboogs.maps.beans.BJCamera;
import org.zarroboogs.maps.ui.BaseActivity;
import org.zarroboogs.maps.ui.anim.AnimEndListener;
import org.zarroboogs.maps.ui.anim.ViewAnimUtils;
import org.zarroboogs.maps.ui.maps.MapsMainActivity;
import org.zarroboogs.maps.R;
import org.zarroboogs.maps.module.TTSController;
import org.zarroboogs.maps.presenters.MarkerInteractor;
import org.zarroboogs.maps.presenters.MarkerInteractorImpl;
import org.zarroboogs.maps.utils.SettingUtils;
import org.zarroboogs.maps.utils.Utils;
import java.util.ArrayList;
import java.util.List; | 6,710 | package org.zarroboogs.maps.ui.navi;
/**
* 路径规划结果展示界面
*/
public class NaviRouteActivity extends BaseActivity implements OnClickListener,
OnMapLoadedListener{
// View
private ImageButton mStartNaviButton;// 实时导航按钮
private MapView mMapView;// 地图控件
private ImageView mRouteBackView;// 返回按钮
private TextView mRouteDistanceView;// 距离显示控件
private TextView mRouteTimeView;// 时间显示控件
private TextView mRouteCostView;// 花费显示控件
private ListView mRoutSettingListView;
private TextView mShowRoutType;
// 地图导航资源
private AMap mAmap;
private AMapNavi mAmapNavi;
private RouteOverLay mRouteOverLay;
private boolean mIsMapLoaded = false;
private List<NaviLatLng> mEndNavi;
private List<NaviLatLng> mStartNavi;
public static final String NAVI_ENDS = "navi_ends";
public static final String NAVI_START = "navi_start";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
mEndNavi = getIntent().getParcelableArrayListExtra(NAVI_ENDS);
mStartNavi = getIntent().getParcelableArrayListExtra(NAVI_START);
Log.d("NaviRouteActivity ", "onCreate- " + mEndNavi.get(0).getLatitude());
initView(savedInstanceState);
mAmapNavi = AMapNavi.getInstance(this);
mAmapNavi.setAMapNaviListener(naviRouteListener);
boolean startGps = mAmapNavi.startGPS();
Log.d("NaviRouteActivity ", "onCreate- startGps- " + startGps);
boolean iscalDrive = mAmapNavi.calculateDriveRoute(mStartNavi, mEndNavi, null, AMapNavi.DrivingDefault);
Log.d("NaviRouteActivity ", "onCreate- calculateDriveRoute- " + iscalDrive);
if (SettingUtils.readCurrentCameraState() == SettingUtils.SWITCH_ON){ | package org.zarroboogs.maps.ui.navi;
/**
* 路径规划结果展示界面
*/
public class NaviRouteActivity extends BaseActivity implements OnClickListener,
OnMapLoadedListener{
// View
private ImageButton mStartNaviButton;// 实时导航按钮
private MapView mMapView;// 地图控件
private ImageView mRouteBackView;// 返回按钮
private TextView mRouteDistanceView;// 距离显示控件
private TextView mRouteTimeView;// 时间显示控件
private TextView mRouteCostView;// 花费显示控件
private ListView mRoutSettingListView;
private TextView mShowRoutType;
// 地图导航资源
private AMap mAmap;
private AMapNavi mAmapNavi;
private RouteOverLay mRouteOverLay;
private boolean mIsMapLoaded = false;
private List<NaviLatLng> mEndNavi;
private List<NaviLatLng> mStartNavi;
public static final String NAVI_ENDS = "navi_ends";
public static final String NAVI_START = "navi_start";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
mEndNavi = getIntent().getParcelableArrayListExtra(NAVI_ENDS);
mStartNavi = getIntent().getParcelableArrayListExtra(NAVI_START);
Log.d("NaviRouteActivity ", "onCreate- " + mEndNavi.get(0).getLatitude());
initView(savedInstanceState);
mAmapNavi = AMapNavi.getInstance(this);
mAmapNavi.setAMapNaviListener(naviRouteListener);
boolean startGps = mAmapNavi.startGPS();
Log.d("NaviRouteActivity ", "onCreate- startGps- " + startGps);
boolean iscalDrive = mAmapNavi.calculateDriveRoute(mStartNavi, mEndNavi, null, AMapNavi.DrivingDefault);
Log.d("NaviRouteActivity ", "onCreate- calculateDriveRoute- " + iscalDrive);
if (SettingUtils.readCurrentCameraState() == SettingUtils.SWITCH_ON){ | MarkerInteractor markerInteractor = new MarkerInteractorImpl(); | 6 | 2023-10-31 01:21:54+00:00 | 8k |
zxzf1234/jimmer-ruoyivuepro | backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/convert/infra/oauth2/OAuth2OpenConvert.java | [
{
"identifier": "KeyValue",
"path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/core/KeyValue.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class KeyValue<K, V> {\n\n private K key;\n private V value;\n\n}"
},
{
"identifier": "UserTypeEnum",
"path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/UserTypeEnum.java",
"snippet": "@AllArgsConstructor\n@Getter\npublic enum UserTypeEnum implements IntArrayValuable {\n\n MEMBER(1, \"会员\"), // 面向 c 端,普通用户\n ADMIN(2, \"管理员\"); // 面向 b 端,管理后台\n\n public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(UserTypeEnum::getValue).toArray();\n\n /**\n * 类型\n */\n private final Integer value;\n /**\n * 类型名\n */\n private final String name;\n\n public static UserTypeEnum valueOf(Integer value) {\n return ArrayUtil.firstMatch(userType -> userType.getValue().equals(value), UserTypeEnum.values());\n }\n\n @Override\n public int[] array() {\n return ARRAYS;\n }\n}"
},
{
"identifier": "CollectionUtils",
"path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/collection/CollectionUtils.java",
"snippet": "public class CollectionUtils {\n\n public static boolean containsAny(Object source, Object... targets) {\n return Arrays.asList(targets).contains(source);\n }\n\n public static boolean isAnyEmpty(Collection<?>... collections) {\n return Arrays.stream(collections).anyMatch(CollectionUtil::isEmpty);\n }\n\n public static <T> List<T> filterList(Collection<T> from, Predicate<T> predicate) {\n if (CollUtil.isEmpty(from)) {\n return new ArrayList<>();\n }\n return from.stream().filter(predicate).collect(Collectors.toList());\n }\n\n public static <T, R> List<T> distinct(Collection<T> from, Function<T, R> keyMapper) {\n if (CollUtil.isEmpty(from)) {\n return new ArrayList<>();\n }\n return distinct(from, keyMapper, (t1, t2) -> t1);\n }\n\n public static <T, R> List<T> distinct(Collection<T> from, Function<T, R> keyMapper, BinaryOperator<T> cover) {\n if (CollUtil.isEmpty(from)) {\n return new ArrayList<>();\n }\n return new ArrayList<>(convertMap(from, keyMapper, Function.identity(), cover).values());\n }\n\n public static <T, U> List<U> convertList(Collection<T> from, Function<T, U> func) {\n if (CollUtil.isEmpty(from)) {\n return new ArrayList<>();\n }\n return from.stream().map(func).filter(Objects::nonNull).collect(Collectors.toList());\n }\n\n public static <T, U> List<U> convertList(Collection<T> from, Function<T, U> func, Predicate<T> filter) {\n if (CollUtil.isEmpty(from)) {\n return new ArrayList<>();\n }\n return from.stream().filter(filter).map(func).filter(Objects::nonNull).collect(Collectors.toList());\n }\n\n public static <T, U> Set<U> convertSet(Collection<T> from, Function<T, U> func) {\n if (CollUtil.isEmpty(from)) {\n return new HashSet<>();\n }\n return from.stream().map(func).filter(Objects::nonNull).collect(Collectors.toSet());\n }\n\n public static <T, U> Set<U> convertSet(Collection<T> from, Function<T, U> func, Predicate<T> filter) {\n if (CollUtil.isEmpty(from)) {\n return new HashSet<>();\n }\n return from.stream().filter(filter).map(func).filter(Objects::nonNull).collect(Collectors.toSet());\n }\n\n public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return convertMap(from, keyFunc, Function.identity());\n }\n\n public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc, Supplier<? extends Map<K, T>> supplier) {\n if (CollUtil.isEmpty(from)) {\n return supplier.get();\n }\n return convertMap(from, keyFunc, Function.identity(), supplier);\n }\n\n public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return convertMap(from, keyFunc, valueFunc, (v1, v2) -> v1);\n }\n\n public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, BinaryOperator<V> mergeFunction) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return convertMap(from, keyFunc, valueFunc, mergeFunction, HashMap::new);\n }\n\n public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, Supplier<? extends Map<K, V>> supplier) {\n if (CollUtil.isEmpty(from)) {\n return supplier.get();\n }\n return convertMap(from, keyFunc, valueFunc, (v1, v2) -> v1, supplier);\n }\n\n public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, BinaryOperator<V> mergeFunction, Supplier<? extends Map<K, V>> supplier) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return from.stream().collect(Collectors.toMap(keyFunc, valueFunc, mergeFunction, supplier));\n }\n\n public static <T, K> Map<K, List<T>> convertMultiMap(Collection<T> from, Function<T, K> keyFunc) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return from.stream().collect(Collectors.groupingBy(keyFunc, Collectors.mapping(t -> t, Collectors.toList())));\n }\n\n public static <T, K, V> Map<K, List<V>> convertMultiMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return from.stream()\n .collect(Collectors.groupingBy(keyFunc, Collectors.mapping(valueFunc, Collectors.toList())));\n }\n\n // 暂时没想好名字,先以 2 结尾噶\n public static <T, K, V> Map<K, Set<V>> convertMultiMap2(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {\n if (CollUtil.isEmpty(from)) {\n return new HashMap<>();\n }\n return from.stream().collect(Collectors.groupingBy(keyFunc, Collectors.mapping(valueFunc, Collectors.toSet())));\n }\n\n public static <T, K> Map<K, T> convertImmutableMap(Collection<T> from, Function<T, K> keyFunc) {\n if (CollUtil.isEmpty(from)) {\n return Collections.emptyMap();\n }\n ImmutableMap.Builder<K, T> builder = ImmutableMap.builder();\n from.forEach(item -> builder.put(keyFunc.apply(item), item));\n return builder.build();\n }\n\n public static boolean containsAny(Collection<?> source, Collection<?> candidates) {\n return org.springframework.util.CollectionUtils.containsAny(source, candidates);\n }\n\n public static <T> T getFirst(List<T> from) {\n return !CollectionUtil.isEmpty(from) ? from.get(0) : null;\n }\n\n public static <T> T findFirst(List<T> from, Predicate<T> predicate) {\n if (CollUtil.isEmpty(from)) {\n return null;\n }\n return from.stream().filter(predicate).findFirst().orElse(null);\n }\n\n public static <T, V extends Comparable<? super V>> V getMaxValue(List<T> from, Function<T, V> valueFunc) {\n if (CollUtil.isEmpty(from)) {\n return null;\n }\n assert from.size() > 0; // 断言,避免告警\n T t = from.stream().max(Comparator.comparing(valueFunc)).get();\n return valueFunc.apply(t);\n }\n\n public static <T, V extends Comparable<? super V>> V getMinValue(List<T> from, Function<T, V> valueFunc) {\n if (CollUtil.isEmpty(from)) {\n return null;\n }\n assert from.size() > 0; // 断言,避免告警\n T t = from.stream().min(Comparator.comparing(valueFunc)).get();\n return valueFunc.apply(t);\n }\n\n public static <T, V extends Comparable<? super V>> V getSumValue(List<T> from, Function<T, V> valueFunc, BinaryOperator<V> accumulator) {\n if (CollUtil.isEmpty(from)) {\n return null;\n }\n assert from.size() > 0; // 断言,避免告警\n return from.stream().map(valueFunc).reduce(accumulator).get();\n }\n\n public static <T> void addIfNotNull(Collection<T> coll, T item) {\n if (item == null) {\n return;\n }\n coll.add(item);\n }\n\n public static <T> Collection<T> singleton(T deptId) {\n return deptId == null ? Collections.emptyList() : Collections.singleton(deptId);\n }\n\n}"
},
{
"identifier": "SecurityFrameworkUtils",
"path": "backend/yudao-framework/yudao-spring-boot-starter-security/src/main/java/cn/iocoder/yudao/framework/security/core/util/SecurityFrameworkUtils.java",
"snippet": "public class SecurityFrameworkUtils {\n\n public static final String AUTHORIZATION_BEARER = \"Bearer\";\n\n private SecurityFrameworkUtils() {}\n\n /**\n * 从请求中,获得认证 Token\n *\n * @param request 请求\n * @param header 认证 Token 对应的 Header 名字\n * @return 认证 Token\n */\n public static String obtainAuthorization(HttpServletRequest request, String header) {\n String authorization = request.getHeader(header);\n if (!StringUtils.hasText(authorization)) {\n return null;\n }\n int index = authorization.indexOf(AUTHORIZATION_BEARER + \" \");\n if (index == -1) { // 未找到\n return null;\n }\n return authorization.substring(index + 7).trim();\n }\n\n /**\n * 获得当前认证信息\n *\n * @return 认证信息\n */\n public static Authentication getAuthentication() {\n SecurityContext context = SecurityContextHolder.getContext();\n if (context == null) {\n return null;\n }\n return context.getAuthentication();\n }\n\n /**\n * 获取当前用户\n *\n * @return 当前用户\n */\n @Nullable\n public static LoginUser getLoginUser() {\n Authentication authentication = getAuthentication();\n if (authentication == null) {\n return null;\n }\n return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;\n }\n\n /**\n * 获得当前用户的编号,从上下文中\n *\n * @return 用户编号\n */\n @Nullable\n public static Long getLoginUserId() {\n LoginUser loginUser = getLoginUser();\n return loginUser != null ? loginUser.getId() : null;\n }\n\n /**\n * 设置当前用户\n *\n * @param loginUser 登录用户\n * @param request 请求\n */\n public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {\n // 创建 Authentication,并设置到上下文\n Authentication authentication = buildAuthentication(loginUser, request);\n SecurityContextHolder.getContext().setAuthentication(authentication);\n\n // 额外设置到 request 中,用于 ApiAccessLogFilter 可以获取到用户编号;\n // 原因是,Spring Security 的 Filter 在 ApiAccessLogFilter 后面,在它记录访问日志时,线上上下文已经没有用户编号等信息\n WebFrameworkUtils.setLoginUserId(request, loginUser.getId());\n WebFrameworkUtils.setLoginUserType(request, loginUser.getUserType());\n }\n\n private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {\n // 创建 UsernamePasswordAuthenticationToken 对象\n UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(\n loginUser, null, Collections.emptyList());\n authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));\n return authenticationToken;\n }\n\n}"
},
{
"identifier": "OAuth2OpenAccessTokenRespVO",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/oauth2/open/OAuth2OpenAccessTokenRespVO.java",
"snippet": "@Schema(description = \"管理后台 - 【开放接口】访问令牌 Response VO\")\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class OAuth2OpenAccessTokenRespVO {\n\n @Schema(description = \"访问令牌\", required = true, example = \"tudou\")\n @JsonProperty(\"access_token\")\n private String accessToken;\n\n @Schema(description = \"刷新令牌\", required = true, example = \"nice\")\n @JsonProperty(\"refresh_token\")\n private String refreshToken;\n\n @Schema(description = \"令牌类型\", required = true, example = \"bearer\")\n @JsonProperty(\"token_type\")\n private String tokenType;\n\n @Schema(description = \"过期时间,单位:秒\", required = true, example = \"42430\")\n @JsonProperty(\"expires_in\")\n private Long expiresIn;\n\n @Schema(description = \"授权范围,如果多个授权范围,使用空格分隔\", example = \"user_info\")\n private String scope;\n\n}"
},
{
"identifier": "OAuth2OpenAuthorizeInfoRespVO",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/oauth2/open/OAuth2OpenAuthorizeInfoRespVO.java",
"snippet": "@Schema(description = \"管理后台 - 授权页的信息 Response VO\")\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class OAuth2OpenAuthorizeInfoRespVO {\n\n /**\n * 客户端\n */\n private Client client;\n\n @Schema(description = \"scope 的选中信息,使用 List 保证有序性,Key 是 scope,Value 为是否选中\", required = true)\n private List<KeyValue<String, Boolean>> scopes;\n\n @Data\n @NoArgsConstructor\n @AllArgsConstructor\n public static class Client {\n\n @Schema(description = \"应用名\", required = true, example = \"土豆\")\n private String name;\n\n @Schema(description = \"应用图标\", required = true, example = \"https://www.iocoder.cn/xx.png\")\n private String logo;\n\n }\n\n}"
},
{
"identifier": "OAuth2OpenCheckTokenRespVO",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/vo/infra/oauth2/open/OAuth2OpenCheckTokenRespVO.java",
"snippet": "@Schema(description = \"管理后台 - 【开放接口】校验令牌 Response VO\")\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class OAuth2OpenCheckTokenRespVO {\n\n @Schema(description = \"用户编号\", required = true, example = \"666\")\n @JsonProperty(\"user_id\")\n private Long userId;\n @Schema(description = \"用户类型,参见 UserTypeEnum 枚举\", required = true, example = \"2\")\n @JsonProperty(\"user_type\")\n private Integer userType;\n\n @Schema(description = \"客户端编号\", required = true, example = \"car\")\n @JsonProperty(\"client_id\")\n private String clientId;\n @Schema(description = \"授权范围\", required = true, example = \"user_info\")\n private List<String> scopes;\n\n @Schema(description = \"访问令牌\", required = true, example = \"tudou\")\n @JsonProperty(\"access_token\")\n private String accessToken;\n\n @Schema(description = \"过期时间,时间戳 / 1000,即单位:秒\", required = true, example = \"1593092157\")\n private Long exp;\n\n}"
},
{
"identifier": "SystemOauth2AccessToken",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/model/infra/oauth2/SystemOauth2AccessToken.java",
"snippet": "@Entity\n@Table(name=\"system_oauth2_access_token\")\npublic interface SystemOauth2AccessToken extends BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n long id();\n\n long userId();\n\n int userType();\n\n String accessToken();\n\n String refreshToken();\n\n\n String clientId();\n\n @Nullable\n @Serialized\n List<String> scopes();\n\n LocalDateTime expiresTime();\n\n}"
},
{
"identifier": "SystemOauth2Approve",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/model/infra/oauth2/SystemOauth2Approve.java",
"snippet": "@Entity\n@Table(name=\"system_oauth2_approve\")\npublic interface SystemOauth2Approve extends BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n long id();\n\n long userId();\n\n int userType();\n\n String clientId();\n\n String scope();\n\n boolean approved();\n\n LocalDateTime expiresTime();\n\n}"
},
{
"identifier": "SystemOauth2Client",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/model/infra/oauth2/SystemOauth2Client.java",
"snippet": "@Entity\n@Table(name=\"system_oauth2_client\")\npublic interface SystemOauth2Client extends BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n long id();\n\n String clientId();\n\n String secret();\n\n String name();\n\n @Nullable\n String logo();\n\n @Nullable\n String description();\n\n int status();\n\n int accessTokenValiditySeconds();\n\n int refreshTokenValiditySeconds();\n\n @Serialized\n List<String> redirectUris();\n\n @Serialized\n List<String> authorizedGrantTypes();\n\n @Nullable\n @Serialized\n List<String> scopes();\n\n @Nullable\n @Serialized\n List<String> autoApproveScopes();\n\n @Nullable\n @Serialized\n List<String> authorities();\n\n @Nullable\n @Serialized\n List<String> resourceIds();\n\n @Nullable\n String additionalInformation();\n\n}"
},
{
"identifier": "OAuth2Utils",
"path": "backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/util/oauth2/OAuth2Utils.java",
"snippet": "public class OAuth2Utils {\n\n /**\n * 构建授权码模式下,重定向的 URI\n *\n * copy from Spring Security OAuth2 的 AuthorizationEndpoint 类的 getSuccessfulRedirect 方法\n *\n * @param redirectUri 重定向 URI\n * @param authorizationCode 授权码\n * @param state 状态\n * @return 授权码模式下的重定向 URI\n */\n public static String buildAuthorizationCodeRedirectUri(String redirectUri, String authorizationCode, String state) {\n Map<String, String> query = new LinkedHashMap<>();\n query.put(\"code\", authorizationCode);\n if (state != null) {\n query.put(\"state\", state);\n }\n return HttpUtils.append(redirectUri, query, null, false);\n }\n\n /**\n * 构建简化模式下,重定向的 URI\n *\n * copy from Spring Security OAuth2 的 AuthorizationEndpoint 类的 appendAccessToken 方法\n *\n * @param redirectUri 重定向 URI\n * @param accessToken 访问令牌\n * @param state 状态\n * @param expireTime 过期时间\n * @param scopes 授权范围\n * @param additionalInformation 附加信息\n * @return 简化授权模式下的重定向 URI\n */\n public static String buildImplicitRedirectUri(String redirectUri, String accessToken, String state, LocalDateTime expireTime,\n Collection<String> scopes, Map<String, Object> additionalInformation) {\n Map<String, Object> vars = new LinkedHashMap<String, Object>();\n Map<String, String> keys = new HashMap<String, String>();\n vars.put(\"access_token\", accessToken);\n vars.put(\"token_type\", SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());\n if (state != null) {\n vars.put(\"state\", state);\n }\n if (expireTime != null) {\n vars.put(\"expires_in\", getExpiresIn(expireTime));\n }\n if (CollUtil.isNotEmpty(scopes)) {\n vars.put(\"scope\", buildScopeStr(scopes));\n }\n if (CollUtil.isNotEmpty(additionalInformation)) {\n for (String key : additionalInformation.keySet()) {\n Object value = additionalInformation.get(key);\n if (value != null) {\n keys.put(\"extra_\" + key, key);\n vars.put(\"extra_\" + key, value);\n }\n }\n }\n // Do not include the refresh token (even if there is one)\n return HttpUtils.append(redirectUri, vars, keys, true);\n }\n\n public static String buildUnsuccessfulRedirect(String redirectUri, String responseType, String state,\n String error, String description) {\n Map<String, String> query = new LinkedHashMap<String, String>();\n query.put(\"error\", error);\n query.put(\"error_description\", description);\n if (state != null) {\n query.put(\"state\", state);\n }\n return HttpUtils.append(redirectUri, query, null, !responseType.contains(\"code\"));\n }\n\n public static long getExpiresIn(LocalDateTime expireTime) {\n return LocalDateTimeUtil.between(LocalDateTime.now(), expireTime, ChronoUnit.SECONDS);\n }\n\n public static String buildScopeStr(Collection<String> scopes) {\n return CollUtil.join(scopes, \" \");\n }\n\n public static List<String> buildScopes(String scope) {\n return StrUtil.split(scope, ' ');\n }\n\n}"
}
] | import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenAccessTokenRespVO;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenAuthorizeInfoRespVO;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenCheckTokenRespVO;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2AccessToken;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2Approve;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2Client;
import cn.iocoder.yudao.service.util.oauth2.OAuth2Utils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | 5,967 | package cn.iocoder.yudao.service.convert.infra.oauth2;
@Mapper
public interface OAuth2OpenConvert {
OAuth2OpenConvert INSTANCE = Mappers.getMapper(OAuth2OpenConvert.class);
default OAuth2OpenAccessTokenRespVO convert(SystemOauth2AccessToken bean) {
OAuth2OpenAccessTokenRespVO respVO = convert0(bean);
respVO.setTokenType(SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());
respVO.setExpiresIn(OAuth2Utils.getExpiresIn(bean.expiresTime()));
respVO.setScope(OAuth2Utils.buildScopeStr(bean.scopes()));
return respVO;
}
OAuth2OpenAccessTokenRespVO convert0(SystemOauth2AccessToken bean);
default OAuth2OpenCheckTokenRespVO convert2(SystemOauth2AccessToken bean) {
OAuth2OpenCheckTokenRespVO respVO = convert3(bean);
respVO.setExp(LocalDateTimeUtil.toEpochMilli(bean.expiresTime()) / 1000L);
respVO.setUserType(UserTypeEnum.ADMIN.getValue());
return respVO;
}
OAuth2OpenCheckTokenRespVO convert3(SystemOauth2AccessToken bean);
default OAuth2OpenAuthorizeInfoRespVO convert(SystemOauth2Client client, List<SystemOauth2Approve> approves) {
// 构建 scopes
List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.scopes().size()); | package cn.iocoder.yudao.service.convert.infra.oauth2;
@Mapper
public interface OAuth2OpenConvert {
OAuth2OpenConvert INSTANCE = Mappers.getMapper(OAuth2OpenConvert.class);
default OAuth2OpenAccessTokenRespVO convert(SystemOauth2AccessToken bean) {
OAuth2OpenAccessTokenRespVO respVO = convert0(bean);
respVO.setTokenType(SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());
respVO.setExpiresIn(OAuth2Utils.getExpiresIn(bean.expiresTime()));
respVO.setScope(OAuth2Utils.buildScopeStr(bean.scopes()));
return respVO;
}
OAuth2OpenAccessTokenRespVO convert0(SystemOauth2AccessToken bean);
default OAuth2OpenCheckTokenRespVO convert2(SystemOauth2AccessToken bean) {
OAuth2OpenCheckTokenRespVO respVO = convert3(bean);
respVO.setExp(LocalDateTimeUtil.toEpochMilli(bean.expiresTime()) / 1000L);
respVO.setUserType(UserTypeEnum.ADMIN.getValue());
return respVO;
}
OAuth2OpenCheckTokenRespVO convert3(SystemOauth2AccessToken bean);
default OAuth2OpenAuthorizeInfoRespVO convert(SystemOauth2Client client, List<SystemOauth2Approve> approves) {
// 构建 scopes
List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.scopes().size()); | Map<String, SystemOauth2Approve> approveMap = CollectionUtils.convertMap(approves, SystemOauth2Approve::scope); | 2 | 2023-10-27 06:35:24+00:00 | 8k |
matheusmisumoto/workout-logger-api | src/main/java/dev/matheusmisumoto/workoutloggerapi/controller/WorkoutController.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": "Exercise",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/model/Exercise.java",
"snippet": "@Entity\r\n@Table(name = \"exercises\")\r\npublic class Exercise extends RepresentationModel<Exercise> 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\t\r\n\tprivate String name;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate ExerciseTargetType target;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate ExerciseEquipmentType equipment;\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 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 getTarget() {\r\n\t\treturn target.getDescription();\r\n\t}\r\n\tpublic void setTarget(ExerciseTargetType target) {\r\n\t\tthis.target = target;\r\n\t}\r\n\tpublic String getEquipment() {\r\n\t\treturn equipment.getDescription();\r\n\t}\r\n\tpublic void setEquipment(ExerciseEquipmentType equipment) {\r\n\t\tthis.equipment = equipment;\r\n\t}\r\n\r\n}\r"
},
{
"identifier": "User",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/model/User.java",
"snippet": "@Entity\r\n@Table(name = \"users\")\r\npublic class User implements UserDetails {\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\tprivate String name;\r\n\tprivate String login;\r\n\tprivate int oauthId;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate OAuthProviderType oauthProvider;\r\n\r\n\tprivate String avatarUrl;\r\n\tprivate String password;\r\n\t\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate UserRoleType role;\r\n\t\r\n\t@JsonFormat(pattern = \"dd/MM/yyyy HH:mm:ss\")\r\n\tprivate LocalDateTime joinedAt;\r\n\t\r\n\t@OneToMany(mappedBy=\"user\", cascade=CascadeType.ALL, orphanRemoval=true)\r\n\tprivate List<Workout> workout;\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 String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic String getLogin() {\r\n\t\treturn login;\r\n\t}\r\n\r\n\tpublic void setLogin(String login) {\r\n\t\tthis.login = login;\r\n\t}\r\n\r\n\tpublic int getOauthId() {\r\n\t\treturn oauthId;\r\n\t}\r\n\r\n\tpublic void setOauthId(int oauthId) {\r\n\t\tthis.oauthId = oauthId;\r\n\t}\r\n\r\n\tpublic OAuthProviderType getOauthProvider() {\r\n\t\treturn oauthProvider;\r\n\t}\r\n\r\n\tpublic void setOauthProvider(OAuthProviderType oauthProvider) {\r\n\t\tthis.oauthProvider = oauthProvider;\r\n\t}\r\n\r\n\tpublic String getAvatarUrl() {\r\n\t\treturn avatarUrl;\r\n\t}\r\n\r\n\tpublic void setAvatarUrl(String avatarUrl) {\r\n\t\tthis.avatarUrl = avatarUrl;\r\n\t}\r\n\r\n\tpublic void setPassword(String password) {\r\n\t\tthis.password = password;\r\n\t}\r\n\r\n\tpublic void setRole(UserRoleType role) {\r\n\t\tthis.role = role;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\r\n\t\tif(this.role == UserRoleType.ADMIN) return List.of(new SimpleGrantedAuthority(\"ROLE_ADMIN\"), new SimpleGrantedAuthority(\"ROLE_MEMBER\"), new SimpleGrantedAuthority(\"ROLE_DEMO\"));\r\n\t\tif(this.role == UserRoleType.MEMBER) return List.of(new SimpleGrantedAuthority(\"ROLE_MEMBER\"), new SimpleGrantedAuthority(\"ROLE_DEMO\"));\r\n\t\telse return List.of(new SimpleGrantedAuthority(\"ROLE_DEMO\"));\r\n\t\t\r\n\t}\r\n\r\n\tpublic LocalDateTime getJoinedAt() {\r\n\t\treturn joinedAt;\r\n\t}\r\n\r\n\tpublic void setJoinedAt(LocalDateTime joinedAt) {\r\n\t\tthis.joinedAt = joinedAt;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getPassword() {\r\n\t\treturn password;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getUsername() {\r\n\t\treturn login;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isAccountNonExpired() {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isAccountNonLocked() {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isCredentialsNonExpired() {\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isEnabled() {\r\n\t\treturn true;\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": "UserRepository",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/repository/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User, UUID> {\r\n\t\r\n\tOptional<User> findByOauthId(int oauthId);\r\n\t\r\n\t@Query(value = \"SELECT COUNT(*) FROM workouts w INNER JOIN users u ON w.user_id = u.id WHERE w.user_id = ?1\", nativeQuery = true)\r\n\tint totalWorkouts(UUID userId);\r\n\t\r\n\t@Query(value = \"SELECT SUM(s.weight * s.reps) FROM workouts_sets s INNER JOIN workouts w ON w.id = s.workout_id WHERE w.user_id = ?1 GROUP BY w.user_id\", nativeQuery = true)\r\n\tDouble calculateUserTotalWeightLifted(UUID userId);\r\n\t\r\n\tUserDetails findByLogin(String login);\r\n}\r"
},
{
"identifier": "WorkoutRepository",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/repository/WorkoutRepository.java",
"snippet": "@Repository\r\npublic interface WorkoutRepository extends JpaRepository<Workout, UUID> {\r\n\t\r\n\tOptional<Workout> findByIdAndUser(UUID id, User user);\r\n\tList<Workout> findTop10ByUserOrderByDateDesc(User user);\r\n\tList<Workout> findAllByUserOrderByDateDesc(User user);\r\n\t\r\n\t@Query(value = \"SELECT b.* FROM workouts b JOIN workouts_sets c ON b.id = c.workout_id \"\r\n\t\t\t+ \"WHERE c.exercise_id = ?2 \"\r\n\t\t\t+ \"AND b.user_id = ?1 \"\r\n\t\t\t+ \"GROUP BY b.id \"\r\n\t\t\t+ \"ORDER BY b.date DESC \"\r\n\t\t\t+ \"LIMIT 6\", nativeQuery = true)\r\n\tList<Workout> findLatestWorkoutsWithExercise(UUID userid, UUID exerciseid);\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": "JWTService",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/security/JWTService.java",
"snippet": "@Service\r\npublic class JWTService {\r\n\t\r\n\t@Value(\"${api.secret.token.secret}\")\r\n\tprivate String secret;\r\n\t\r\n\t// Using standards claims described on\r\n\t// https://www.iana.org/assignments/jwt/jwt.xhtml\r\n\t\r\n\tpublic String generateToken(User user) {\r\n\t\ttry {\r\n\t\t\tAlgorithm algorithm = Algorithm.HMAC256(secret);\r\n\t\t\t\t\t\t\r\n\t\t\tString token = JWT.create()\r\n\t\t\t\t\t.withIssuer(\"FitLogr\")\r\n\t\t\t\t\t.withClaim(\"name\", user.getName())\r\n\t\t\t\t\t.withClaim(\"picture\", user.getAvatarUrl())\r\n\t\t\t\t\t.withClaim(\"roles\", user.getAuthorities().toArray()[0].toString())\r\n\t\t\t\t\t.withSubject(user.getId().toString())\r\n\t\t\t\t\t.withExpiresAt(\r\n\t\t\t\t\t\t\tLocalDateTime.now().plusWeeks(1).toInstant(ZoneOffset.UTC)\r\n\t\t\t\t\t)\r\n\t\t\t\t\t.sign(algorithm);\r\n\r\n\t\t\treturn token;\r\n\t\t} catch (JWTCreationException exception) {\r\n\t\t\tthrow new RuntimeException(\"Error while generating token\", exception);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic String validateToken(String token) {\r\n\t\ttry {\r\n\t\t\tAlgorithm algorithm = Algorithm.HMAC256(secret);\r\n\t\t\treturn JWT.require(algorithm)\r\n\t\t\t\t\t.withIssuer(\"FitLogr\")\r\n\t\t\t\t\t.build()\r\n\t\t\t\t\t.verify(token)\r\n\t\t\t\t\t.getSubject();\r\n\t\t} catch (JWTCreationException exception) {\r\n\t\t\tthrow new RuntimeException(\"Error while validating token\", exception);\r\n\t\t}\r\n\t}\r\n\r\n}\r"
},
{
"identifier": "WorkoutStatusType",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/type/WorkoutStatusType.java",
"snippet": "public enum WorkoutStatusType {\r\n\tTEMPLATE, IN_PROGRESS, COMPLETED;\r\n\t\r\n\tprivate WorkoutStatusType() {\r\n\t}\r\n\t\r\n\tpublic static WorkoutStatusType valueOfDescription(String description) {\r\n\t\tfor (WorkoutStatusType status : WorkoutStatusType.values()) {\r\n\t\t\tif (status.toString().equalsIgnoreCase(description)) {\r\n\t\t\t\treturn status;\r\n\t }\r\n\t }\r\n\t throw new IllegalArgumentException(\"No matching WorkoutStatusType for description: \" + description);\r\n\t}\r\n}\r"
},
{
"identifier": "WorkoutUtil",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/util/WorkoutUtil.java",
"snippet": "public class WorkoutUtil {\r\n\t\r\n\tpublic void recordSets(ExerciseRepository exerciseRepository, \r\n\t\t\t\t\t\t WorkoutSetRepository workoutSetRepository,\r\n\t\t\t\t\t\t Workout workout,\r\n\t\t\t\t\t\t WorkoutRecordDTO workoutRecordDTO) {\r\n\t\tif(!workoutRecordDTO.exercises().isEmpty()) {\r\n\t\t\t// The order of the exercises will be based on the order given by JSON\t\t\t\r\n\t\t\tint exerciseIndex = 1;\r\n\t\t\tfor (WorkoutExerciseRecordDTO exercise : workoutRecordDTO.exercises()) {\r\n\t\t\t\t// Get the exercise object based on the ID\r\n\t\t\t\tvar exerciseId = exerciseRepository.findById(exercise.id()).get();\r\n\t\t\t\t// The order of the sets will be based on the order given by JSON\r\n\t\t\t\tint setIndex = 1;\r\n\t\t\t\tfor (WorkoutSetRecordDTO set : exercise.sets()) {\r\n\t\t\t\t\tvar workoutSet = new WorkoutSet();\r\n\t\t\t\t\tworkoutSet.setWorkout(workout);\r\n\t\t\t\t\tworkoutSet.setExercise(exerciseId);\r\n\t\t\t\t\tworkoutSet.setExerciseOrder(exerciseIndex);\r\n\t\t\t\t\tworkoutSet.setSetOrder(setIndex++);\r\n\t\t\t\t\tworkoutSet.setType(WorkoutSetType.valueOfDescription(set.type()));\r\n\t\t\t\t\tBeanUtils.copyProperties(set, workoutSet);\r\n\t\t\t\t\tworkoutSetRepository.save(workoutSet);\r\n\t\t\t\t}\r\n\t\t\t\texerciseIndex++;\r\n\t\t\t}\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic WorkoutShowDTO buildWorkoutJSON(Optional<Workout> workout, WorkoutSetRepository workoutSetRepository) {\r\n\t\t// Get the training metadata\r\n\t\tvar workoutData = workout.get();\r\n\t\t\t\t\t\r\n\t\t// Get the list of exercises done, already considering the order\r\n\t\tvar exercisesData = workoutSetRepository.findExercisesFromWorkout(workoutData);\r\n\t\tvar totalLifted = workoutSetRepository.calculateTotalWeightLifted(workoutData);\r\n\t\tvar totalLiftedRounded = 0;\r\n\t\tif(totalLifted != null) { \r\n\t\t\ttotalLiftedRounded = (int) Math.round(totalLifted);\r\n\t\t}\r\n\t\t\t\t\r\n\t\t// From that, get the details of the exercise, and the sets data considering the order\r\n\t\t// Attach the list of sets on the exercise \r\n\t\tList<WorkoutExerciseShowDTO> exercises = exercisesData.stream()\r\n\t\t\t\t.map(exercise -> {\r\n\t\t\t\t\tvar setsData = workoutSetRepository.findByWorkoutAndExerciseOrderBySetOrderAsc(workout.get(), exercise);\r\n\t\t\t\t\tList<WorkoutSetShowDTO> sets = setsData.stream()\r\n\t\t\t\t\t\t\t.map(set -> {\r\n\t\t\t\t\t\t\t\tWorkoutSetShowDTO setDTO = new WorkoutSetShowDTO(\r\n\t\t\t\t\t\t\t\t\t\tset.getType(),\r\n\t\t\t\t\t\t\t\t\t\tset.getWeight(),\r\n\t\t\t\t\t\t\t\t\t\tset.getReps()\r\n\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\treturn setDTO;\r\n\t\t\t\t\t\t\t}).collect(Collectors.toList());\r\n\t\t\t\r\n\t\t\t\t\tWorkoutExerciseShowDTO exerciseDTO = new WorkoutExerciseShowDTO(\r\n\t\t\t\t\t\t\texercise.getId(),\r\n\t\t\t\t\t\t\texercise.getName(),\r\n\t\t\t\t\t\t\texercise.getTarget(),\r\n\t\t\t\t\t\t\texercise.getEquipment(),\r\n\t\t\t\t\t\t\tsets\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\treturn exerciseDTO;\r\n\t\t\t\t\t}\r\n\t\t\t\t).collect(Collectors.toList());;\r\n\t\t\r\n\t\t// Attach the list of exercises on the workout that will be returned as JSON\r\n\t\treturn new WorkoutShowDTO(\r\n\t\t\t\t\tworkoutData.getId(),\r\n\t\t\t\t\tworkoutData.getUser().getId(),\r\n\t\t\t\t\tworkoutData.getDate(),\r\n\t\t\t\t\tworkoutData.getName(),\r\n\t\t\t\t\tworkoutData.getComment(),\r\n\t\t\t\t\tworkoutData.getDuration(),\r\n\t\t\t\t\ttotalLiftedRounded,\r\n\t\t\t\t\tworkoutData.getStatus(),\r\n\t\t\t\t\texercises\r\n\t\t\t\t);\r\n\t}\r\n\t\r\n\tpublic WorkoutShortShowDTO buildWorkoutCardJSON(Workout workout, WorkoutSetRepository workoutSetRepository) {\r\n\t\t\t\t\t\r\n\t\t// Get the total of exercises and weight lifted\r\n\t\tvar totalLifted = workoutSetRepository.calculateTotalWeightLifted(workout);\r\n\t\tvar totalLiftedRounded = 0;\r\n\t\tif(totalLifted != null) { \r\n\t\t\ttotalLiftedRounded = (int) Math.round(totalLifted);\r\n\t\t}\r\n\t\t\r\n\t\tvar totalExercises = workoutSetRepository.calculateTotalExercises(workout);\r\n\t\tvar getTargetMuscles = workoutSetRepository.listTargetMuscles(workout.getId());\r\n\t\tList<String> listTargetMuscles = getTargetMuscles.stream()\r\n\t\t\t\t\t\t\t\t\t\t\t.map(muscle -> {\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn muscle.getDescription();\r\n\t\t\t\t\t\t\t\t\t\t\t}).collect(Collectors.toList());\r\n\t\t\r\n\t\t\t\t\t\t\t\r\n\t\treturn new WorkoutShortShowDTO(\r\n\t\t\t\t\tworkout.getId(),\r\n\t\t\t\t\tworkout.getUser().getId(),\r\n\t\t\t\t\tworkout.getDate(),\r\n\t\t\t\t\tworkout.getName(),\r\n\t\t\t\t\tworkout.getComment(),\r\n\t\t\t\t\tworkout.getDuration(),\r\n\t\t\t\t\tlistTargetMuscles,\r\n\t\t\t\t\ttotalLiftedRounded,\r\n\t\t\t\t\ttotalExercises\r\n\t\t\t\t);\r\n\t}\r\n}\r"
}
] | import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dev.matheusmisumoto.workoutloggerapi.dto.PreviousStatsDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.PreviousStatsWorkoutsDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutRecordDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutSetShowDTO;
import dev.matheusmisumoto.workoutloggerapi.model.Workout;
import dev.matheusmisumoto.workoutloggerapi.model.Exercise;
import dev.matheusmisumoto.workoutloggerapi.model.User;
import dev.matheusmisumoto.workoutloggerapi.repository.ExerciseRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.UserRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.WorkoutRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.WorkoutSetRepository;
import dev.matheusmisumoto.workoutloggerapi.security.JWTService;
import dev.matheusmisumoto.workoutloggerapi.type.WorkoutStatusType;
import dev.matheusmisumoto.workoutloggerapi.util.WorkoutUtil;
import jakarta.servlet.http.HttpServletRequest;
| 4,568 | package dev.matheusmisumoto.workoutloggerapi.controller;
@RestController
@RequestMapping("/v1/workouts")
public class WorkoutController {
@Autowired
WorkoutRepository workoutRepository;
@Autowired
ExerciseRepository exerciseRepository;
@Autowired
WorkoutSetRepository workoutSetRepository;
@Autowired
UserRepository userRepository;
@Autowired
JWTService jwtService;
@PostMapping
public ResponseEntity<Object> saveWorkout(HttpServletRequest request,
@RequestBody WorkoutRecordDTO workoutRecordDTO) {
// Retrieve logged user ID from JWT
var token = request.getHeader("Authorization").replace("Bearer ", "");
var loggedUserId = UUID.fromString(jwtService.validateToken(token));
// Save metadata
| package dev.matheusmisumoto.workoutloggerapi.controller;
@RestController
@RequestMapping("/v1/workouts")
public class WorkoutController {
@Autowired
WorkoutRepository workoutRepository;
@Autowired
ExerciseRepository exerciseRepository;
@Autowired
WorkoutSetRepository workoutSetRepository;
@Autowired
UserRepository userRepository;
@Autowired
JWTService jwtService;
@PostMapping
public ResponseEntity<Object> saveWorkout(HttpServletRequest request,
@RequestBody WorkoutRecordDTO workoutRecordDTO) {
// Retrieve logged user ID from JWT
var token = request.getHeader("Authorization").replace("Bearer ", "");
var loggedUserId = UUID.fromString(jwtService.validateToken(token));
// Save metadata
| var workout = new Workout();
| 0 | 2023-10-29 23:18:38+00:00 | 8k |
jaszlo/Playerautoma | src/main/java/net/jasper/mod/util/keybinds/Constants.java | [
{
"identifier": "PlayerRecorder",
"path": "src/main/java/net/jasper/mod/automation/PlayerRecorder.java",
"snippet": "public class PlayerRecorder {\n\n private static final Logger LOGGER = PlayerAutomaClient.LOGGER;\n\n public static Recording record = new Recording();\n\n public static State state = IDLE;\n\n // Will execute one task per tick\n public static final TaskQueue tasks = new TaskQueue(TaskQueue.MEDIUM_PRIORITY);\n\n // Gets set in mixin SlotClickedCallback. Should only every contain one item. Else user made more than 50 clicks per second ???\n // Is used to handle asynchronous nature of slot clicks\n public static Queue<SlotClick> lastSlotClicked = new ConcurrentLinkedDeque<>();\n\n public static void registerInputRecorder() {\n // Register Task-Queues\n tasks.register(\"playerActions\");\n\n ClientTickEvents.END_CLIENT_TICK.register(client -> {\n // Check if recording is possible\n if (!state.isRecording() || client.player == null) {\n return;\n }\n\n // Create current KeyMap (Map of which keys to pressed state)\n List<Boolean> currentKeyMap = new ArrayList<>();\n for (KeyBinding k : client.options.allKeys) {\n currentKeyMap.add(k.isPressed());\n }\n\n // Create a new RecordEntry and add it to the record\n Recording.RecordEntry newEntry = new Recording.RecordEntry(\n currentKeyMap,\n new LookingDirection(client.player.getYaw(), client.player.getPitch()),\n client.player.getInventory().selectedSlot,\n lastSlotClicked.poll(),\n client.currentScreen == null ? null : client.currentScreen.getClass()\n );\n record.add(newEntry);\n });\n }\n\n public static void startRecord() {\n if (state.isAny(RECORDING, REPLAYING)) {\n return;\n }\n PlayerController.writeToChat(\"Started Recording\");\n clearRecord();\n PlayerController.centerPlayer();\n lastSlotClicked.clear();\n state = RECORDING;\n }\n\n public static void stopRecord() {\n if (state.isRecording()) {\n PlayerController.writeToChat(\"Stopped Recording\");\n state = IDLE;\n LOGGER.info(\"new record of size: \" + record.entries.size());\n }\n }\n\n public static void clearRecord() {\n record.clear();\n }\n\n public static void startReplay() {\n if (state.isAny(RECORDING, REPLAYING) || record.isEmpty()) {\n return;\n }\n state = state.isLooping() ? LOOPING : REPLAYING;\n if (state.isReplaying()) PlayerController.writeToChat(\"Started Replay\");\n\n PlayerController.centerPlayer();\n MinecraftClient client = MinecraftClient.getInstance();\n assert client.player != null;\n\n for (Recording.RecordEntry entry : record.entries) {\n // Get all data for current record tick (i) to replay\n List<Boolean> keyMap = entry.keysPressed();\n LookingDirection currentLookingDirection = entry.lookingDirection();\n int selectedSlot = entry.slotSelection();\n SlotClick clickedSlot = entry.slotClicked();\n Class<?> currentScreen = entry.currentScreen();\n\n // Replay Ticks\n tasks.add(() -> {\n\n // Update looking direction\n client.player.setPitch(currentLookingDirection.pitch());\n client.player.setYaw(currentLookingDirection.yaw());\n\n // Update selected inventory slot\n client.player.getInventory().selectedSlot = selectedSlot;\n\n // Update keys pressed\n int j = 0;\n for (KeyBinding k : client.options.allKeys) {\n k.setPressed(keyMap.get(j++));\n }\n\n\n // Close screen if needed\n if (client.currentScreen != null && currentScreen == null) {\n client.currentScreen.close();\n client.setScreen(null);\n }\n\n // Inventory is not opened via Keybinding therefore open manually if needed\n if (client.currentScreen == null && currentScreen == InventoryScreen.class) {\n client.setScreen(new InventoryScreen(client.player));\n }\n\n // Click Slot in inventory if possible\n if (clickedSlot != null) PlayerController.clickSlot(clickedSlot);\n });\n }\n\n if (!state.isLooping()) {\n // Finish Replay if not looping\n tasks.add(() -> {\n state = IDLE;\n PlayerController.writeToChat(\"Replay Done\");\n });\n }\n\n if (state.isLooping()) {\n // Replay Again (Looping)\n tasks.add(PlayerRecorder::startReplay);\n }\n }\n\n public static void startLoop() {\n if (state.isAny(RECORDING, REPLAYING) || record.isEmpty()) {\n return;\n }\n PlayerController.writeToChat(\"Started Looped Replay\");\n state = LOOPING;\n startReplay();\n }\n\n public static void stopReplay() {\n // Only stop replay if replaying or looping\n if (!state.isReplaying() && !state.isLooping()) {\n return;\n }\n PlayerController.writeToChat(\"Stopped Replay\");\n\n state = IDLE;\n\n // Clear all tasks to stop replay\n tasks.clear();\n InventoryAutomation.inventoryTasks.clear();\n\n // Toggle of all keys to stop player from doing anything\n for (KeyBinding k : MinecraftClient.getInstance().options.allKeys) {\n k.setPressed(false);\n }\n }\n\n public static void storeRecord(String name) {\n if (record.isEmpty()) {\n PlayerController.writeToChat(\"Cannot store empty recording\");\n return;\n } else if (state.isAny(RECORDING, REPLAYING)) {\n PlayerController.writeToChat(\"Cannot store recording while recording or replaying\");\n return;\n }\n\n File selected = null;\n ObjectOutputStream objectOutputStream = null;\n String basePath = MinecraftClient.getInstance().runDirectory.getAbsolutePath() + \"/recordings/\";\n try {\n // If file already exists create new file with \"_new\" before file type.\n selected = new File(basePath + name);\n String newName = name.substring(0, name.length() - 4) + \"_new.rec\";\n if (selected.exists()) {\n selected = new File(basePath + newName);\n }\n objectOutputStream = new ObjectOutputStream(new FileOutputStream(selected));\n if (objectOutputStream == null) throw new IOException(\"objectInputStream is null\");\n objectOutputStream.writeObject(record);\n objectOutputStream.close();\n PlayerController.writeToChat(\"Stored Recording\");\n } catch(IOException e) {\n e.printStackTrace();\n try {\n if (objectOutputStream != null) objectOutputStream.close();\n LOGGER.info(\"Deletion of failed file: \" + selected.delete());\n } catch (IOException closeFailed) {\n closeFailed.printStackTrace();\n LOGGER.warn(\"Error closing file in error handling!\"); // This should not happen :(\n }\n PlayerController.writeToChat(\"Failed to store recording\");\n LOGGER.info(\"Failed to create output stream for selected file\");\n }\n }\n\n\n public static void loadRecord(File selected) {\n if (state.isAny(RECORDING, REPLAYING)) {\n PlayerController.writeToChat(\"Cannot load recording while recording or replaying\");\n return;\n }\n ObjectInputStream objectInputStream = null;\n try {\n objectInputStream = new ObjectInputStream(new FileInputStream(selected));\n // This can happen when a file is selected and then deleted via the file explorer\n if (objectInputStream == null) throw new IOException(\"objectInputStream is null\");\n record = (Recording) objectInputStream.readObject();\n objectInputStream.close();\n PlayerController.writeToChat(\"Loaded Recording\");\n } catch (Exception e) {\n e.printStackTrace();\n try {\n if (objectInputStream != null) objectInputStream.close();\n } catch (IOException closeFailed) {\n closeFailed.printStackTrace();\n LOGGER.warn(\"Error closing file in error handling!\"); // This should not happen :(\n }\n PlayerController.writeToChat(\"Invalid file\");\n }\n }\n\n 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 }\n}"
},
{
"identifier": "PlayerAutomaMenu",
"path": "src/main/java/net/jasper/mod/gui/PlayerAutomaMenu.java",
"snippet": "public class PlayerAutomaMenu extends Screen {\n\n public static PlayerAutomaMenu SINGLETON = new PlayerAutomaMenu(\"PlayerAutomaMenu\");\n private static boolean isOpen = false;\n\n public PlayerAutomaMenu(String title) {\n super(Text.literal(title));\n }\n private static final int BUTTON_WIDTH = 200;\n private static final int BUTTON_HEIGHT = 20;\n\n // Player Recorder\n public static class Buttons {\n // Player Recorder\n public static ButtonWidget START_RECORDING;\n public static ButtonWidget STOP_RECORDING;\n public static ButtonWidget START_REPLAY;\n public static ButtonWidget STOP_REPLAY;\n public static ButtonWidget START_LOOP;\n public static ButtonWidget STORE_RECORDING;\n public static ButtonWidget LOAD_RECORDING;\n public static ButtonWidget CANCEL_REPLAY;\n\n }\n\n public static void open() {\n if (!isOpen && !handled) {\n MinecraftClient.getInstance().setScreen(SINGLETON);\n\n isOpen = !isOpen;\n }\n\n handled = false;\n }\n\n private static boolean handled = false;\n @Override\n public boolean keyPressed(int keyCode, int scanCode, int modifiers) {\n if (keyCode == InputUtil.GLFW_KEY_O) {\n handled = true;\n SINGLETON.close();\n }\n\n return super.keyPressed(keyCode, scanCode, modifiers);\n }\n\n @Override\n public boolean shouldPause() {\n return false;\n }\n\n @Override\n public void close() {\n isOpen = false;\n MinecraftClient client = MinecraftClient.getInstance();\n client.setScreen(null);\n client.mouse.lockCursor();\n }\n\n @Override\n protected void init() {\n Buttons.START_RECORDING = ButtonWidget.builder(Text.literal(\"Start Recording\"), button -> {\n SINGLETON.close();\n PlayerRecorder.startRecord();\n })\n .dimensions(width / 2 - 205, 20, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Start Recording your movement and close the Menu\")))\n .build();\n\n Buttons.STOP_RECORDING = ButtonWidget.builder(Text.literal(\"Stop Recording\"), button -> {\n SINGLETON.close();\n PlayerRecorder.stopRecord();\n })\n .dimensions(width / 2 + 5, 20, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Stop Recording your movements and close the Menu\")))\n .build();\n\n Buttons.START_REPLAY = ButtonWidget.builder(Text.literal(\"Start Replay\"), button -> {\n SINGLETON.close();\n PlayerRecorder.startReplay();\n })\n .dimensions(width / 2 - 205, 45, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Start Replaying your recorded movements and close the Menu\")))\n .build();\n\n Buttons.STOP_REPLAY = ButtonWidget.builder(Text.literal(\"Stop Replay\"), button -> {\n SINGLETON.close();\n PlayerRecorder.stopReplay();\n\n })\n .dimensions(width / 2 + 5, 45, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Start Replaying your recorded movements and close the Menu\")))\n .build();\n\n Buttons.START_LOOP = ButtonWidget.builder(Text.literal(\"Start Looping Replay\"), button -> {\n SINGLETON.close();\n PlayerRecorder.startLoop();\n })\n .dimensions(width / 2 - 205, 70, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Start Looping your recorded movements and close the Menu\")))\n .build();\n\n Buttons.CANCEL_REPLAY = ButtonWidget.builder(Text.literal(\"Cancel Replay\"), button -> {\n SINGLETON.close();\n PlayerRecorder.stopReplay();\n })\n .dimensions(width / 2 + 5, 70, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Cancel Replaying your recorded movements and close the Menu\")))\n .build();\n\n Buttons.STORE_RECORDING = ButtonWidget.builder(Text.literal(\"Store Record To File\"), button -> {\n SINGLETON.close();\n RecordingStorer.open();\n })\n .dimensions(width / 2 - 205, 95, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Stores your Recording to a .rec file on your Hard Drive\")))\n .build();\n\n Buttons.LOAD_RECORDING = ButtonWidget.builder(Text.literal(\"Load Record From File\"), button -> {\n SINGLETON.close();\n RecordingSelector.open();\n })\n .dimensions(width / 2 + 5, 95, BUTTON_WIDTH, BUTTON_HEIGHT)\n .tooltip(Tooltip.of(Text.literal(\"Loads a Record From a .rec file from your Hard Drive\")))\n .build();\n\n this.addDrawableChild(Buttons.START_RECORDING);\n this.addDrawableChild(Buttons.STOP_RECORDING);\n this.addDrawableChild(Buttons.START_REPLAY);\n this.addDrawableChild(Buttons.STOP_REPLAY);\n this.addDrawableChild(Buttons.START_LOOP);\n this.addDrawableChild(Buttons.CANCEL_REPLAY);\n this.addDrawableChild(Buttons.STORE_RECORDING);\n this.addDrawableChild(Buttons.LOAD_RECORDING);\n }\n}"
},
{
"identifier": "RecordingSelector",
"path": "src/main/java/net/jasper/mod/gui/RecordingSelector.java",
"snippet": "public class RecordingSelector extends Screen {\n\n private RecordingSelectionListWidget recordingSelectionList;\n private final String directoryPath;\n\n // Should no longer use a singleton when used in general\n public static final RecordingSelector SINGLETON = new RecordingSelector(\"Select a Recording\", PlayerAutomaClient.RECORDING_PATH);\n public static boolean isOpen;\n\n public RecordingSelector(String title, String directoryPath) {\n super(Text.of(title));\n this.directoryPath = directoryPath;\n isOpen = false;\n this.init();\n }\n\n public static void open() {\n if (!isOpen) {\n SINGLETON.recordingSelectionList.updateFiles();\n MinecraftClient.getInstance().setScreen(SINGLETON);\n isOpen = !isOpen;\n }\n }\n\n @Override\n public void close() {\n isOpen = false;\n MinecraftClient client = MinecraftClient.getInstance();\n client.setScreen(null);\n client.mouse.lockCursor();\n }\n\n protected void init() {\n this.recordingSelectionList = new RecordingSelectionListWidget(MinecraftClient.getInstance(), this.directoryPath);\n this.addSelectableChild(this.recordingSelectionList);\n\n // Button placement:\n // [Delete] [Open Recording Folder] [Done]\n\n this.addDrawableChild(ButtonWidget.builder(\n Text.of(\"Delete\"),\n (button) -> this.onDelete()\n )\n .dimensions(this.width / 2 - 65 - 140, this.height - 38, 130, 20)\n .build());\n\n this.addDrawableChild(ButtonWidget.builder(\n Text.of(\"Open Recording Folder\"),\n (button) -> Util.getOperatingSystem().open(new File(this.directoryPath).toURI())\n )\n .dimensions(this.width / 2 - 65, this.height - 38, 130, 20)\n .build());\n\n this.addDrawableChild(ButtonWidget.builder(\n ScreenTexts.DONE,\n (button) -> this.onDone()\n )\n .dimensions(this.width / 2 - 65 + 140, this.height - 38, 130, 20)\n .build());\n\n super.init();\n }\n\n private void onDone() {\n isOpen = false;\n RecordingSelectionListWidget.RecordingEntry recEntry = this.recordingSelectionList.getSelectedOrNull();\n if (recEntry != null) {\n PlayerRecorder.loadRecord(recEntry.file);\n }\n MinecraftClient.getInstance().setScreen(null);\n }\n\n private void onDelete() {\n RecordingSelectionListWidget.RecordingEntry recEntry = this.recordingSelectionList.getSelectedOrNull();\n if (recEntry != null) {\n PlayerAutomaClient.LOGGER.info(\"Deletion of file result: \" + recEntry.file.delete());\n this.recordingSelectionList.updateFiles();\n }\n }\n\n public boolean keyPressed(int keyCode, int scanCode, int modifiers) {\n if (KeyCodes.isToggle(keyCode)) {\n RecordingSelectionListWidget.RecordingEntry languageEntry = this.recordingSelectionList.getSelectedOrNull();\n if (languageEntry != null) {\n languageEntry.onPressed();\n this.onDone();\n return true;\n }\n }\n\n return super.keyPressed(keyCode, scanCode, modifiers);\n }\n\n public void render(DrawContext context, int mouseX, int mouseY, float delta) {\n super.render(context, mouseX, mouseY, delta);\n this.recordingSelectionList.render(context, mouseX, mouseY, delta);\n context.drawCenteredTextWithShadow(this.textRenderer, this.title, this.width / 2, 16, 16777215);\n }\n\n public void renderBackground(DrawContext context, int mouseX, int mouseY, float delta) {\n this.renderBackgroundTexture(context);\n }\n\n private class RecordingSelectionListWidget extends AlwaysSelectedEntryListWidget<RecordingSelectionListWidget.RecordingEntry> {\n final String directoryPath;\n public RecordingSelectionListWidget(MinecraftClient client, String directoryPath) {\n super(client, RecordingSelector.this.width, RecordingSelector.this.height - 93, 32, 18);\n this.directoryPath = directoryPath;\n this.updateFiles();\n\n if (this.getSelectedOrNull() != null) {\n this.centerScrollOn(this.getSelectedOrNull());\n }\n }\n\n public void updateFiles() {\n this.clearEntries();\n File[] fileList = new File(this.directoryPath).listFiles();\n if (fileList == null) {\n return;\n }\n for (File file : fileList) {\n if (file.getName().endsWith(\".rec\")) {\n RecordingEntry entry = new RecordingEntry(file.getName(), file);\n this.addEntry(entry);\n }\n }\n }\n\n protected int getScrollbarPositionX() {\n return super.getScrollbarPositionX() + 20;\n }\n\n public int getRowWidth() {\n return super.getRowWidth() + 50;\n }\n\n public class RecordingEntry extends AlwaysSelectedEntryListWidget.Entry<RecordingSelector.RecordingSelectionListWidget.RecordingEntry> {\n final String fileName;\n final File file;\n private long clickTime;\n\n public RecordingEntry(String fileName, File file) {\n this.fileName = fileName;\n this.file = file;\n }\n\n public void render(DrawContext context, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) {\n context.drawCenteredTextWithShadow(RecordingSelector.this.textRenderer, this.fileName, RecordingSelector.RecordingSelectionListWidget.this.width / 2, y + 1, 16777215);\n }\n\n public boolean mouseClicked(double mouseX, double mouseY, int button) {\n this.onPressed();\n if (Util.getMeasuringTimeMs() - this.clickTime < 250L) {\n RecordingSelector.this.onDone();\n }\n\n this.clickTime = Util.getMeasuringTimeMs();\n return true;\n }\n\n void onPressed() {\n RecordingSelector.RecordingSelectionListWidget.this.setSelected(this);\n }\n\n @Override\n public Text getNarration() {\n return Text.of(this.fileName);\n }\n }\n }\n}"
},
{
"identifier": "RecordingStorer",
"path": "src/main/java/net/jasper/mod/gui/RecordingStorer.java",
"snippet": "public class RecordingStorer extends Screen {\n\n\n public static final RecordingStorer SINGLETON = new RecordingStorer();\n public static boolean isOpen;\n private TextFieldWidget input;\n\n protected RecordingStorer() {\n super(Text.of(\"RecordingStorer\"));\n isOpen = false;\n\n }\n protected void init() {\n TextWidget text = new TextWidget(\n this.width / 2 - 100,\n this.height / 2 - 30,\n 200,\n 20,\n Text.of(\"Enter Recording Name\"),\n MinecraftClient.getInstance().textRenderer\n );\n\n TextFieldWidget textField = new TextFieldWidget(\n MinecraftClient.getInstance().textRenderer,\n this.width / 2 - 100,\n this.height / 2 - 10,\n 200,\n 20,\n Text.of(\"Recording Name\")\n );\n // Set Text Field Properties\n textField.setTooltip(Tooltip.of(Text.of(\"Enter Recording Name. Input does not require '.rec' ending\")));\n textField.setEditable(true);\n\n // Format the date and time as name of recording\n String datedName = LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"dd_MM_yyyy_HH_mm\")) + \".rec\";\n textField.setPlaceholder(Text.of(datedName));\n textField.setText(datedName);\n\n this.input = textField;\n\n ButtonWidget save = new ButtonWidget.Builder(\n Text.of(\"Save\"),\n (button) -> {\n String name = this.input.getText();\n name += name.endsWith(\".rec\") ? \"\" : \".rec\";\n PlayerRecorder.storeRecord(name);\n this.close();\n }).dimensions(this.width / 2 - 100, this.height / 2 + 10, 200, 20)\n .tooltip(Tooltip.of(Text.of(\"Save Recording to .minecraft/recordings\")))\n .build();\n\n this.addDrawableChild(textField);\n this.addDrawableChild(text);\n this.addDrawableChild(save);\n }\n\n public static void open() {\n if (!isOpen) {\n MinecraftClient.getInstance().setScreen(SINGLETON);\n SINGLETON.input.active = true;\n isOpen = !isOpen;\n }\n\n }\n\n @Override\n public void close() {\n isOpen = false;\n MinecraftClient client = MinecraftClient.getInstance();\n client.setScreen(null);\n client.mouse.lockCursor();\n }\n}"
}
] | import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.jasper.mod.automation.PlayerRecorder;
import net.jasper.mod.gui.PlayerAutomaMenu;
import net.jasper.mod.gui.RecordingSelector;
import net.jasper.mod.gui.RecordingStorer;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW; | 5,763 | package net.jasper.mod.util.keybinds;
/**
* Class storing all KeyBinding-Constants
*/
public class Constants {
protected static final int AMOUNT_KEYBINDS = 8;
private static final String KEYBINDING_CATEGORY = "Playerautoma";
private static final String[] names = {
// Player Recoding Keybinds
"Start Recording",
"Stop Recording",
"Replay Recording",
"Cancel Replay",
"Loop Replay",
"Store Recording",
"Load Recording",
// Open Menu
"Open Mod Menu"
};
private static final KeyBinding[] bindings = {
// Player Recoding Keybinds
new KeyBinding(names[0], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_G, KEYBINDING_CATEGORY),
new KeyBinding(names[1], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_H, KEYBINDING_CATEGORY),
new KeyBinding(names[2], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_J, KEYBINDING_CATEGORY),
new KeyBinding(names[3], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_K, KEYBINDING_CATEGORY),
new KeyBinding(names[4], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_L, KEYBINDING_CATEGORY),
new KeyBinding(names[5], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_U, KEYBINDING_CATEGORY),
new KeyBinding(names[6], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_I, KEYBINDING_CATEGORY),
// Open Menu
new KeyBinding(names[7], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_O, KEYBINDING_CATEGORY)
};
public static final KeyBinding CANCEL_REPLAY = bindings[3];
private static final Runnable[] callbackMethods = {
// Player Recording Keybinds | package net.jasper.mod.util.keybinds;
/**
* Class storing all KeyBinding-Constants
*/
public class Constants {
protected static final int AMOUNT_KEYBINDS = 8;
private static final String KEYBINDING_CATEGORY = "Playerautoma";
private static final String[] names = {
// Player Recoding Keybinds
"Start Recording",
"Stop Recording",
"Replay Recording",
"Cancel Replay",
"Loop Replay",
"Store Recording",
"Load Recording",
// Open Menu
"Open Mod Menu"
};
private static final KeyBinding[] bindings = {
// Player Recoding Keybinds
new KeyBinding(names[0], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_G, KEYBINDING_CATEGORY),
new KeyBinding(names[1], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_H, KEYBINDING_CATEGORY),
new KeyBinding(names[2], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_J, KEYBINDING_CATEGORY),
new KeyBinding(names[3], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_K, KEYBINDING_CATEGORY),
new KeyBinding(names[4], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_L, KEYBINDING_CATEGORY),
new KeyBinding(names[5], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_U, KEYBINDING_CATEGORY),
new KeyBinding(names[6], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_I, KEYBINDING_CATEGORY),
// Open Menu
new KeyBinding(names[7], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_O, KEYBINDING_CATEGORY)
};
public static final KeyBinding CANCEL_REPLAY = bindings[3];
private static final Runnable[] callbackMethods = {
// Player Recording Keybinds | PlayerRecorder::startRecord, | 0 | 2023-10-25 11:30:02+00:00 | 8k |
SUFIAG/Hotel-Reservation-System-Java-And-PHP | src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Hotel_Reservation_Screen.java | [
{
"identifier": "HRS",
"path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/HRS.java",
"snippet": "public class HRS {\n private Vector<Customer> customers;\n private Vector<Hotel> hotels;\n private Vector<Vendor> vendors;\n private writerAndReader readAndWrite;\n private static HRS hrs;\n\n // constructor\n private HRS(Context context) {\n // initializing data members\n customers = new Vector<>();\n hotels = new Vector<>();\n vendors = new Vector<>();\n readAndWrite = new writerAndReader(context);\n\n // fetching old data from server\n readAndWrite.getCustomersFromServer(customers);\n readAndWrite.getVendorsFromServer(vendors);\n readAndWrite.getHotelsFromServer(hotels, new VolleyCallBack() {\n @Override\n public void onSuccess() {\n for (int i = 0; i < hotels.size(); ++i) {\n readAndWrite.getRoomsFromServer(hotels.get(i));\n }\n readAndWrite.getReservationsFromServer(hotels);\n }\n });\n }\n\n // getters\n public static HRS getInstance(Context context) {\n if (hrs == null) {\n hrs = new HRS(context);\n }\n return hrs;\n }\n public Vector<Customer> getCustomers() {\n return customers;\n }\n public Vector<Hotel> getHotels() {\n return hotels;\n }\n public Vector<Vendor> getVendors() {\n return vendors;\n }\n public writerAndReader getReadAndWrite() {\n return readAndWrite;\n }\n\n // setters\n public void setCustomers(Vector<Customer> customers) {\n this.customers = customers;\n }\n public void setHotels(Vector<Hotel> hotels) {\n this.hotels = hotels;\n }\n public void setReadAndWrite(writerAndReader readAndWrite) {\n this.readAndWrite = readAndWrite;\n }\n public void setVendors(Vector<Vendor> vendors) { this.vendors = vendors; }\n\n // function to check if customer with same email already exists or not\n public boolean validateCustomerEmail(String email) {\n for (int i = 0; i < customers.size(); ++i) {\n if (email.equals(customers.get(i).getEmail())) {\n return false;\n }\n }\n return true;\n }\n\n // function to check if customer has logged in correctly or not\n public boolean validateCustomerAccount(String email, String pass) {\n for (int i = 0; i < customers.size(); ++i) {\n if (email.equals(customers.get(i).getEmail()) && customers.get(i).getPassword().equals(pass)) {\n return true;\n }\n }\n return false;\n }\n\n // function to check if vendor with same email already exists or not\n public boolean validateVendorEmail(String email) {\n for (int i = 0; i < vendors.size(); ++i) {\n if (email.equals(vendors.get(i).getEmail())) {\n return false;\n }\n }\n return true;\n }\n\n // function to check if vendor has logged in correctly or not\n public boolean validateVendorAccount(String email, String pass) {\n for (int i = 0; i < vendors.size(); ++i) {\n if (email.equals(vendors.get(i).getEmail()) && vendors.get(i).getPassword().equals(pass)) {\n return true;\n }\n }\n return false;\n }\n\n // function to check if hotel with same name and location already exists or not\n public boolean validateHotel(String name, String loc) {\n for (int i = 0; i < hotels.size(); ++i) {\n if (name.equals(hotels.get(i).getName()) && loc.equals(hotels.get(i).getLocation())) {\n return false;\n }\n }\n return true;\n }\n\n // function for customer registration\n public void registerCustomer(String name, String email, String pass,\n String add, String phone, String cnic, String accNo, Uri dp,\n VolleyCallBack volleyCallBack) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < customers.size(); ++i) {\n if (customers.get(i).getID() > ID) {\n ID = customers.get(i).getID();\n }\n }\n ID++;\n\n //registering customer\n Customer c = new Customer(ID, email, pass, name, add, phone, cnic, accNo, \"\");\n readAndWrite.insertCustomerDataIntoServer(c, dp, volleyCallBack);\n customers.add(c);\n }\n\n //function for vendor registration\n public void registerVendor(String name, String email, String pass,\n String add, String phone, String cnic, String accNo, Uri dp,\n VolleyCallBack volleyCallBack) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < vendors.size(); ++i) {\n if (vendors.get(i).getID() > ID) {\n ID = vendors.get(i).getID();\n }\n }\n ID++;\n\n //registering vendor\n Vendor v = new Vendor(ID, email, pass, name, add, phone, cnic, accNo, \"\");\n readAndWrite.insertVendorDataIntoServer(v, dp, volleyCallBack);\n vendors.add(v);\n }\n\n //function for hotel registration\n public void registerHotel(String name, String add, String loc, String singleRooms, String doubleRooms,\n String singleRoomPrice, String doubleRoomPrice, String registered_by) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < hotels.size(); ++i) {\n if (hotels.get(i).getID() > ID) {\n ID = hotels.get(i).getID();\n }\n }\n ID++;\n\n //registering hotel\n Hotel h = new Hotel(ID, name, add, loc, singleRooms, doubleRooms, singleRoomPrice, doubleRoomPrice, registered_by);\n hotels.add(h);\n readAndWrite.insertHotelIntoServer(h);\n readAndWrite.insertRoomsIntoServer(h);\n }\n\n //function for hotel booking\n public Vector<Hotel> getHotels(String location, String noOfPersons, LocalDate checkInDate, String roomType, boolean both) {\n Vector<Hotel> searchedHotels = new Vector<>();\n for (int i = 0; i < hotels.size(); ++i) {\n if (hotels.get(i).getLocation().equals(location)) {\n Hotel h1 = new Hotel();\n h1.setAddress(hotels.get(i).getAddress());\n h1.setName(hotels.get(i).getName());\n h1.setID(hotels.get(i).getID());\n h1.setRooms(hotels.get(i).getRooms());\n h1.setTotalRooms(hotels.get(i).getTotalRooms());\n h1.setLocation(hotels.get(i).getLocation());\n h1.setDoubleRoomPrice(hotels.get(i).getDoubleRoomPrice());\n h1.setDoubleRooms(hotels.get(i).getDoubleRooms());\n h1.setSingleRooms(hotels.get(i).getSingleRooms());\n h1.setSingleRoomPrice(hotels.get(i).getSingleRoomPrice());\n h1.setReservations(hotels.get(i).getReservations());\n Vector<Room> r;\n r = hotels.get(i).getRooms(noOfPersons, checkInDate, roomType, both);\n if (r != null) {\n h1.setRooms(r);\n searchedHotels.add(h1);\n }\n }\n }\n return searchedHotels;\n }\n\n //function for reserving room\n public void makeReservation(String email, Hotel h, LocalDate checkInDate, LocalDate checkOutDate) {\n //finding customer and calling for reservation\n for (int i = 0; i < customers.size(); ++i) {\n if (customers.get(i).getEmail().equals(email)) {\n Reservation reservation = h.reserveRoom(checkInDate, checkOutDate, customers.get(i), hotels);\n readAndWrite.truncateATable(\"rooms\", new VolleyCallBack() {\n @Override\n public void onSuccess() {\n for (int j = 0; j < hotels.size(); ++j) {\n readAndWrite.insertRoomsIntoServer(hotels.get(j));\n }\n }\n });\n if (reservation != null) {\n readAndWrite.insertReservationIntoServer(reservation);\n }\n break;\n }\n }\n }\n\n // Search Customer On Email Basis\n public Customer searchCustomerByMail(String Email){\n for(int i=0;i<customers.size();++i){\n if(Email.equals(customers.get(i).getEmail())){\n return customers.get(i);\n }\n }\n return null;\n }\n // Search Vendor On Email Basis\n public Vendor searchVendorByMail(String Email){\n for(int i=0;i<vendors.size();++i){\n if(Email.equals(vendors.get(i).getEmail())){\n return vendors.get(i);\n }\n }\n return null;\n }\n // Search Hotel On Name and Location Basis\n public Hotel searchHotelByNameLoc(String Name,String Loc){\n for(int i=0;i<hotels.size();++i){\n if(Name.equals(hotels.get(i).getName()) && Loc.equals(hotels.get(i).getLocation())){\n return hotels.get(i);\n }\n }\n return null;\n }\n\n // Login Customer On Email and Password Basis\n public Boolean LoginCustomer(String Email,String Pass){\n for(int i=0;i<customers.size();++i){\n if(Email.equals(customers.get(i).getEmail()) && Pass.equals(customers.get(i).getPassword())){\n return true;\n }\n }\n return false;\n }\n // Login Vendor On Email and Password Basis\n public Boolean LoginVendor(String Email,String Pass){\n for(int i=0;i<vendors.size();++i){\n if(Email.equals(vendors.get(i).getEmail()) && Pass.equals(vendors.get(i).getPassword())){\n return true;\n }\n }\n return false;\n }\n}"
},
{
"identifier": "Hotel",
"path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Hotel.java",
"snippet": "public class Hotel {\n private int ID, totalRooms;\n private String singleRooms, doubleRooms, singleRoomPrice, doubleRoomPrice, name, address, location, registered_by;\n private Vector<Room> rooms;\n private Vector<Reservation> reservations;\n\n //constructors\n public Hotel() {\n }\n public Hotel(int id, String Name, String add, String loc, String sRooms, String dRooms,\n String sRoomPrice, String dRoomPrice, String registered_by) {\n //assigning values to data members\n ID = id;\n name = Name;\n address = add;\n totalRooms = Integer.parseInt(sRooms) + Integer.parseInt(dRooms);\n singleRooms = sRooms;\n doubleRooms = dRooms;\n location = loc;\n singleRoomPrice = sRoomPrice;\n doubleRoomPrice = dRoomPrice;\n this.registered_by = registered_by;\n reservations = new Vector<>();\n\n //making rooms in hotel\n rooms = new Vector<>();\n for (int i = 0; i < totalRooms; ++i) {\n Room r1;\n if (i < Integer.parseInt(singleRooms)) {\n r1 = new Room(i + 1, \"Single\");\n } else {\n r1 = new Room(i + 1, \"Double\");\n }\n rooms.add(r1);\n }\n }\n\n //getters\n public String getName() {\n return name;\n }\n public String getAddress() {\n return address;\n }\n public int getID() {\n return ID;\n }\n public int getTotalRooms() {\n return totalRooms;\n }\n public Vector<Room> getRooms() {\n return rooms;\n }\n public String getLocation() {\n return location;\n }\n public String getDoubleRooms() {\n return doubleRooms;\n }\n public String getSingleRooms() {\n return singleRooms;\n }\n public String getSingleRoomPrice() {\n return singleRoomPrice;\n }\n public Vector<Reservation> getReservations() {\n return reservations;\n }\n public String getDoubleRoomPrice() {\n return doubleRoomPrice;\n }\n public String getRegistered_by() { return registered_by; }\n\n //setters\n public void setID(int ID) {\n this.ID = ID;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public void setRooms(Vector<Room> rooms) {\n this.rooms = rooms;\n }\n public void setTotalRooms(int totalRooms) {\n this.totalRooms = totalRooms;\n }\n public void setLocation(String location) {\n this.location = location;\n }\n public void setDoubleRooms(String doubleRooms) {\n this.doubleRooms = doubleRooms;\n }\n public void setReservations(Vector<Reservation> reservations) { this.reservations = reservations; }\n public void setSingleRooms(String singleRooms) {\n this.singleRooms = singleRooms;\n }\n public void setSingleRoomPrice(String singleRoomPrice) { this.singleRoomPrice = singleRoomPrice; }\n public void setDoubleRoomPrice(String doubleRoomPrice) { this.doubleRoomPrice = doubleRoomPrice; }\n public void setRegistered_by(String registered_by) { this.registered_by = registered_by; }\n\n //return rooms of hotel which can accommodate user requirements\n public Vector<Room> getRooms(String noOfPersons, LocalDate checkInDate, String roomType, Boolean both) {\n int personsCount = 0;\n Vector<Room> searchedRooms = new Vector<>();\n\n for (int i = 0; i < totalRooms; ++i) {\n if (rooms.get(i).isAvailable() || checkInDate.isEqual(rooms.get(i).getAvailableDate()) ||\n checkInDate.isAfter(rooms.get(i).getAvailableDate())) {\n if (both == true) {\n if (rooms.get(i).getType().equals(\"Single\")) {\n personsCount += 1;\n } else {\n personsCount += 2;\n }\n searchedRooms.add(rooms.get(i));\n }\n else {\n if (rooms.get(i).getType().equals(\"Single\") && roomType.equals(\"Single\")) {\n personsCount += 1;\n searchedRooms.add(rooms.get(i));\n } else if (rooms.get(i).getType().equals(\"Double\") && roomType.equals(\"Double\")){\n personsCount += 2;\n searchedRooms.add(rooms.get(i));\n }\n }\n }\n\n if (personsCount >= Integer.parseInt(noOfPersons)) {\n return searchedRooms;\n }\n }\n return null;\n }\n\n //function for reserving room in a hotel\n public Reservation reserveRoom(LocalDate checkInDate, LocalDate checkOutDate, Customer c, Vector<Hotel> hotels) {\n int temp = 0;\n for (int i = 0; i < rooms.size(); ++i) {\n rooms.get(i).setAvailable(false);\n rooms.get(i).setAvailableDate(checkOutDate.plusDays(1));\n }\n for (int i = 0; i < hotels.size(); ++i) {\n if (hotels.get(i).getID() == ID) {\n for (int j = 0; j < hotels.get(i).getRooms().size(); ++j) {\n if (hotels.get(i).getRooms().get(j).getNumber() == rooms.get(temp).getNumber()) {\n hotels.get(i).getRooms().get(j).setAvailable(rooms.get(temp).isAvailable());\n hotels.get(i).getRooms().get(j).setAvailableDate(rooms.get(temp).getAvailableDate());\n if ((temp + 1) != rooms.size()) {\n temp++;\n }\n }\n }\n\n String roomNumbers = \"\";\n for (int j = 0; j < rooms.size(); ++j) {\n roomNumbers += rooms.get(j).getNumber();\n if (j != rooms.size() - 1) {\n roomNumbers += \", \";\n }\n }\n\n int totalPriceCal=0;\n for (int j=0;j<rooms.size();j++){\n if (rooms.get(j).getType().equals(\"Single\")){\n totalPriceCal= totalPriceCal + Integer.parseInt(singleRoomPrice);\n }\n else{\n totalPriceCal= totalPriceCal + Integer.parseInt(doubleRoomPrice);\n }\n }\n\n Hotel hotel = hotels.get(i);\n Reservation r1 = new Reservation(hotel.getName(), hotel.getLocation(),\n Integer.toString(rooms.size()), roomNumbers, Integer.toString(totalPriceCal),\n checkInDate.toString(), checkOutDate.toString(), c.getEmail());\n hotels.get(i).getReservations().add(r1);\n return r1;\n }\n }\n return null;\n }\n}"
},
{
"identifier": "Reservation",
"path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Reservation.java",
"snippet": "public class Reservation {\n private String customerEmail, checkInDate, checkOutDate, hotelName, hotelLocation, roomNumbers, totalRooms, totalPrice;\n\n public Reservation(String hotelName, String hotelLocation, String totalRooms, String roomNumbers,\n String totalPrice, String checkInDate, String checkOutDate, String customerEmail) {\n this.customerEmail = customerEmail;\n this.checkInDate = checkInDate;\n this.checkOutDate = checkOutDate;\n this.hotelName = hotelName;\n this.hotelLocation = hotelLocation;\n this.roomNumbers = roomNumbers;\n this.totalRooms = totalRooms;\n this.totalPrice = totalPrice;\n }\n\n public String getTotalRooms() {\n return totalRooms;\n }\n\n public void setTotalRooms(String totalRooms) {\n this.totalRooms = totalRooms;\n }\n\n public String getTotalPrice() {\n return totalPrice;\n }\n\n public void setTotalPrice(String totalPrice) {\n this.totalPrice = totalPrice;\n }\n\n public String getCustomerEmail() {\n return customerEmail;\n }\n\n public void setCustomerEmail(String customerEmail) {\n this.customerEmail = customerEmail;\n }\n\n public String getCheckInDate() {\n return checkInDate;\n }\n\n public void setCheckInDate(String checkInDate) {\n this.checkInDate = checkInDate;\n }\n\n public String getCheckOutDate() {\n return checkOutDate;\n }\n\n public void setCheckOutDate(String checkOutDate) {\n this.checkOutDate = checkOutDate;\n }\n\n public String getHotelName() {\n return hotelName;\n }\n\n public void setHotelName(String hotelName) {\n this.hotelName = hotelName;\n }\n\n public String getHotelLocation() {\n return hotelLocation;\n }\n\n public void setHotelLocation(String hotelLocation) {\n this.hotelLocation = hotelLocation;\n }\n\n public String getRoomNumbers() {\n return roomNumbers;\n }\n\n public void setRoomNumbers(String roomNumbers) {\n this.roomNumbers = roomNumbers;\n }\n}"
},
{
"identifier": "Room",
"path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Room.java",
"snippet": "public class Room {\n private int number;\n private String type;\n private LocalDate availableDate;\n private boolean available;\n\n //constructor\n public Room() {}\n public Room(int no, String Type) {\n //assigning values to data members\n number = no;\n type = Type;\n available = true;\n availableDate = null;\n }\n\n //getters\n public int getNumber() {\n return number;\n }\n public String getType() {\n return type;\n }\n public boolean isAvailable() {\n return available;\n }\n public LocalDate getAvailableDate() { return availableDate; }\n\n //setters\n public void setAvailable(boolean available) {\n this.available = available;\n }\n public void setNumber(int number) {\n this.number = number;\n }\n public void setType(String type) {\n this.type = type;\n }\n public void setAvailableDate(LocalDate availableDate) { this.availableDate = availableDate; }\n}"
}
] | import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.sameetasadullah.i180479_i180531.R;
import com.sameetasadullah.i180479_i180531.logicLayer.HRS;
import com.sameetasadullah.i180479_i180531.logicLayer.Hotel;
import com.sameetasadullah.i180479_i180531.logicLayer.Reservation;
import com.sameetasadullah.i180479_i180531.logicLayer.Room;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Vector; | 5,353 | package com.sameetasadullah.i180479_i180531.presentationLayer;
public class Hotel_Reservation_Screen extends AppCompatActivity {
RelativeLayout endButton;
TextView hotelName,rooms,totalPrice,totalRooms;
HRS hrs;
String Email,checkInDate,checkOutDate,HotelName,HotelLocation;
Hotel h1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_reservation_screen);
hotelName = findViewById(R.id.tv_hotel_name);
rooms = findViewById(R.id.tv_rooms);
totalPrice = findViewById(R.id.tv_total_price);
totalRooms = findViewById(R.id.tv_total_rooms);
endButton = findViewById(R.id.END_button);
hrs = HRS.getInstance(Hotel_Reservation_Screen.this);
Email = getIntent().getStringExtra("Email");
HotelName = getIntent().getStringExtra("Hotel_name");
HotelLocation = getIntent().getStringExtra("Hotel_Loc");
checkInDate = getIntent().getStringExtra("checkinDate");
checkOutDate = getIntent().getStringExtra("checkOutDate");
h1 = hrs.searchHotelByNameLoc(HotelName,HotelLocation);
| package com.sameetasadullah.i180479_i180531.presentationLayer;
public class Hotel_Reservation_Screen extends AppCompatActivity {
RelativeLayout endButton;
TextView hotelName,rooms,totalPrice,totalRooms;
HRS hrs;
String Email,checkInDate,checkOutDate,HotelName,HotelLocation;
Hotel h1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_reservation_screen);
hotelName = findViewById(R.id.tv_hotel_name);
rooms = findViewById(R.id.tv_rooms);
totalPrice = findViewById(R.id.tv_total_price);
totalRooms = findViewById(R.id.tv_total_rooms);
endButton = findViewById(R.id.END_button);
hrs = HRS.getInstance(Hotel_Reservation_Screen.this);
Email = getIntent().getStringExtra("Email");
HotelName = getIntent().getStringExtra("Hotel_name");
HotelLocation = getIntent().getStringExtra("Hotel_Loc");
checkInDate = getIntent().getStringExtra("checkinDate");
checkOutDate = getIntent().getStringExtra("checkOutDate");
h1 = hrs.searchHotelByNameLoc(HotelName,HotelLocation);
| Vector<Reservation> res= h1.getReservations(); | 2 | 2023-10-25 20:58:45+00:00 | 8k |
achmaddaniel24/kupass | app/src/main/java/com/achmaddaniel/kupass/activity/HomePage.java | [
{
"identifier": "ListAdapter",
"path": "app/src/main/java/com/achmaddaniel/kupass/adapter/ListAdapter.java",
"snippet": "public class ListAdapter extends BaseAdapter {\n\t\n\tprivate ArrayList<ListItem> mList;\n\tprivate Context mContext;\n\t\n\tpublic ListAdapter(Context context) {\n\t\tmContext = context;\n\t}\n\t\n\tpublic void setFilteredList(ArrayList<ListItem> list) {\n\t\tmList = list;\n\t\tnotifyDataSetChanged();\n\t}\n\t\n\tpublic void setList(ArrayList<ListItem> list) {\n\t\tmList = list;\n\t}\n\t\n\tpublic ArrayList<ListItem> getList() {\n\t\treturn mList;\n\t}\n\t\n\tpublic String getItemTitle(int position) {\n\t\tListItem item = mList.get(position);\n\t\treturn item.getPasswordName();\n\t}\n\t\n\tpublic String getItemSubtitle(int position) {\n\t\tListItem item = mList.get(position);\n\t\treturn item.getNote();\n\t}\n\t\n\tpublic ListItem getCurrentItem(int position) {\n\t\treturn mList.get(position);\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\treturn mList.size();\n\t}\n\t\n\t@Override\n\tpublic Object getItem(int position) {\n\t\treturn mList.get(position);\n\t}\n\t\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn position;\n\t}\n\t\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tconvertView = LayoutInflater.from(mContext).inflate(R.layout.item_list_layout, parent, false);\n\t\t((TextView)convertView.findViewById(R.id.item_title)).setText(getItemTitle(position));\n\t\t((TextView)convertView.findViewById(R.id.item_subtitle)).setText(getItemSubtitle(position));\n\t\treturn convertView;\n\t}\n}"
},
{
"identifier": "ListItem",
"path": "app/src/main/java/com/achmaddaniel/kupass/adapter/ListItem.java",
"snippet": "public class ListItem implements Serializable {\n\t\n\tprivate long mId;\n\tprivate String mPasswordName;\n\tprivate String mUserName;\n\tprivate String mPassword;\n\tprivate String mNote;\n\t\n\tpublic ListItem(long id, String username, String password) {\n\t\tthis(id, \"Password\", username, password);\n\t}\n\t\n\tpublic ListItem(long id, String passwordName, String username, String password) {\n\t\tthis(id, passwordName, username, password, \"\");\n\t}\n\t\n\tpublic ListItem(long id, String passwordName, String username, String password, String note) {\n\t\tmId = id;\n\t\tmPasswordName = passwordName;\n\t\tmUserName = username;\n\t\tmPassword = password;\n\t\tmNote = note;\n\t}\n\t\n\tpublic long getId() {\n\t\treturn mId;\n\t}\n\t\n\tpublic String getPasswordName() {\n\t\treturn mPasswordName;\n\t}\n\t\n\tpublic String getUserName() {\n\t\treturn mUserName;\n\t}\n\t\n\tpublic String getPassword() {\n\t\treturn mPassword;\n\t}\n\t\n\tpublic String getNote() {\n\t\treturn mNote;\n\t}\n\t\n\tpublic void setPasswordName(String passwordName) {\n\t\tmPasswordName = passwordName;\n\t}\n\t\n\tpublic void setUserName(String username) {\n\t\tmUserName = username;\n\t}\n\t\n\tpublic void setPassword(String password) {\n\t\tmPassword = password;\n\t}\n\t\n\tpublic void setNote(String note) {\n\t\tmNote = note;\n\t}\n}"
},
{
"identifier": "Preference",
"path": "app/src/main/java/com/achmaddaniel/kupass/database/Preference.java",
"snippet": "public class Preference {\n\t\n\tprivate static Context mContext;\n\t\n\tprivate static SharedPreferences get(Context context) {\n\t\treturn mContext.getSharedPreferences(\"preferences\", mContext.MODE_PRIVATE);\n\t}\n\t\n\tpublic static void init(Context context) {\n\t\tmContext = context;\n\t}\n\t\n\tpublic static void setExportMethod(int method) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"export_method\", method);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getExportMethod() {\n\t\treturn get(mContext).getInt(\"export_method\", ConstantVar.EXPORT_TEXT);\n\t}\n\t\n\tpublic static void setLanguage(int language) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"language\", language);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getLanguage() {\n\t\treturn get(mContext).getInt(\"language\", ConstantVar.LANG_EN);\n\t}\n\t\n\tpublic static void setTheme(int theme) {\n\t\tSharedPreferences.Editor editor = get(mContext).edit();\n\t\teditor.putInt(\"theme\", theme);\n\t\teditor.apply();\n\t}\n\t\n\tpublic static int getTheme() {\n\t\treturn get(mContext).getInt(\"theme\", ConstantVar.THEME_SYSTEM);\n\t}\n}"
},
{
"identifier": "SQLDataHelper",
"path": "app/src/main/java/com/achmaddaniel/kupass/database/SQLDataHelper.java",
"snippet": "public class SQLDataHelper extends SQLiteOpenHelper {\n\t\n\tprivate static final String DATABASE_NAME = \"local_database.db\";\n\tprivate static final int DATABASE_VERSION = 1;\n\t\n\t// Table & Column name\n\tpublic static final String TABLE_NAME = \"list_password\";\n\tpublic static final String COLUMN_ID = BaseColumns._ID;\n\tpublic static final String COLUMN_PASSWORD_NAME = \"password_name\";\n\tpublic static final String COLUMN_USERNAME = \"username\";\n\tpublic static final String COLUMN_PASSWORD = \"password\";\n\tpublic static final String COLUMN_NOTE = \"note\";\n\t\n\t// Query\n\tprivate static final String TABLE_CREATE =\n\t\t\"CREATE TABLE \" + TABLE_NAME + \" (\" +\n\t\tCOLUMN_ID + \" INTEGER PRIMARY KEY AUTOINCREMENT, \" +\n\t\tCOLUMN_PASSWORD_NAME + \" TEXT, \" +\n\t\tCOLUMN_USERNAME + \" TEXT, \" +\n\t\tCOLUMN_PASSWORD + \" TEXT, \" +\n\t\tCOLUMN_NOTE + \" TEXT);\";\n\n\tpublic SQLDataHelper(Context context) {\n\t\tsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n\t}\n\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tdb.execSQL(TABLE_CREATE);\n\t}\n\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME);\n\t\tonCreate(db);\n\t}\n\t\n\tpublic long create(String passwordName, String username, String password, String note) {\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(COLUMN_PASSWORD_NAME, passwordName);\n\t\tvalues.put(COLUMN_USERNAME, username);\n\t\tvalues.put(COLUMN_PASSWORD, password);\n\t\tvalues.put(COLUMN_NOTE, note);\n\t\tlong newRowId = db.insert(TABLE_NAME, null, values);\n\t\tdb.close();\n\t\treturn newRowId;\n\t}\n\t\n\tpublic int update(long id, String passwordName, String username, String password, String note) {\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(COLUMN_PASSWORD_NAME, passwordName);\n\t\tvalues.put(COLUMN_USERNAME, username);\n\t\tvalues.put(COLUMN_PASSWORD, password);\n\t\tvalues.put(COLUMN_NOTE, note);\n\t\tint rowsUpdated = db.update(TABLE_NAME, values, COLUMN_ID + \" = ?\", new String[]{String.valueOf(id)});\n\t\tdb.close();\n\t\treturn rowsUpdated;\n\t}\n\t\n\tpublic int delete(long id) {\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tint rowsDeleted = db.delete(TABLE_NAME, COLUMN_ID + \" = ?\", new String[]{String.valueOf(id)});\n\t\tdb.close();\n\t\treturn rowsDeleted;\n\t}\n\t\n\tpublic int getCount() {\n\t\tSQLiteDatabase db = this.getReadableDatabase();\n\t\tCursor cursor = db.rawQuery(\"SELECT * FROM \" + TABLE_NAME, null);\n\t\tint count = cursor.getCount();\n\t\tcursor.close();\n\t\tdb.close();\n\t\treturn count;\n\t}\n\t\n\tpublic ArrayList<ListItem> getAll() {\n\t\tArrayList<ListItem> result = new ArrayList<>();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_NAME;\n\t\tSQLiteDatabase db = this.getWritableDatabase();\n\t\tCursor cursor = db.rawQuery(selectQuery, null);\n\t\tif(cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tresult.add(new ListItem(\n\t\t\t\t\tcursor.getLong(cursor.getColumnIndex(COLUMN_ID)),\n\t\t\t\t\tcursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD_NAME)),\n\t\t\t\t\tcursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)),\n\t\t\t\t\tcursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD)),\n\t\t\t\t\tcursor.getString(cursor.getColumnIndex(COLUMN_NOTE))\n\t\t\t\t));\n\t\t\t} while(cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\tdb.close();\n\t\treturn result;\n\t}\n}"
},
{
"identifier": "ConstantVar",
"path": "app/src/main/java/com/achmaddaniel/kupass/core/ConstantVar.java",
"snippet": "public class ConstantVar {\n\t\n\tpublic static final int LANG_EN = 0;\n\tpublic static final int LANG_IN = 1;\n\t\n\tpublic static final int THEME_SYSTEM = 0;\n\tpublic static final int THEME_LIGHT\t = 1;\n\tpublic static final int THEME_DARK\t = 2;\n\t\n\t// public static final int EXPORT_CSV\t= 0;\n\tpublic static final int EXPORT_JSON = 0; // Default: 1\n\tpublic static final int EXPORT_TEXT = 1; // Default: 2\n\t// public static final int EXPORT_XLSX = 3; // Depedencies not support in CodeAssist\n\t\n\tpublic static final String STRING_NULL\t= null;\n\tpublic static final String STRING_EMPTY = \"\";\n}"
},
{
"identifier": "FilePermissionHandler",
"path": "app/src/main/java/com/achmaddaniel/kupass/core/FilePermissionHandler.java",
"snippet": "public class FilePermissionHandler {\n\t\n\tprivate static final int READ_WRITE_PERMISSION_REQUEST_CODE = 100;\n\tprivate Activity mActivity;\n\t\n\tpublic FilePermissionHandler(Activity activity, Context context) {\n\t\tmActivity = activity;\n\t\tScoopedStorage.init(mActivity, context);\n\t}\n\t\n\tpublic boolean checkReadWritePermission() {\n\t\tint readPermission\t= ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE);\n\t\tint writePermission = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);\n\t\treturn readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;\n\t}\n\t\n\tpublic void requestReadWritePermission() {\n\t\tString[] permissions = {\n\t\t\tManifest.permission.READ_EXTERNAL_STORAGE,\n\t\t\tManifest.permission.WRITE_EXTERNAL_STORAGE\n\t\t};\n\t\tActivityCompat.requestPermissions(mActivity, permissions, READ_WRITE_PERMISSION_REQUEST_CODE);\n\t}\n\t\n\t// Deprecated code :(\n\tpublic void onActivityResult(int requestCode, int resultCode, Intent data) {\n\t\tif(requestCode == ScoopedStorage.REQUEST_ACTION_CODE) {\n\t\t\tif(resultCode == mActivity.RESULT_OK) {\n\t\t\t\tif(ScoopedStorage.create(data))\n\t\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_success_export), Toast.LENGTH_SHORT).show();\n\t\t\t\telse\n\t\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_failed_export), Toast.LENGTH_SHORT).show();\n\t\t\t} else\n\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_failed_export), Toast.LENGTH_SHORT).show();\n\t\t} /* else if(requestCode == ScoopedStorage.REQUEST_ACTION_XLSX) {\n\t\t\tif(resultCode == mActivity.RESULT_OK) {\n\t\t\t\tif(ScoopedStorage.createXlsx(data))\n\t\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_success_export), Toast.LENGTH_SHORT).show();\n\t\t\t\telse\n\t\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_failed_export), Toast.LENGTH_SHORT).show();\n\t\t\t} else\n\t\t\t\tToast.makeText(mActivity, mActivity.getString(R.string.toast_failed_export), Toast.LENGTH_SHORT).show();\n\t\t} */\n\t}\n}"
},
{
"identifier": "FileUtil",
"path": "app/src/main/java/com/achmaddaniel/kupass/core/FileUtil.java",
"snippet": "public class FileUtil {\n\t\n\tprivate ArrayList<Password> mListPassword;\n\t\n\tpublic FileUtil() {\n\t\tmListPassword = new ArrayList<>();\n\t}\n\t\n\tpublic FileUtil(ArrayList<Password> listPassword) {\n\t\tmListPassword = listPassword;\n\t}\n\t\n\tpublic void generateToCsvFile() {\n\t}\n\t\n\tpublic void generateToJsonFile() {\n\t\tGson gson = new GsonBuilder().setPrettyPrinting().create();\n\t\tArrayList<PasswordJSON> json = new ArrayList<>();\n\t\tfor(Password password : mListPassword)\n\t\t\tjson.add(convertToJSON(password));\n\t\tScoopedStorage.createFile(gson.toJson(json), ConstantVar.EXPORT_JSON);\n\t}\n\t\n\tpublic void generateToTextFile() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor(Password password : mListPassword)\n\t\t\tsb.append(password.toString());\n\t\tScoopedStorage.createFile(sb.toString(), ConstantVar.EXPORT_TEXT);\n\t}\n\t\n\tpublic void generateToXlsxFile() {\n\t\t/** Not Support in CodeAssist\n\t\tGson gson = new GsonBuilder().setPrettyPrinting().create();\n\t\tArrayList<PasswordJSON> json = new ArrayList<>();\n\t\tfor(Password password : mListPassword)\n\t\t\tjson.add(convertToJSON(password));\n\t\t\n\t\tJSONArray jsonArray = new JSONArray(gson.toJson(json));\n\t\tWorkbook workbook = new XSSFWorkbook();\n\t\tSheet sheet = workbook.createSheet(\"Password\");\n\t\tRow headerRow = sheet.createRow(0);\n\t\t\n\t\tString[] headers = {\n\t\t\t\"password_name\",\n\t\t\t\"username\",\n\t\t\t\"password\",\n\t\t\t\"note\"\n\t\t};\n\t\t\n\t\tfor(int i = 0; i < headers.length; i++) {\n\t\t\tCell cell = headerRow.createCell(i);\n\t\t\tcell.setCellValue(headers[i]);\n\t\t}\n\t\t\n\t\t// Write to Excel\n\t\tfor(int i = 0; i < jsonArray.length(); i++) {\n\t\t\tJSONObject jsonObject = jsonArray.getJSONObject(i);\n\t\t\tRow dataRow = sheet.createRow(i++);\n\t\t\tfor(int j = 0; j < headers.length; j++)\n\t\t\t\tdataRow.createCell(j).setCellValue(jsonObject.getString(headers[j]));\n\t\t}\n\t\tScoopedStorage.createFileXlsx(workbook);\n\t\t**/\n\t}\n\t\n\tprivate PasswordJSON convertToJSON(Password password) {\n\t\tPasswordJSON result = new PasswordJSON(password.getPasswordName());\n\t\tresult.add(\"username\", password.getUserName());\n\t\tresult.add(\"password\", password.getPassword());\n\t\tresult.add(\"note\", password.getNote());\n\t\treturn result;\n\t}\n\t\n\tprivate class PasswordJSON {\n\t\t\n\t\t@SerializedName(\"properties\")\n\t\tprivate Map<String, String> mProperties;\n\t\t\n\t\t@SerializedName(\"password_name\")\n\t\tprivate String mPasswordName;\n\t\t\n\t\tpublic PasswordJSON(String name) {\n\t\t\tmProperties = new LinkedHashMap<>();\n\t\t\tmPasswordName = name;\n\t\t}\n\t\t\n\t\tpublic void add(String key, String value) {\n\t\t\tmProperties.put(key, value);\n\t\t}\n\t}\n}"
},
{
"identifier": "Password",
"path": "app/src/main/java/com/achmaddaniel/kupass/core/Password.java",
"snippet": "public class Password {\n\t\n\tprivate String mPasswordName;\n\tprivate String mUserName;\n\tprivate String mPassword;\n\tprivate String mNote;\n\t\n\tpublic Password(ListItem item) {\n\t\tmPasswordName = item.getPasswordName();\n\t\tmUserName = item.getUserName();\n\t\tmPassword = item.getPassword();\n\t\tmNote = item.getNote();\n\t}\n\t\n\tpublic String getPasswordName() {\n\t\treturn mPasswordName;\n\t}\n\t\n\tpublic String getUserName() {\n\t\treturn mUserName;\n\t}\n\t\n\tpublic String getPassword() {\n\t\treturn mPassword;\n\t}\n\t\n\tpublic String getNote() {\n\t\treturn mNote;\n\t}\n\t\n\tpublic String toString() {\n\t\treturn mPasswordName + \":\\n\" +\n\t\t\t \" - username: \" + mUserName + \"\\n\" +\n\t\t\t \" - password: \" + mPassword + \"\\n\" +\n\t\t\t \" - note: \" + mNote + \"\\n\\n\";\n\t}\n}"
}
] | import com.achmaddaniel.kupass.R;
import com.achmaddaniel.kupass.adapter.ListAdapter;
import com.achmaddaniel.kupass.adapter.ListItem;
import com.achmaddaniel.kupass.database.Preference;
import com.achmaddaniel.kupass.database.SQLDataHelper;
import com.achmaddaniel.kupass.core.ConstantVar;
import com.achmaddaniel.kupass.core.FilePermissionHandler;
import com.achmaddaniel.kupass.core.FileUtil;
import com.achmaddaniel.kupass.core.Password;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.view.View;
import android.view.LayoutInflater;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.ArrayList; | 5,583 | mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
ArrayList<ListItem> filter = new ArrayList<>();
for(ListItem item : mListItem)
if(item.getPasswordName().toLowerCase().contains(newText.toLowerCase()))
filter.add(item);
if(!filter.isEmpty())
mAdapter.setFilteredList(filter);
return true;
}
});
update();
}
private void update() {
mListItem = mSQL.getAll();
mAdapter.setList(mListItem);
if(!(mListItem.size() > 0))
mListView.setBackgroundColor(getResources().getColor(R.color.transparent));
else
mListView.setBackgroundResource(R.drawable.list_item_background);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((adapter, view, position, id) -> {
ListItem currentItem = mAdapter.getCurrentItem(position);
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
((TextInputEditText)inflater.findViewById(R.id.password_name)).setText(currentItem.getPasswordName());
((TextInputEditText)inflater.findViewById(R.id.username)).setText(currentItem.getUserName());
((TextInputEditText)inflater.findViewById(R.id.password)).setText(currentItem.getPassword());
((TextInputEditText)inflater.findViewById(R.id.note)).setText(currentItem.getNote());
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_edit))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_save), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.update(currentItem.getId(), passwordName, username, password, note);
showToast(getString(R.string.toast_success_update));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
mListView.setOnItemLongClickListener((adapter, view, position, id) -> {
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_delete))
.setMessage(getString(R.string.dialog_message_delete))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_delete), (dialog, which) -> {
mSQL.delete(mListItem.get(position).getId());
showToast(getString(R.string.toast_success_delete));
update();
})
.create()
.show();
return true;
});
}
// Handle FAB onClickListener
private void fabHandle() {
mFab.setOnClickListener((view) -> {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
});
mCreatePassFab.setOnClickListener((view) -> {
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_create))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_create), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.create(passwordName, username, password, note);
showToast(getString(R.string.toast_success));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
// Export
mExportFab.setOnClickListener((view) -> {
if(!(mListItem.size() > 0)) {
setFabVisibility(false);
showToast(getString(R.string.toast_no_data));
return;
}
CharSequence[] listExport = getResources().getStringArray(R.array.export_method_list);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_export))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_export), (dialog, which) -> {
checkPermission();
if(mPermissionHandler.checkReadWritePermission()) {
ArrayList<Password> listPassword = new ArrayList<>();
for(ListItem item : mListItem)
listPassword.add(new Password(item)); | package com.achmaddaniel.kupass.activity;
public class HomePage extends AppCompatActivity {
// Initialize widget variable
private SearchView mSearchView;
private FloatingActionButton mFab;
private FloatingActionButton mCreatePassFab;
private FloatingActionButton mExportFab;
private FloatingActionButton mSettingsFab;
private FilePermissionHandler mPermissionHandler;
private boolean mIsFabClicked = false;
private ListAdapter mAdapter;
private ArrayList<ListItem> mListItem;
private SQLDataHelper mSQL;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
checkPermission();
initialisation();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mPermissionHandler.onActivityResult(requestCode, resultCode, data);
}
private void initialisation() {
Preference.init(this);
mSQL = new SQLDataHelper(this);
mAdapter = new ListAdapter(this);
mListItem = new ArrayList<>();
mListView = findViewById(R.id.list_view);
// Init language
Resources res = getResources();
Configuration config = res.getConfiguration();
switch(Preference.getLanguage()) {
case ConstantVar.LANG_EN:
config.setLocale(Locale.getDefault());
break;
case ConstantVar.LANG_IN:
config.setLocale(new Locale("in"));
break;
}
res.updateConfiguration(config, res.getDisplayMetrics());
// Theme
switch(Preference.getTheme()) {
case ConstantVar.THEME_SYSTEM:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case ConstantVar.THEME_LIGHT:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case ConstantVar.THEME_DARK:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
}
// FAB Initialisation
mFab = findViewById(R.id.fab);
mCreatePassFab = findViewById(R.id.fab_add);
mExportFab = findViewById(R.id.fab_export);
mSettingsFab = findViewById(R.id.fab_settings);
fabHandle();
setFabVisibility(false);
// Search function
mSearchView = findViewById(R.id.search_view);
mSearchView.clearFocus();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
ArrayList<ListItem> filter = new ArrayList<>();
for(ListItem item : mListItem)
if(item.getPasswordName().toLowerCase().contains(newText.toLowerCase()))
filter.add(item);
if(!filter.isEmpty())
mAdapter.setFilteredList(filter);
return true;
}
});
update();
}
private void update() {
mListItem = mSQL.getAll();
mAdapter.setList(mListItem);
if(!(mListItem.size() > 0))
mListView.setBackgroundColor(getResources().getColor(R.color.transparent));
else
mListView.setBackgroundResource(R.drawable.list_item_background);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((adapter, view, position, id) -> {
ListItem currentItem = mAdapter.getCurrentItem(position);
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
((TextInputEditText)inflater.findViewById(R.id.password_name)).setText(currentItem.getPasswordName());
((TextInputEditText)inflater.findViewById(R.id.username)).setText(currentItem.getUserName());
((TextInputEditText)inflater.findViewById(R.id.password)).setText(currentItem.getPassword());
((TextInputEditText)inflater.findViewById(R.id.note)).setText(currentItem.getNote());
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_edit))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_save), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.update(currentItem.getId(), passwordName, username, password, note);
showToast(getString(R.string.toast_success_update));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
mListView.setOnItemLongClickListener((adapter, view, position, id) -> {
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_delete))
.setMessage(getString(R.string.dialog_message_delete))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_delete), (dialog, which) -> {
mSQL.delete(mListItem.get(position).getId());
showToast(getString(R.string.toast_success_delete));
update();
})
.create()
.show();
return true;
});
}
// Handle FAB onClickListener
private void fabHandle() {
mFab.setOnClickListener((view) -> {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
});
mCreatePassFab.setOnClickListener((view) -> {
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_create))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_create), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.create(passwordName, username, password, note);
showToast(getString(R.string.toast_success));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
// Export
mExportFab.setOnClickListener((view) -> {
if(!(mListItem.size() > 0)) {
setFabVisibility(false);
showToast(getString(R.string.toast_no_data));
return;
}
CharSequence[] listExport = getResources().getStringArray(R.array.export_method_list);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_export))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_export), (dialog, which) -> {
checkPermission();
if(mPermissionHandler.checkReadWritePermission()) {
ArrayList<Password> listPassword = new ArrayList<>();
for(ListItem item : mListItem)
listPassword.add(new Password(item)); | FileUtil data = new FileUtil(listPassword); | 6 | 2023-10-26 20:28:08+00:00 | 8k |
MachineMC/Cogwheel | cogwheel-core/src/main/java/org/machinemc/cogwheel/serialization/Serializers.java | [
{
"identifier": "DataVisitor",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/DataVisitor.java",
"snippet": "public interface DataVisitor {\n\n int READ_ACCESS = 0x01, WRITE_ACCESS = 0x02, FULL_ACCESS = READ_ACCESS | WRITE_ACCESS;\n\n @Contract(\"_ -> this\")\n DataVisitor visit(String key);\n\n @Contract(\"_ -> this\")\n DataVisitor visitSection(String key);\n\n /**\n * @return this\n */\n DataVisitor enterSection();\n\n /**\n * @return this\n */\n DataVisitor exitSection();\n\n /**\n * @return this\n */\n DataVisitor visitRoot();\n\n boolean isPresent();\n\n Optional<Number> readNumber();\n\n Optional<String> readString();\n\n Optional<Boolean> readBoolean();\n\n Optional<Object[]> readArray();\n\n <T extends Collection<Object>> Optional<T> readCollection(Supplier<T> factory);\n\n Optional<Map<String, Object>> readMap();\n\n Optional<ConfigAdapter<?>> readConfig();\n\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n default Optional<Object> readObject() {\n if (!isPresent()) return Optional.empty();\n return ((Optional) readNumber())\n .or(this::readString)\n .or(this::readBoolean)\n .or(this::readArray)\n .or(this::readMap);\n }\n\n /**\n * @return this\n */\n DataVisitor writeNull();\n\n @Contract(\"_ -> this\")\n DataVisitor writeNumber(Number number);\n\n @Contract(\"_ -> this\")\n DataVisitor writeString(String string);\n\n @Contract(\"_ -> this\")\n DataVisitor writeBoolean(Boolean bool);\n\n @Contract(\"_ -> this\")\n DataVisitor writeArray(Object[] array);\n\n @Contract(\"_ -> this\")\n DataVisitor writeCollection(Collection<?> collection);\n\n @Contract(\"_ -> this\")\n DataVisitor writeMap(Map<String, Object> map);\n\n DataVisitor writeConfig(ConfigAdapter<?> configAdapter);\n\n String getCurrentKey();\n\n int getFlags();\n\n DataVisitor withFlags(int newFlags);\n\n default boolean canRead() {\n return (getFlags() & READ_ACCESS) != 0;\n }\n\n default boolean canWrite() {\n return (getFlags() & WRITE_ACCESS) != 0;\n }\n\n}"
},
{
"identifier": "ErrorHandler",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/ErrorHandler.java",
"snippet": "public interface ErrorHandler {\n\n ErrorHandler SUPPRESSING = (context, error) -> {};\n ErrorHandler NORMAL = new DefaultErrorHandler();\n Function<Function<String, ? extends RuntimeException>, ErrorHandler> THROW_EXCEPTION = throwable -> (context, error) -> {\n throw throwable.apply(error.type() + \": \" + error.message());\n };\n\n void handle(SerializerContext context, ErrorEntry error);\n\n}"
},
{
"identifier": "ArrayUtils",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/ArrayUtils.java",
"snippet": "public final class ArrayUtils {\n\n private ArrayUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Creates a new array instance of the specified component type and length.\n *\n * @param componentType The component type of the array.\n * @param length The length of the array.\n * @param <T> The type of elements in the array.\n * @return A new array instance.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T[] newArrayInstance(Class<T> componentType, int length) {\n return (T[]) Array.newInstance(componentType, length);\n }\n\n /**\n * Creates a new array instance of the specified component type and dimensions.\n *\n * @param componentType The component type of the array.\n * @param dimensions The dimensions of the array.\n * @param <T> The type of elements in the array.\n * @return A new array instance.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T[] newArrayInstance(Class<T> componentType, int... dimensions) {\n return (T[]) Array.newInstance(componentType, dimensions);\n }\n\n @SafeVarargs\n public static <T> T[] array(T... array) {\n return array;\n }\n\n public static Byte[] wrapArray(byte[] array) {\n Byte[] wrapped = new Byte[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Short[] wrapArray(short[] array) {\n Short[] wrapped = new Short[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Integer[] wrapArray(int[] array) {\n Integer[] wrapped = new Integer[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Long[] wrapArray(long[] array) {\n Long[] wrapped = new Long[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Float[] wrapArray(float[] array) {\n Float[] wrapped = new Float[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Double[] wrapArray(double[] array) {\n Double[] wrapped = new Double[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Boolean[] wrapArray(boolean[] array) {\n Boolean[] wrapped = new Boolean[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static Character[] wrapArray(char[] array) {\n Character[] wrapped = new Character[array.length];\n for (int i = 0; i < array.length; i++)\n wrapped[i] = array[i];\n return wrapped;\n }\n\n public static byte[] unwrapArray(Byte[] array) {\n byte[] primitive = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static short[] unwrapArray(Short[] array) {\n short[] primitive = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static int[] unwrapArray(Integer[] array) {\n int[] primitive = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static long[] unwrapArray(Long[] array) {\n long[] primitive = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static float[] unwrapArray(Float[] array) {\n float[] primitive = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static double[] unwrapArray(Double[] array) {\n double[] primitive = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static boolean[] unwrapArray(Boolean[] array) {\n boolean[] primitive = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n public static char[] unwrapArray(Character[] array) {\n char[] primitive = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n if (array[i] == null) continue;\n primitive[i] = array[i];\n }\n return primitive;\n }\n\n}"
},
{
"identifier": "JavaUtils",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/JavaUtils.java",
"snippet": "public final class JavaUtils {\n\n // Mapping of primitive types to their wrapped types\n private static final Map<Class<?>, Class<?>> primitiveToWrapped = Map.of(\n byte.class, Byte.class,\n short.class, Short.class,\n int.class, Integer.class,\n long.class, Long.class,\n float.class, Float.class,\n double.class, Double.class,\n boolean.class, Boolean.class,\n char.class, Character.class,\n void.class, Void.class\n );\n\n private static byte DEFAULT_BYTE;\n private static short DEFAULT_SHORT;\n private static int DEFAULT_INT;\n private static long DEFAULT_LONG;\n private static float DEFAULT_FLOAT;\n private static double DEFAULT_DOUBLE;\n private static boolean DEFAULT_BOOLEAN;\n private static char DEFAULT_CHAR;\n\n // Mapping of primitive types to their default values\n private static final Map<Class<?>, Object> defaultValues = Map.of(\n byte.class, DEFAULT_BYTE,\n short.class, DEFAULT_SHORT,\n int.class, DEFAULT_INT,\n long.class, DEFAULT_LONG,\n float.class, DEFAULT_FLOAT,\n double.class, DEFAULT_DOUBLE,\n boolean.class, DEFAULT_BOOLEAN,\n char.class, DEFAULT_CHAR\n );\n\n private JavaUtils() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Wraps a primitive type with its corresponding wrapped type.\n *\n * @param primitive The primitive class to wrap.\n * @return The wrapped class for the given primitive class.\n * @throws IllegalArgumentException if the provided class is not a primitive class.\n */\n public static Class<?> wrapPrimitiveClass(Class<?> primitive) throws IllegalArgumentException {\n if (!primitive.isPrimitive()) throw new IllegalArgumentException(primitive + \" is not a primitive class\");\n return primitiveToWrapped.get(primitive);\n }\n\n /**\n * Gets the default value for a given class.\n *\n * @param cls The class for which to retrieve the default value.\n * @return The default value for the provided class.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getDefaultValue(Class<T> cls) {\n return (T) defaultValues.get(cls);\n }\n\n public static boolean hasConstructor(Class<?> cls, Class<?>... parameters) {\n try {\n cls.getDeclaredConstructor(parameters);\n return true;\n } catch (NoSuchMethodException e) {\n return false;\n }\n }\n\n public static <T> T newInstance(Class<T> cls) {\n return newInstance(cls, ArrayUtils.array());\n }\n\n public static <T> T newInstance(Class<T> cls, Class<?>[] parameters, Object... arguments) {\n try {\n Constructor<T> constructor = cls.getDeclaredConstructor(parameters);\n constructor.setAccessible(true);\n return constructor.newInstance(arguments);\n } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {\n return null;\n }\n }\n\n public static Field getField(Class<?> cls, String name) {\n try {\n return cls.getDeclaredField(name);\n } catch (NoSuchFieldException e) {\n return null;\n }\n }\n\n public static Object getValue(Field field, @Nullable Object holder) {\n try {\n field.setAccessible(true);\n return field.get(holder);\n } catch (IllegalAccessException ignored) {\n return null;\n }\n }\n\n public static Object getValue(RecordComponent recordComponent, Object holder) {\n try {\n Method accessor = recordComponent.getAccessor();\n accessor.setAccessible(true);\n return accessor.invoke(holder);\n } catch (InvocationTargetException | IllegalAccessException ignored) {\n return null;\n }\n }\n\n /**\n * Retrieves an enum constant by its name from the given enum type.\n *\n * @param type The enum class from which to retrieve the constant.\n * @param string The name of the enum constant.\n * @param <T> The type of the enum.\n * @return The enum constant or null if the type is not an enum or the constant is not found.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> @Nullable T getEnumConstant(Class<T> type, String string) {\n if (!type.isEnum()) return null;\n return (T) Enum.valueOf(type.asSubclass(Enum.class), string);\n }\n\n /**\n * Gets the class representation of a given type, which may be a {@link Class}, {@link ParameterizedType}, or {@link GenericArrayType}.\n *\n * @param type The type to extract the class from.\n * @param <T> The resulting class type.\n * @return The class representation of the provided type.\n * @throws IllegalStateException if the provided type is not a {@link Class}, {@link ParameterizedType}, or {@link GenericArrayType}.\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> Class<T> asClass(Type type) {\n return (Class<T>) switch (type) {\n case Class<?> cls -> cls;\n case ParameterizedType parameterized -> parameterized.getRawType();\n case GenericArrayType arrayType -> {\n List<Integer> dimensions = new LinkedList<>();\n Type currentType = arrayType;\n do {\n currentType = ((GenericArrayType) currentType).getGenericComponentType();\n dimensions.add(0);\n } while (!(currentType instanceof ParameterizedType));\n int[] dimensionsArray = new int[dimensions.size()];\n for (int i = 0; i < dimensionsArray.length; i++)\n dimensionsArray[i] = dimensions.get(i);\n yield ArrayUtils.newArrayInstance(asClass(currentType), dimensionsArray).getClass();\n }\n default -> throw new IllegalStateException(\"Unexpected type: \" + type);\n };\n }\n\n public static <T> Class<T> asClass(AnnotatedType annotatedType) {\n return asClass(annotatedType.getType());\n }\n\n public static String toString(Object object, String defaultIfNull) {\n if (object == null) return defaultIfNull;\n return toString(object);\n }\n\n public static String toString(Object object) {\n return switch (object) {\n case Object[] array -> Arrays.deepToString(array);\n case byte[] array -> Arrays.toString(array);\n case short[] array -> Arrays.toString(array);\n case int[] array -> Arrays.toString(array);\n case long[] array -> Arrays.toString(array);\n case float[] array -> Arrays.toString(array);\n case double[] array -> Arrays.toString(array);\n case boolean[] array -> Arrays.toString(array);\n case char[] array -> Arrays.toString(array);\n default -> String.valueOf(object);\n };\n }\n\n}"
},
{
"identifier": "NumberUtils",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/NumberUtils.java",
"snippet": "public final class NumberUtils {\n\n private NumberUtils() {\n throw new UnsupportedOperationException();\n }\n\n @Contract(\"null -> fail\")\n public static Number parse(String string) throws NumberFormatException {\n if (isInteger(string)) return parseInteger(string);\n return parseDecimal(string);\n }\n\n @Contract(\"null -> fail\")\n public static BigInteger parseInteger(String string) throws NumberFormatException {\n return isInteger(string) ? new BigInteger(string) : parseDecimal(string).toBigInteger();\n }\n\n @Contract(\"null -> fail\")\n public static BigDecimal parseDecimal(String string) throws NumberFormatException {\n return new BigDecimal(string);\n }\n\n @Contract(\"null, _, _ -> fail\")\n public static Number clamp(Number number, long min, long max) {\n return switch (Objects.requireNonNull(number, \"number\")) {\n case BigInteger bigInteger -> {\n try {\n yield Math.clamp(bigInteger.longValueExact(), min, max);\n } catch (ArithmeticException e) {\n yield bigInteger.signum() == -1 ? min : max;\n }\n }\n case BigDecimal bigDecimal -> clamp(bigDecimal.toBigInteger(), min, max);\n default -> {\n long longValue = number.longValue();\n double doubleValue = number.doubleValue();\n if (longValue != doubleValue)\n yield doubleValue < 0 ? min : max;\n yield Math.clamp(longValue, min, max);\n }\n };\n }\n\n @Contract(\"null -> fail\")\n public static ClampedNumber clamped(Number number) {\n return new ClampedNumber(number);\n }\n\n private static boolean isInteger(Number number) {\n return isInteger(Objects.requireNonNull(number, \"number\").toString());\n }\n\n private static boolean isInteger(String string) {\n return string.indexOf('.') == -1;\n }\n\n public static class ClampedNumber extends Number {\n\n private final Number number;\n private Byte clampedByte;\n private Short clampedShort;\n private Integer clampedInt;\n private Long clampedLong;\n\n @Contract(\"null -> fail\")\n public ClampedNumber(Number number) {\n this.number = Objects.requireNonNull(number, \"number\");\n }\n\n @Override\n public byte byteValue() {\n if (clampedByte == null) clampedByte = clamp(number, Byte.MIN_VALUE, Byte.MAX_VALUE).byteValue();\n return clampedByte;\n }\n\n @Override\n public short shortValue() {\n if (clampedShort == null) clampedShort = clamp(number, Short.MIN_VALUE, Short.MAX_VALUE).shortValue();\n return clampedShort;\n }\n\n @Override\n public int intValue() {\n if (clampedInt == null) clampedInt = clamp(number, Integer.MIN_VALUE, Integer.MAX_VALUE).intValue();\n return clampedInt;\n }\n\n @Override\n public long longValue() {\n if (clampedLong == null) clampedLong = clamp(number, Long.MIN_VALUE, Long.MAX_VALUE).longValue();\n return clampedLong;\n }\n\n @Override\n public float floatValue() {\n return number.floatValue();\n }\n\n @Override\n public double doubleValue() {\n return number.doubleValue();\n }\n\n @Override\n public String toString() {\n return number.toString();\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n\n ClampedNumber that = (ClampedNumber) object;\n\n return number.equals(that.number);\n }\n\n @Override\n public int hashCode() {\n return number.hashCode();\n }\n\n }\n\n}"
},
{
"identifier": "ClassBuilder",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/classbuilder/ClassBuilder.java",
"snippet": "public abstract class ClassBuilder<T> {\n\n protected final Class<T> cls;\n private final Map<String, Component<?>> components;\n\n public ClassBuilder(Class<T> cls) {\n this(cls, HashMap::new);\n }\n\n protected ClassBuilder(Class<T> cls, Supplier<Map<String, Component<?>>> supplier) {\n this(cls, supplier.get());\n }\n\n protected ClassBuilder(Class<T> cls, Map<String, Component<?>> components) {\n this.cls = cls;\n this.components = components;\n }\n\n public Class<T> getType() {\n return cls;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <C> Component<C> getComponent(String name, Class<C> type) {\n checkComponentExists(name);\n Component<?> component = getComponent(name);\n return component != null ? component.getType().isAssignableFrom(type) ? (Component<C>) component : null : null;\n }\n\n public Component<?> getComponent(String name) {\n checkComponentExists(name);\n return components.get(name);\n }\n\n protected <C> Component<C> getOrCreateComponent(String name, Class<C> type) {\n checkComponentExists(name);\n Component<C> component = getComponent(name, type);\n return component != null ? component : createComponent(name, type);\n }\n\n protected <C> Component<C> createComponent(String name, Class<C> type) {\n checkComponentExists(name);\n if (getComponent(name, type) != null) return null;\n setComponent(name, type, null);\n return getComponent(name, type);\n }\n\n public <C> void setComponent(String name, Class<C> type, @Nullable C value) {\n checkComponentExists(name);\n components.put(name, new Component<>(name, type, value));\n }\n\n public Collection<Component<?>> getComponents() {\n return components.values();\n }\n\n public abstract boolean componentExists(String name);\n\n public abstract T build();\n\n private void checkComponentExists(String name) {\n if (!componentExists(name))\n throw new IllegalArgumentException(\"Component '\" + name + \"' in class '\" + cls.getName() + \"' doesn't exist\");\n }\n\n public static class Component<T> {\n\n private final String name;\n private final Class<T> type;\n private @Nullable T value;\n\n public Component(String name, Class<T> type) {\n this(name, type, null);\n }\n\n public Component(String name, Class<T> type, @Nullable T value) {\n this.name = name;\n this.type = type;\n this.value = value != null ? value : JavaUtils.getDefaultValue(type);\n }\n\n public String getName() {\n return name;\n }\n\n public Class<T> getType() {\n return type;\n }\n\n public @Nullable T getValue() {\n return value;\n }\n\n public void setValue(@Nullable T value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return new StringJoiner(\", \", Component.class.getSimpleName() + \"[\", \"]\")\n .add(\"name='\" + name + \"'\")\n .add(\"type=\" + type)\n .add(\"value=\" + value)\n .toString();\n }\n\n }\n\n}"
},
{
"identifier": "ObjectBuilder",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/classbuilder/ObjectBuilder.java",
"snippet": "public class ObjectBuilder<T> extends ClassBuilder<T> {\n\n private final ClassInitiator classInitiator;\n\n public ObjectBuilder(Class<T> cls, ClassInitiator classInitiator) {\n super(cls);\n this.classInitiator = classInitiator;\n }\n\n @Override\n public boolean componentExists(String name) {\n return getField(name) != null;\n }\n\n @Override\n public T build() {\n T object = classInitiator.newInstance(cls);\n getComponents().forEach(component -> {\n Field field = getField(component.getName());\n setField(field, object, component.getValue());\n });\n return object;\n }\n\n private Field getField(String name) {\n Field field = null;\n Class<?> current = cls;\n while (!current.equals(Object.class) && field == null) {\n field = JavaUtils.getField(current, name);\n current = current.getSuperclass();\n }\n return field;\n }\n\n private static void setField(@Nullable Field field, Object holder, Object value) {\n if (field == null) return;\n field.setAccessible(true);\n try {\n field.set(holder, value);\n } catch (IllegalAccessException ignored) {}\n }\n\n}"
},
{
"identifier": "RecordBuilder",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/classbuilder/RecordBuilder.java",
"snippet": "public class RecordBuilder<T extends Record> extends ClassBuilder<T> {\n\n private final Map<String, RecordComponent> components;\n private boolean checkedDefault;\n private @Nullable T defaultRecord;\n\n public RecordBuilder(Class<T> cls) {\n super(cls);\n RecordComponent[] components = cls.getRecordComponents();\n this.components = LinkedHashMap.newLinkedHashMap(components.length);\n for (RecordComponent component : components)\n this.components.put(component.getName(), component);\n }\n\n @Override\n public boolean componentExists(String name) {\n return components.containsKey(name);\n }\n\n @Override\n public T build() {\n if (!checkedDefault) {\n checkedDefault = true;\n defaultRecord = JavaUtils.hasConstructor(cls) ? JavaUtils.newInstance(cls) : null;\n }\n List<Component<?>> componentList = new ArrayList<>();\n components.forEach((name, component) -> componentList.add(getComponent(defaultRecord, component)));\n Class<?>[] parameters = componentList.stream()\n .map(Component::getType)\n .toArray(Class[]::new);\n Object[] arguments = componentList.stream()\n .map(Component::getValue)\n .toArray();\n return JavaUtils.newInstance(cls, parameters, arguments);\n }\n\n @SuppressWarnings(\"unchecked\")\n private <C> Component<C> getComponent(@Nullable T defaultRecord, RecordComponent recordComponent) {\n String name = recordComponent.getName();\n Class<C> type = (Class<C>) recordComponent.getType();\n Component<C> component = getComponent(name, type);\n if (component != null) return component;\n if (defaultRecord == null) return createComponent(name, type);\n return new Component<>(name, type, (C) JavaUtils.getValue(recordComponent, defaultRecord));\n }\n\n}"
},
{
"identifier": "ErrorContainer",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/error/ErrorContainer.java",
"snippet": "public class ErrorContainer implements Iterable<ErrorEntry> {\n\n private final @Nullable ErrorContainer parent;\n private final List<ErrorEntry> entries = new ArrayList<>();\n\n public ErrorContainer() {\n this(null);\n }\n\n public ErrorContainer(@Nullable ErrorContainer parent) {\n this.parent = parent;\n }\n\n public void error(String message) {\n error(ErrorType.CUSTOM, message);\n }\n\n public void error(ErrorType type, String message) {\n error(new ErrorEntry(type, message));\n }\n\n public void error(ErrorEntry entry) {\n entries.add(entry);\n if (parent != null)\n parent.error(entry);\n }\n\n public void handleErrors(SerializerContext context) {\n if (!hasErrors()) return;\n ErrorHandler handler = context.properties().errorHandler();\n entries.removeIf(entry -> {\n handler.handle(context, entry);\n return true;\n });\n }\n\n public boolean hasErrors() {\n return !entries.isEmpty();\n }\n\n @Override\n public @NotNull Iterator<ErrorEntry> iterator() {\n return entries.iterator();\n }\n\n}"
},
{
"identifier": "ErrorType",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/util/error/ErrorType.java",
"snippet": "public enum ErrorType {\n\n /**\n * Error type indicating that a required key was not found.\n */\n KEY_NOT_FOUND,\n\n /**\n * Error type indicating that an unexpected key was encountered.\n */\n UNEXPECTED_KEY,\n\n /**\n * Error type indicating that an object could not be serialized.\n */\n SERIALIZER_NOT_FOUND,\n\n /**\n * Custom error type for user-defined error cases.\n */\n CUSTOM,\n MISMATCHED_TYPES,\n\n}"
}
] | import org.jetbrains.annotations.Nullable;
import org.machinemc.cogwheel.DataVisitor;
import org.machinemc.cogwheel.ErrorHandler;
import org.machinemc.cogwheel.config.*;
import org.machinemc.cogwheel.util.ArrayUtils;
import org.machinemc.cogwheel.util.JavaUtils;
import org.machinemc.cogwheel.util.NumberUtils;
import org.machinemc.cogwheel.util.classbuilder.ClassBuilder;
import org.machinemc.cogwheel.util.classbuilder.ObjectBuilder;
import org.machinemc.cogwheel.util.classbuilder.RecordBuilder;
import org.machinemc.cogwheel.util.error.ErrorContainer;
import org.machinemc.cogwheel.util.error.ErrorEntry;
import org.machinemc.cogwheel.util.error.ErrorType;
import java.io.File;
import java.lang.reflect.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Stream; | 6,960 | package org.machinemc.cogwheel.serialization;
public class Serializers {
public static <T extends Serializer<?>> T newSerializer(Class<T> serializerClass, SerializerContext context) {
if (JavaUtils.hasConstructor(serializerClass, SerializerContext.class)) | package org.machinemc.cogwheel.serialization;
public class Serializers {
public static <T extends Serializer<?>> T newSerializer(Class<T> serializerClass, SerializerContext context) {
if (JavaUtils.hasConstructor(serializerClass, SerializerContext.class)) | return JavaUtils.newInstance(serializerClass, ArrayUtils.array(SerializerContext.class), context); | 2 | 2023-10-25 11:31:02+00:00 | 8k |
frc7787/FTC-Centerstage | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/opmode/TrackingWheelLateralDistanceTuner.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID_FB = new PIDCoefficients(0, 0, 0);// was named Translational_PID\n public static PIDCoefficients TRANSLATIONAL_PID_LR = TRANSLATIONAL_PID_FB ;//new PIDCoefficients(0, 0, 0);// With Mecanum wheels having a lateral PID with different values is useful\n public static PIDCoefficients HEADING_PID = new PIDCoefficients(8, 0, 0);\n\n public static double LATERAL_MULTIPLIER = 41.8 / 41.875;\n\n public static double VX_WEIGHT = 1;\n public static double VY_WEIGHT = 1;\n public static double OMEGA_WEIGHT = 1;\n\n private TrajectorySequenceRunner trajectorySequenceRunner;\n\n private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH);\n private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(DriveConstants.MAX_ACCEL);\n\n private TrajectoryFollower follower;\n\n private DcMotorEx leftFront, leftRear, rightRear, rightFront;\n private List<DcMotorEx> motors;\n\n private VoltageSensor batteryVoltageSensor;\n\n private List<Integer> lastEncPositions = new ArrayList<>();\n private List<Integer> lastEncVels = new ArrayList<>();\n\n public SampleMecanumDrive(HardwareMap hardwareMap) {\n super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.TRACK_WIDTH, DriveConstants.TRACK_WIDTH, LATERAL_MULTIPLIER);\n\n follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID_FB, TRANSLATIONAL_PID_LR, HEADING_PID,\n new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);// Modified to allow L/R tuning with another PID\n\n LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap);\n\n batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next();\n\n for (LynxModule module : hardwareMap.getAll(LynxModule.class)) {\n module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO);\n }\n\n leftFront = hardwareMap.get(DcMotorEx.class, \"Front Left Drive Motor\");\n leftRear = hardwareMap.get(DcMotorEx.class, \"Back Left Drive Motor\");\n rightRear = hardwareMap.get(DcMotorEx.class, \"Back Right Drive Motor\");\n rightFront = hardwareMap.get(DcMotorEx.class, \"Front Right Drive Motor\");\n\n motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront);\n\n for (DcMotorEx motor : motors) {\n MotorConfigurationType motorConfigurationType = motor.getMotorType().clone();\n motorConfigurationType.setAchieveableMaxRPMFraction(1.0);\n motor.setMotorType(motorConfigurationType);\n }\n\n if (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); }\n\n setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);\n\n if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) {\n setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.MOTOR_VELO_PID);\n }\n\n leftFront.setDirection(DcMotorSimple.Direction.REVERSE);\n leftRear.setDirection(DcMotorSimple.Direction.FORWARD);\n rightFront.setDirection(DcMotorSimple.Direction.FORWARD);\n\n List<Integer> lastTrackingEncPositions = new ArrayList<>();\n List<Integer> lastTrackingEncVels = new ArrayList<>();\n\n // TODO: if desired, use setLocalizer() to change the localization method\n setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels));\n\n trajectorySequenceRunner = new TrajectorySequenceRunner(\n follower, HEADING_PID, batteryVoltageSensor,\n lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels\n );\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) {\n return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) {\n return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) {\n return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT);\n }\n\n public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) {\n return new TrajectorySequenceBuilder(\n startPose,\n VEL_CONSTRAINT, ACCEL_CONSTRAINT,\n DriveConstants.MAX_ANG_VEL, DriveConstants.MAX_ANG_ACCEL\n );\n }\n\n public void turnAsync(double angle) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(\n trajectorySequenceBuilder(getPoseEstimate())\n .turn(angle)\n .build()\n );\n }\n\n public void turn(double angle) {\n turnAsync(angle);\n waitForIdle();\n }\n\n public void followTrajectoryAsync(Trajectory trajectory) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(\n trajectorySequenceBuilder(trajectory.start())\n .addTrajectory(trajectory)\n .build()\n );\n }\n\n public void followTrajectory(Trajectory trajectory) {\n followTrajectoryAsync(trajectory);\n waitForIdle();\n }\n\n public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {\n trajectorySequenceRunner.followTrajectorySequenceAsync(trajectorySequence);\n }\n\n public void followTrajectorySequence(TrajectorySequence trajectorySequence) {\n followTrajectorySequenceAsync(trajectorySequence);\n waitForIdle();\n }\n\n public Pose2d getLastError() {\n return trajectorySequenceRunner.getLastPoseError();\n }\n\n public void update() {\n updatePoseEstimate();\n DriveSignal signal = trajectorySequenceRunner.update(getPoseEstimate(), getPoseVelocity());\n if (signal != null) setDriveSignal(signal);\n }\n\n public void waitForIdle() {\n while (!Thread.currentThread().isInterrupted() && isBusy())\n update();\n }\n\n public boolean isBusy() {\n return trajectorySequenceRunner.isBusy();\n }\n\n public void setMode(DcMotor.RunMode runMode) {\n for (DcMotorEx motor : motors) {\n motor.setMode(runMode);\n }\n }\n\n public void setZeroPowerBehavior(DcMotor.ZeroPowerBehavior zeroPowerBehavior) {\n for (DcMotorEx motor : motors) {\n motor.setZeroPowerBehavior(zeroPowerBehavior);\n }\n }\n\n public void setPIDFCoefficients(DcMotor.RunMode runMode, PIDFCoefficients coefficients) {\n PIDFCoefficients compensatedCoefficients = new PIDFCoefficients(\n coefficients.p, coefficients.i, coefficients.d,\n coefficients.f * 12 / batteryVoltageSensor.getVoltage()\n );\n\n for (DcMotorEx motor : motors) {\n motor.setPIDFCoefficients(runMode, compensatedCoefficients);\n }\n }\n\n public void setWeightedDrivePower(Pose2d drivePower) {\n Pose2d vel = drivePower;\n\n if (Math.abs(drivePower.getX()) + Math.abs(drivePower.getY())\n + Math.abs(drivePower.getHeading()) > 1) {\n // re-normalize the powers according to the weights\n double denom = VX_WEIGHT * Math.abs(drivePower.getX())\n + VY_WEIGHT * Math.abs(drivePower.getY())\n + OMEGA_WEIGHT * Math.abs(drivePower.getHeading());\n\n vel = new Pose2d(\n VX_WEIGHT * drivePower.getX(),\n VY_WEIGHT * drivePower.getY(),\n OMEGA_WEIGHT * drivePower.getHeading()\n ).div(denom);\n }\n\n setDrivePower(vel);\n }\n\n @NonNull\n @Override\n public List<Double> getWheelPositions() {\n lastEncPositions.clear();\n\n List<Double> wheelPositions = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n int position = motor.getCurrentPosition();\n lastEncPositions.add(position);\n wheelPositions.add(DriveConstants.encoderTicksToInches(position));\n }\n return wheelPositions;\n }\n\n @Override\n public List<Double> getWheelVelocities() {\n lastEncVels.clear();\n\n List<Double> wheelVelocities = new ArrayList<>();\n for (DcMotorEx motor : motors) {\n int vel = (int) motor.getVelocity();\n lastEncVels.add(vel);\n wheelVelocities.add(DriveConstants.encoderTicksToInches(vel));\n }\n return wheelVelocities;\n }\n\n @Override\n public void setMotorPowers(double v, double v1, double v2, double v3) {\n leftFront.setPower(v);\n leftRear.setPower(v1);\n rightRear.setPower(v2);\n rightFront.setPower(v3);\n }\n\n @Override\n public double getRawExternalHeading() {\n return 0.0;\n }\n\n @Override\n public Double getExternalHeadingVelocity() {\n return 0.0;\n }\n\n public static TrajectoryVelocityConstraint getVelocityConstraint(double maxVel, double maxAngularVel, double trackWidth) {\n return new MinVelocityConstraint(Arrays.asList(\n new AngularVelocityConstraint(maxAngularVel),\n new MecanumVelocityConstraint(maxVel, trackWidth)\n ));\n }\n\n public static TrajectoryAccelerationConstraint getAccelerationConstraint(double maxAccel) {\n return new ProfileAccelerationConstraint(maxAccel);\n }\n}"
},
{
"identifier": "StandardTrackingWheelLocalizer",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/StandardTrackingWheelLocalizer.java",
"snippet": "@Config\npublic class StandardTrackingWheelLocalizer extends ThreeTrackingWheelLocalizer {\n public static double TICKS_PER_REV = 8192;\n public static double WHEEL_RADIUS = 1.1811; // in\n public static double GEAR_RATIO = 1; // output (wheel) speed / input (encoder) speed\n\n public static double LATERAL_DISTANCE = 8.3d; // in; distance between the left and right wheels\n public static double FORWARD_OFFSET = 7.25; // in; offset of the lateral wheel\n\n private final Encoder leftEncoder, rightEncoder, frontEncoder;\n\n public static double X_MULTIPLIER = 1.12386; // Multiplier in the X direction\n public static double Y_MULTIPLIER = 1.00423280423; // Multiplier in the Y direction\n\n private final List<Integer> lastEncPositions, lastEncVels;\n\n public StandardTrackingWheelLocalizer(HardwareMap hardwareMap, List<Integer> lastTrackingEncPositions, List<Integer> lastTrackingEncVels) {\n super(Arrays.asList(\n new Pose2d(0, LATERAL_DISTANCE / 2, 0), // left\n new Pose2d(0, -LATERAL_DISTANCE / 2, 0), // right\n new Pose2d(FORWARD_OFFSET, 0, Math.toRadians(90)) // front\n ));\n\n lastEncPositions = lastTrackingEncPositions;\n lastEncVels = lastTrackingEncVels;\n\n leftEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, \"Front Left Drive Motor\"));\n rightEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, \"Front Right Drive Motor\"));\n frontEncoder = new Encoder(hardwareMap.get(DcMotorEx.class, \"Back Left Drive Motor\"));\n\n leftEncoder.setDirection(Encoder.Direction.REVERSE);\n }\n\n public static double encoderTicksToInches(double ticks) {\n return WHEEL_RADIUS * 2 * Math.PI * GEAR_RATIO * ticks / TICKS_PER_REV;\n }\n\n @NonNull\n @Override\n public List<Double> getWheelPositions() {\n int leftPos = leftEncoder.getCurrentPosition();\n int rightPos = rightEncoder.getCurrentPosition();\n int frontPos = frontEncoder.getCurrentPosition();\n\n lastEncPositions.clear();\n lastEncPositions.add(leftPos);\n lastEncPositions.add(rightPos);\n lastEncPositions.add(frontPos);\n\n return Arrays.asList(\n encoderTicksToInches(leftPos) * X_MULTIPLIER,\n encoderTicksToInches(rightPos) * X_MULTIPLIER,\n encoderTicksToInches(frontPos) * Y_MULTIPLIER\n );\n }\n\n @NonNull\n @Override\n public List<Double> getWheelVelocities() {\n int leftVel = (int) leftEncoder.getCorrectedVelocity();\n int rightVel = (int) rightEncoder.getCorrectedVelocity();\n int frontVel = (int) frontEncoder.getCorrectedVelocity();\n\n lastEncVels.clear();\n lastEncVels.add(leftVel);\n lastEncVels.add(rightVel);\n lastEncVels.add(frontVel);\n\n return Arrays.asList(\n encoderTicksToInches(leftVel) * X_MULTIPLIER,\n encoderTicksToInches(rightVel) * X_MULTIPLIER,\n encoderTicksToInches(frontVel) * Y_MULTIPLIER\n );\n }\n}"
}
] | import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.util.Angle;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.RoadRunner.drive.StandardTrackingWheelLocalizer; | 4,192 | package org.firstinspires.ftc.teamcode.RoadRunner.drive.opmode;
/**
* Opmode designed to assist the user in tuning the `StandardTrackingWheelLocalizer`'s
* LATERAL_DISTANCE value. The LATERAL_DISTANCE is the center-to-center distance of the parallel
* wheels.
*
* Tuning Routine:
*
* 1. Set the LATERAL_DISTANCE value in StandardTrackingWheelLocalizer.java to the physical
* measured value. This need only be an estimated value as you will be tuning it anyways.
*
* 2. Make a mark on the bot (with a piece of tape or sharpie or however you wish) and make an
* similar mark right below the indicator on your bot. This will be your reference point to
* ensure you've turned exactly 360°.
*
* 3. Although not entirely necessary, having the bot's pose being drawn in dashbooard does help
* identify discrepancies in the LATERAL_DISTANCE value. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash
* if you are using the Control Hub.
* Ensure the field is showing (select the field view in top right of the page).
*
* 4. Press play to begin the tuning routine.
*
* 5. Use the right joystick on gamepad 1 to turn the bot counterclockwise.
*
* 6. Spin the bot 10 times, counterclockwise. Make sure to keep track of these turns.
*
* 7. Once the bot has finished spinning 10 times, press A to finishing the routine. The indicators
* on the bot and on the ground you created earlier should be lined up.
*
* 8. Your effective LATERAL_DISTANCE will be given. Stick this value into your
* StandardTrackingWheelLocalizer.java class.
*
* 9. If this value is incorrect, run the routine again while adjusting the LATERAL_DISTANCE value
* yourself. Read the heading output and follow the advice stated in the note below to manually
* nudge the values yourself.
*
* Note:
* It helps to pay attention to how the pose on the field is drawn in dashboard. A blue circle with
* a line from the circumference to the center should be present, representing the bot. The line
* indicates forward. If your LATERAL_DISTANCE value is tuned currently, the pose drawn in
* dashboard should keep track with the pose of your actual bot. If the drawn bot turns slower than
* the actual bot, the LATERAL_DISTANCE should be decreased. If the drawn bot turns faster than the
* actual bot, the LATERAL_DISTANCE should be increased.
*
* If your drawn bot oscillates around a point in dashboard, don't worry. This is because the
* position of the perpendicular wheel isn't perfectly set and causes a discrepancy in the
* effective center of rotation. You can ignore this effect. The center of rotation will be offset
* slightly but your heading will still be fine. This does not affect your overall tracking
* precision. The heading should still line up.
*/
@Config
@TeleOp(name = "Tracking Wheel Lateral Distance Tuner", group = "drive")
@Disabled
public class TrackingWheelLateralDistanceTuner extends LinearOpMode {
public static int NUM_TURNS = 10;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode.RoadRunner.drive.opmode;
/**
* Opmode designed to assist the user in tuning the `StandardTrackingWheelLocalizer`'s
* LATERAL_DISTANCE value. The LATERAL_DISTANCE is the center-to-center distance of the parallel
* wheels.
*
* Tuning Routine:
*
* 1. Set the LATERAL_DISTANCE value in StandardTrackingWheelLocalizer.java to the physical
* measured value. This need only be an estimated value as you will be tuning it anyways.
*
* 2. Make a mark on the bot (with a piece of tape or sharpie or however you wish) and make an
* similar mark right below the indicator on your bot. This will be your reference point to
* ensure you've turned exactly 360°.
*
* 3. Although not entirely necessary, having the bot's pose being drawn in dashbooard does help
* identify discrepancies in the LATERAL_DISTANCE value. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash
* if you are using the Control Hub.
* Ensure the field is showing (select the field view in top right of the page).
*
* 4. Press play to begin the tuning routine.
*
* 5. Use the right joystick on gamepad 1 to turn the bot counterclockwise.
*
* 6. Spin the bot 10 times, counterclockwise. Make sure to keep track of these turns.
*
* 7. Once the bot has finished spinning 10 times, press A to finishing the routine. The indicators
* on the bot and on the ground you created earlier should be lined up.
*
* 8. Your effective LATERAL_DISTANCE will be given. Stick this value into your
* StandardTrackingWheelLocalizer.java class.
*
* 9. If this value is incorrect, run the routine again while adjusting the LATERAL_DISTANCE value
* yourself. Read the heading output and follow the advice stated in the note below to manually
* nudge the values yourself.
*
* Note:
* It helps to pay attention to how the pose on the field is drawn in dashboard. A blue circle with
* a line from the circumference to the center should be present, representing the bot. The line
* indicates forward. If your LATERAL_DISTANCE value is tuned currently, the pose drawn in
* dashboard should keep track with the pose of your actual bot. If the drawn bot turns slower than
* the actual bot, the LATERAL_DISTANCE should be decreased. If the drawn bot turns faster than the
* actual bot, the LATERAL_DISTANCE should be increased.
*
* If your drawn bot oscillates around a point in dashboard, don't worry. This is because the
* position of the perpendicular wheel isn't perfectly set and causes a discrepancy in the
* effective center of rotation. You can ignore this effect. The center of rotation will be offset
* slightly but your heading will still be fine. This does not affect your overall tracking
* precision. The heading should still line up.
*/
@Config
@TeleOp(name = "Tracking Wheel Lateral Distance Tuner", group = "drive")
@Disabled
public class TrackingWheelLateralDistanceTuner extends LinearOpMode {
public static int NUM_TURNS = 10;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-10-31 16:06:46+00:00 | 8k |
Fuzss/diagonalwalls | 1.18/Common/src/main/java/fuzs/diagonalwindows/world/level/block/StarCollisionBlock.java | [
{
"identifier": "DiagonalWindows",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/DiagonalWindows.java",
"snippet": "public class DiagonalWindows implements ModConstructor {\n public static final String MOD_ID = \"diagonalwindows\";\n public static final String MOD_NAME = \"Diagonal Windows\";\n public static final Logger LOGGER = LogManager.getLogger(DiagonalWindows.MOD_NAME);\n\n @Override\n public void onConstructMod() {\n ModRegistry.touch();\n }\n\n public static ResourceLocation id(String path) {\n return new ResourceLocation(MOD_ID, path);\n }\n}"
},
{
"identifier": "DiagonalBlock",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/api/world/level/block/DiagonalBlock.java",
"snippet": "public interface DiagonalBlock extends IDiagonalBlock {\n BooleanProperty NORTH_EAST = BooleanProperty.create(\"north_east\");\n BooleanProperty SOUTH_EAST = BooleanProperty.create(\"south_east\");\n BooleanProperty SOUTH_WEST = BooleanProperty.create(\"south_west\");\n BooleanProperty NORTH_WEST = BooleanProperty.create(\"north_west\");\n\n /**\n * @return have diagonal properties successfully been applied to this block\n */\n @Override\n boolean hasProperties();\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n @Override\n default boolean canConnectDiagonally() {\n return this.supportsDiagonalConnections();\n }\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n boolean supportsDiagonalConnections();\n\n /**\n * @param neighborState neighbor block state to check if it can connect to me diagonally\n * @param neighborDirectionToMe my direction from the neighbor blocks point of view\n * @return is a diagonal connection between both blocks allowed\n */\n boolean canConnectToMe(BlockState neighborState, EightWayDirection neighborDirectionToMe);\n}"
},
{
"identifier": "EightWayDirection",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/api/world/level/block/EightWayDirection.java",
"snippet": "public enum EightWayDirection implements StringRepresentable {\n SOUTH(0, new Vec3i(0, 0, 1)),\n WEST(1, new Vec3i(-1, 0, 0)),\n NORTH(2, new Vec3i(0, 0, -1)),\n EAST(3, new Vec3i(1, 0, 0)),\n SOUTH_WEST(0, new Vec3i(-1, 0, 1)),\n NORTH_WEST(1, new Vec3i(-1, 0, -1)),\n NORTH_EAST(2, new Vec3i(1, 0, -1)),\n SOUTH_EAST(3, new Vec3i(1, 0, 1));\n\n private static final Map<String, EightWayDirection> DIRECTIONS_BY_KEY = Stream.of(EightWayDirection.values()).collect(Collectors.toMap(EightWayDirection::getSerializedName, Function.identity()));\n\n private final int data2d;\n private final Vec3i directionVec;\n\n EightWayDirection(int data2d, Vec3i directionVec) {\n this.data2d = data2d;\n this.directionVec = directionVec;\n }\n\n public static EightWayDirection toEightWayDirection(Direction direction) {\n return getCardinalDirections()[direction.get2DDataValue()];\n }\n\n public static EightWayDirection byIndex(int index, boolean intercardinal) {\n index = ((index % 4) + 4) % 4;\n return intercardinal ? getIntercardinalDirections()[index] : getCardinalDirections()[index];\n }\n\n public static EightWayDirection[] getCardinalDirections() {\n return new EightWayDirection[]{SOUTH, WEST, NORTH, EAST};\n }\n\n public static EightWayDirection[] getIntercardinalDirections() {\n return new EightWayDirection[]{SOUTH_WEST, NORTH_WEST, NORTH_EAST, SOUTH_EAST};\n }\n\n public int getX() {\n return this.directionVec.getX();\n }\n\n public int getY() {\n return this.directionVec.getY();\n }\n\n public int getZ() {\n return this.directionVec.getZ();\n }\n\n public boolean compareAxis(EightWayDirection other) {\n if (this.isCardinal() != other.isCardinal()) return false;\n return (this.getX() + other.getX() + this.getY() + other.getY() + this.getZ() + other.getZ()) == 0;\n }\n\n @Nullable\n public static EightWayDirection byName(String name) {\n return DIRECTIONS_BY_KEY.get(name);\n }\n\n public boolean isCardinal() {\n return !this.isIntercardinal();\n }\n\n public boolean isIntercardinal() {\n return this.directionVec.getX() != 0 && this.directionVec.getZ() != 0;\n }\n\n public int getHorizontalIndex() {\n return 1 << (this.isIntercardinal() ? 4 + this.data2d : this.data2d);\n }\n\n public Vec3[] transform(Vec3[] vectors) {\n if (this.directionVec.getX() != 0) {\n vectors = VoxelUtils.ortho(vectors);\n }\n if (this.directionVec.getX() == -1 || this.directionVec.getZ() == -1) {\n vectors = VoxelUtils.mirror(vectors);\n }\n return vectors;\n }\n\n public EightWayDirection opposite() {\n return EightWayDirection.byIndex((this.data2d + 2), this.isIntercardinal());\n }\n\n public EightWayDirection[] getCardinalNeighbors() {\n if (this.isIntercardinal()) {\n return new EightWayDirection[]{EightWayDirection.byIndex(this.data2d, false), EightWayDirection.byIndex(this.data2d + 1, false)};\n }\n throw new IllegalStateException(\"Direction already is cardinal\");\n }\n\n public EightWayDirection[] getIntercardinalNeighbors() {\n if (this.isCardinal()) {\n return new EightWayDirection[]{EightWayDirection.byIndex(this.data2d + 3, true), EightWayDirection.byIndex(this.data2d, true)};\n }\n throw new IllegalStateException(\"Direction already is intercardinal\");\n }\n\n public Direction toDirection() {\n if (this.isCardinal()) {\n return Direction.from2DDataValue(this.data2d);\n }\n throw new IllegalStateException(\"Cannot convert intercardinal direction to vanilla direction\");\n }\n\n public EightWayDirection rotateClockWise() {\n return byIndex(this.isIntercardinal() ? this.data2d + 1 : this.data2d, !this.isIntercardinal());\n }\n\n public EightWayDirection rotateCounterClockWise() {\n return byIndex(this.isIntercardinal() ? this.data2d : this.data2d + 3, !this.isIntercardinal());\n }\n\n @Override\n public String getSerializedName() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}"
},
{
"identifier": "NoneVoxelShape",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/world/phys/shapes/NoneVoxelShape.java",
"snippet": "public class NoneVoxelShape extends ExtensibleVoxelShape {\n private final VoxelShape collisionShape;\n private final VoxelShape outlineShapeBase;\n private final List<Vec3[]> outlineShapeEdges;\n\n public NoneVoxelShape(VoxelShape collisionShape, Vec3... outlineShapeEdges) {\n this(collisionShape, Shapes.empty(), outlineShapeEdges);\n }\n\n public NoneVoxelShape(VoxelShape collisionShape, VoxelShape outlineShapeBase, Vec3... outlineShapeEdges) {\n super(collisionShape);\n this.collisionShape = collisionShape;\n this.outlineShapeBase = outlineShapeBase;\n this.outlineShapeEdges = this.createOutlineList(outlineShapeEdges);\n }\n\n private List<Vec3[]> createOutlineList(Vec3[] outlineShapeEdges) {\n if (outlineShapeEdges.length % 2 != 0) throw new IllegalStateException(\"Edges must be in groups of two points\");\n List<Vec3[]> list = Lists.newArrayList();\n for (int i = 0; i < outlineShapeEdges.length; i += 2) {\n list.add(new Vec3[]{outlineShapeEdges[i], outlineShapeEdges[i + 1]});\n }\n return list;\n }\n\n @Override\n protected DoubleList getCoords(Direction.Axis axis) {\n return ((VoxelShapeAccessor) this.collisionShape).callGetCoords(axis);\n }\n\n @Override\n public void forAllEdges(Shapes.DoubleLineConsumer boxConsumer) {\n this.outlineShapeBase.forAllEdges(boxConsumer);\n for (Vec3[] edge : this.outlineShapeEdges) {\n boxConsumer.consume(edge[0].x, edge[0].y, edge[0].z, edge[1].x, edge[1].y, edge[1].z);\n }\n }\n}"
},
{
"identifier": "VoxelCollection",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/world/phys/shapes/VoxelCollection.java",
"snippet": "public class VoxelCollection extends ExtensibleVoxelShape {\n private VoxelShape collisionShape;\n private VoxelShape outlineShape;\n private VoxelShape particleShape;\n private final List<NoneVoxelShape> noneVoxels = Lists.newArrayList();\n\n public VoxelCollection() {\n this(Shapes.empty());\n }\n\n public VoxelCollection(VoxelShape baseShape) {\n super(baseShape);\n this.collisionShape = baseShape;\n this.outlineShape = baseShape;\n this.particleShape = baseShape;\n }\n\n @Override\n protected DoubleList getCoords(Direction.Axis axis) {\n return ((VoxelShapeAccessor) this.collisionShape).callGetCoords(axis);\n }\n\n private void setCollisionShape(VoxelShape voxelShape) {\n this.collisionShape = voxelShape;\n ((VoxelShapeAccessor) this).setShape(((VoxelShapeAccessor) this.collisionShape).getShape());\n }\n\n public void addVoxelShape(VoxelShape voxelShape) {\n this.addVoxelShape(voxelShape, voxelShape);\n }\n\n public void addVoxelShape(VoxelShape voxelShape, VoxelShape particleShape) {\n if (voxelShape instanceof NoneVoxelShape) {\n this.addNoneVoxelShape((NoneVoxelShape) voxelShape);\n } else {\n this.setCollisionShape(Shapes.or(this.collisionShape, voxelShape));\n this.outlineShape = Shapes.or(this.outlineShape, voxelShape);\n }\n this.particleShape = Shapes.or(this.particleShape, particleShape);\n }\n\n private void addNoneVoxelShape(NoneVoxelShape voxelShape) {\n this.noneVoxels.add(voxelShape);\n // combine collision shapes\n this.setCollisionShape(Shapes.or(this.collisionShape, voxelShape));\n }\n\n public void forAllParticleBoxes(Shapes.DoubleLineConsumer doubleLineConsumer) {\n this.particleShape.forAllBoxes(doubleLineConsumer);\n }\n\n @Override\n public void forAllEdges(Shapes.DoubleLineConsumer boxConsumer) {\n this.outlineShape.forAllEdges(boxConsumer);\n this.noneVoxels.forEach(voxelShape -> voxelShape.forAllEdges(boxConsumer));\n }\n}"
},
{
"identifier": "VoxelUtils",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/world/phys/shapes/VoxelUtils.java",
"snippet": "public class VoxelUtils {\n\n public static Vec3[] scaleDown(Vec3[] edges) {\n return scale(edges, 0.0625);\n }\n\n public static Vec3[] scale(Vec3[] edges, double amount) {\n return Stream.of(edges).map(edge -> edge.scale(amount)).toArray(Vec3[]::new);\n }\n\n public static Vec3[] flipX(Vec3[] edges) {\n return Stream.of(edges).map(edge -> new Vec3(16.0 - edge.x, edge.y, edge.z)).toArray(Vec3[]::new);\n }\n\n public static Vec3[] flipZ(Vec3[] edges) {\n return Stream.of(edges).map(edge -> new Vec3(edge.x, edge.y, 16.0 - edge.z)).toArray(Vec3[]::new);\n }\n\n public static Vec3[] mirror(Vec3[] edges) {\n return flipZ(flipX(edges));\n }\n\n public static Vec3[] ortho(Vec3[] edges) {\n return Stream.of(edges).map(edge -> new Vec3(edge.z, edge.y, edge.x)).toArray(Vec3[]::new);\n }\n\n public static VoxelShape makeCuboidShape(Vec3[] outline) {\n Vec3 start = outline[0];\n Vec3 end = outline[1];\n double startX = Math.min(start.x, end.x);\n double startY = Math.min(start.y, end.y);\n double startZ = Math.min(start.z, end.z);\n double endX = Math.max(start.x, end.x);\n double endY = Math.max(start.y, end.y);\n double endZ = Math.max(start.z, end.z);\n return Block.box(startX, startY, startZ, endX, endY, endZ);\n }\n\n public static Vec3[] createVectorArray(Float... values) {\n return createVectorArray(Stream.of(values).map(Float::doubleValue).toArray(Double[]::new));\n }\n\n public static Vec3[] createVectorArray(Double... values) {\n if (values.length % 3 != 0) throw new IllegalStateException(\"Unable to create proper number of vectors\");\n Vec3[] array = new Vec3[values.length / 3];\n for (int i = 0; i < array.length; i++) {\n int index = 3 * i;\n array[i] = new Vec3(values[index], values[index + 1], values[index + 2]);\n }\n return array;\n }\n\n /**\n * @param corners provided edges as top left, top right, bottom left and bottom right\n * @return vectors as pairs representing the edges\n */\n public static Vec3[] create12Edges(Vec3[] corners) {\n if (corners.length != 8) throw new IllegalStateException(\"Amount of corners must be 8\");\n return new Vec3[]{\n // skew side\n corners[0], corners[1],\n corners[1], corners[3],\n corners[3], corners[2],\n corners[2], corners[0],\n // connections between skew sides\n corners[0], corners[4],\n corners[1], corners[5],\n corners[2], corners[6],\n corners[3], corners[7],\n // other skew side\n corners[4], corners[5],\n corners[5], corners[7],\n corners[7], corners[6],\n corners[6], corners[4]\n };\n }\n\n}"
}
] | import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import fuzs.diagonalwindows.DiagonalWindows;
import fuzs.diagonalwindows.api.world.level.block.DiagonalBlock;
import fuzs.diagonalwindows.api.world.level.block.EightWayDirection;
import fuzs.diagonalwindows.world.phys.shapes.NoneVoxelShape;
import fuzs.diagonalwindows.world.phys.shapes.VoxelCollection;
import fuzs.diagonalwindows.world.phys.shapes.VoxelUtils;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.CrossCollisionBlock;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream; | 3,905 | package fuzs.diagonalwindows.world.level.block;
public interface StarCollisionBlock extends DiagonalBlock {
/**
* calculating shape unions is rather expensive, and since {@link VoxelShape} is immutable we use a cache for all diagonal blocks with the same shape
*/
Map<List<Float>, VoxelShape[]> DIMENSIONS_TO_SHAPE_CACHE = Maps.newHashMap(); | package fuzs.diagonalwindows.world.level.block;
public interface StarCollisionBlock extends DiagonalBlock {
/**
* calculating shape unions is rather expensive, and since {@link VoxelShape} is immutable we use a cache for all diagonal blocks with the same shape
*/
Map<List<Float>, VoxelShape[]> DIMENSIONS_TO_SHAPE_CACHE = Maps.newHashMap(); | Map<EightWayDirection, BooleanProperty> DIRECTION_TO_PROPERTY_MAP = Util.make(Maps.newEnumMap(EightWayDirection.class), (directions) -> { | 2 | 2023-10-27 09:06:16+00:00 | 8k |
slatepowered/slate | slate-common/src/main/java/slatepowered/slate/packages/key/URLFilesDownload.java | [
{
"identifier": "Logger",
"path": "slate-common/src/main/java/slatepowered/slate/logging/Logger.java",
"snippet": "public interface Logger {\r\n\r\n /* Information */\r\n void info(Object... msg);\r\n default void info(Supplier<Object> msg) { info(msg.get()); }\r\n\r\n /* Warnings */\r\n void warn(Object... msg);\r\n default void warn(Supplier<Object> msg) { warn(msg.get()); }\r\n\r\n default void warning(Object... msg) {\r\n warn(msg);\r\n }\r\n\r\n default void warning(Supplier<Object> msg) {\r\n warn(msg);\r\n }\r\n\r\n /* Relatively unimportant errors */\r\n void error(Object... msg);\r\n default void error(Supplier<Object> msg) { error(msg); }\r\n\r\n /* Severe errors */\r\n void severe(Object... msg);\r\n default void severe(Supplier<Object> msg) { severe(msg); }\r\n\r\n /* Fatal errors */\r\n void fatal(Object... msg);\r\n default void fatal(Supplier<Object> msg) { fatal(msg); }\r\n\r\n /* Debug messages */\r\n void debug(Object... msg);\r\n default void debug(Supplier<Object> msg) { if (Logging.DEBUG) debug(msg.get()); }\r\n\r\n default void trace(Object... msg) {\r\n if (Logging.DEBUG) {\r\n debug(msg);\r\n\r\n // print the stack trace\r\n StackTraceElement[] elements = new RuntimeException().getStackTrace();\r\n for (int i = 1; i < elements.length; i++) {\r\n debug(elements[i]);\r\n }\r\n }\r\n }\r\n\r\n default void trace(Supplier<Object> msg) {\r\n if (Logging.DEBUG) trace(msg.get());\r\n }\r\n\r\n /**\r\n * Create a logger which doesn't do anything when the methods\r\n * are called.\r\n *\r\n * @return The voiding logger.\r\n */\r\n static Logger voiding() {\r\n return new Logger() {\r\n @Override\r\n public void info(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void warn(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void error(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void severe(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void fatal(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void debug(Object... msg) {\r\n\r\n }\r\n };\r\n }\r\n\r\n}\r"
},
{
"identifier": "Logging",
"path": "slate-common/src/main/java/slatepowered/slate/logging/Logging.java",
"snippet": "public class Logging {\r\n\r\n /**\r\n * Whether to do debug logging.\r\n */\r\n public static boolean DEBUG;\r\n\r\n /**\r\n * The current set logger provider.\r\n */\r\n private static LoggerProvider provider;\r\n\r\n static {\r\n DEBUG = Boolean.parseBoolean(System.getProperty(\"slate.debug\", \"false\"));\r\n }\r\n\r\n /**\r\n * Set whether debug messages should be shown.\r\n *\r\n * @param debug The debug flag value.\r\n */\r\n public static void setDebug(boolean debug) {\r\n DEBUG = debug;\r\n }\r\n\r\n public static void setProvider(LoggerProvider provider1) {\r\n if (provider != null)\r\n return; // silently fail\r\n provider = provider1;\r\n }\r\n\r\n /**\r\n * Get the currently active logger provider.\r\n *\r\n * @return The logger provider.\r\n */\r\n public static LoggerProvider getProvider() {\r\n return provider;\r\n }\r\n\r\n /**\r\n * Get the consistently configured logger for the given name.\r\n *\r\n * @param name The name.\r\n * @return The logger.\r\n */\r\n public static Logger getLogger(String name) {\r\n return provider != null ? provider.getLogger(name) : Logger.voiding();\r\n }\r\n\r\n}\r"
},
{
"identifier": "PackageKey",
"path": "slate-common/src/main/java/slatepowered/slate/packages/PackageKey.java",
"snippet": "public interface PackageKey<P extends LocalPackage> {\r\n\r\n /**\r\n * Hash this key to a UUID.\r\n *\r\n * @return The UUID.\r\n */\r\n UUID toUUID();\r\n\r\n /**\r\n * Get the provider key for this package.\r\n *\r\n * @return The provider key.\r\n */\r\n default String getProvider() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Get the operational package key which should be used for local operations.\r\n *\r\n * @return The base package key.\r\n */\r\n default PackageKey<P> baseKey() {\r\n return this;\r\n }\r\n\r\n /**\r\n * Get the identifier for the resources of this package.\r\n *\r\n * @return The identifier.\r\n */\r\n default String getIdentifier() {\r\n return toUUID().toString();\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n default CompletableFuture<P> findOrInstall(PackageManager manager) {\r\n return manager.findOrInstallPackage(this);\r\n }\r\n\r\n /**\r\n * Utility: convert the given string to a valid UUID\r\n */\r\n static UUID stringToUUID(String str) {\r\n return UUID.nameUUIDFromBytes(str.getBytes(StandardCharsets.UTF_8));\r\n }\r\n\r\n /**\r\n * Create a named package key wrapping the given key type.\r\n *\r\n * @param key The key.\r\n * @param name The name.\r\n * @param <P> The package type.\r\n * @return The named package key.\r\n */\r\n static <P extends LocalPackage> PackageKey<P> wrapNamed(PackageKey<P> key,\r\n String name) {\r\n return new PackageKey<P>() {\r\n // The cached UUID of this package key\r\n private final UUID uuid = stringToUUID(name);\r\n\r\n @Override\r\n public UUID toUUID() {\r\n return uuid;\r\n }\r\n\r\n @Override\r\n public PackageKey<P> baseKey() {\r\n return key;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return name;\r\n }\r\n\r\n @Override\r\n public String getIdentifier() {\r\n return name;\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Create a named package key.\r\n *\r\n * @param name The name.\r\n * @param <P> The package type.\r\n * @return The named package key.\r\n */\r\n static <P extends LocalPackage> PackageKey<P> named(String name) {\r\n return new PackageKey<P>() {\r\n // The cached UUID of this package key\r\n private final UUID uuid = stringToUUID(name);\r\n\r\n @Override\r\n public UUID toUUID() {\r\n return uuid;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return name;\r\n }\r\n\r\n @Override\r\n public String getIdentifier() {\r\n return name;\r\n }\r\n };\r\n }\r\n\r\n}\r"
},
{
"identifier": "PackageManager",
"path": "slate-common/src/main/java/slatepowered/slate/packages/PackageManager.java",
"snippet": "@SuppressWarnings(\"rawtypes\")\r\npublic class PackageManager implements Service {\r\n\r\n private static final Logger LOGGER = Logging.getLogger(\"PackageManager\");\r\n\r\n public static final ServiceKey<PackageManager> KEY = ServiceKey.local(PackageManager.class);\r\n\r\n /**\r\n * The service manager this package manager has access to.\r\n */\r\n protected final ServiceManager serviceManager;\r\n\r\n /**\r\n * The cached local packages by package key.\r\n */\r\n protected final Map<PackageKey, LocalPackage> localPackageMap = new ConcurrentHashMap<>();\r\n\r\n /**\r\n * The cached resolved packages.\r\n */\r\n protected final Map<PackageKey, ResolvedPackage> resolvedPackageCache = new ConcurrentHashMap<>();\r\n\r\n /**\r\n * The local package directory.\r\n */\r\n protected final Path directory;\r\n\r\n /**\r\n * The list of package resolvers.\r\n */\r\n protected final List<PackageResolver> packageResolvers = new ArrayList<>();\r\n\r\n public PackageManager(ServiceManager serviceManager, Path directory) {\r\n this.serviceManager = serviceManager;\r\n this.directory = directory;\r\n\r\n try {\r\n Files.createDirectories(directory);\r\n } catch (Throwable t) {\r\n throw new RuntimeException(\"Failed to initialize local package manager dir(\" + directory + \")\", t);\r\n }\r\n }\r\n\r\n public ServiceManager getServiceManager() {\r\n return serviceManager;\r\n }\r\n\r\n /**\r\n * Registers each resolver in the given varargs array\r\n * as a package resolver for this package manager.\r\n *\r\n * @param resolvers The resolvers to register.\r\n * @return This.\r\n */\r\n public PackageManager with(PackageResolver... resolvers) {\r\n packageResolvers.addAll(Arrays.asList(resolvers));\r\n return this;\r\n }\r\n\r\n /**\r\n * Get a cached package for the given key.\r\n *\r\n * @param key The key.\r\n * @return The cached local package or null if absent/not cached.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public <P extends LocalPackage> P getCachedPackage(PackageKey<P> key) {\r\n return (P) localPackageMap.get(key);\r\n }\r\n\r\n /**\r\n * Newly resolve the given package key.\r\n *\r\n * @param key The package key.\r\n * @return The result future.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n protected <P extends LocalPackage> CompletableFuture<ResolvedPackage<?, P>> resolvePackage0(PackageKey<P> key) {\r\n LOGGER.debug(\"Resolving package key: \" + key);\r\n if (key.baseKey() instanceof TrivialPackageKey) {\r\n CompletableFuture<ResolvedPackage<?, P>> future = ((TrivialPackageKey<P>)key.baseKey()).resolve(this);\r\n if (future != null) {\r\n LOGGER.debug(\" Resolved by TrivialPackageKey\");\r\n return future;\r\n }\r\n }\r\n\r\n // try the resolvers\r\n for (PackageResolver resolver : packageResolvers) {\r\n if (resolver.canResolve(this, key)) {\r\n CompletableFuture<ResolvedPackage<?, ?>> future =\r\n resolver.tryResolve(this, key);\r\n if (future != null) {\r\n LOGGER.debug(\" Resolved by PackageResolver: \" + resolver);\r\n return (CompletableFuture<ResolvedPackage<?,P>>)(Object) future;\r\n }\r\n }\r\n }\r\n\r\n throw new IllegalStateException(\"Failed to resolve package `\" + key + \"`\");\r\n }\r\n\r\n /**\r\n * Find the given key in the cache or newly resolve the given package key.\r\n *\r\n * @param key The package key.\r\n * @return The resolved package future.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public <P extends LocalPackage> CompletableFuture<ResolvedPackage<?, P>> resolvePackage(PackageKey<P> key) {\r\n ResolvedPackage<?, P> resolvedPackage = resolvedPackageCache.get(key);\r\n if (resolvedPackage != null) {\r\n return CompletableFuture.completedFuture(resolvedPackage);\r\n }\r\n\r\n CompletableFuture<ResolvedPackage<?, P>> future = resolvePackage0(key);\r\n future.whenComplete(((resolved, throwable) -> {\r\n if (throwable != null) {\r\n LOGGER.warning(\"Failed to resolve package by key: \" + key);\r\n throwable.printStackTrace();\r\n return;\r\n }\r\n\r\n LOGGER.debug(\"Resolved packageKey(\" + key + \") -> resolvedPackage(\" + resolved + \")\");\r\n resolvedPackageCache.put(key, resolved);\r\n\r\n // store this result in the package instance\r\n final LocalPackage localPackage = getCachedPackage(key);\r\n }));\r\n\r\n return future;\r\n }\r\n\r\n /**\r\n * Find or load a locally installed package.\r\n *\r\n * @param key The key.\r\n * @return The package or null if absent.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public <P extends LocalPackage> P findOrLoadPackage(PackageKey<P> key) {\r\n P localPackage = getCachedPackage(key);\r\n // todo: currently joining the resolving process, idk if that's good\r\n return localPackage != null ? localPackage : findOrLoadPackage(resolvePackage(key).join());\r\n }\r\n\r\n /**\r\n * Find or load a locally installed package by resolved key.\r\n *\r\n * @param resolvedKey The resolved key.\r\n * @return The package or null if absent.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public <P extends LocalPackage> P findOrLoadPackage(ResolvedPackage<?, P> resolvedKey) {\r\n LOGGER.debug(\"Find or load package resolvedKey(\" + resolvedKey + \")\");\r\n PackageKey<P> key = resolvedKey.getKey();\r\n P localPackage = getCachedPackage(key);\r\n\r\n if (localPackage == null) {\r\n String dirName = key.getIdentifier();\r\n Path path = directory.resolve(dirName);\r\n\r\n // try to load data to local package, this should\r\n // check whether the path exists itself if that's needed;\r\n // for dynamic packages this should working without an existing\r\n // file or directory\r\n LOGGER.debug(\"Trying to load installed package data from path(\" + path + \") by(\" + resolvedKey + \")\");\r\n localPackage = resolvedKey.loadLocally(this, path);\r\n\r\n if (localPackage == null) LOGGER.debug(\" No installed package found: localPackage = null\");\r\n else LOGGER.debug(\" Found and loaded localPackage: \" + localPackage);\r\n }\r\n\r\n return localPackage;\r\n }\r\n\r\n /**\r\n * Find the given package if locally cached or else\r\n * try and install the package locally.\r\n *\r\n * @param resolvedKey The resolved key.\r\n * @return The future for the local package.\r\n */\r\n public <P extends LocalPackage> CompletableFuture<P> findOrInstallPackage(ResolvedPackage<?, P> resolvedKey) {\r\n PackageKey<P> key = resolvedKey.getKey();\r\n P localPackage = findOrLoadPackage(resolvedKey);\r\n if (localPackage == null) {\r\n // install package\r\n LOGGER.debug(\"Installing package resolvedKey(\" + resolvedKey + \") uuid(\" + key.toUUID() + \")\");\r\n return resolvedKey.installLocally(\r\n this,\r\n this.directory.resolve(key.toUUID().toString())\r\n ).exceptionally(throwable -> {\r\n// LOGGER.warn(\"Failed to install package \" + resolvedKey);\r\n// throwable.printStackTrace();\r\n\r\n throw new RuntimeException(\"Failed to install package \" + resolvedKey, throwable);\r\n });\r\n }\r\n\r\n return CompletableFuture.completedFuture(localPackage);\r\n }\r\n\r\n /**\r\n * Find the given package if locally cached or else\r\n * try and install the package locally.\r\n *\r\n * @param key The key.\r\n * @return The future for the local package.\r\n */\r\n public <P extends LocalPackage> CompletableFuture<P> findOrInstallPackage(PackageKey<P> key) {\r\n return resolvePackage(key).thenCompose(this::findOrInstallPackage);\r\n }\r\n\r\n}\r"
},
{
"identifier": "LocalFilesPackage",
"path": "slate-common/src/main/java/slatepowered/slate/packages/local/LocalFilesPackage.java",
"snippet": "public class LocalFilesPackage extends LocalPackage {\r\n\r\n public LocalFilesPackage(PackageManager manager, ResolvedPackage<?, ?> key, Path path) {\r\n super(manager, key, path);\r\n }\r\n\r\n}\r"
}
] | import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import slatepowered.slate.logging.Logger;
import slatepowered.slate.logging.Logging;
import slatepowered.slate.packages.PackageKey;
import slatepowered.slate.packages.PackageManager;
import slatepowered.slate.packages.local.LocalFilesPackage;
import slatepowered.veru.data.Pair;
import slatepowered.veru.io.IOUtil;
import slatepowered.veru.misc.Throwables;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
| 3,693 | package slatepowered.slate.packages.key;
/**
* A resolved package key which downloads a file.
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class URLFilesDownload extends ResolvedPackageKeyUnion<URLFilesDownload, LocalFilesPackage> {
| package slatepowered.slate.packages.key;
/**
* A resolved package key which downloads a file.
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class URLFilesDownload extends ResolvedPackageKeyUnion<URLFilesDownload, LocalFilesPackage> {
| private static final Logger LOGGER = Logging.getLogger("URLFilesDownload");
| 0 | 2023-10-30 08:58:02+00:00 | 8k |
Ax3dGaming/Sons-Of-Sins-Organs-Addition | src/main/java/com/axed/compat/JEISosorgansPlugin.java | [
{
"identifier": "ModBlocks",
"path": "src/main/java/com/axed/block/ModBlocks.java",
"snippet": "public class ModBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID);\n\n public static final RegistryObject<Block> ORGAN_CREATOR = registerBlock(\"organ_creator\", () -> new OrganCreatorBlock());\n\n\n\n private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block) {\n RegistryObject<T> toReturn = BLOCKS.register(name, block);\n registerBlockItem(name, toReturn);\n return toReturn;\n }\n\n private static <T extends Block> RegistryObject<Item> registerBlockItem(String name, RegistryObject<T> block) {\n return ModItems.ITEMS.register(name, () -> new BlockItem(block.get(), new Item.Properties()));\n }\n\n public static void register(IEventBus eventBus) {\n BLOCKS.register(eventBus);\n }\n}"
},
{
"identifier": "ModBlockEntities",
"path": "src/main/java/com/axed/block/entity/ModBlockEntities.java",
"snippet": "public class ModBlockEntities {\n public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES =\n DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, sosorgans.MODID);\n\n public static final RegistryObject<BlockEntityType<OrganCreatorBlockEntity>> ORGAN_CREATOR_BE =\n BLOCK_ENTITIES.register(\"organ_creator_be\", () ->\n BlockEntityType.Builder.of(OrganCreatorBlockEntity::new,\n ModBlocks.ORGAN_CREATOR.get()).build(null));\n\n\n public static void register(IEventBus eventBus) {\n BLOCK_ENTITIES.register(eventBus);\n }\n}"
},
{
"identifier": "ModRecipes",
"path": "src/main/java/com/axed/recipe/ModRecipes.java",
"snippet": "public class ModRecipes {\n public static final DeferredRegister<RecipeSerializer<?>> SERIALIZERS =\n DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, sosorgans.MODID);\n\n public static final RegistryObject<RecipeSerializer<OrganCreatorRecipe>> ORGAN_CREATION_SERIALIZER =\n SERIALIZERS.register(\"organ_creation\", () -> OrganCreatorRecipe.Serializer.INSTANCE);\n\n public static void register(IEventBus eventBus) {\n SERIALIZERS.register(eventBus);\n }\n}"
},
{
"identifier": "OrganCreatorRecipe",
"path": "src/main/java/com/axed/recipe/OrganCreatorRecipe.java",
"snippet": "public class OrganCreatorRecipe implements Recipe<SimpleContainer> {\n private final NonNullList<Ingredient> inputItems;\n private final ItemStack output;\n private final ResourceLocation id;\n\n public OrganCreatorRecipe(NonNullList<Ingredient> inputItems, ItemStack output, ResourceLocation id) {\n this.inputItems = inputItems;\n this.output = output;\n this.id = id;\n }\n\n @Override\n public boolean matches(SimpleContainer pContainer, Level pLevel) {\n if(pLevel.isClientSide()) {\n return false;\n }\n\n return inputItems.get(0).test(pContainer.getItem(0)) && inputItems.get(1).test(pContainer.getItem(1));\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return inputItems;\n }\n\n @Override\n public ItemStack assemble(SimpleContainer pContainer, RegistryAccess pRegistryAccess) {\n return output.copy();\n }\n\n @Override\n public boolean canCraftInDimensions(int pWidth, int pHeight) {\n return true;\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess pRegistryAccess) {\n return output.copy();\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return Serializer.INSTANCE;\n }\n\n @Override\n public RecipeType<?> getType() {\n return Type.INSTANCE;\n }\n\n public static class Type implements RecipeType<OrganCreatorRecipe> {\n private Type() {}\n public static final Type INSTANCE = new Type();\n public static final String ID = \"organ_creation\";\n }\n\n public static class Serializer implements RecipeSerializer<OrganCreatorRecipe> {\n public static final Serializer INSTANCE = new Serializer();\n public static final ResourceLocation ID = new ResourceLocation(sosorgans.MODID, \"organ_creation\");\n\n @Override\n public OrganCreatorRecipe fromJson(ResourceLocation id, JsonObject json) {\n ItemStack output = ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"output\"));\n\n JsonArray ingredients = GsonHelper.getAsJsonArray(json, \"ingredients\");\n NonNullList<Ingredient> inputs = NonNullList.withSize(2, Ingredient.EMPTY);\n\n for(int i = 0; i < inputs.size(); i++) {\n inputs.set(i, Ingredient.fromJson(ingredients.get(i)));\n }\n\n return new OrganCreatorRecipe(inputs, output, id);\n }\n\n @Override\n public @Nullable OrganCreatorRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n NonNullList<Ingredient> inputs = NonNullList.withSize(buf.readInt(), Ingredient.EMPTY);\n\n for(int i = 0; i < inputs.size(); i++) {\n inputs.set(i, Ingredient.fromNetwork(buf));\n }\n\n ItemStack output = buf.readItem();\n return new OrganCreatorRecipe(inputs, output, id);\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, OrganCreatorRecipe recipe) {\n buf.writeInt(recipe.getIngredients().size());\n\n for (Ingredient ing : recipe.getIngredients()) {\n ing.toNetwork(buf);\n }\n\n buf.writeItemStack(recipe.getResultItem(null), false);\n }\n }\n}"
},
{
"identifier": "ModMenuTypes",
"path": "src/main/java/com/axed/screen/ModMenuTypes.java",
"snippet": "public class ModMenuTypes {\n public static final DeferredRegister<MenuType<?>> MENUS =\n DeferredRegister.create(ForgeRegistries.MENU_TYPES, sosorgans.MODID);\n\n public static final RegistryObject<MenuType<OrganCreatorMenu>> ORGAN_CREATOR_MENU =\n registerMenuType(\"organ_creator_menu\", OrganCreatorMenu::new);\n\n\n private static <T extends AbstractContainerMenu>RegistryObject<MenuType<T>> registerMenuType(String name, IContainerFactory<T> factory) {\n return MENUS.register(name, () -> IForgeMenuType.create(factory));\n }\n\n public static void register(IEventBus eventBus) {\n MENUS.register(eventBus);\n }\n}"
},
{
"identifier": "OrganCreatorMenu",
"path": "src/main/java/com/axed/screen/OrganCreatorMenu.java",
"snippet": "public class OrganCreatorMenu extends AbstractContainerMenu {\n public final OrganCreatorBlockEntity blockEntity;\n private final Level level;\n private final ContainerData data;\n\n public OrganCreatorMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) {\n this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos()), new SimpleContainerData(3));\n }\n\n public OrganCreatorMenu(int pContainerId, Inventory inv, BlockEntity entity, ContainerData data) {\n super(ModMenuTypes.ORGAN_CREATOR_MENU.get(), pContainerId);\n checkContainerSize(inv, 3);\n blockEntity = ((OrganCreatorBlockEntity) entity);\n this.level = inv.player.level();\n this.data = data;\n\n addPlayerInventory(inv);\n addPlayerHotbar(inv);\n\n this.blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(iItemHandler -> {\n this.addSlot(new SlotItemHandler(iItemHandler, 0, 64, 11));\n this.addSlot(new SlotItemHandler(iItemHandler, 1, 96, 11));\n this.addSlot(new SlotItemHandler(iItemHandler, 2, 80, 59));\n });\n\n addDataSlots(data);\n }\n\n public boolean isCrafting() {\n return data.get(0) > 0;\n }\n\n public int getScaledProgress() {\n int progress = this.data.get(0);\n int maxProgress = this.data.get(1); // Max Progress\n int progressArrowSize = 26; // This is the height in pixels of your arrow\n\n return maxProgress != 0 && progress != 0 ? progress * progressArrowSize / maxProgress : 0;\n }\n\n // CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons\n // must assign a slot number to each of the slots used by the GUI.\n // For this container, we can see both the tile inventory's slots as well as the player inventory slots and the hotbar.\n // Each time we add a Slot to the container, it automatically increases the slotIndex, which means\n // 0 - 8 = hotbar slots (which will map to the InventoryPlayer slot numbers 0 - 8)\n // 9 - 35 = player inventory slots (which map to the InventoryPlayer slot numbers 9 - 35)\n // 36 - 44 = TileInventory slots, which map to our TileEntity slot numbers 0 - 8)\n private static final int HOTBAR_SLOT_COUNT = 9;\n private static final int PLAYER_INVENTORY_ROW_COUNT = 3;\n private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;\n private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;\n private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT;\n private static final int VANILLA_FIRST_SLOT_INDEX = 0;\n private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT;\n\n // THIS YOU HAVE TO DEFINE!\n private static final int TE_INVENTORY_SLOT_COUNT = 3; // must be the number of slots you have!\n @Override\n public ItemStack quickMoveStack(Player playerIn, int pIndex) {\n Slot sourceSlot = slots.get(pIndex);\n if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; //EMPTY_ITEM\n ItemStack sourceStack = sourceSlot.getItem();\n ItemStack copyOfSourceStack = sourceStack.copy();\n\n // Check if the slot clicked is one of the vanilla container slots\n if (pIndex < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) {\n // This is a vanilla container slot so merge the stack into the tile inventory\n if (!moveItemStackTo(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX\n + TE_INVENTORY_SLOT_COUNT, false)) {\n return ItemStack.EMPTY; // EMPTY_ITEM\n }\n } else if (pIndex < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) {\n // This is a TE slot so merge the stack into the players inventory\n if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) {\n return ItemStack.EMPTY;\n }\n } else {\n System.out.println(\"Invalid slotIndex:\" + pIndex);\n return ItemStack.EMPTY;\n }\n // If stack size == 0 (the entire stack was moved) set slot contents to null\n if (sourceStack.getCount() == 0) {\n sourceSlot.set(ItemStack.EMPTY);\n } else {\n sourceSlot.setChanged();\n }\n sourceSlot.onTake(playerIn, sourceStack);\n return copyOfSourceStack;\n }\n\n @Override\n public boolean stillValid(Player pPlayer) {\n return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()),\n pPlayer, ModBlocks.ORGAN_CREATOR.get());\n }\n\n private void addPlayerInventory(Inventory playerInventory) {\n for (int i = 0; i < 3; ++i) {\n for (int l = 0; l < 9; ++l) {\n this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18));\n }\n }\n }\n\n private void addPlayerHotbar(Inventory playerInventory) {\n for (int i = 0; i < 9; ++i) {\n this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));\n }\n }\n}"
},
{
"identifier": "OrganCreatorScreen",
"path": "src/main/java/com/axed/screen/OrganCreatorScreen.java",
"snippet": "public class OrganCreatorScreen extends AbstractContainerScreen<OrganCreatorMenu> {\n private static final ResourceLocation TEXTURE =\n new ResourceLocation(sosorgans.MODID, \"textures/gui/organ_creator_gui.png\");\n\n public OrganCreatorScreen(OrganCreatorMenu pMenu, Inventory pPlayerInventory, Component pTitle) {\n super(pMenu, pPlayerInventory, pTitle);\n }\n\n @Override\n protected void renderBg(GuiGraphics guiGraphics, float pPartialTick, int pMouseX, int pMouseY) {\n RenderSystem.setShader(GameRenderer::getPositionTexShader);\n RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);\n RenderSystem.setShaderTexture(0, TEXTURE);\n int x = (width - imageWidth) / 2;\n int y = (height - imageHeight) / 2;\n\n guiGraphics.blit(TEXTURE, x, y, 0, 0, imageWidth, imageHeight);\n\n renderProgressArrow(guiGraphics, x, y);\n }\n\n private void renderProgressArrow(GuiGraphics guiGraphics, int x, int y) {\n if(menu.isCrafting()) {\n guiGraphics.blit(TEXTURE, x + 84, y + 30, 176, 0, 8, menu.getScaledProgress());\n }\n }\n\n @Override\n public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) {\n renderBackground(guiGraphics);\n super.render(guiGraphics, mouseX, mouseY, delta);\n renderTooltip(guiGraphics, mouseX, mouseY);\n }\n}"
},
{
"identifier": "sosorgans",
"path": "src/main/java/com/axed/sosorgans.java",
"snippet": "@Mod(sosorgans.MODID)\npublic class sosorgans\n{\n public static final String MODID = \"sosorgans\";\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public sosorgans()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n SERIALIZERS.register(modEventBus);\n BLOCKS.register(modEventBus);\n ITEMS.register(modEventBus);\n BLOCK_ENTITIES.register(modEventBus);\n CREATIVE_MODE_TABS.register(modEventBus);\n MENUS.register(modEventBus);\n\n MinecraftForge.EVENT_BUS.register(this);\n\n //modEventBus.addListener(this::addCreative);\n\n ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);\n }\n\n private void commonSetup(final FMLCommonSetupEvent event){}\n\n //private void addCreative(BuildCreativeModeTabContentsEvent event)\n //{\n //if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)\n //event.accept();\n //}\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n // Do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n MenuScreens.register(ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreatorScreen::new);\n }\n }\n}"
}
] | import com.axed.block.ModBlocks;
import com.axed.block.entity.ModBlockEntities;
import com.axed.recipe.ModRecipes;
import com.axed.recipe.OrganCreatorRecipe;
import com.axed.screen.ModMenuTypes;
import com.axed.screen.OrganCreatorMenu;
import com.axed.screen.OrganCreatorScreen;
import com.axed.sosorgans;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.JeiPlugin;
import mezz.jei.api.registration.*;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeManager;
import java.util.List; | 4,132 | package com.axed.compat;
@JeiPlugin
public class JEISosorgansPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(sosorgans.MODID, "jei_plugin");
}
@Override
public void registerCategories(IRecipeCategoryRegistration registration) {
registration.addRecipeCategories(new OrganCreationCategory(registration.getJeiHelpers().getGuiHelper()));
}
public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) {
registration.addRecipeTransferHandler(OrganCreatorMenu.class, ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreationCategory.ORGAN_CREATION_TYPE, 36, 2, 0, 36);
}
@Override
public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(new ItemStack(ModBlocks.ORGAN_CREATOR.get()), OrganCreationCategory.ORGAN_CREATION_TYPE);
}
@Override
public void registerRecipes(IRecipeRegistration registration) {
RecipeManager recipeManager = Minecraft.getInstance().level.getRecipeManager();
| package com.axed.compat;
@JeiPlugin
public class JEISosorgansPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(sosorgans.MODID, "jei_plugin");
}
@Override
public void registerCategories(IRecipeCategoryRegistration registration) {
registration.addRecipeCategories(new OrganCreationCategory(registration.getJeiHelpers().getGuiHelper()));
}
public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) {
registration.addRecipeTransferHandler(OrganCreatorMenu.class, ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreationCategory.ORGAN_CREATION_TYPE, 36, 2, 0, 36);
}
@Override
public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(new ItemStack(ModBlocks.ORGAN_CREATOR.get()), OrganCreationCategory.ORGAN_CREATION_TYPE);
}
@Override
public void registerRecipes(IRecipeRegistration registration) {
RecipeManager recipeManager = Minecraft.getInstance().level.getRecipeManager();
| List<OrganCreatorRecipe> organRecipes = recipeManager.getAllRecipesFor(OrganCreatorRecipe.Type.INSTANCE); | 3 | 2023-10-25 19:33:18+00:00 | 8k |
gianlucameloni/shelly-em | src/main/java/com/gmeloni/shelly/service/ScheduledService.java | [
{
"identifier": "GetEMStatusResponse",
"path": "src/main/java/com/gmeloni/shelly/dto/rest/GetEMStatusResponse.java",
"snippet": "@Data\npublic class GetEMStatusResponse {\n @JsonProperty(\"unixtime\")\n private Long unixTime;\n @JsonProperty(\"emeters\")\n private List<RawEMSample> rawEMSamples;\n}"
},
{
"identifier": "HourlyEMEnergy",
"path": "src/main/java/com/gmeloni/shelly/model/HourlyEMEnergy.java",
"snippet": "@Entity\n@Table(name = \"hourly_em_energy\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PUBLIC)\n@Getter\n@EqualsAndHashCode\n@NamedNativeQuery(\n name = \"SelectHourlyAggregateByYearMonthDay\",\n query = \"\"\"\n select\n hour(from_timestamp) as hour,\n grid_energy_in,\n grid_energy_out,\n pv_energy_in,\n pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and\n day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd'))\n order by\n hour desc\n \"\"\",\n resultSetMapping = \"SelectHourlyAggregateByYearMonthDayMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectHourlyAggregateByYearMonthDayMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"hour\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n },\n targetClass = HourlyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYearMonthDay\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and\n day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMonthDayMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMonthDayMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class),\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectDailyAggregateByYearMonth\",\n query = \"\"\"\n select\n day(from_timestamp) as day,\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd'))\n group by\n day(from_timestamp)\n order by\n day desc\n \"\"\",\n resultSetMapping = \"SelectDailyAggregateByYearMonthMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectDailyAggregateByYearMonthMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"day\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class)\n },\n targetClass = DailyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYearMonth\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMonthMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMonthMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectMonthlyAggregateByYear\",\n query = \"\"\"\n select\n month(from_timestamp) as month,\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd'))\n group by\n year(from_timestamp), month(from_timestamp)\n order by\n month desc\n \"\"\",\n resultSetMapping = \"SelectMonthlyAggregateByYearMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectMonthlyAggregateByYearMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"month\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class)\n },\n targetClass = MonthlyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYear\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotals\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n \"\"\",\n resultSetMapping = \"SelectTotalsMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\npublic class HourlyEMEnergy implements Serializable {\n @Id\n @Column(name = \"from_timestamp\")\n private LocalDateTime fromTimestamp;\n @Column(name = \"to_timestamp\")\n private LocalDateTime toTimestamp;\n @Column(name = \"grid_energy_in\")\n private Double gridEnergyIn;\n @Column(name = \"grid_energy_out\")\n private Double gridEnergyOut;\n @Column(name = \"pv_energy_in\")\n private Double pvEnergyIn;\n @Column(name = \"pv_energy_out\")\n private Double pvEnergyOut;\n @Column(name = \"max_grid_voltage\")\n private Double maxGridVoltage;\n @Column(name = \"min_grid_voltage\")\n private Double minGridVoltage;\n @Column(name = \"max_pv_voltage\")\n private Double maxPvVoltage;\n @Column(name = \"min_pv_voltage\")\n private Double minPvVoltage;\n}"
},
{
"identifier": "RawEMData",
"path": "src/main/java/com/gmeloni/shelly/model/RawEMData.java",
"snippet": "@Entity\n@Table(name = \"raw_em_data\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PUBLIC)\n@Getter\n@EqualsAndHashCode\npublic class RawEMData implements Serializable {\n @Id\n @Column(name = \"sample_timestamp\")\n private LocalDateTime sampleTimestamp;\n @Column(name = \"grid_power\")\n private Double gridPower;\n @Column(name = \"pv_power\")\n private Double pvPower;\n @Column(name = \"grid_voltage\")\n private Double gridVoltage;\n @Column(name = \"pv_voltage\")\n private Double pvVoltage;\n}"
},
{
"identifier": "HourlyEMEnergyRepository",
"path": "src/main/java/com/gmeloni/shelly/repository/HourlyEMEnergyRepository.java",
"snippet": "@Repository\npublic interface HourlyEMEnergyRepository extends CrudRepository<HourlyEMEnergy, LocalDateTime> {\n}"
},
{
"identifier": "RawEMDataRepository",
"path": "src/main/java/com/gmeloni/shelly/repository/RawEMDataRepository.java",
"snippet": "@Repository\npublic interface RawEMDataRepository extends CrudRepository<RawEMData, LocalDateTime> {\n\n @Query(value = \"select * from raw_em_data where sample_timestamp >= ?1 and sample_timestamp < ?2\", nativeQuery = true)\n List<RawEMData> findAllBySampleTimestampBetween(LocalDateTime from, LocalDateTime to);\n\n RawEMData findTopByOrderBySampleTimestampDesc();\n\n}"
},
{
"identifier": "DATE_AND_TIME_FORMAT",
"path": "src/main/java/com/gmeloni/shelly/Constants.java",
"snippet": "public static final String DATE_AND_TIME_FORMAT = \"yyyy-MM-dd HH:mm:ss\";"
}
] | import com.gmeloni.shelly.dto.rest.GetEMStatusResponse;
import com.gmeloni.shelly.model.HourlyEMEnergy;
import com.gmeloni.shelly.model.RawEMData;
import com.gmeloni.shelly.repository.HourlyEMEnergyRepository;
import com.gmeloni.shelly.repository.RawEMDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.TimeZone;
import static com.gmeloni.shelly.Constants.DATE_AND_TIME_FORMAT; | 3,883 | package com.gmeloni.shelly.service;
@Service
public class ScheduledService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
@Autowired
private RawEMDataService rawEMDataService;
@Autowired
private RawEMDataRepository rawEmDataRepository;
@Autowired
private HourlyEMEnergyRepository hourlyEMEnergyRepository;
@Value("${raw-em.sampling.period.milliseconds}")
private String samplingPeriodInMilliseconds;
@Value("${raw-em.sampling.threshold}")
private Double samplingThreshold;
@Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}")
public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
LocalDateTime sampleDateTime = LocalDateTime.ofInstant(
Instant.ofEpochSecond(getEMStatusResponse.getUnixTime()),
TimeZone.getTimeZone("Europe/Rome").toZoneId()
);
Double gridPower = getEMStatusResponse.getRawEMSamples().get(0).getPower();
Double pvPower = getEMStatusResponse.getRawEMSamples().get(1).getPower();
Double gridVoltage = getEMStatusResponse.getRawEMSamples().get(0).getVoltage();
Double pvVoltage = getEMStatusResponse.getRawEMSamples().get(1).getVoltage();
RawEMData rawEmData = new RawEMData(
sampleDateTime,
gridPower,
pvPower,
gridVoltage,
pvVoltage
);
rawEmDataRepository.save(rawEmData);
log.info("Saved raw EM data: [{}, {}, {}, {}, {}]", sampleFormatter.format(sampleDateTime), String.format("%.2f", gridPower), String.format("%.2f", pvPower), String.format("%.2f", gridVoltage), String.format("%.2f", pvVoltage));
}
@Scheduled(cron = "${raw-em.hourly-aggregate.cron.schedule}", zone = "Europe/Rome")
public void processHourlyAggregatedData() {
final double dt = Double.parseDouble(samplingPeriodInMilliseconds) / 1000 / 3600;
LocalDateTime fromTimestamp = LocalDateTime.now().minusHours(1).truncatedTo(ChronoUnit.HOURS);
LocalDateTime toTimestamp = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
List<RawEMData> rawEMDataSamples = rawEmDataRepository.findAllBySampleTimestampBetween(fromTimestamp, toTimestamp);
Double gridEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() > samplingThreshold))
.mapToDouble(d -> d.getGridPower() * dt)
.sum();
Double gridEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getGridPower()) * dt)
.sum();
Double pvEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() > samplingThreshold))
.mapToDouble(d -> d.getPvPower() * dt)
.sum();
Double pvEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getPvPower()) * dt)
.sum();
Double maxGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.max()
.getAsDouble();
Double minGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.min()
.getAsDouble();
Double maxPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.max()
.getAsDouble();
Double minPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.min()
.getAsDouble(); | package com.gmeloni.shelly.service;
@Service
public class ScheduledService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
@Autowired
private RawEMDataService rawEMDataService;
@Autowired
private RawEMDataRepository rawEmDataRepository;
@Autowired
private HourlyEMEnergyRepository hourlyEMEnergyRepository;
@Value("${raw-em.sampling.period.milliseconds}")
private String samplingPeriodInMilliseconds;
@Value("${raw-em.sampling.threshold}")
private Double samplingThreshold;
@Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}")
public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
LocalDateTime sampleDateTime = LocalDateTime.ofInstant(
Instant.ofEpochSecond(getEMStatusResponse.getUnixTime()),
TimeZone.getTimeZone("Europe/Rome").toZoneId()
);
Double gridPower = getEMStatusResponse.getRawEMSamples().get(0).getPower();
Double pvPower = getEMStatusResponse.getRawEMSamples().get(1).getPower();
Double gridVoltage = getEMStatusResponse.getRawEMSamples().get(0).getVoltage();
Double pvVoltage = getEMStatusResponse.getRawEMSamples().get(1).getVoltage();
RawEMData rawEmData = new RawEMData(
sampleDateTime,
gridPower,
pvPower,
gridVoltage,
pvVoltage
);
rawEmDataRepository.save(rawEmData);
log.info("Saved raw EM data: [{}, {}, {}, {}, {}]", sampleFormatter.format(sampleDateTime), String.format("%.2f", gridPower), String.format("%.2f", pvPower), String.format("%.2f", gridVoltage), String.format("%.2f", pvVoltage));
}
@Scheduled(cron = "${raw-em.hourly-aggregate.cron.schedule}", zone = "Europe/Rome")
public void processHourlyAggregatedData() {
final double dt = Double.parseDouble(samplingPeriodInMilliseconds) / 1000 / 3600;
LocalDateTime fromTimestamp = LocalDateTime.now().minusHours(1).truncatedTo(ChronoUnit.HOURS);
LocalDateTime toTimestamp = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
List<RawEMData> rawEMDataSamples = rawEmDataRepository.findAllBySampleTimestampBetween(fromTimestamp, toTimestamp);
Double gridEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() > samplingThreshold))
.mapToDouble(d -> d.getGridPower() * dt)
.sum();
Double gridEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getGridPower()) * dt)
.sum();
Double pvEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() > samplingThreshold))
.mapToDouble(d -> d.getPvPower() * dt)
.sum();
Double pvEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getPvPower()) * dt)
.sum();
Double maxGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.max()
.getAsDouble();
Double minGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.min()
.getAsDouble();
Double maxPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.max()
.getAsDouble();
Double minPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.min()
.getAsDouble(); | hourlyEMEnergyRepository.save(new HourlyEMEnergy(fromTimestamp, toTimestamp, gridEnergyIn, gridEnergyOut, pvEnergyIn, pvEnergyOut, maxGridVoltage, minGridVoltage, maxPvVoltage, minPvVoltage)); | 1 | 2023-10-26 19:52:00+00:00 | 8k |
DimitarDSimeonov/ShopApp | src/main/java/bg/softuni/shop_app/model/entity/Product.java | [
{
"identifier": "Category",
"path": "src/main/java/bg/softuni/shop_app/model/entity/enums/Category.java",
"snippet": "public enum Category {\n VEHICLE(\"Превозни средства\"),\n ELECTRONIC(\"Електроника\"),\n ESTATE(\"Имоти\"),\n CLOTHING(\"Облекло\"),\n OTHER(\"Други\");\n\n private String displayName;\n\n Category(String displayName) {\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n}"
},
{
"identifier": "Location",
"path": "src/main/java/bg/softuni/shop_app/model/entity/enums/Location.java",
"snippet": "public enum Location {\n SOFIA(\"София\"),\n PLOVDIV(\"Пловдив\"),\n VARNA(\"Варна\"),\n BURGAS(\"Бургас\"),\n RUSE(\"Русе\"),\n STARA_ZAGORA(\"Стара Загора\"),\n PLEVEN(\"Плевен\"),\n DOBRICH(\"Добрич\"),\n SLIVEN(\"Сливен\"),\n SHUMEN(\"Шумен\"),\n PERNIK(\"Перник\"),\n PAZARDZHIK(\"Пазарджик\"),\n YAMBOL(\"Ямбол\"),\n HASKOVO(\"Хасково\"),\n BLAGOEVGRAD(\"Благоевград\"),\n VELIKO_TARNOVO(\"Велико Търново\"),\n VRATZA(\"Враца\"),\n GABROVO(\"Габрово\"),\n ASENOVGRAD(\"Асеновград\"),\n VIDIN(\"Видин\"),\n KAZANLAK(\"Казанлък\"),\n KARDJALI(\"Кърджали\"),\n KUSTENDIL(\"Кюстендил\"),\n MONTANA(\"Монтана\"),\n TARGOVISHTE(\"Търговище\"),\n DIMITROVGRAD(\"Димитровград\"),\n SILISTRA(\"Силистра\"),\n LOVECH(\"Ловеч\"),\n DUPNITZA(\"Дупница\"),\n RAZGRAD(\"Разград\"),\n GORNA_ORYAHOVITZA(\"Горна Оряховица\"),\n SVISHTOV(\"Свищов\"),\n PETRICH(\"Петрич\"),\n SMOLYAN(\"Смолян\"),\n SANDANSKI(\"Сандански\"),\n SAMOKOV(\"Самоков\"),\n VELINGRAD(\"Велинград\"),\n SEVLIEVO(\"Севлиево\"),\n LOM(\"Лом\"),\n NOVA_ZAGORA(\"Нова Загора\"),\n KARLOVO(\"Карлово\"),\n AITOS(\"Айтос\"),\n TROYAN(\"Троян\"),\n BOTEVGRAD(\"Ботевград\"),\n HARMANLI(\"Харманли\"),\n PESHTERA(\"Пещера\"),\n GOCE_DELCHEV(\"Гоце Делчев\"),\n SVILENGRAD(\"Свиленград\"),\n KARNOBAT(\"Карнобат\"),\n PANAGYURISHTE(\"Панагюрище\"),\n CHIRPAN(\"Чирпан\"),\n POPOVO(\"Попово\"),\n RAKOVSKI(\"Раковски\"),\n RADOIR(\"Радомир\"),\n PARVOMAY(\"Първомай\"),\n NOVI_ISKAR(\"Нови Искър\"),\n POMORIE(\"Поморие\"),\n NESEBAR(\"Несебър\"),\n CHERVEN_BRYAG(\"Червен Бряг\"),\n KOZLODUY(\"Козлодуй\"),\n IHTIMAN(\"Ихтиман\"),\n NOVI_PAZAR(\"Нови Пазар\"),\n BERKOVITZA(\"Берковица\"),\n RADNEVO(\"Раднево\"),\n PROVADIYA(\"Провадия\"),\n RAZLOG(\"Разлог\"),\n BALCHIK(\"Балчик\"),\n BYALA_SLATINA(\"Бяла Слатина\"),\n KAVARNA(\"Каварна\"),\n KOSTINBROD(\"Костинброд\"),\n BANKYA(\"Банкя\"),\n STABMOIYSKI(\"Стамболийски\"),\n ETROPOLE(\"Етрополе\"),\n KNEZHA(\"Кнежа\"),\n LEVSKI(\"Левски\"),\n PAVLIKENI(\"Павликени\"),\n MEZDRA(\"Мездра\"),\n ELHOVO(\"Елхово\"),\n TETEVEN(\"Тетевен\"),\n LUKOVIT(\"Луковит\"),\n TUTRAKAN(\"Тутракан\"),\n TRYAVNA(\"Трявна\"),\n DEVNYA(\"Девня\"),\n SREDETZ(\"Средец\"),\n OMURTAG(\"Омуртаг\"),\n SOPOT(\"Сопот\"),\n ISPERIH(\"Исперих\"),\n VELIKI_PRESLAV(\"Велики Преслав\"),\n BYALA(\"Бяла\"),\n RAKITOVO(\"Ракитово\"),\n GALABOVO(\"Гълъбово\"),\n KRICHIM(\"Кричим\"),\n LYASKOVETZ(\"Лясковец\"),\n SEPTEMVRI(\"Септември\"),\n MOMCHILGRAD(\"Момчилград\"),\n BANSKO(\"Банско\"),\n BELENE(\"Белене\"),\n AKSAKOVO(\"Аксаково\"),\n BELOSLAV(\"Белослав\"),\n SVOGE(\"Своге\"),\n DRYANOVO(\"Дряново\"),\n LUBIMETZ(\"Любимец\"),\n KUBRAT(\"Кубрат\"),\n PIRDOP(\"Пирдоп\"),\n ELIN_PELIN(\"Елин Пелин\"),\n SIMITLI(\"Симитли\"),\n SLIVNITZA(\"Сливница\"),\n ZLATOGRAD(\"Златоград\"),\n HISARYA(\"Хисаря\"),\n DULOVO(\"Дулово\"),\n DOLNI_CHIFLIK(\"Долни Чифлик\"),\n SIMEONOVGRAD(\"Симеоновград\"),\n GENERAL_TOSHEVO(\"Генерал Тошево\"),\n TERVEL(\"Тервел\"),\n KOSTENETZ(\"Костенец\"),\n DEVIN(\"Девин\"),\n MADAN(\"Мадан\"),\n STRALDZA(\"Стралджа\"),\n TZAREVO(\"Царево\"),\n VARSHETZ(\"Вършец\"),\n TVARDITZA(\"Твърдица\"),\n KUKLEN(\"Куклен\"),\n BOBOV_DOL(\"Бобов Дол\"),\n KOTEL(\"Котел\"),\n SAEDINENIE(\"Съединение\"),\n ELENA(\"Елена\"),\n ORYAHOVO(\"Оряхово\"),\n YAKORUDA(\"Якоруда\"),\n BOJURISHTE(\"Божурище\"),\n TOPOLOVGRAD(\"Тополовград\"),\n BELOGRADCHIK(\"Белоградчик\"),\n STRAJITZA(\"Стражица\"),\n KAMENA(\"Камено\"),\n CHEPELARE(\"Чепеларе\"),\n SOZOPOL(\"Созопол\"),\n PERUHTITZA(\"Перущица\"),\n SUVOROVO(\"Суворово\"),\n ZLATITZA(\"Златица\"),\n KRUMOVGRAD(\"Крумовград\"),\n DOLNA_BANYA(\"Долна Баня\"),\n DALGODOL(\"Дългопол\"),\n VETOVO(\"Ветово\"),\n POLSKI_TRAMBESH(\"Полски Тръмбеш\"),\n TRASTENIK(\"Тръстеник\"),\n KAINARE(\"Койнаре\"),\n DOLNI_DABNIK(\"Долни Дъбник\"),\n SLAVYANOVO(\"Славяново\"),\n GODECH(\"Годеч\"),\n PRAVETZ(\"Правец\"),\n IGNATIEVO(\"Игнатиево\"),\n KOSTANDVO(\"Костандово\"),\n BRATZIGOVO(\"Брацигово\"),\n DVE_MOGILI(\"Две Могили\"),\n STRELCHA(\"Стрелча\"),\n NEDELINO(\"Неделино\"),\n SVETI_VLAS(\"Свети Влас\"),\n SAPAREVA_BANYA(\"Сапарева Ббаня\"),\n BREZNIK(\"Брезник\"),\n SMYADOVO(\"Смядово\"),\n ARDINO(\"Ардино\"),\n DEBELETZ(\"Дебелец\"),\n NIKOPOL(\"Никопол\"),\n SHIVACHEVO(\"Шивачево\"),\n BELOVO(\"Белово\"),\n TZAR_KALOYAN(\"Цар Калоян\"),\n MARTEN(\"Мартен\"),\n IVAYLOVGRAD(\"Ивайловград\"),\n KRESNA(\"Кресна\"),\n VARBITZA(\"Върбица\"),\n RUDOZEM(\"Рудозем\"),\n VALCHEDRAM(\"Вълчедръм\"),\n PRIMORSKO(\"Приморско\"),\n GLODZEVO(\"Глоджево\"),\n LETNITZA(\"Летница\"),\n MAGLIZH(\"Мъглиж\"),\n ISKAR(\"Искър\"),\n SHABLA(\"Шабла\"),\n GULYANTZI(\"Гулянци\"),\n DOLNA_MITROPOLIYA(\"Долна Митрополия\"),\n KRAN(\"Крън\"),\n VALCHI_DOL(\"Вълчи Дол\"),\n SLIVO_POLE(\"Сливо Поле\"),\n BANYA(\"Баня\"),\n DRAGOMAN(\"Драгоман\"),\n SUNGURLARE(\"Сунгурларе\"),\n BATAK(\"Батак\"),\n DZEBEL(\"Джебел\"),\n ZAVET(\"Завет\"),\n KRIVODOL(\"Криводол\"),\n MIZIYA(\"Мизия\"),\n BELITZA(\"Белица\"),\n KASPICHAN(\"Каспичан\"),\n KULA(\"Кула\"),\n NIKOLAEVO(\"Николаево\"),\n VETREN(\"Ветрен\"),\n GURKOVO(\"Гурково\"),\n ROMAN(\"Роман\"),\n KALOFER(\"Калофер\"),\n KABLESHKOVO(\"Каблешково\"),\n APRILTZI(\"Априлци\"),\n BUHOVO(\"Бухово\"),\n DOLNA_ORYAHOVITZA(\"Долна Оряховица\"),\n PAVEL_BANYA(\"Павел Баня\"),\n YABLANITZA(\"Ябланица\"),\n RILA(\"Рила\"),\n OPAKA(\"Опака\"),\n UGARCHIN(\"Угърчин\"),\n ZLATARITZA(\"Златарица\"),\n HADZIDIMOVO(\"Хаджидимово\"),\n DOBRINISHTE(\"Добринище\"),\n OBZOR(\"Обзор\"),\n BYALA_CHERKVA(\"Бяла Черква\"),\n DUNAVTZI(\"Дунавци\"),\n BREGOVO(\"Брегово\"),\n TRAN(\"Трън\"),\n SADOVO(\"Садово\"),\n KALIFAREVO(\"Килифарево\"),\n LAKI(\"Лъки\"),\n MALKO_TARNOVO(\"Малко Търново\"),\n DOSPAT(\"Доспат\"),\n KOPRIVSHTITZA(\"Копривщица\"),\n KOCHERINOVO(\"Кочериново\"),\n LOZNITZA(\"Лозница\"),\n BOROVO(\"Борово\"),\n CHENOMORETZ(\"Черноморец\"),\n BATANOVTZI(\"Батановци\"),\n PORDIM(\"Пордим\"),\n AHELOY(\"Ахелой\"),\n SUHINDOL(\"Сухиндол\"),\n BALGAROVO(\"Българово\"),\n BREZOVO(\"Брезово\"),\n GLAVNITZA(\"Главиница\"),\n KAOLINOVO(\"Каолиново\"),\n CHIPROVTZI(\"Чипровци\"),\n MERICHLERI(\"Меричлери\"),\n ZEMEN(\"Земен\"),\n PLACHKOVTZI(\"Плачковци\"),\n KERMEN(\"Кермен\"),\n MOMIN_PROHOD(\"Момин Проход\"),\n ALFATAR(\"Алфатар\"),\n GRAMADA(\"Грамада\"),\n SENOVO(\"Сеново\"),\n BOICHINOVTZI(\"Бойчиновци\"),\n ANTONOVO(\"Антоново\"),\n AHTOPOL(\"Ахтопол\"),\n BOBOSHEVO(\"Бобошево\"),\n SHIPKA(\"Шипка\"),\n BOLYAROVO(\"Болярово\"),\n DIMOVO(\"Димово\"),\n BRUSARTZI(\"Брусарци\"),\n KITEN(\"Китен\"),\n KLISURA(\"Клисура\"),\n PLISKA(\"Плиска\"),\n MADZAROVO(\"Маджарово\"),\n MELNIK(\"Мелник\");\n\n private String displayName;\n\n Location(String displayName) {\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n}"
}
] | import bg.softuni.shop_app.model.entity.enums.Category;
import bg.softuni.shop_app.model.entity.enums.Location;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; | 3,721 | package bg.softuni.shop_app.model.entity;
@Getter
@Setter
@Entity
@Table(name = "products")
public class Product extends BaseEntity{
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String description;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Enumerated(EnumType.STRING)
private Category category;
@Column(name = "date_of_post")
private LocalDateTime dateOfPost;
@Enumerated(EnumType.STRING) | package bg.softuni.shop_app.model.entity;
@Getter
@Setter
@Entity
@Table(name = "products")
public class Product extends BaseEntity{
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String description;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Enumerated(EnumType.STRING)
private Category category;
@Column(name = "date_of_post")
private LocalDateTime dateOfPost;
@Enumerated(EnumType.STRING) | private Location location; | 1 | 2023-10-27 13:33:23+00:00 | 8k |
achrafaitibba/invoiceYou | src/main/java/com/onxshield/invoiceyou/invoicestatement/service/invoiceService.java | [
{
"identifier": "requestException",
"path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/exceptions/requestException.java",
"snippet": "@Getter\npublic class requestException extends RuntimeException{\n\n private HttpStatus httpStatus;\n public requestException(String message) {\n super(message);\n }\n\n public requestException(String message, HttpStatus httpStatus){\n super(message);\n this.httpStatus = httpStatus;\n }\n\n}"
},
{
"identifier": "numberToWordUtil",
"path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/util/numberToWordUtil.java",
"snippet": "public class numberToWordUtil {\n\n //In case someone reading this code (numberToWordUtil)\n //I just want you to know that I copied this code from a forum, I needed it hh\n //I can do it, but copying it was easier and faster hehe\n private static final String[] dizaineNames = {\n \"\",\n \"\",\n \"vingt\",\n \"trente\",\n \"quarante\",\n \"cinquante\",\n \"soixante\",\n \"soixante\",\n \"quatre-vingt\",\n \"quatre-vingt\"\n };\n\n private static final String[] uniteNames1 = {\n \"\",\n \"un\",\n \"deux\",\n \"trois\",\n \"quatre\",\n \"cinq\",\n \"six\",\n \"sept\",\n \"huit\",\n \"neuf\",\n \"dix\",\n \"onze\",\n \"douze\",\n \"treize\",\n \"quatorze\",\n \"quinze\",\n \"seize\",\n \"dix-sept\",\n \"dix-huit\",\n \"dix-neuf\"\n };\n\n private static final String[] uniteNames2 = {\n \"\",\n \"\",\n \"deux\",\n \"trois\",\n \"quatre\",\n \"cinq\",\n \"six\",\n \"sept\",\n \"huit\",\n \"neuf\",\n \"dix\"\n };\n\n private numberToWordUtil() {}\n\n private static String convertZeroToHundred(int number) {\n\n int laDizaine = number / 10;\n int lUnite = number % 10;\n String resultat = \"\";\n\n switch (laDizaine) {\n case 1 :\n case 7 :\n case 9 :\n lUnite = lUnite + 10;\n break;\n default:\n }\n\n // s�parateur \"-\" \"et\" \"\"\n String laLiaison = \"\";\n if (laDizaine > 1) {\n laLiaison = \"-\";\n }\n // cas particuliers\n switch (lUnite) {\n case 0:\n laLiaison = \"\";\n break;\n case 1 :\n if (laDizaine == 8) {\n laLiaison = \"-\";\n }\n else {\n laLiaison = \" et \";\n }\n break;\n case 11 :\n if (laDizaine==7) {\n laLiaison = \" et \";\n }\n break;\n default:\n }\n\n // dizaines en lettres\n switch (laDizaine) {\n case 0:\n resultat = uniteNames1[lUnite];\n break;\n case 8 :\n if (lUnite == 0) {\n resultat = dizaineNames[laDizaine];\n }\n else {\n resultat = dizaineNames[laDizaine]\n + laLiaison + uniteNames1[lUnite];\n }\n break;\n default :\n resultat = dizaineNames[laDizaine]\n + laLiaison + uniteNames1[lUnite];\n }\n return resultat;\n }\n\n private static String convertLessThanOneThousand(int number) {\n\n int lesCentaines = number / 100;\n int leReste = number % 100;\n String sReste = convertZeroToHundred(leReste);\n\n String resultat;\n switch (lesCentaines) {\n case 0:\n resultat = sReste;\n break;\n case 1 :\n if (leReste > 0) {\n resultat = \"cent \" + sReste;\n }\n else {\n resultat = \"cent\";\n }\n break;\n default :\n if (leReste > 0) {\n resultat = uniteNames2[lesCentaines] + \" cent \" + sReste;\n }\n else {\n resultat = uniteNames2[lesCentaines] + \" cents\";\n }\n }\n return resultat;\n }\n\n public static String convert(long number) {\n // 0 � 999 999 999 999\n if (number == 0) { return \"ZERO\"; }\n\n String snumber = Long.toString(number);\n\n // pad des \"0\"\n String mask = \"000000000000\";\n DecimalFormat df = new DecimalFormat(mask);\n snumber = df.format(number);\n\n // XXXnnnnnnnnn\n int lesMilliards = Integer.parseInt(snumber.substring(0,3));\n // nnnXXXnnnnnn\n int lesMillions = Integer.parseInt(snumber.substring(3,6));\n // nnnnnnXXXnnn\n int lesCentMille = Integer.parseInt(snumber.substring(6,9));\n // nnnnnnnnnXXX\n int lesMille = Integer.parseInt(snumber.substring(9,12));\n\n String tradMilliards;\n switch (lesMilliards) {\n case 0:\n tradMilliards = \"\";\n break;\n case 1 :\n tradMilliards = convertLessThanOneThousand(lesMilliards)\n + \" MILLIARD \";\n break;\n default :\n tradMilliards = convertLessThanOneThousand(lesMilliards)\n + \" MILLIARDS \";\n }\n String resultat = tradMilliards;\n\n String tradMillions;\n switch (lesMillions) {\n case 0:\n tradMillions = \"\";\n break;\n case 1 :\n tradMillions = convertLessThanOneThousand(lesMillions)\n + \" MILLION \";\n break;\n default :\n tradMillions = convertLessThanOneThousand(lesMillions)\n + \" MILLIONS \";\n }\n resultat = resultat + tradMillions;\n\n String tradCentMille;\n switch (lesCentMille) {\n case 0:\n tradCentMille = \"\";\n break;\n case 1 :\n tradCentMille = \"MILLE \";\n break;\n default :\n tradCentMille = convertLessThanOneThousand(lesCentMille)\n + \" MILLE \";\n }\n resultat = resultat + tradCentMille;\n\n String tradMille;\n tradMille = convertLessThanOneThousand(lesMille);\n resultat = resultat + tradMille;\n\n return resultat.concat(\" DIRHAMS\").toUpperCase();\n }\n}"
},
{
"identifier": "doubleTwoDigitConverter",
"path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/util/doubleTwoDigitConverter.java",
"snippet": "public class doubleTwoDigitConverter {\n\n public static double twoDigitTVA(Double tva){\n DecimalFormat decimalFormat = new DecimalFormat(\"#.##\");\n return Double.parseDouble(decimalFormat.format(tva));\n }\n}"
}
] | import com.onxshield.invoiceyou.invoicestatement.dto.request.invoiceRequest;
import com.onxshield.invoiceyou.invoicestatement.dto.response.basicInvoiceResponse;
import com.onxshield.invoiceyou.invoicestatement.dto.response.merchandiseResponse;
import com.onxshield.invoiceyou.invoicestatement.exceptions.requestException;
import com.onxshield.invoiceyou.invoicestatement.model.*;
import com.onxshield.invoiceyou.invoicestatement.repository.*;
import com.onxshield.invoiceyou.invoicestatement.util.numberToWordUtil;
import com.onxshield.invoiceyou.invoicestatement.util.doubleTwoDigitConverter;
import jakarta.transaction.Transactional;
import lombok.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.time.Year;
import java.util.List;
import java.util.Optional; | 4,212 | merchandiseRequest -> {
merchandise merchandiseToSave;
Optional<inventory> inventory = inventoryRepository.findByProductProductId(merchandiseRequest.productId());
Double availability = inventory.get().getAvailability();
if (availability >= merchandiseRequest.quantity() && availability > 0) {
Double totalByProduct = merchandiseRequest.quantity() * inventory.get().getSellPrice();
inventory.get().setAvailability(availability - merchandiseRequest.quantity());
merchandiseToSave = new merchandise();
merchandiseToSave.setProduct(productRepository.findById(merchandiseRequest.productId()).get());
merchandiseToSave.setQuantity(merchandiseRequest.quantity());
merchandiseToSave.setTotal(totalByProduct);
return merchandiseRepository.save(merchandiseToSave);
} else {
throw new requestException("Product isn't available in the inventory, out of stock", HttpStatus.CONFLICT);
}
}
)
.toList();
}
public invoice createInvoice(invoiceRequest request) {
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = null;
if (request.merchandiseList() != null) {
savedMerchandise = merchandiseRequestToMerchandise(request);
}
invoice invoiceToSave = invoice.builder()
.invoiceId(request.invoiceId())
.invoiceDate(request.invoiceDate())
.client(client.get())
.totalTTC(request.totalTTC())
.TVA(twoDigitTVA(request.totalTTC().doubleValue() / 6))
.spelledTotal(numberToWordUtil.convert(request.totalTTC()))
.paymentMethod(paymentMethod.valueOf(request.paymentMethod()))
.bankName(request.bankName())
.checkNumber(request.checkNumber())
.paymentDate(request.paymentDate())
.printed(Boolean.valueOf(request.printed()))
.invoiceAction(action.valueOf(request.invoiceAction()))
.invoiceStatus(status.valueOf(request.invoiceStatus()))
.invoiceFile(request.invoiceFile())
.merchandiseList(savedMerchandise)
.discount(request.discount())
.build();
invoice saved = invoiceRepository.save(invoiceToSave);
if (request.merchandiseList() != null) {
//savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
}
return saved;
} else throw new requestException("Invoice already exist", HttpStatus.CONFLICT);
}
private void deleteInvoiceNumberByInvoiceNumber(String invoiceNumber) {
Optional<invoiceNumber> invoiceN = invoiceNumberRepository.findById(invoiceNumber);
if (invoiceN.isPresent()) {
invoiceNumberRepository.deleteById(invoiceNumber);
}
}
public invoice updateInvoice(invoiceRequest request) {
// update the invoice ID? if yes (merchandise should be updated also)
// and the list of available ID should have a new record (the previous Invoice id)
/////////////////////////////////////////
Optional<invoice> toUpdate = invoiceRepository.findById(request.invoiceId());
if (toUpdate.isPresent()) {
Optional<client> client = clientRepository.findById(request.clientId());
toUpdate.get().setInvoiceDate(request.invoiceDate());
toUpdate.get().setClient(client.get());
toUpdate.get().setTotalTTC(request.totalTTC());
toUpdate.get().setSpelledTotal(convertNumberToWords(request.totalTTC()));
toUpdate.get().setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
toUpdate.get().setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
toUpdate.get().setBankName(request.bankName());
toUpdate.get().setCheckNumber(request.checkNumber());
toUpdate.get().setPaymentDate(request.paymentDate());
toUpdate.get().setPrinted(Boolean.valueOf(request.printed()));
toUpdate.get().setInvoiceAction(action.valueOf(request.invoiceAction()));
toUpdate.get().setInvoiceStatus(status.valueOf(request.invoiceStatus()));
toUpdate.get().setInvoiceFile(request.invoiceFile());
toUpdate.get().setDiscount(request.discount());
if (merchandiseRepository.findAllByInvoice_InvoiceId(request.invoiceId()) != null) {
deleteAllMerchandiseUpdateInventory(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> merchToUpdate = merchandiseRepository.findById(merch.getMerchId());
merchToUpdate.get().setInvoice(toUpdate.get());
}
}
return invoiceRepository.save(toUpdate.get());
} else throw new requestException("The invoice doesn't exist", HttpStatus.NOT_FOUND);
}
public void deleteAllMerchandiseUpdateInventory(String invoiceId) {
List<merchandise> merchandiseList = merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId);
if (merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId) != null) {
for (merchandise merch : merchandiseList
) {
Optional<inventory> toUpdate = inventoryRepository.findByProductProductId(merch.getProduct().getProductId());
Double availableQuantity = toUpdate.get().getAvailability();
toUpdate.get().setAvailability(availableQuantity + merch.getQuantity());
}
merchandiseRepository.deleteByInvoice_InvoiceId(invoiceId);
}
}
public double twoDigitTVA(Double tva) {
| package com.onxshield.invoiceyou.invoicestatement.service;
@Service
@RequiredArgsConstructor
@Transactional
public class invoiceService {
private final invoiceRepository invoiceRepository;
private final clientRepository clientRepository;
private final inventoryRepository inventoryRepository;
private final productRepository productRepository;
private final merchandiseRepository merchandiseRepository;
private final invoiceNumberRepository invoiceNumberRepository;
static long latestInvoiceNumber = 1225;
public invoice createBasicInvoice(invoiceRequest request) {
//find inventory by product id
//check availability
//get the sell price
//calculate total by product = sell price * quantity
//add the total by product to totalTTC
//decrease availability in the inventory
//BUILD the merchandise instances
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
invoice invoiceToSave = new invoice();
invoiceToSave.setInvoiceId(request.invoiceId());
invoiceToSave.setInvoiceDate(request.invoiceDate());
invoiceToSave.setClient(client.get());
invoiceToSave.setTotalTTC(request.totalTTC());
invoiceToSave.setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
invoiceToSave.setSpelledTotal(convertNumberToWords(request.totalTTC().longValue()));
invoiceToSave.setMerchandiseList(savedMerchandise);
invoiceToSave.setCheckNumber(request.checkNumber());
invoiceToSave.setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
invoiceToSave.setDiscount(request.discount());
invoice saved = invoiceRepository.save(invoiceToSave);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
return saved;
} else {
throw new requestException("The Id you provided already used by other invoice", HttpStatus.CONFLICT);
}
}
public String convertNumberToWords(Long total) {
return numberToWordUtil.convert(total).toUpperCase();
}
public String[] getAvailableInvoiceNumbers() {
List<String> numbers = invoiceNumberRepository.findAll()
.stream()
.map(invoiceNumber::getInvoiceNumber)
.toList();
return numbers.toArray(new String[0]);
}
public String generateInvoiceNumber() {
int currentYear = Year.now().getValue();
int lastTwoDigits = currentYear % 100;
latestInvoiceNumber++;
String toSave = "ST" + latestInvoiceNumber + "/" + String.format("%02d", lastTwoDigits);
invoiceNumberRepository.save(new invoiceNumber(toSave));
latestInvoiceNumber++;
return "ST" + latestInvoiceNumber + "/" + String.format("%02d", lastTwoDigits);
}
public invoice getInvoiceById(String invoiceId) {
Optional<invoice> invoice = invoiceRepository.findById(invoiceId);
if (invoice.isPresent()) {
return invoice.get();
} else throw new requestException("The Id you provided doesn't exist", HttpStatus.CONFLICT);
}
public basicInvoiceResponse getBasicInvoiceById(String invoiceId) {
invoice invoice = getInvoiceById(invoiceId);
return new basicInvoiceResponse(
invoice.getClient().getName(),
invoice.getInvoiceId(),
invoice.getClient().getICE(),
invoice.getInvoiceDate(),
invoice.getMerchandiseList().stream().map(
merchandise -> new merchandiseResponse(
merchandise.getMerchId(),
merchandise.getProduct().getName(),
merchandise.getProduct().getUnit().toString(),
merchandise.getQuantity(),
inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice(),
merchandise.getQuantity().longValue() * inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice().longValue()
)
)
.toList(),
invoice.getTotalTTC(),
invoice.getTVA(),
invoice.getSpelledTotal(),
invoice.getPaymentMethod().toString(),
invoice.getCheckNumber(),
invoice.getDiscount()
);
}
public Page<invoice> getAllInvoices(Integer pageNumber, Integer size, String direction, String sortBy) {
Sort soring = Sort.by(Sort.Direction.valueOf(direction.toUpperCase()), sortBy);
Pageable page = PageRequest.of(pageNumber, size, soring);
return invoiceRepository.findAll(page);
}
public List<merchandise> merchandiseRequestToMerchandise(invoiceRequest request) {
return request.merchandiseList().stream()
.map(
merchandiseRequest -> {
merchandise merchandiseToSave;
Optional<inventory> inventory = inventoryRepository.findByProductProductId(merchandiseRequest.productId());
Double availability = inventory.get().getAvailability();
if (availability >= merchandiseRequest.quantity() && availability > 0) {
Double totalByProduct = merchandiseRequest.quantity() * inventory.get().getSellPrice();
inventory.get().setAvailability(availability - merchandiseRequest.quantity());
merchandiseToSave = new merchandise();
merchandiseToSave.setProduct(productRepository.findById(merchandiseRequest.productId()).get());
merchandiseToSave.setQuantity(merchandiseRequest.quantity());
merchandiseToSave.setTotal(totalByProduct);
return merchandiseRepository.save(merchandiseToSave);
} else {
throw new requestException("Product isn't available in the inventory, out of stock", HttpStatus.CONFLICT);
}
}
)
.toList();
}
public invoice createInvoice(invoiceRequest request) {
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = null;
if (request.merchandiseList() != null) {
savedMerchandise = merchandiseRequestToMerchandise(request);
}
invoice invoiceToSave = invoice.builder()
.invoiceId(request.invoiceId())
.invoiceDate(request.invoiceDate())
.client(client.get())
.totalTTC(request.totalTTC())
.TVA(twoDigitTVA(request.totalTTC().doubleValue() / 6))
.spelledTotal(numberToWordUtil.convert(request.totalTTC()))
.paymentMethod(paymentMethod.valueOf(request.paymentMethod()))
.bankName(request.bankName())
.checkNumber(request.checkNumber())
.paymentDate(request.paymentDate())
.printed(Boolean.valueOf(request.printed()))
.invoiceAction(action.valueOf(request.invoiceAction()))
.invoiceStatus(status.valueOf(request.invoiceStatus()))
.invoiceFile(request.invoiceFile())
.merchandiseList(savedMerchandise)
.discount(request.discount())
.build();
invoice saved = invoiceRepository.save(invoiceToSave);
if (request.merchandiseList() != null) {
//savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
}
return saved;
} else throw new requestException("Invoice already exist", HttpStatus.CONFLICT);
}
private void deleteInvoiceNumberByInvoiceNumber(String invoiceNumber) {
Optional<invoiceNumber> invoiceN = invoiceNumberRepository.findById(invoiceNumber);
if (invoiceN.isPresent()) {
invoiceNumberRepository.deleteById(invoiceNumber);
}
}
public invoice updateInvoice(invoiceRequest request) {
// update the invoice ID? if yes (merchandise should be updated also)
// and the list of available ID should have a new record (the previous Invoice id)
/////////////////////////////////////////
Optional<invoice> toUpdate = invoiceRepository.findById(request.invoiceId());
if (toUpdate.isPresent()) {
Optional<client> client = clientRepository.findById(request.clientId());
toUpdate.get().setInvoiceDate(request.invoiceDate());
toUpdate.get().setClient(client.get());
toUpdate.get().setTotalTTC(request.totalTTC());
toUpdate.get().setSpelledTotal(convertNumberToWords(request.totalTTC()));
toUpdate.get().setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
toUpdate.get().setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
toUpdate.get().setBankName(request.bankName());
toUpdate.get().setCheckNumber(request.checkNumber());
toUpdate.get().setPaymentDate(request.paymentDate());
toUpdate.get().setPrinted(Boolean.valueOf(request.printed()));
toUpdate.get().setInvoiceAction(action.valueOf(request.invoiceAction()));
toUpdate.get().setInvoiceStatus(status.valueOf(request.invoiceStatus()));
toUpdate.get().setInvoiceFile(request.invoiceFile());
toUpdate.get().setDiscount(request.discount());
if (merchandiseRepository.findAllByInvoice_InvoiceId(request.invoiceId()) != null) {
deleteAllMerchandiseUpdateInventory(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> merchToUpdate = merchandiseRepository.findById(merch.getMerchId());
merchToUpdate.get().setInvoice(toUpdate.get());
}
}
return invoiceRepository.save(toUpdate.get());
} else throw new requestException("The invoice doesn't exist", HttpStatus.NOT_FOUND);
}
public void deleteAllMerchandiseUpdateInventory(String invoiceId) {
List<merchandise> merchandiseList = merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId);
if (merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId) != null) {
for (merchandise merch : merchandiseList
) {
Optional<inventory> toUpdate = inventoryRepository.findByProductProductId(merch.getProduct().getProductId());
Double availableQuantity = toUpdate.get().getAvailability();
toUpdate.get().setAvailability(availableQuantity + merch.getQuantity());
}
merchandiseRepository.deleteByInvoice_InvoiceId(invoiceId);
}
}
public double twoDigitTVA(Double tva) {
| return doubleTwoDigitConverter.twoDigitTVA(tva); | 2 | 2023-10-29 11:16:37+00:00 | 8k |
Melledy/LunarCore | src/main/java/emu/lunarcore/command/commands/WorldLevelCommand.java | [
{
"identifier": "CommandArgs",
"path": "src/main/java/emu/lunarcore/command/CommandArgs.java",
"snippet": "@Getter\npublic class CommandArgs {\n private String raw;\n private List<String> list;\n private Player sender;\n private Player target;\n \n private int targetUid;\n private int amount;\n private int level = -1;\n private int rank = -1;\n private int promotion = -1;\n private int stage = -1;\n \n private Int2IntMap map;\n private ObjectSet<String> flags;\n\n public CommandArgs(Player sender, List<String> args) {\n this.sender = sender;\n this.raw = String.join(\" \", args);\n this.list = args;\n \n // Parse args. Maybe regex is better.\n var it = this.list.iterator();\n while (it.hasNext()) {\n // Lower case first\n String arg = it.next().toLowerCase();\n \n try {\n if (arg.length() >= 2 && !Character.isDigit(arg.charAt(0)) && Character.isDigit(arg.charAt(arg.length() - 1))) {\n if (arg.startsWith(\"@\")) { // Target UID\n this.targetUid = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n } else if (arg.startsWith(\"x\")) { // Amount\n this.amount = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n } else if (arg.startsWith(\"lv\")) { // Level\n this.level = Utils.parseSafeInt(arg.substring(2));\n it.remove();\n } else if (arg.startsWith(\"r\")) { // Rank\n this.rank = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n } else if (arg.startsWith(\"e\")) { // Eidolons\n this.rank = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n } else if (arg.startsWith(\"p\")) { // Promotion\n this.promotion = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n } else if (arg.startsWith(\"s\")) { // Stage or Superimposition\n this.stage = Utils.parseSafeInt(arg.substring(1));\n it.remove();\n }\n } else if (arg.startsWith(\"-\")) { // Flag\n if (this.flags == null) this.flags = new ObjectOpenHashSet<>();\n this.flags.add(arg);\n it.remove();\n } else if (arg.contains(\":\") || arg.contains(\",\")) {\n String[] split = arg.split(\"[:,]\");\n if (split.length >= 2) {\n int key = Integer.parseInt(split[0]);\n int value = Integer.parseInt(split[1]);\n \n if (this.map == null) this.map = new Int2IntOpenHashMap();\n this.map.put(key, value);\n \n it.remove();\n }\n }\n } catch (Exception e) {\n \n }\n }\n \n // Get target player\n if (targetUid != 0) {\n if (LunarCore.getGameServer() != null) {\n target = LunarCore.getGameServer().getOnlinePlayerByUid(targetUid);\n }\n } else {\n target = sender;\n }\n \n if (target != null) {\n this.targetUid = target.getUid();\n }\n }\n \n public int size() {\n return this.list.size();\n }\n \n public String get(int index) {\n if (index < 0 || index >= list.size()) {\n return \"\";\n }\n return this.list.get(index);\n }\n \n /**\n * Sends a message to the command sender\n * @param message\n */\n public void sendMessage(String message) {\n if (sender != null) {\n sender.sendMessage(message);\n } else {\n LunarCore.getLogger().info(message);\n }\n }\n \n public boolean hasFlag(String flag) {\n if (this.flags == null) return false;\n return this.flags.contains(flag);\n }\n \n // Utility commands\n \n /**\n * Changes the properties of an avatar based on the arguments provided\n * @param avatar The targeted avatar to change\n * @return A boolean of whether or not any changes were made to the avatar\n */\n public boolean setProperties(GameAvatar avatar) {\n boolean hasChanged = false;\n\n // Try to set level\n if (this.getLevel() > 0) {\n avatar.setLevel(Math.min(this.getLevel(), 80));\n avatar.setPromotion(Utils.getMinPromotionForLevel(avatar.getLevel()));\n hasChanged = true;\n }\n \n // Try to set promotion (ascension level)\n if (this.getPromotion() >= 0) {\n avatar.setPromotion(Math.min(this.getPromotion(), avatar.getExcel().getMaxPromotion()));\n hasChanged = true;\n }\n \n // Try to set rank (eidolons)\n if (this.getRank() >= 0) {\n avatar.setRank(Math.min(this.getRank(), avatar.getExcel().getMaxRank()));\n hasChanged = true;\n }\n \n // Try to set skill trees\n if (this.getStage() > 0) {\n for (int pointId : avatar.getExcel().getSkillTreeIds()) {\n var skillTree = GameData.getAvatarSkillTreeExcel(pointId, 1);\n if (skillTree == null) continue;\n \n int minLevel = skillTree.isDefaultUnlock() ? 1 : 0;\n int pointLevel = Math.max(Math.min(this.getStage(), skillTree.getMaxLevel()), minLevel);\n \n avatar.getSkills().put(pointId, pointLevel);\n }\n hasChanged = true;\n }\n \n // Handle flags\n if (this.hasFlag(\"-takerewards\")) {\n if (avatar.setRewards(0b00101010)) {\n hasChanged = true;\n }\n } else if (this.hasFlag(\"-clearrewards\")) {\n if (avatar.setRewards(0)) { // Note: Requires the player to restart their game to show\n hasChanged = true;\n }\n }\n \n return hasChanged;\n }\n \n /**\n * Changes the properties of an item based on the arguments provided\n * @param item The targeted item to change\n * @return A boolean of whether or not any changes were made to the item\n */\n public boolean setProperties(GameItem item) {\n boolean hasChanged = false;\n \n if (item.getExcel().isEquipment()) {\n // Try to set level\n if (this.getLevel() > 0) {\n item.setLevel(Math.min(this.getLevel(), 80));\n item.setPromotion(Utils.getMinPromotionForLevel(item.getLevel()));\n hasChanged = true;\n }\n \n // Try to set promotion\n if (this.getPromotion() >= 0) {\n item.setPromotion(Math.min(this.getPromotion(), item.getExcel().getEquipmentExcel().getMaxPromotion()));\n hasChanged = true;\n }\n \n // Try to set rank (superimposition)\n if (this.getRank() >= 0) {\n item.setRank(Math.min(this.getRank(), item.getExcel().getEquipmentExcel().getMaxRank()));\n hasChanged = true;\n } else if (this.getStage() >= 0) {\n item.setRank(Math.min(this.getStage(), item.getExcel().getEquipmentExcel().getMaxRank()));\n hasChanged = true;\n }\n } else if (item.getExcel().isRelic()) {\n // Sub stats\n if (this.getMap() != null) {\n // Reset substats first\n item.resetSubAffixes();\n \n int maxCount = (int) Math.floor(LunarCore.getConfig().getServerOptions().maxCustomRelicLevel / 3) + 1;\n hasChanged = true;\n \n for (var entry : this.getMap().int2IntEntrySet()) {\n if (entry.getIntValue() <= 0) continue;\n \n var subAffix = GameData.getRelicSubAffixExcel(item.getExcel().getRelicExcel().getSubAffixGroup(), entry.getIntKey());\n if (subAffix == null) continue;\n \n // Set count\n int count = Math.min(entry.getIntValue(), maxCount);\n item.getSubAffixes().add(new GameItemSubAffix(subAffix, count));\n }\n }\n \n // Main stat\n if (this.getStage() > 0) {\n var mainAffix = GameData.getRelicMainAffixExcel(item.getExcel().getRelicExcel().getMainAffixGroup(), this.getStage());\n if (mainAffix != null) {\n item.setMainAffix(mainAffix.getAffixID());\n hasChanged = true;\n }\n }\n \n // Try to set level\n if (this.getLevel() > 0) {\n // Set relic level\n item.setLevel(Math.min(this.getLevel(), LunarCore.getConfig().getServerOptions().maxCustomRelicLevel));\n \n // Apply sub stat upgrades to the relic\n int upgrades = item.getMaxNormalSubAffixCount() - item.getCurrentSubAffixCount();\n if (upgrades > 0) {\n item.addSubAffixes(upgrades);\n }\n \n hasChanged = true;\n }\n \n // Handle flags\n if (this.hasFlag(\"-maxsteps\")) {\n if (item.getSubAffixes() == null) {\n item.resetSubAffixes();\n }\n \n item.getSubAffixes().forEach(subAffix -> subAffix.setStep(subAffix.getCount() * 2));\n }\n }\n \n return hasChanged;\n }\n}"
},
{
"identifier": "CommandHandler",
"path": "src/main/java/emu/lunarcore/command/CommandHandler.java",
"snippet": "public interface CommandHandler {\n \n public default Command getData() {\n return this.getClass().getAnnotation(Command.class);\n }\n \n public default String getLabel() {\n return getData().label();\n }\n \n public void execute(CommandArgs args);\n \n}"
},
{
"identifier": "Utils",
"path": "src/main/java/emu/lunarcore/util/Utils.java",
"snippet": "public class Utils {\n private static final char[] HEX_ARRAY = \"0123456789abcdef\".toCharArray();\n \n public static final Object EMPTY_OBJECT = new Object();\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n\n public static String bytesToHex(byte[] bytes) {\n if (bytes == null || bytes.length == 0) return \"\";\n char[] hexChars = new char[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = HEX_ARRAY[v >>> 4];\n hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];\n }\n return new String(hexChars);\n }\n\n public static byte[] hexToBytes(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i+1), 16));\n }\n return data;\n }\n\n public static String capitalize(String s) {\n StringBuilder sb = new StringBuilder(s);\n sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));\n return sb.toString();\n }\n\n public static String lowerCaseFirstChar(String s) {\n StringBuilder sb = new StringBuilder(s);\n sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));\n return sb.toString();\n }\n\n /**\n * Creates a string with the path to a file.\n * @param path The path to the file.\n * @return A path using the operating system's file separator.\n */\n public static String toFilePath(String path) {\n return path.replace(\"/\", File.separator);\n }\n\n /**\n * Checks if a file exists on the file system.\n * @param path The path to the file.\n * @return True if the file exists, false otherwise.\n */\n public static boolean fileExists(String path) {\n return new File(path).exists();\n }\n\n /**\n * Creates a folder on the file system.\n * @param path The path to the folder.\n * @return True if the folder was created, false otherwise.\n */\n public static boolean createFolder(String path) {\n return new File(path).mkdirs();\n }\n\n public static long getCurrentSeconds() {\n return Math.floorDiv(System.currentTimeMillis(), 1000);\n }\n\n public static int getMinPromotionForLevel(int level) {\n return Math.max(Math.min((int) ((level - 11) / 10D), 6), 0);\n }\n\n /**\n * Parses the string argument as a signed decimal integer. Returns a 0 if the string argument is not an integer.\n */\n public static int parseSafeInt(String s) {\n if (s == null) {\n return 0;\n }\n\n int i = 0;\n\n try {\n i = Integer.parseInt(s);\n } catch (Exception e) {\n i = 0;\n }\n\n return i;\n }\n\n /**\n * Parses the string argument as a signed decimal long. Returns a 0 if the string argument is not a long.\n */\n public static long parseSafeLong(String s) {\n if (s == null) {\n return 0;\n }\n\n long i = 0;\n\n try {\n i = Long.parseLong(s);\n } catch (Exception e) {\n i = 0;\n }\n\n return i;\n }\n \n /**\n * Add 2 integers without overflowing\n */\n public static int safeAdd(int a, int b) {\n return safeAdd(a, b, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n \n public static int safeAdd(int a, int b, long max, long min) {\n long sum = (long) a + (long) b;\n \n if (sum > max) {\n return (int) max;\n } else if (sum < min) {\n return (int) min;\n }\n \n return (int) sum;\n }\n \n /**\n * Subtract 2 integers without overflowing\n */\n public static int safeSubtract(int a, int b) {\n return safeSubtract(a, b, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n \n public static int safeSubtract(int a, int b, long max, long min) {\n long sum = (long) a - (long) b;\n \n if (sum > max) {\n return (int) max;\n } else if (sum < min) {\n return (int) min;\n }\n \n return (int) sum;\n }\n\n public static double generateRandomDouble() {\n return ThreadLocalRandom.current().nextDouble();\n }\n\n public static int randomRange(int min, int max) {\n return ThreadLocalRandom.current().nextInt(min, max + 1);\n }\n\n public static int randomElement(int[] array) {\n return array[ThreadLocalRandom.current().nextInt(0, array.length)];\n }\n\n public static <T> T randomElement(List<T> list) {\n return list.get(ThreadLocalRandom.current().nextInt(0, list.size()));\n }\n \n public static int randomElement(IntList list) {\n return list.getInt(ThreadLocalRandom.current().nextInt(0, list.size()));\n }\n\n /**\n * Checks if an integer array contains a value\n * @param array\n * @param value The value to check for\n */\n public static boolean arrayContains(int[] array, int value) {\n for (int i = 0; i < array.length; i++) {\n if (array[i] == value) return true;\n }\n return false;\n }\n\n /**\n * Base64 encodes a given byte array.\n * @param toEncode An array of bytes.\n * @return A base64 encoded string.\n */\n public static String base64Encode(byte[] toEncode) {\n return Base64.getEncoder().encodeToString(toEncode);\n }\n\n /**\n * Base64 decodes a given string.\n * @param toDecode A base64 encoded string.\n * @return An array of bytes.\n */\n public static byte[] base64Decode(String toDecode) {\n return Base64.getDecoder().decode(toDecode);\n }\n\n /**\n * Checks if a port is open on a given host.\n *\n * @param host The host to check.\n * @param port The port to check.\n * @return True if the port is open, false otherwise.\n */\n public static boolean isPortOpen(String host, int port) {\n try (var serverSocket = new ServerSocket()) {\n serverSocket.setReuseAddress(false);\n serverSocket.bind(new InetSocketAddress(InetAddress.getByName(host), port), 1);\n return true;\n } catch (Exception ex) {\n return false;\n }\n }\n}"
}
] | import emu.lunarcore.command.Command;
import emu.lunarcore.command.CommandArgs;
import emu.lunarcore.command.CommandHandler;
import emu.lunarcore.util.Utils; | 4,280 | package emu.lunarcore.command.commands;
@Command(label = "worldlevel", aliases = {"wl"}, permission = "player.worldlevel", requireTarget = true, desc = "/worldlevel [world level]. Sets the targeted player's equilibrium level.")
public class WorldLevelCommand implements CommandHandler {
@Override | package emu.lunarcore.command.commands;
@Command(label = "worldlevel", aliases = {"wl"}, permission = "player.worldlevel", requireTarget = true, desc = "/worldlevel [world level]. Sets the targeted player's equilibrium level.")
public class WorldLevelCommand implements CommandHandler {
@Override | public void execute(CommandArgs args) { | 0 | 2023-10-10 12:57:35+00:00 | 8k |
jar-analyzer/jar-analyzer | src/main/java/org/sqlite/SQLiteJDBCLoader.java | [
{
"identifier": "LibraryLoaderUtil",
"path": "src/main/java/org/sqlite/util/LibraryLoaderUtil.java",
"snippet": "public class LibraryLoaderUtil {\n\n public static final String NATIVE_LIB_BASE_NAME = \"sqlitejdbc\";\n\n /**\n * Get the OS-specific resource directory within the jar, where the relevant sqlitejdbc native\n * library is located.\n */\n public static String getNativeLibResourcePath() {\n String packagePath = SQLiteJDBCLoader.class.getPackage().getName().replace(\".\", \"/\");\n return String.format(\n \"/%s/native/%s\", packagePath, OSInfo.getNativeLibFolderPathForCurrentOS());\n }\n\n /** Get the OS-specific name of the sqlitejdbc native library. */\n public static String getNativeLibName() {\n return System.mapLibraryName(NATIVE_LIB_BASE_NAME);\n }\n\n public static boolean hasNativeLib(String path, String libraryName) {\n return SQLiteJDBCLoader.class.getResource(path + \"/\" + libraryName) != null;\n }\n}"
},
{
"identifier": "OSInfo",
"path": "src/main/java/org/sqlite/util/OSInfo.java",
"snippet": "public class OSInfo {\n protected static ProcessRunner processRunner = new ProcessRunner();\n private static final HashMap<String, String> archMapping = new HashMap<>();\n\n public static final String X86 = \"x86\";\n public static final String X86_64 = \"x86_64\";\n public static final String IA64_32 = \"ia64_32\";\n public static final String IA64 = \"ia64\";\n public static final String PPC = \"ppc\";\n public static final String PPC64 = \"ppc64\";\n\n static {\n // x86 mappings\n archMapping.put(X86, X86);\n archMapping.put(\"i386\", X86);\n archMapping.put(\"i486\", X86);\n archMapping.put(\"i586\", X86);\n archMapping.put(\"i686\", X86);\n archMapping.put(\"pentium\", X86);\n\n // x86_64 mappings\n archMapping.put(X86_64, X86_64);\n archMapping.put(\"amd64\", X86_64);\n archMapping.put(\"em64t\", X86_64);\n archMapping.put(\"universal\", X86_64); // Needed for openjdk7 in Mac\n\n // Itanium 64-bit mappings\n archMapping.put(IA64, IA64);\n archMapping.put(\"ia64w\", IA64);\n\n // Itanium 32-bit mappings, usually an HP-UX construct\n archMapping.put(IA64_32, IA64_32);\n archMapping.put(\"ia64n\", IA64_32);\n\n // PowerPC mappings\n archMapping.put(PPC, PPC);\n archMapping.put(\"power\", PPC);\n archMapping.put(\"powerpc\", PPC);\n archMapping.put(\"power_pc\", PPC);\n archMapping.put(\"power_rs\", PPC);\n\n // TODO: PowerPC 64bit mappings\n archMapping.put(PPC64, PPC64);\n archMapping.put(\"power64\", PPC64);\n archMapping.put(\"powerpc64\", PPC64);\n archMapping.put(\"power_pc64\", PPC64);\n archMapping.put(\"power_rs64\", PPC64);\n archMapping.put(\"ppc64el\", PPC64);\n archMapping.put(\"ppc64le\", PPC64);\n }\n\n public static void main(String[] args) {\n if (args.length >= 1) {\n if (\"--os\".equals(args[0])) {\n System.out.print(getOSName());\n return;\n } else if (\"--arch\".equals(args[0])) {\n System.out.print(getArchName());\n return;\n }\n }\n\n System.out.print(getNativeLibFolderPathForCurrentOS());\n }\n\n public static String getNativeLibFolderPathForCurrentOS() {\n return getOSName() + \"/\" + getArchName();\n }\n\n public static String getOSName() {\n return translateOSNameToFolderName(System.getProperty(\"os.name\"));\n }\n\n public static boolean isAndroid() {\n return isAndroidRuntime() || isAndroidTermux();\n }\n\n public static boolean isAndroidRuntime() {\n return System.getProperty(\"java.runtime.name\", \"\").toLowerCase().contains(\"android\");\n }\n\n public static boolean isAndroidTermux() {\n try {\n return processRunner.runAndWaitFor(\"uname -o\").toLowerCase().contains(\"android\");\n } catch (Exception ignored) {\n return false;\n }\n }\n\n public static boolean isMusl() {\n Path mapFilesDir = Paths.get(\"/proc/self/map_files\");\n try (Stream<Path> dirStream = Files.list(mapFilesDir)) {\n return dirStream\n .map(\n path -> {\n try {\n return path.toRealPath().toString();\n } catch (IOException e) {\n return \"\";\n }\n })\n .anyMatch(s -> s.toLowerCase().contains(\"musl\"));\n } catch (Exception ignored) {\n // fall back to checking for alpine linux in the event we're using an older kernel which\n // may not fail the above check\n return isAlpineLinux();\n }\n }\n\n private static boolean isAlpineLinux() {\n try (Stream<String> osLines = Files.lines(Paths.get(\"/etc/os-release\"))) {\n return osLines.anyMatch(l -> l.startsWith(\"ID\") && l.contains(\"alpine\"));\n } catch (Exception ignored2) {\n }\n return false;\n }\n\n static String getHardwareName() {\n try {\n return processRunner.runAndWaitFor(\"uname -m\");\n } catch (Throwable e) {\n LogHolder.logger.error(\"Error while running uname -m\", e);\n return \"unknown\";\n }\n }\n\n static String resolveArmArchType() {\n if (System.getProperty(\"os.name\").contains(\"Linux\")) {\n String armType = getHardwareName();\n // armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l,\n // aarch64, i686\n\n // for Android, we fold everything that is not aarch64 into arm\n if (isAndroid()) {\n if (armType.startsWith(\"aarch64\")) {\n // Use arm64\n return \"aarch64\";\n } else {\n return \"arm\";\n }\n }\n\n if (armType.startsWith(\"armv6\")) {\n // Raspberry PI\n return \"armv6\";\n } else if (armType.startsWith(\"armv7\")) {\n // Generic\n return \"armv7\";\n } else if (armType.startsWith(\"armv5\")) {\n // Use armv5, soft-float ABI\n return \"arm\";\n } else if (armType.startsWith(\"aarch64\")) {\n // Use arm64\n return \"aarch64\";\n }\n\n // Java 1.8 introduces a system property to determine armel or armhf\n // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545\n String abi = System.getProperty(\"sun.arch.abi\");\n if (abi != null && abi.startsWith(\"gnueabihf\")) {\n return \"armv7\";\n }\n\n // For java7, we still need to run some shell commands to determine ABI of JVM\n String javaHome = System.getProperty(\"java.home\");\n try {\n // determine if first JVM found uses ARM hard-float ABI\n int exitCode = Runtime.getRuntime().exec(\"which readelf\").waitFor();\n if (exitCode == 0) {\n String[] cmdarray = {\n \"/bin/sh\",\n \"-c\",\n \"find '\"\n + javaHome\n + \"' -name 'libjvm.so' | head -1 | xargs readelf -A | \"\n + \"grep 'Tag_ABI_VFP_args: VFP registers'\"\n };\n exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();\n if (exitCode == 0) {\n return \"armv7\";\n }\n } else {\n LogHolder.logger.warn(\n \"readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed\");\n }\n } catch (IOException | InterruptedException e) {\n // ignored: fall back to \"arm\" arch (soft-float ABI)\n }\n }\n // Use armv5, soft-float ABI\n return \"arm\";\n }\n\n public static String getArchName() {\n String override = System.getProperty(\"org.sqlite.osinfo.architecture\");\n if (override != null) {\n return override;\n }\n\n String osArch = System.getProperty(\"os.arch\");\n\n if (osArch.startsWith(\"arm\")) {\n osArch = resolveArmArchType();\n } else {\n String lc = osArch.toLowerCase(Locale.US);\n if (archMapping.containsKey(lc)) return archMapping.get(lc);\n }\n return translateArchNameToFolderName(osArch);\n }\n\n static String translateOSNameToFolderName(String osName) {\n if (osName.contains(\"Windows\")) {\n return \"Windows\";\n } else if (osName.contains(\"Mac\") || osName.contains(\"Darwin\")) {\n return \"Mac\";\n } else if (osName.contains(\"AIX\")) {\n return \"AIX\";\n } else if (isMusl()) {\n return \"Linux-Musl\";\n } else if (isAndroid()) {\n return \"Linux-Android\";\n } else if (osName.contains(\"Linux\")) {\n return \"Linux\";\n } else {\n return osName.replaceAll(\"\\\\W\", \"\");\n }\n }\n\n static String translateArchNameToFolderName(String archName) {\n return archName.replaceAll(\"\\\\W\", \"\");\n }\n\n /**\n * Class-wrapper around the logger object to avoid build-time initialization of the logging\n * framework in native-image\n */\n private static class LogHolder {\n private static final Logger logger = LoggerFactory.getLogger(OSInfo.class);\n }\n}"
},
{
"identifier": "StringUtils",
"path": "src/main/java/org/sqlite/util/StringUtils.java",
"snippet": "public class StringUtils {\n public static String join(List<String> list, String separator) {\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String item : list) {\n if (first) first = false;\n else sb.append(separator);\n\n sb.append(item);\n }\n return sb.toString();\n }\n}"
}
] | import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.util.LibraryLoaderUtil;
import org.sqlite.util.OSInfo;
import org.sqlite.util.StringUtils; | 4,555 | }
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extracts and loads the specified library file to the target folder
*
* @param libFolderForCurrentOS Library path.
* @param libraryFileName Library name.
* @param targetFolder Target folder.
* @return
*/
private static boolean extractAndLoadLibraryFile(
String libFolderForCurrentOS, String libraryFileName, String targetFolder)
throws FileException {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName =
String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + LOCK_EXT;
Path extractedLibFile = Paths.get(targetFolder, extractedLibFileName);
Path extractedLckFile = Paths.get(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
try (InputStream reader = getResourceAsStream(nativeLibraryFilePath)) {
if (Files.notExists(extractedLckFile)) {
Files.createFile(extractedLckFile);
}
Files.copy(reader, extractedLibFile, StandardCopyOption.REPLACE_EXISTING);
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.toFile().deleteOnExit();
extractedLckFile.toFile().deleteOnExit();
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.toFile().setReadable(true);
extractedLibFile.toFile().setWritable(true, true);
extractedLibFile.toFile().setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
try (InputStream nativeIn = getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = Files.newInputStream(extractedLibFile)) {
if (!contentsEquals(nativeIn, extractedLibIn)) {
throw new FileException(
String.format(
"Failed to write a native library file at %s",
extractedLibFile));
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch (IOException e) {
logger.error("Unexpected IOException", e);
return false;
}
}
// Replacement of java.lang.Class#getResourceAsStream(String) to disable sharing the resource
// stream
// in multiple class loaders and specifically to avoid
// https://bugs.openjdk.java.net/browse/JDK-8205976
private static InputStream getResourceAsStream(String name) {
// Remove leading '/' since all our resource paths include a leading directory
// See:
// https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Class.java#L3054
String resolvedName = name.substring(1);
ClassLoader cl = SQLiteJDBCLoader.class.getClassLoader();
URL url = cl.getResource(resolvedName);
if (url == null) {
return null;
}
try {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
} catch (IOException e) {
logger.error("Could not connect", e);
return null;
}
}
/**
* Loads native library using the given path and name of the library.
*
* @param path Path of the native library.
* @param name Name of the native library.
* @return True for successfully loading; false otherwise.
*/
private static boolean loadNativeLibrary(String path, String name) {
File libPath = new File(path, name);
if (libPath.exists()) {
try {
System.load(new File(path, name).getAbsolutePath());
return true;
} catch (UnsatisfiedLinkError e) {
logger.error(
"Failed to load native library: {}. osinfo: {}",
name,
OSInfo.getNativeLibFolderPathForCurrentOS(),
e);
return false;
}
} else {
return false;
}
}
private static boolean loadNativeLibraryJdk() {
try { | /*--------------------------------------------------------------------------
* Copyright 2007 Taro L. Saito
*
* 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.
*--------------------------------------------------------------------------*/
// --------------------------------------
// SQLite JDBC Project
//
// SQLite.java
// Since: 2007/05/10
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite;
/**
* Set the system properties, org.sqlite.lib.path, org.sqlite.lib.name, appropriately so that the
* SQLite JDBC driver can find *.dll, *.dylib and *.so files, according to the current OS (win,
* linux, mac).
*
* <p>The library files are automatically extracted from this project's package (JAR).
*
* <p>usage: call {@link #initialize()} before using SQLite JDBC driver.
*
* @author leo
*/
public class SQLiteJDBCLoader {
private static final Logger logger = LoggerFactory.getLogger(SQLiteJDBCLoader.class);
private static final String LOCK_EXT = ".lck";
private static boolean extracted = false;
/**
* Loads SQLite native JDBC library.
*
* @return True if SQLite native library is successfully loaded; false otherwise.
*/
public static synchronized boolean initialize() throws Exception {
// only cleanup before the first extract
if (!extracted) {
cleanup();
}
loadSQLiteNativeLibrary();
return extracted;
}
private static File getTempDir() {
return new File(
System.getProperty("org.sqlite.tmpdir", System.getProperty("java.io.tmpdir")));
}
/**
* Deleted old native libraries e.g. on Windows the DLL file is not removed on VM-Exit (bug #80)
*/
static void cleanup() {
String searchPattern = "sqlite-" + getVersion();
try (Stream<Path> dirList = Files.list(getTempDir().toPath())) {
dirList.filter(
path ->
!path.getFileName().toString().endsWith(LOCK_EXT)
&& path.getFileName()
.toString()
.startsWith(searchPattern))
.forEach(
nativeLib -> {
Path lckFile = Paths.get(nativeLib + LOCK_EXT);
if (Files.notExists(lckFile)) {
try {
Files.delete(nativeLib);
} catch (Exception e) {
logger.error("Failed to delete old native lib", e);
}
}
});
} catch (IOException e) {
logger.error("Failed to open directory", e);
}
}
/**
* Checks if the SQLite JDBC driver is set to native mode.
*
* @return True if the SQLite JDBC driver is set to native Java mode; false otherwise.
*/
public static boolean isNativeMode() throws Exception {
// load the driver
initialize();
return extracted;
}
/**
* Computes the MD5 value of the input stream.
*
* @param input InputStream.
* @return Encrypted string for the InputStream.
* @throws IOException
* @throws NoSuchAlgorithmException
*/
static String md5sum(InputStream input) throws IOException {
BufferedInputStream in = new BufferedInputStream(input);
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
DigestInputStream digestInputStream = new DigestInputStream(in, digest);
for (; digestInputStream.read() >= 0; ) {}
ByteArrayOutputStream md5out = new ByteArrayOutputStream();
md5out.write(digest.digest());
return md5out.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm is not available: " + e);
} finally {
in.close();
}
}
private static boolean contentsEquals(InputStream in1, InputStream in2) throws IOException {
if (!(in1 instanceof BufferedInputStream)) {
in1 = new BufferedInputStream(in1);
}
if (!(in2 instanceof BufferedInputStream)) {
in2 = new BufferedInputStream(in2);
}
int ch = in1.read();
while (ch != -1) {
int ch2 = in2.read();
if (ch != ch2) {
return false;
}
ch = in1.read();
}
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extracts and loads the specified library file to the target folder
*
* @param libFolderForCurrentOS Library path.
* @param libraryFileName Library name.
* @param targetFolder Target folder.
* @return
*/
private static boolean extractAndLoadLibraryFile(
String libFolderForCurrentOS, String libraryFileName, String targetFolder)
throws FileException {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName =
String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + LOCK_EXT;
Path extractedLibFile = Paths.get(targetFolder, extractedLibFileName);
Path extractedLckFile = Paths.get(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
try (InputStream reader = getResourceAsStream(nativeLibraryFilePath)) {
if (Files.notExists(extractedLckFile)) {
Files.createFile(extractedLckFile);
}
Files.copy(reader, extractedLibFile, StandardCopyOption.REPLACE_EXISTING);
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.toFile().deleteOnExit();
extractedLckFile.toFile().deleteOnExit();
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.toFile().setReadable(true);
extractedLibFile.toFile().setWritable(true, true);
extractedLibFile.toFile().setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
try (InputStream nativeIn = getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = Files.newInputStream(extractedLibFile)) {
if (!contentsEquals(nativeIn, extractedLibIn)) {
throw new FileException(
String.format(
"Failed to write a native library file at %s",
extractedLibFile));
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch (IOException e) {
logger.error("Unexpected IOException", e);
return false;
}
}
// Replacement of java.lang.Class#getResourceAsStream(String) to disable sharing the resource
// stream
// in multiple class loaders and specifically to avoid
// https://bugs.openjdk.java.net/browse/JDK-8205976
private static InputStream getResourceAsStream(String name) {
// Remove leading '/' since all our resource paths include a leading directory
// See:
// https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Class.java#L3054
String resolvedName = name.substring(1);
ClassLoader cl = SQLiteJDBCLoader.class.getClassLoader();
URL url = cl.getResource(resolvedName);
if (url == null) {
return null;
}
try {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
} catch (IOException e) {
logger.error("Could not connect", e);
return null;
}
}
/**
* Loads native library using the given path and name of the library.
*
* @param path Path of the native library.
* @param name Name of the native library.
* @return True for successfully loading; false otherwise.
*/
private static boolean loadNativeLibrary(String path, String name) {
File libPath = new File(path, name);
if (libPath.exists()) {
try {
System.load(new File(path, name).getAbsolutePath());
return true;
} catch (UnsatisfiedLinkError e) {
logger.error(
"Failed to load native library: {}. osinfo: {}",
name,
OSInfo.getNativeLibFolderPathForCurrentOS(),
e);
return false;
}
} else {
return false;
}
}
private static boolean loadNativeLibraryJdk() {
try { | System.loadLibrary(LibraryLoaderUtil.NATIVE_LIB_BASE_NAME); | 0 | 2023-10-07 15:42:35+00:00 | 8k |
EasyProgramming/easy-mqtt | server/src/main/java/com/ep/mqtt/server/server/MqttServer.java | [
{
"identifier": "MqttWebSocketCodec",
"path": "server/src/main/java/com/ep/mqtt/server/codec/MqttWebSocketCodec.java",
"snippet": "public class MqttWebSocketCodec extends MessageToMessageCodec<BinaryWebSocketFrame, ByteBuf> {\n\n @Override\n protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {\n out.add(new BinaryWebSocketFrame(msg.retain()));\n }\n\n @Override\n protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg, List<Object> out) throws Exception {\n out.add(msg.retain().content());\n }\n}"
},
{
"identifier": "MqttServerProperties",
"path": "server/src/main/java/com/ep/mqtt/server/config/MqttServerProperties.java",
"snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"mqtt.server\")\npublic class MqttServerProperties {\n\n /**\n * 是否开启Epoll模式, linux下建议开启\n */\n private Boolean isUseEpoll = false;\n\n /**\n * 是否开启ssl\n */\n private Boolean isOpenSsl = false;\n\n /**\n * SSL密钥文件密码\n */\n private String sslCertificatePassword;\n\n /**\n * SSL证书文件的绝对路径,只支持pfx格式的证书\n */\n private String sslCertificatePath;\n\n /**\n * tcp端口(mqtt协议的端口)\n */\n private Integer tcpPort = 8081;\n\n /**\n * websocket端口\n */\n private Integer websocketPort = 8082;\n\n /**\n * websocket连接地址\n */\n private String websocketPath = \"/websocket\";\n\n /**\n * 认证接口地址,如果为null或空字符串则不鉴权\n */\n private String authenticationUrl;\n\n /**\n * 监听器的线程池大小\n */\n private Integer listenerPoolSize = Runtime.getRuntime().availableProcessors() * 2;\n\n /**\n * 处理消息线程池的大小\n */\n private Integer dealMessageThreadPoolSize = Runtime.getRuntime().availableProcessors() * 3;\n}"
},
{
"identifier": "DefaultDeal",
"path": "server/src/main/java/com/ep/mqtt/server/deal/DefaultDeal.java",
"snippet": "@Slf4j\n@Component\npublic class DefaultDeal {\n\n @Autowired\n private StringRedisTemplate stringRedisTemplate;\n\n @Autowired\n private SubscribeStore subscribeStore;\n\n @Autowired\n private MqttServerProperties mqttServerProperties;\n\n @Autowired\n private RetainMessageStore retainMessageStore;\n\n public boolean authentication(MqttConnectMessage mqttConnectMessage) {\n if (StringUtils.isBlank(mqttServerProperties.getAuthenticationUrl())) {\n return true;\n }\n String userName = mqttConnectMessage.payload().userName();\n byte[] password = mqttConnectMessage.payload().passwordInBytes();\n String returnStr = HttpUtil.getInstance().postJson(mqttServerProperties.getAuthenticationUrl(),\n JsonUtil.obj2String(new AuthenticationRequest(userName, new String(password))), null);\n return Boolean.parseBoolean(returnStr);\n }\n\n public void cleanExistSession(String clientId, String sessionId) {\n Session session = SessionManager.get(clientId);\n if (session != null && !session.getSessionId().equals(sessionId)) {\n session.getChannelHandlerContext().disconnect();\n }\n CleanExistSessionMsg cleanExistSessionMsg = new CleanExistSessionMsg();\n cleanExistSessionMsg.setClientId(clientId);\n cleanExistSessionMsg.setSessionId(sessionId);\n stringRedisTemplate.convertAndSend(ChannelKey.CLEAR_EXIST_SESSION.getKey(),\n JsonUtil.obj2String(cleanExistSessionMsg));\n }\n\n public ClientInfoVo getClientInfo(String clientId) {\n HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();\n String clientJsonStr = hashOperations.get(StoreKey.CLIENT_INFO_KEY.formatKey(), clientId);\n return JsonUtil.string2Obj(clientJsonStr, ClientInfoVo.class);\n }\n\n public void clearClientData(String clientId) {\n cleanLocalData(clientId);\n cleanRemoteData(clientId);\n }\n\n private void cleanLocalData(String clientId) {\n // 发送取消订阅广播\n ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg();\n manageTopicFilterMsg.setClientId(clientId);\n manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.UN_SUBSCRIBE.getKey());\n stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(),\n JsonUtil.obj2String(manageTopicFilterMsg));\n }\n\n private void cleanRemoteData(String clientId) {\n HashOperations<String, String, Integer> stringObjectObjectHashOperations = stringRedisTemplate.opsForHash();\n Map<String, Integer> clientTopicFilterMap =\n stringObjectObjectHashOperations.entries(StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId));\n String messageKey = StoreKey.MESSAGE_KEY.formatKey(clientId);\n String recMessageKey = StoreKey.REC_MESSAGE_KEY.formatKey(clientId);\n String relMessageKey = StoreKey.REL_MESSAGE_KEY.formatKey(clientId);\n String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId);\n String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(clientId);\n stringRedisTemplate.execute(new SessionCallback<Void>() {\n @SuppressWarnings({\"unchecked\", \"NullableProblems\"})\n @Override\n public Void execute(RedisOperations operations) throws DataAccessException {\n // 移除订阅关系\n for (Map.Entry<String, Integer> clientTopicFilter : clientTopicFilterMap.entrySet()) {\n operations.opsForHash().delete((StoreKey.TOPIC_FILTER_KEY.formatKey(clientTopicFilter.getKey())),\n clientId);\n }\n // 移除客户端的相关数据\n operations.delete(\n Sets.newHashSet(clientTopicFilterKey, messageKey, recMessageKey, relMessageKey, genMessageIdKey));\n // 移除会话信息\n operations.opsForHash().delete(StoreKey.CLIENT_INFO_KEY.formatKey(), clientId);\n return null;\n }\n });\n }\n\n public void saveClientInfo(ClientInfoVo clientInfoVo) {\n stringRedisTemplate.opsForHash().put(StoreKey.CLIENT_INFO_KEY.formatKey(), clientInfoVo.getClientId(),\n JsonUtil.obj2String(clientInfoVo));\n }\n\n public List<Integer> subscribe(String clientId, List<TopicVo> topicVoList) {\n List<Integer> subscribeResultList = Lists.newArrayList();\n ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg();\n manageTopicFilterMsg.setClientId(clientId);\n manageTopicFilterMsg.setTopicVoList(topicVoList);\n manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.SUBSCRIBE.getKey());\n stringRedisTemplate.execute((RedisCallback<Void>)connection -> {\n for (TopicVo topicVo : topicVoList) {\n String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId);\n connection.hSet(clientTopicFilterKey.getBytes(), topicVo.getTopicFilter().getBytes(),\n String.valueOf(topicVo.getQos()).getBytes());\n connection.hSet((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(),\n clientId.getBytes(), String.valueOf(topicVo.getQos()).getBytes());\n }\n return null;\n });\n stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(),\n JsonUtil.obj2String(manageTopicFilterMsg));\n return subscribeResultList;\n }\n\n public void unSubscribe(String clientId, List<TopicVo> topicVoList) {\n for (TopicVo topicVo : topicVoList) {\n TopicUtil.validateTopicFilter(topicVo.getTopicFilter());\n }\n // 发送取消订阅广播\n ManageTopicFilterMsg manageTopicFilterMsg = new ManageTopicFilterMsg();\n manageTopicFilterMsg.setClientId(clientId);\n manageTopicFilterMsg.setManageType(ManageTopicFilterMsg.ManageType.UN_SUBSCRIBE.getKey());\n manageTopicFilterMsg.setTopicVoList(topicVoList);\n stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_TOPIC_FILTER.getKey(),\n JsonUtil.obj2String(manageTopicFilterMsg));\n stringRedisTemplate.execute((RedisCallback<Void>)connection -> {\n for (TopicVo topicVo : topicVoList) {\n connection.hDel((StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(clientId)).getBytes(),\n topicVo.getTopicFilter().getBytes());\n connection.hDel((StoreKey.TOPIC_FILTER_KEY.formatKey(topicVo.getTopicFilter())).getBytes(),\n clientId.getBytes());\n }\n return null;\n });\n\n }\n\n public void dealMessage(MessageVo messageVo) {\n Integer isRetain = messageVo.getIsRetained();\n MqttQoS fromMqttQoS = MqttQoS.valueOf(messageVo.getFromQos());\n String payload = messageVo.getPayload();\n if (YesOrNo.YES.getValue().equals(isRetain)) {\n // qos == 0 || payload 为零字节,清除该主题下的保留消息\n if (MqttQoS.AT_MOST_ONCE == fromMqttQoS || StringUtils.isBlank(payload)) {\n delTopicRetainMessage(messageVo.getTopic());\n }\n // 存储保留消息\n else {\n saveTopicRetainMessage(messageVo);\n }\n }\n if (MqttQoS.EXACTLY_ONCE.equals(fromMqttQoS)) {\n saveRecMessage(messageVo);\n return;\n }\n sendMessage(messageVo);\n }\n\n public void sendMessage(MessageVo messageVo) {\n long startTime = System.currentTimeMillis();\n // 先根据topic做匹配\n Map<String, Integer> matchMap = subscribeStore.searchSubscribe(messageVo.getTopic());\n List<MessageVo> batchSendMessageVoList = new ArrayList<>();\n ArrayList<Map.Entry<String, Integer>> matchClientList = Lists.newArrayList(matchMap.entrySet());\n for (int i = 0; i < matchClientList.size(); i++) {\n Map.Entry<String, Integer> entry = matchClientList.get(i);\n Integer toQos = Math.min(messageVo.getFromQos(), entry.getValue());\n messageVo.setToQos(toQos);\n messageVo.setToClientId(entry.getKey());\n Integer messageId = genMessageId(messageVo.getToClientId());\n if (messageId != null) {\n messageVo.setToMessageId(String.valueOf(messageId));\n switch (MqttQoS.valueOf(messageVo.getToQos())) {\n case AT_MOST_ONCE:\n batchSendMessageVoList.add(messageVo);\n break;\n case AT_LEAST_ONCE:\n case EXACTLY_ONCE:\n String messageKey = StoreKey.MESSAGE_KEY.formatKey(messageVo.getToClientId());\n RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.SAVE_MESSAGE, Long.class);\n Long flag = stringRedisTemplate.execute(redisScript, Lists.newArrayList(messageKey),\n messageVo.getToMessageId(), JsonUtil.obj2String(messageVo));\n if (flag != null) {\n batchSendMessageVoList.add(messageVo);\n }\n break;\n default:\n break;\n }\n }\n if (batchSendMessageVoList.size() >= 100 || i == matchMap.entrySet().size() - 1) {\n stringRedisTemplate.convertAndSend(ChannelKey.SEND_MESSAGE.getKey(),\n JsonUtil.obj2String(batchSendMessageVoList));\n batchSendMessageVoList.clear();\n }\n }\n log.info(\"complete send message, cost {}ms\", System.currentTimeMillis() - startTime);\n }\n\n private Integer genMessageId(String clientId) {\n String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(clientId);\n RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.GEN_MESSAGE_ID, Long.class);\n Long messageId = stringRedisTemplate.execute(redisScript, Lists.newArrayList(genMessageIdKey));\n if (messageId != null) {\n return Math.toIntExact(messageId % 65535 + 1);\n }\n return null;\n }\n\n public void delMessage(String clientId, Integer messageId) {\n stringRedisTemplate.opsForHash().delete(StoreKey.MESSAGE_KEY.formatKey(clientId), String.valueOf(messageId));\n }\n\n public void saveTopicRetainMessage(MessageVo messageVo) {\n messageVo.setToQos(messageVo.getFromQos());\n // 远程存储保留消息\n stringRedisTemplate.opsForHash().put(StoreKey.RETAIN_MESSAGE_KEY.formatKey(), messageVo.getTopic(),\n JsonUtil.obj2String(messageVo));\n // 发送redis消息,存储本地保留消息\n ManageRetainMessageMsg manageRetainMessageMsg = new ManageRetainMessageMsg();\n manageRetainMessageMsg.setManageType(ManageRetainMessageMsg.ManageType.ADD.getKey());\n manageRetainMessageMsg.setMessageVo(messageVo);\n stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_RETAIN_MESSAGE.getKey(),\n JsonUtil.obj2String(manageRetainMessageMsg));\n }\n\n public void delTopicRetainMessage(String topic) {\n // 远程删除保留消息\n stringRedisTemplate.opsForHash().delete(StoreKey.RETAIN_MESSAGE_KEY.formatKey(), topic);\n // 发送redis消息,删除本地保留消息\n ManageRetainMessageMsg manageRetainMessageMsg = new ManageRetainMessageMsg();\n manageRetainMessageMsg.setManageType(ManageRetainMessageMsg.ManageType.REMOVE.getKey());\n MessageVo messageVo = new MessageVo();\n messageVo.setTopic(topic);\n manageRetainMessageMsg.setMessageVo(messageVo);\n stringRedisTemplate.convertAndSend(ChannelKey.MANAGE_RETAIN_MESSAGE.getKey(),\n JsonUtil.obj2String(manageRetainMessageMsg));\n }\n\n public void sendTopicRetainMessage(String clientId, List<TopicVo> successSubscribeTopicList) {\n // 使用本地的保留消息进行匹配\n ChannelHandlerContext channelHandlerContext = SessionManager.get(clientId).getChannelHandlerContext();\n for (TopicVo topicVo : successSubscribeTopicList) {\n List<MessageVo> messageVoList = retainMessageStore.getRetainMessage(topicVo.getTopicFilter());\n for (MessageVo messageVo : messageVoList) {\n messageVo.setToClientId(clientId);\n Integer messageId = genMessageId(clientId);\n if (messageId == null) {\n continue;\n }\n messageVo.setToMessageId(String.valueOf(messageId));\n switch (MqttQoS.valueOf(messageVo.getToQos())) {\n case AT_LEAST_ONCE:\n case EXACTLY_ONCE:\n stringRedisTemplate.opsForHash().put(StoreKey.MESSAGE_KEY.formatKey(messageVo.getToClientId()),\n messageVo.getToMessageId(), JsonUtil.obj2String(messageVo));\n break;\n default:\n break;\n }\n MqttUtil.sendPublish(channelHandlerContext, messageVo);\n }\n }\n\n }\n\n public void saveRecMessage(MessageVo messageVo) {\n String recMessageKey = StoreKey.REC_MESSAGE_KEY.formatKey(messageVo.getFromClientId());\n RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.SAVE_REC_MESSAGE);\n stringRedisTemplate.execute(redisScript, Lists.newArrayList(recMessageKey),\n String.valueOf(messageVo.getFromMessageId()), JsonUtil.obj2String(messageVo));\n }\n\n public void delRecMessage(String clientId, Integer messageId) {\n stringRedisTemplate.opsForHash().delete(StoreKey.REC_MESSAGE_KEY.formatKey(clientId),\n String.valueOf(messageId));\n }\n\n public MessageVo getRecMessage(String clientId, Integer messageId) {\n String hashKey = StoreKey.REC_MESSAGE_KEY.formatKey(clientId);\n String messageVoStr = (String)stringRedisTemplate.opsForHash().get(hashKey, String.valueOf(messageId));\n if (StringUtils.isBlank(messageVoStr)) {\n return null;\n }\n return JsonUtil.string2Obj(messageVoStr, MessageVo.class);\n }\n\n public void saveRelMessage(String clientId, Integer messageId) {\n String relMessageKey = StoreKey.REL_MESSAGE_KEY.formatKey(clientId);\n RedisScript<Long> redisScript = new DefaultRedisScript<>(LuaScript.SAVE_REL_MESSAGE);\n stringRedisTemplate.execute(redisScript, Lists.newArrayList(relMessageKey), String.valueOf(messageId));\n }\n\n public void delRelMessage(String clientId, Integer messageId) {\n stringRedisTemplate.opsForSet().remove(StoreKey.REL_MESSAGE_KEY.formatKey(clientId), String.valueOf(messageId));\n }\n\n /**\n * 客户端的重连动作\n * \n * @param clientInfoVo\n * 客户端信息\n * @param channelHandlerContext\n * netty上下文\n * \n */\n public void reConnect(ClientInfoVo clientInfoVo, ChannelHandlerContext channelHandlerContext) {\n // 更新客户端信息\n ClientInfoVo updateClientInfoVo = new ClientInfoVo();\n BeanUtils.copyProperties(clientInfoVo, updateClientInfoVo);\n updateClientInfoVo.setConnectTime(System.currentTimeMillis());\n saveClientInfo(updateClientInfoVo);\n // 重发未接收消息\n WorkerThreadPool.execute((a) -> {\n String messageKey = StoreKey.MESSAGE_KEY.formatKey(clientInfoVo.getClientId());\n RedisTemplateUtil.hScan(stringRedisTemplate, messageKey, \"*\", 10000, entry -> {\n String messageJsonStr = entry.getValue();\n // 目前只有预设的数据为空字符串\n if (StringUtils.isBlank(messageJsonStr)) {\n return;\n }\n MessageVo messageVo = JsonUtil.string2Obj(messageJsonStr, MessageVo.class);\n Objects.requireNonNull(messageVo);\n messageVo.setIsDup(true);\n MqttUtil.sendPublish(channelHandlerContext, messageVo);\n });\n });\n // 重发PubRec报文\n WorkerThreadPool.execute((a) -> {\n String recMessageKey = StoreKey.REC_MESSAGE_KEY.formatKey(clientInfoVo.getClientId());\n RedisTemplateUtil.hScan(stringRedisTemplate, recMessageKey, \"*\", 10000, entry -> {\n String messageIdStr = entry.getKey();\n // 目前只有预设的数据为空字符串\n if (StringUtils.isBlank(messageIdStr)) {\n return;\n }\n MqttUtil.sendPubRec(channelHandlerContext, Integer.valueOf(messageIdStr));\n });\n });\n // 重发PubRel报文\n WorkerThreadPool.execute((a) -> {\n String relMessageKey = StoreKey.REL_MESSAGE_KEY.formatKey(clientInfoVo.getClientId());\n RedisTemplateUtil.sScan(stringRedisTemplate, relMessageKey, \"*\", 10000, messageIdStr -> {\n // 目前只有预设的数据为空字符串\n if (StringUtils.isBlank(messageIdStr)) {\n return;\n }\n MqttUtil.sendPubRel(channelHandlerContext, Integer.valueOf(messageIdStr));\n });\n });\n }\n\n public void refreshData(Session session) {\n stringRedisTemplate.execute(new SessionCallback<Void>() {\n @SuppressWarnings({\"unchecked\", \"NullableProblems\"})\n @Override\n public Void execute(RedisOperations operations) throws DataAccessException {\n Duration expireTime = Duration.ofMillis(session.getDataExpireTimeMilliSecond());\n String clientTopicFilterKey = StoreKey.CLIENT_TOPIC_FILTER_KEY.formatKey(session.getClientId());\n operations.opsForHash().put(clientTopicFilterKey, \"\", \"\");\n String messageKey = StoreKey.MESSAGE_KEY.formatKey(session.getClientId());\n operations.opsForHash().put(messageKey, \"\", \"\");\n String recMessageKey = StoreKey.REC_MESSAGE_KEY.formatKey(session.getClientId());\n operations.opsForHash().put(recMessageKey, \"\", \"\");\n String relMessageKey = StoreKey.REL_MESSAGE_KEY.formatKey(session.getClientId());\n operations.opsForSet().add(relMessageKey, \"\");\n String genMessageIdKey = StoreKey.GEN_MESSAGE_ID_KEY.formatKey(session.getClientId());\n operations.opsForValue().setIfAbsent(genMessageIdKey, \"0\");\n if (session.getIsCleanSession()) {\n operations.expire(clientTopicFilterKey, expireTime);\n operations.expire(messageKey, expireTime);\n operations.expire(recMessageKey, expireTime);\n operations.expire(relMessageKey, expireTime);\n operations.expire(genMessageIdKey, expireTime);\n }\n return null;\n }\n });\n }\n\n @Data\n public static class AuthenticationRequest {\n\n private String username;\n\n private String password;\n\n public AuthenticationRequest(String username, String password) {\n this.username = username;\n this.password = password;\n }\n }\n\n}"
},
{
"identifier": "MqttMessageHandler",
"path": "server/src/main/java/com/ep/mqtt/server/handler/MqttMessageHandler.java",
"snippet": "@Slf4j\npublic class MqttMessageHandler extends SimpleChannelInboundHandler<MqttMessage> {\n\n private final DefaultDeal defaultDeal;\n\n private final Map<MqttMessageType, AbstractMqttProcessor<?>> abstractMqttProcessorMap;\n\n public MqttMessageHandler(List<AbstractMqttProcessor<?>> abstractMqttProcessorList, DefaultDeal defaultDeal) {\n abstractMqttProcessorMap = abstractMqttProcessorList.stream()\n .collect(Collectors.toMap(AbstractMqttProcessor::getMqttMessageType, b -> b));\n this.defaultDeal = defaultDeal;\n }\n\n @Override\n protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) {\n AbstractMqttProcessor<?> abstractMqttProcessor = abstractMqttProcessorMap.get(msg.fixedHeader().messageType());\n if (abstractMqttProcessor == null) {\n throw new RuntimeException(\"不支持的报文\");\n }\n abstractMqttProcessor.begin(ctx, msg);\n }\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {\n log.error(\"client session id: [{}], client id: [{}] occurred error\", NettyUtil.getSessionId(ctx),\n NettyUtil.getClientId(ctx), cause);\n ctx.close();\n }\n\n @Override\n public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {\n if (evt instanceof IdleStateEvent) {\n IdleStateEvent idleStateEvent = (IdleStateEvent)evt;\n if (idleStateEvent.state() == IdleState.ALL_IDLE) {\n Channel channel = ctx.channel();\n // TODO: 2023/7/1 待实现:发送遗嘱消息\n ctx.close();\n }\n } else {\n super.userEventTriggered(ctx, evt);\n }\n }\n\n @Override\n public void channelInactive(ChannelHandlerContext ctx) {\n log.info(\"client session id: [{}], client id: [{}] inactive\", NettyUtil.getSessionId(ctx),\n NettyUtil.getClientId(ctx));\n String clientId = NettyUtil.getClientId(ctx);\n // 如果有clientId则需要解绑\n if (StringUtils.isNotBlank(clientId)) {\n Session session = SessionManager.get(clientId);\n if (session.getIsCleanSession()) {\n WorkerThreadPool.execute(promise -> defaultDeal.clearClientData(clientId));\n }\n SessionManager.unbind(clientId);\n }\n }\n\n}"
},
{
"identifier": "AbstractMqttProcessor",
"path": "server/src/main/java/com/ep/mqtt/server/processor/AbstractMqttProcessor.java",
"snippet": "@Slf4j\npublic abstract class AbstractMqttProcessor<T extends MqttMessage> {\n\n @Autowired\n protected DefaultDeal defaultDeal;\n\n /**\n * 入口\n */\n public void begin(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) {\n log.debug(\"{}\", castMqttMessage(mqttMessage).toString());\n process(channelHandlerContext, castMqttMessage(mqttMessage));\n }\n\n /**\n * 处理逻辑\n * \n * @param channelHandlerContext\n * netty处理队列上下文\n * @param mqttMessage\n * netty解析的mqtt消息\n */\n protected abstract void process(ChannelHandlerContext channelHandlerContext, T mqttMessage);\n\n /**\n * 获取mqtt消息类型\n * \n * @return mqtt消息类型\n */\n public abstract MqttMessageType getMqttMessageType();\n\n /**\n * 获取对应的mqtt消息\n * \n * @param mqttMessage\n * 父类\n * @return 对应的mqtt消息\n */\n protected abstract T castMqttMessage(MqttMessage mqttMessage);\n\n /**\n * 获取消息id\n * \n * @return 消息id\n */\n protected Integer getMessageId(MqttMessage mqttMessage) {\n if (mqttMessage.variableHeader() instanceof MqttMessageIdVariableHeader) {\n return ((MqttMessageIdVariableHeader)mqttMessage.variableHeader()).messageId();\n } else {\n throw new RuntimeException(\"非法的variableHeader\");\n }\n }\n\n}"
}
] | import com.ep.mqtt.server.codec.MqttWebSocketCodec;
import com.ep.mqtt.server.config.MqttServerProperties;
import com.ep.mqtt.server.deal.DefaultDeal;
import com.ep.mqtt.server.handler.MqttMessageHandler;
import com.ep.mqtt.server.processor.AbstractMqttProcessor;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
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.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.List; | 6,193 | package com.ep.mqtt.server.server;
/**
* @author zbz
* @date 2023/7/1 10:52
*/
@Slf4j
@Component
public class MqttServer {
@Autowired | package com.ep.mqtt.server.server;
/**
* @author zbz
* @date 2023/7/1 10:52
*/
@Slf4j
@Component
public class MqttServer {
@Autowired | private MqttServerProperties mqttServerProperties; | 1 | 2023-10-08 06:41:33+00:00 | 8k |
egorolegovichyakovlev/DroidRec | app/src/main/java/com/yakovlevegor/DroidRec/MainActivity.java | [
{
"identifier": "OnShakeEventHelper",
"path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java",
"snippet": "public class OnShakeEventHelper {\n private SensorEventListener currentListener;\n private boolean hasListenerChanged;\n private Context context;\n private ScreenRecorder.RecordingBinder recordingBinder;\n private float acceleration = 10f;\n private float currentAcceleration = SensorManager.GRAVITY_EARTH;\n private float lastAcceleration = SensorManager.GRAVITY_EARTH;\n private SensorManager sensorManager;\n private Toast toast;\n private SensorEventListener emptyListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent sensorEvent) { }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) { }\n };\n\n public OnShakeEventHelper(ScreenRecorder.RecordingBinder recordingBinder, AppCompatActivity activity) {\n this.recordingBinder = recordingBinder;\n String initialValue = activity.getSharedPreferences(ScreenRecorder.prefsident, 0).getString(\"onshake\", \"Do nothing\");\n currentListener = giveMeSensorListenerFor(initialValue);\n sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);\n context = activity.getApplicationContext();\n\n EventBus.getDefault().register(this);\n }\n\n public void registerListener() {\n sensorManager.registerListener(\n currentListener,\n sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),\n SensorManager.SENSOR_DELAY_NORMAL\n );\n hasListenerChanged = false;\n }\n\n public void unregisterListener() {\n sensorManager.unregisterListener(currentListener);\n }\n\n @Subscribe\n public void onShakePreferenceChanged(OnShakePreferenceChangeEvent event) {\n currentListener = giveMeSensorListenerFor(event.getState());\n hasListenerChanged = true;\n }\n\n public boolean hasListenerChanged() {\n return hasListenerChanged;\n }\n\n private SensorEventListener giveMeSensorListenerFor(Runnable action, String msg) {\n return new SensorEventListener() {\n @Override\n public void onSensorChanged(SensorEvent event) {\n // Fetching x,y,z values\n float x = event.values[0];\n float y = event.values[1];\n float z = event.values[2];\n lastAcceleration = currentAcceleration;\n\n // Getting current accelerations\n // with the help of fetched x,y,z values\n currentAcceleration = (float) sqrt(x * x + y * y + z * z);\n float delta = currentAcceleration - lastAcceleration;\n acceleration = acceleration * 0.9f + delta;\n\n // Display a Toast message if\n // acceleration value is over 12\n if (acceleration > 12 && recordingBinder.isStarted()) {\n action.run();\n showToast(msg);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n\n }\n };\n }\n private SensorEventListener giveMeSensorListenerFor(String state) {\n if(\"Do nothing\".equals(state)) return emptyListener;\n\n if(\"Pause\".equals(state)) return giveMeSensorListenerFor(() -> recordingBinder.recordingPause(), \"Recording is paused\");\n\n if(\"Stop\".equals(state)) return giveMeSensorListenerFor(() -> recordingBinder.stopService(), \"Recording is stopped\");\n\n throw new IllegalArgumentException(\"Should never occur\");\n }\n\n private void showToast(String msg) {\n if(toast != null) toast.cancel();\n toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);\n toast.show();\n }\n}"
},
{
"identifier": "ServiceConnectedEvent",
"path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/event/ServiceConnectedEvent.java",
"snippet": "public class ServiceConnectedEvent {\n private boolean isServiceConnected;\n\n public ServiceConnectedEvent(boolean isServiceConnected) {\n this.isServiceConnected = isServiceConnected;\n }\n\n public boolean isServiceConnected() {\n return isServiceConnected;\n }\n}"
}
] | import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.display.DisplayManager;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
import android.widget.ImageView;
import android.widget.ImageButton;
import android.widget.Chronometer;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout;
import android.widget.LinearLayout;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.AnimatorInflater;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.TooltipCompat;
import com.yakovlevegor.DroidRec.shake.OnShakeEventHelper;
import com.yakovlevegor.DroidRec.shake.event.ServiceConnectedEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList; | 3,761 | recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(255);
recordingStartButtonTransitionBack.start();
break;
}
}
public class ActivityBinder extends Binder {
void recordingStart() {
timeCounter.stop();
timeCounter.setBase(recordingBinder.getTimeStart());
timeCounter.start();
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
if (stateToRestore == true) {
showCounter(true, MainButtonState.TRANSITION_TO_RECORDING);
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
}
}
void recordingStop() {
timeCounter.stop();
timeCounter.setBase(SystemClock.elapsedRealtime());
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
finishedPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
audioPlaybackUnavailable.setVisibility(View.VISIBLE);
}
recordingState = MainButtonActionState.RECORDING_ENDED;
if (stateToRestore == true) {
showCounter(false, MainButtonState.TRANSITION_TO_RECORDING_END);
} else {
timerPanel.setVisibility(View.GONE);
transitionToButtonState(MainButtonState.ENDED_RECORDING_NORMAL);
}
}
void recordingPause(long time) {
timeCounter.setBase(SystemClock.elapsedRealtime()-time);
timeCounter.stop();
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.VISIBLE);
recordingState = MainButtonActionState.RECORDING_PAUSED;
if (stateToRestore == true) {
transitionToButtonState(MainButtonState.TRANSITION_TO_RECORDING_PAUSE);
} else {
transitionToButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
}
}
void recordingResume(long time) {
timeCounter.setBase(time);
timeCounter.start();
recordStop.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
}
void recordingReset() {
finishedPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.VISIBLE);
modesPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.TRANSITION_TO_RESTART);
}
void resetDir(boolean isAudio) {
resetFolder(isAudio);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
recordingBinder = (ScreenRecorder.RecordingBinder)service;
screenRecorderStarted = recordingBinder.isStarted();
recordingBinder.setConnect(new ActivityBinder());
if (serviceToRecording == true) {
serviceToRecording = false;
recordingStart();
}
| /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
package com.yakovlevegor.DroidRec;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_MICROPHONE = 56808;
private static final int REQUEST_MICROPHONE_PLAYBACK = 59465;
private static final int REQUEST_MICROPHONE_RECORD = 58467;
private static final int REQUEST_STORAGE = 58593;
private static final int REQUEST_STORAGE_AUDIO = 58563;
private static final int REQUEST_MODE_CHANGE = 58857;
private ScreenRecorder.RecordingBinder recordingBinder;
boolean screenRecorderStarted = false;
private MediaProjectionManager activityProjectionManager;
private SharedPreferences appSettings;
private SharedPreferences.Editor appSettingsEditor;
Display display;
ImageButton mainRecordingButton;
ImageButton startRecordingButton;
ImageButton recordScreenSetting;
ImageButton recordMicrophoneSetting;
ImageButton recordAudioSetting;
ImageButton recordInfo;
ImageButton recordSettings;
ImageButton recordShare;
ImageButton recordDelete;
ImageButton recordOpen;
ImageButton recordStop;
LinearLayout timerPanel;
LinearLayout modesPanel;
LinearLayout finishedPanel;
LinearLayout optionsPanel;
Chronometer timeCounter;
TextView audioPlaybackUnavailable;
Intent serviceIntent;
public static String appName = "com.yakovlevegor.DroidRec";
public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING";
private boolean stateActivated = false;
private boolean serviceToRecording = false;
private AlertDialog dialog;
private boolean recordModeChosen;
private OnShakeEventHelper onShakeEventHelper;
private boolean isRecording = false;
private boolean recordMicrophone = false;
private boolean recordPlayback = false;
private boolean recordOnlyAudio = false;
private VectorDrawableCompat recordScreenState;
private VectorDrawableCompat recordScreenStateDisabled;
private VectorDrawableCompat recordMicrophoneState;
private VectorDrawableCompat recordMicrophoneStateDisabled;
private VectorDrawableCompat recordPlaybackState;
private VectorDrawableCompat recordPlaybackStateDisabled;
private VectorDrawableCompat recordInfoIcon;
private VectorDrawableCompat recordSettingsIcon;
private VectorDrawableCompat recordShareIcon;
private VectorDrawableCompat recordDeleteIcon;
private VectorDrawableCompat recordOpenIcon;
private VectorDrawableCompat recordStopIcon;
private VectorDrawableCompat recordingStartButtonNormal;
private AnimatedVectorDrawableCompat recordingStartButtonHover;
private AnimatedVectorDrawableCompat recordingStartButtonHoverReleased;
private AnimatedVectorDrawableCompat recordingStartButtonTransitionToRecording;
private VectorDrawableCompat recordingBackgroundNormal;
private AnimatedVectorDrawableCompat recordingBackgroundHover;
private AnimatedVectorDrawableCompat recordingBackgroundHoverReleased;
private AnimatedVectorDrawableCompat recordingBackgroundTransition;
private AnimatedVectorDrawableCompat recordingBackgroundTransitionBack;
private VectorDrawableCompat recordingStartCameraLegs;
private AnimatedVectorDrawableCompat recordingStartCameraLegsAppear;
private AnimatedVectorDrawableCompat recordingStartCameraLegsDisappear;
private VectorDrawableCompat recordingStartCameraMicrophone;
private AnimatedVectorDrawableCompat recordingStartCameraMicrophoneAppear;
private AnimatedVectorDrawableCompat recordingStartCameraMicrophoneDisappear;
private AnimatedVectorDrawableCompat recordingStartCameraBodyWorking;
private AnimatedVectorDrawableCompat recordingStartCameraBodyAppear;
private AnimatedVectorDrawableCompat recordingStartCameraBodyDisappear;
private VectorDrawableCompat recordingStartCameraHeadphones;
private AnimatedVectorDrawableCompat recordingStartCameraHeadphonesAppear;
private AnimatedVectorDrawableCompat recordingStartCameraHeadphonesDisappear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsFirstAppear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsFirstDisappear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsSecondAppear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsSecondDisappear;
private AnimatedVectorDrawableCompat recordingStartAudioBodyWorking;
private AnimatedVectorDrawableCompat recordingStartAudioBodyAppear;
private AnimatedVectorDrawableCompat recordingStartAudioBodyDisappear;
private AnimatedVectorDrawableCompat recordingStartAudioTapeWorking;
private AnimatedVectorDrawableCompat recordingStartAudioTapeAppear;
private AnimatedVectorDrawableCompat recordingStartAudioTapeDisappear;
private VectorDrawableCompat recordingStartAudioHeadphones;
private AnimatedVectorDrawableCompat recordingStartAudioHeadphonesAppear;
private AnimatedVectorDrawableCompat recordingStartAudioHeadphonesDisappear;
private VectorDrawableCompat recordingStartAudioMicrophone;
private AnimatedVectorDrawableCompat recordingStartAudioMicrophoneAppear;
private AnimatedVectorDrawableCompat recordingStartAudioMicrophoneDisappear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsFirstAppear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsFirstDisappear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsSecondAppear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsSecondDisappear;
private AnimatedVectorDrawableCompat recordingStartButtonTransitionBack;
private LayerDrawable mainButtonLayers;
private AnimatedVectorDrawableCompat recordingStatusIconPause;
private boolean stateToRestore = false;
private boolean recordButtonHoverRelease = false;
private boolean recordButtonHoverPressed = false;
private boolean recordButtonLocked = false;
private boolean recordButtonPressed = false;
private enum DarkenState {
TO_DARKEN,
SET_DARKEN,
UNDARKEN_RECORD,
UNDARKEN_END,
}
private enum MainButtonState {
BEFORE_RECORDING_NORMAL,
BEFORE_RECORDING_HOVER,
BEFORE_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RECORDING,
START_RECORDING,
CONTINUE_RECORDING,
WHILE_RECORDING_NORMAL,
WHILE_RECORDING_HOVER,
WHILE_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RECORDING_PAUSE,
WHILE_PAUSE_NORMAL,
WHILE_PAUSE_HOVER,
WHILE_PAUSE_HOVER_RELEASED,
TRANSITION_FROM_PAUSE,
TRANSITION_TO_RECORDING_END,
END_SHOW_REELS,
ENDED_RECORDING_NORMAL,
ENDED_RECORDING_HOVER,
ENDED_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RESTART,
}
private enum MainButtonActionState {
RECORDING_STOPPED,
RECORDING_IN_PROGRESS,
RECORDING_PAUSED,
RECORDING_ENDED,
}
private MainButtonState currentMainButtonState;
private MainButtonState nextMainButtonState = null;
private MainButtonActionState recordingState = MainButtonActionState.RECORDING_STOPPED;
boolean hoverInProgress() {
switch (currentMainButtonState) {
case BEFORE_RECORDING_HOVER:
return recordingStartButtonHover.isRunning();
case WHILE_RECORDING_HOVER:
return recordingBackgroundHover.isRunning();
case WHILE_PAUSE_HOVER:
return recordingBackgroundHover.isRunning();
case ENDED_RECORDING_HOVER:
return recordingBackgroundHover.isRunning();
}
return false;
}
void darkenLayers(ArrayList<Drawable> targetDrawables, float amount, int duration, boolean restore, DarkenState darkState, MainButtonState atState) {
if (darkState == DarkenState.SET_DARKEN) {
int drawablesList = targetDrawables.size();
int drawablesCount = 0;
while (drawablesCount < drawablesList) {
targetDrawables.get(drawablesCount).setColorFilter(new PorterDuffColorFilter(Color.argb((int)(amount*100), 0, 0, 0), PorterDuff.Mode.SRC_ATOP));
drawablesCount += 1;
}
} else {
ValueAnimator colorAnim = ObjectAnimator.ofFloat(0f, amount);
if (restore == true) {
colorAnim = ObjectAnimator.ofFloat(amount, 0f);
}
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
int drawablesList = targetDrawables.size();
int drawablesCount = 0;
while (drawablesCount < drawablesList) {
if (state == 0.0) {
targetDrawables.get(drawablesCount).setColorFilter(null);
} else {
targetDrawables.get(drawablesCount).setColorFilter(new PorterDuffColorFilter(Color.argb((int)(state*100), 0, 0, 0), PorterDuff.Mode.SRC_ATOP));
}
drawablesCount += 1;
}
if (((state == amount && restore == false) || (state == 0.0 && restore == true)) && currentMainButtonState == atState) {
if (darkState == DarkenState.TO_DARKEN) {
setMainButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
} else if (darkState == DarkenState.UNDARKEN_RECORD) {
setMainButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
} else if (darkState == DarkenState.UNDARKEN_END) {
setMainButtonState(MainButtonState.TRANSITION_TO_RECORDING_END);
}
}
}
});
colorAnim.setDuration(duration);
colorAnim.start();
}
}
void showCounter(boolean displayCounter, MainButtonState beforeState) {
if (displayCounter == true) {
timeCounter.setScaleX(0.0f);
timeCounter.setScaleY(0.0f);
timerPanel.setVisibility(View.VISIBLE);
ValueAnimator counterShowAnimX = ObjectAnimator.ofFloat(timeCounter, "scaleX", 0f, 1f);
ValueAnimator counterShowAnimY = ObjectAnimator.ofFloat(timeCounter, "scaleY", 0f, 1f);
counterShowAnimX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
if (state == 1f) {
if (beforeState != null) {
transitionToButtonState(beforeState);
}
}
}
});
counterShowAnimX.setDuration(400);
counterShowAnimY.setDuration(400);
counterShowAnimX.start();
counterShowAnimY.start();
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
ValueAnimator counterShowAnimX = ObjectAnimator.ofFloat(timeCounter, "scaleX", 1f, 0f);
ValueAnimator counterShowAnimY = ObjectAnimator.ofFloat(timeCounter, "scaleY", 1f, 0f);
counterShowAnimX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
if (state == 0f) {
timerPanel.setVisibility(View.GONE);
if (beforeState != null) {
transitionToButtonState(beforeState);
}
}
}
});
counterShowAnimX.setDuration(400);
counterShowAnimY.setDuration(400);
counterShowAnimX.start();
counterShowAnimY.start();
}
}
private void releaseMainButtonFocus() {
if (currentMainButtonState == MainButtonState.BEFORE_RECORDING_HOVER && recordingStartButtonHover.isRunning() == false) {
setMainButtonState(MainButtonState.BEFORE_RECORDING_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.WHILE_RECORDING_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.WHILE_RECORDING_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.WHILE_PAUSE_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.WHILE_PAUSE_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.ENDED_RECORDING_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.ENDED_RECORDING_HOVER_RELEASED);
}
}
private void updateRecordModeData() {
recordMicrophone = appSettings.getBoolean("checksoundmic", false);
recordPlayback = appSettings.getBoolean("checksoundplayback", false);
if (recordPlayback == true && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
recordPlayback = false;
}
recordOnlyAudio = appSettings.getBoolean("recordmode", false);
if (recordOnlyAudio == true && recordPlayback == false && recordMicrophone == false) {
recordOnlyAudio = false;
}
}
private void transitionToButtonState(MainButtonState toState) {
if (hoverInProgress() == false) {
setMainButtonState(toState);
} else {
nextMainButtonState = toState;
}
}
private void setMainButtonState(MainButtonState state) {
MainButtonState prevState = currentMainButtonState;
currentMainButtonState = state;
nextMainButtonState = null;
switch (state) {
case BEFORE_RECORDING_NORMAL:
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_start));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_start));
recordingStartButtonNormal.setAlpha(255);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case BEFORE_RECORDING_HOVER:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(255);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonHover.start();
break;
case BEFORE_RECORDING_HOVER_RELEASED:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(255);
recordingStartButtonHoverReleased.start();
break;
case TRANSITION_TO_RECORDING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(255);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
recordingStartButtonTransitionToRecording.start();
break;
case START_RECORDING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegsAppear.setAlpha(255);
recordingStartCameraLegsAppear.start();
} else {
recordingStartCameraLegsAppear.setAlpha(0);
}
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophoneAppear.setAlpha(255);
recordingStartCameraMicrophoneAppear.start();
} else {
recordingStartCameraMicrophoneAppear.setAlpha(0);
}
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyAppear.setAlpha(255);
recordingStartCameraBodyAppear.start();
} else {
recordingStartCameraBodyAppear.setAlpha(0);
}
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphonesAppear.setAlpha(255);
recordingStartCameraHeadphonesAppear.start();
} else {
recordingStartCameraHeadphonesAppear.setAlpha(0);
}
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyAppear.setAlpha(255);
recordingStartAudioBodyAppear.start();
} else {
recordingStartAudioBodyAppear.setAlpha(0);
}
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeAppear.setAlpha(255);
recordingStartAudioTapeAppear.start();
} else {
recordingStartAudioTapeAppear.setAlpha(0);
}
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphonesAppear.setAlpha(255);
recordingStartAudioHeadphonesAppear.start();
} else {
recordingStartAudioHeadphonesAppear.setAlpha(0);
}
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophoneAppear.setAlpha(255);
recordingStartAudioMicrophoneAppear.start();
} else {
recordingStartAudioMicrophoneAppear.setAlpha(0);
}
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case WHILE_RECORDING_NORMAL:
recordButtonLocked = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.start();
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.start();
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.start();
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case WHILE_RECORDING_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case WHILE_RECORDING_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_TO_RECORDING_PAUSE:
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_resume));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_resume));
ArrayList<Drawable> layersToDarken = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
layersToDarken.add(recordingStartCameraLegs);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
layersToDarken.add(recordingStartCameraMicrophone);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
layersToDarken.add(recordingStartCameraBodyWorking);
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersToDarken.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersToDarken.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersToDarken.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersToDarken.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersToDarken.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersToDarken, 0.8f, 200, false, DarkenState.TO_DARKEN, state);
break;
case WHILE_PAUSE_NORMAL:
recordingState = MainButtonActionState.RECORDING_PAUSED;
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_resume));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_resume));
ArrayList<Drawable> layersSetDark = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersSetDark.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersSetDark.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersSetDark.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersSetDark.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersSetDark.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersSetDark, 0.8f, 200, false, DarkenState.SET_DARKEN, state);
break;
case WHILE_PAUSE_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case WHILE_PAUSE_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_FROM_PAUSE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
ArrayList<Drawable> layersToUndarken = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
layersToUndarken.add(recordingStartCameraLegs);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
layersToUndarken.add(recordingStartCameraMicrophone);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
layersToUndarken.add(recordingStartCameraBodyWorking);
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersToUndarken.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersToUndarken.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersToUndarken.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersToUndarken.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersToUndarken.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersToUndarken, 0.8f, 200, true, DarkenState.UNDARKEN_RECORD, state);
break;
case TRANSITION_TO_RECORDING_END:
mainRecordingButton.setContentDescription(getResources().getString(R.string.recording_finished_title));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.recording_finished_title));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegsDisappear.setAlpha(255);
recordingStartCameraLegsDisappear.start();
} else {
recordingStartCameraLegsDisappear.setAlpha(0);
}
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophoneDisappear.setAlpha(255);
recordingStartCameraMicrophoneDisappear.start();
} else {
recordingStartCameraMicrophoneDisappear.setAlpha(0);
}
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyDisappear.setAlpha(255);
recordingStartCameraBodyDisappear.start();
} else {
recordingStartCameraBodyDisappear.setAlpha(0);
}
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphonesDisappear.setAlpha(255);
recordingStartCameraHeadphonesDisappear.start();
} else {
recordingStartCameraHeadphonesDisappear.setAlpha(0);
}
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyDisappear.setAlpha(255);
recordingStartAudioBodyDisappear.start();
} else {
recordingStartAudioBodyDisappear.setAlpha(0);
}
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeDisappear.setAlpha(255);
recordingStartAudioTapeDisappear.start();
} else {
recordingStartAudioTapeDisappear.setAlpha(0);
}
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphonesDisappear.setAlpha(255);
recordingStartAudioHeadphonesDisappear.start();
} else {
recordingStartAudioHeadphonesDisappear.setAlpha(0);
}
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophoneDisappear.setAlpha(255);
recordingStartAudioMicrophoneDisappear.start();
} else {
recordingStartAudioMicrophoneDisappear.setAlpha(0);
}
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case END_SHOW_REELS:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegs.setColorFilter(null);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophone.setColorFilter(null);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyWorking.setColorFilter(null);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphones.setColorFilter(null);
recordingStartAudioHeadphones.setColorFilter(null);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsFirstAppear.setAlpha(255);
recordingStopCameraReelsFirstAppear.start();
} else {
recordingStopCameraReelsFirstAppear.setAlpha(0);
}
recordingStopCameraReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsSecondAppear.setAlpha(255);
recordingStopCameraReelsSecondAppear.start();
} else {
recordingStopCameraReelsSecondAppear.setAlpha(0);
}
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyWorking.setColorFilter(null);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeWorking.setColorFilter(null);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophone.setColorFilter(null);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsFirstAppear.setAlpha(255);
recordingStopAudioReelsFirstAppear.start();
} else {
recordingStopAudioReelsFirstAppear.setAlpha(0);
}
recordingStopAudioReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsSecondAppear.setAlpha(255);
recordingStopAudioReelsSecondAppear.start();
} else {
recordingStopAudioReelsSecondAppear.setAlpha(0);
}
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case ENDED_RECORDING_NORMAL:
recordingState = MainButtonActionState.RECORDING_ENDED;
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.recording_finished_title));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.recording_finished_title));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegs.setColorFilter(null);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophone.setColorFilter(null);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyWorking.setColorFilter(null);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphones.setColorFilter(null);
recordingStartAudioHeadphones.setColorFilter(null);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsFirstAppear.setAlpha(255);
} else {
recordingStopCameraReelsFirstAppear.setAlpha(0);
}
recordingStopCameraReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsSecondAppear.setAlpha(255);
} else {
recordingStopCameraReelsSecondAppear.setAlpha(0);
}
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyWorking.setColorFilter(null);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeWorking.setColorFilter(null);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophone.setColorFilter(null);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsFirstAppear.setAlpha(255);
} else {
recordingStopAudioReelsFirstAppear.setAlpha(0);
}
recordingStopAudioReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsSecondAppear.setAlpha(255);
} else {
recordingStopAudioReelsSecondAppear.setAlpha(0);
}
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case ENDED_RECORDING_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case ENDED_RECORDING_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_TO_RESTART:
recordingState = MainButtonActionState.RECORDING_STOPPED;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_start));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_start));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(255);
recordingStartButtonTransitionBack.start();
break;
}
}
public class ActivityBinder extends Binder {
void recordingStart() {
timeCounter.stop();
timeCounter.setBase(recordingBinder.getTimeStart());
timeCounter.start();
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
if (stateToRestore == true) {
showCounter(true, MainButtonState.TRANSITION_TO_RECORDING);
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
}
}
void recordingStop() {
timeCounter.stop();
timeCounter.setBase(SystemClock.elapsedRealtime());
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
finishedPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
audioPlaybackUnavailable.setVisibility(View.VISIBLE);
}
recordingState = MainButtonActionState.RECORDING_ENDED;
if (stateToRestore == true) {
showCounter(false, MainButtonState.TRANSITION_TO_RECORDING_END);
} else {
timerPanel.setVisibility(View.GONE);
transitionToButtonState(MainButtonState.ENDED_RECORDING_NORMAL);
}
}
void recordingPause(long time) {
timeCounter.setBase(SystemClock.elapsedRealtime()-time);
timeCounter.stop();
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.VISIBLE);
recordingState = MainButtonActionState.RECORDING_PAUSED;
if (stateToRestore == true) {
transitionToButtonState(MainButtonState.TRANSITION_TO_RECORDING_PAUSE);
} else {
transitionToButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
}
}
void recordingResume(long time) {
timeCounter.setBase(time);
timeCounter.start();
recordStop.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
}
void recordingReset() {
finishedPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.VISIBLE);
modesPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.TRANSITION_TO_RESTART);
}
void resetDir(boolean isAudio) {
resetFolder(isAudio);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
recordingBinder = (ScreenRecorder.RecordingBinder)service;
screenRecorderStarted = recordingBinder.isStarted();
recordingBinder.setConnect(new ActivityBinder());
if (serviceToRecording == true) {
serviceToRecording = false;
recordingStart();
}
| EventBus.getDefault().post(new ServiceConnectedEvent(true)); | 1 | 2023-10-09 00:04:13+00:00 | 8k |
lunasaw/gb28181-proxy | gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/MessageProcessorClient.java | [
{
"identifier": "BroadcastNotifyMessageHandler",
"path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/handler/notify/BroadcastNotifyMessageHandler.java",
"snippet": "@Component\n@Slf4j\n@Getter\n@Setter\npublic class BroadcastNotifyMessageHandler extends MessageClientHandlerAbstract {\n\n public static final String CMD_TYPE = \"Broadcast\";\n\n private String cmdType = CMD_TYPE;\n\n public BroadcastNotifyMessageHandler(MessageProcessorClient messageProcessorClient, SipUserGenerateClient sipUserGenerateClient) {\n super(messageProcessorClient, sipUserGenerateClient);\n }\n\n\n @Override\n public String getRootType() {\n return ClientMessageRequestProcessor.METHOD + NOTIFY;\n }\n\n @Override\n public void handForEvt(RequestEvent event) {\n DeviceSession deviceSession = getDeviceSession(event);\n String userId = deviceSession.getUserId();\n\n // 设备查询\n FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice();\n if (fromDevice == null || !fromDevice.getUserId().equals(userId)) {\n throw new RuntimeException(\"查询设备失败\");\n }\n\n DeviceBroadcastNotify broadcastNotify = parseXml(DeviceBroadcastNotify.class);\n\n messageProcessorClient.broadcastNotify(broadcastNotify);\n }\n\n @Override\n public String getCmdType() {\n return cmdType;\n }\n}"
},
{
"identifier": "CatalogQueryMessageClientHandler",
"path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/handler/query/CatalogQueryMessageClientHandler.java",
"snippet": "@Component\n@Slf4j\n@Getter\n@Setter\npublic class CatalogQueryMessageClientHandler extends MessageClientHandlerAbstract {\n\n public static final String CMD_TYPE = \"Catalog\";\n\n private String cmdType = CMD_TYPE;\n\n public CatalogQueryMessageClientHandler(MessageProcessorClient messageProcessorClient, SipUserGenerateClient sipUserGenerateClient) {\n super(messageProcessorClient, sipUserGenerateClient);\n }\n\n\n @Override\n public String getRootType() {\n return ClientMessageRequestProcessor.METHOD + QUERY;\n }\n\n\n @Override\n public void handForEvt(RequestEvent event) {\n DeviceSession deviceSession = getDeviceSession(event);\n\n String userId = deviceSession.getUserId();\n String sipId = deviceSession.getSipId();\n\n // 设备查询\n FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice();\n ToDevice toDevice = (ToDevice)sipUserGenerate.getToDevice(sipId);\n if (toDevice == null) {\n return;\n }\n\n DeviceQuery deviceQuery = parseXml(DeviceQuery.class);\n\n // 请求序列化编号,上游后续处理\n String sn = deviceQuery.getSn();\n DeviceResponse deviceResponse = messageProcessorClient.getDeviceItem(userId);\n deviceResponse.setSn(sn);\n\n ClientSendCmd.deviceChannelCatalogResponse(fromDevice, toDevice, deviceResponse);\n }\n\n @Override\n public String getCmdType() {\n return cmdType;\n }\n}"
},
{
"identifier": "DeviceInfoQueryMessageClientHandler",
"path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/handler/query/DeviceInfoQueryMessageClientHandler.java",
"snippet": "@Component\n@Slf4j\n@Getter\n@Setter\npublic class DeviceInfoQueryMessageClientHandler extends MessageClientHandlerAbstract {\n\n public static final String CMD_TYPE = \"DeviceInfo\";\n\n private String cmdType = CMD_TYPE;\n\n public DeviceInfoQueryMessageClientHandler(MessageProcessorClient messageProcessorClient, SipUserGenerateClient sipUserGenerateClient) {\n super(messageProcessorClient, sipUserGenerateClient);\n }\n\n\n @Override\n public String getRootType() {\n return ClientMessageRequestProcessor.METHOD + QUERY;\n }\n\n\n @Override\n public void handForEvt(RequestEvent event) {\n\n DeviceSession deviceSession = getDeviceSession(event);\n String userId = deviceSession.getUserId();\n String sipId = deviceSession.getSipId();\n\n // 设备查询\n FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice();\n ToDevice toDevice = (ToDevice)sipUserGenerate.getToDevice(sipId);\n\n DeviceQuery deviceQuery = parseXml(DeviceQuery.class);\n\n String sn = deviceQuery.getSn();\n DeviceInfo deviceInfo = messageProcessorClient.getDeviceInfo(userId);\n deviceInfo.setSn(sn);\n\n ClientSendCmd.deviceInfoResponse(fromDevice, toDevice, deviceInfo);\n }\n\n @Override\n public String getCmdType() {\n return cmdType;\n }\n}"
},
{
"identifier": "DeviceStatusQueryMessageClientHandler",
"path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/handler/query/DeviceStatusQueryMessageClientHandler.java",
"snippet": "@Component\n@Slf4j\n@Getter\n@Setter\npublic class DeviceStatusQueryMessageClientHandler extends MessageClientHandlerAbstract {\n\n public static final String CMD_TYPE = \"DeviceStatus\";\n\n private String root = QUERY;\n private String cmdType = CMD_TYPE;\n\n public DeviceStatusQueryMessageClientHandler(MessageProcessorClient messageProcessorClient, SipUserGenerateClient sipUserGenerateClient) {\n super(messageProcessorClient, sipUserGenerateClient);\n }\n\n\n @Override\n public String getRootType() {\n return ClientMessageRequestProcessor.METHOD + QUERY;\n }\n\n\n @Override\n public void handForEvt(RequestEvent event) {\n DeviceSession deviceSession = getDeviceSession(event);\n String userId = deviceSession.getUserId();\n String sipId = deviceSession.getSipId();\n\n // 设备查询\n FromDevice fromDevice = (FromDevice)sipUserGenerate.getFromDevice();\n if (fromDevice == null) {\n return;\n }\n ToDevice toDevice = (ToDevice)sipUserGenerate.getToDevice(sipId);\n\n DeviceQuery deviceQuery = parseXml(DeviceQuery.class);\n\n String sn = deviceQuery.getSn();\n\n DeviceStatus deviceStatus = messageProcessorClient.getDeviceStatus(userId);\n deviceStatus.setSn(sn);\n\n ClientSendCmd.deviceStatusResponse(fromDevice, toDevice, deviceStatus.getOnline());\n }\n\n @Override\n public String getCmdType() {\n return cmdType;\n }\n}"
},
{
"identifier": "DeviceAlarmNotify",
"path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/notify/DeviceAlarmNotify.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@XmlRootElement(name = \"Notify\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceAlarmNotify extends XmlBean {\n @XmlElement(name = \"CmdType\")\n public String cmdType;\n\n @XmlElement(name = \"SN\")\n public String sn;\n\n @XmlElement(name = \"DeviceID\")\n public String deviceId;\n\n @XmlElement(name = \"AlarmPriority\")\n public String alarmPriority;\n\n @XmlElement(name = \"AlarmMethod\")\n public String alarmMethod;\n\n /**\n * ISO8601\n */\n @XmlElement(name = \"AlarmTime\")\n public String alarmTime;\n\n /**\n * 经度\n */\n @XmlElement(name = \"Longitude\")\n public String longitude;\n\n /**\n * 纬度\n */\n @XmlElement(name = \"Latitude\")\n public String latitude;\n\n @XmlElement(name = \"Info\")\n private AlarmInfo info;\n\n public DeviceAlarmNotify(String cmdType, String sn, String deviceId) {\n this.cmdType = cmdType;\n this.sn = sn;\n this.deviceId = deviceId;\n }\n\n public static void main(String[] args) {\n DeviceAlarmNotify deviceCatalog = new DeviceAlarmNotify();\n deviceCatalog.setDeviceId(\"123\");\n DeviceItem deviceItem = new DeviceItem();\n deviceItem.setAddress(\"!23\");\n System.out.println(deviceCatalog);\n }\n\n public DeviceAlarmNotify setAlarm(DeviceAlarm deviceAlarm) {\n setAlarmPriority(deviceAlarm.getAlarmPriority());\n setAlarmMethod(deviceAlarm.getAlarmMethod());\n setAlarmTime(DateUtils.formatTime(DateUtils.ISO8601_PATTERN, deviceAlarm.getAlarmTime()));\n setLongitude(String.valueOf(deviceAlarm.getLongitude()));\n setLatitude(String.valueOf(deviceAlarm.getLatitude()));\n setInfo(new AlarmInfo(deviceAlarm.getAlarmType()));\n return this;\n }\n\n @Getter\n @Setter\n @AllArgsConstructor\n @NoArgsConstructor\n @XmlRootElement(name = \"Info\")\n @XmlAccessorType(XmlAccessType.FIELD)\n public static class AlarmInfo {\n\n @XmlElement(name = \"AlarmType\")\n public String alarmType;\n }\n}"
},
{
"identifier": "DeviceBroadcastNotify",
"path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/notify/DeviceBroadcastNotify.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@XmlRootElement(name = \"Notify\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceBroadcastNotify extends XmlBean {\n @XmlElement(name = \"CmdType\")\n public String cmdType;\n\n @XmlElement(name = \"SN\")\n public String sn;\n\n @XmlElement(name = \"SourceID\")\n public String sourceId;\n\n @XmlElement(name = \"TargetID\")\n public String targetId;\n\n\n}"
},
{
"identifier": "DeviceAlarmQuery",
"path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/query/DeviceAlarmQuery.java",
"snippet": "@Getter\n@Setter\n@XmlRootElement(name = \"Query\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceAlarmQuery extends XmlBean {\n @XmlElement(name = \"CmdType\")\n public String cmdType;\n\n @XmlElement(name = \"SN\")\n public String sn;\n\n @XmlElement(name = \"DeviceID\")\n public String deviceId;\n\n @XmlElement(name = \"StartTime\")\n public String startTime;\n\n @XmlElement(name = \"EndTime\")\n public String endTime;\n\n @XmlElement(name = \"StartAlarmPriority\")\n public String startAlarmPriority;\n\n /**\n * \n */\n @XmlElement(name = \"endAlarmPriority\")\n public String endAlarmPriority;\n\n @XmlElement(name = \"AlarmType\")\n public String alarmType;\n\n public DeviceAlarmQuery() {}\n\n public DeviceAlarmQuery(String cmdType, String sn, String deviceId) {\n this.cmdType = cmdType;\n this.sn = sn;\n this.deviceId = deviceId;\n }\n\n public static void main(String[] args) {\n\n }\n}"
},
{
"identifier": "DeviceConfigDownload",
"path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/query/DeviceConfigDownload.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@XmlRootElement(name = \"Query\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceConfigDownload extends DeviceBase {\n\n\n /**\n * 查询配置参数类型(必选),可查询的配 置 类 型 包 括\n * 基 本 参 数 配 置:BasicParam,\n * 视 频 参数范围:VideoParamOpt,SVAC\n * 编 码 配 置:SVACEncodeConfig,SVAC\n * 解 码 配 置:SVACDe-codeConfig。\n * 可同时查询多个配置类型,各类型以“/”分隔,可返回与查询\n * SN 值相同的多个响应,每个响应对应一个配置类型\n */\n @XmlElement(name = \"ConfigType\")\n public String configType;\n\n public DeviceConfigDownload(String cmdType, String sn, String deviceId) {\n super(cmdType, sn, deviceId);\n }\n\n}"
},
{
"identifier": "DeviceRecordQuery",
"path": "gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/query/DeviceRecordQuery.java",
"snippet": "@Getter\n@Setter\n@XmlRootElement(name = \"Query\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class DeviceRecordQuery extends XmlBean {\n @XmlElement(name = \"CmdType\")\n public String cmdType;\n\n @XmlElement(name = \"SN\")\n public String sn;\n\n @XmlElement(name = \"DeviceID\")\n public String deviceId;\n\n @XmlElement(name = \"StartTime\")\n public String startTime;\n\n @XmlElement(name = \"EndTime\")\n public String endTime;\n\n @XmlElement(name = \"Secrecy\")\n public String secrecy;\n\n /**\n * 大华NVR要求必须增加一个值为all的文本元素节点Type\n *\n * all(time 或 alarm 或 manual 或 all)\n */\n @XmlElement(name = \"Type\")\n public String type;\n\n public DeviceRecordQuery() {}\n\n public DeviceRecordQuery(String cmdType, String sn, String deviceId) {\n this.cmdType = cmdType;\n this.sn = sn;\n this.deviceId = deviceId;\n }\n\n public static void main(String[] args) {\n\n DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.getDefault()).withZone(ZoneId.of(\"Asia/Shanghai\"));\n\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault()).withZone(ZoneId.of(\"Asia/Shanghai\"));\n\n String format = dateTimeFormatter.format(formatter.parse(\"2023-11-11 10:10:10\"));\n System.out.println(format);\n\n String s = DateUtils.formatTime(DateUtils.ISO8601_PATTERN, new Date());\n System.out.println(s);\n }\n}"
}
] | import io.github.lunasaw.gb28181.common.entity.response.*;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.notify.BroadcastNotifyMessageHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.CatalogQueryMessageClientHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.DeviceInfoQueryMessageClientHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.DeviceStatusQueryMessageClientHandler;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceAlarmNotify;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceBroadcastNotify;
import io.github.lunasaw.gb28181.common.entity.query.DeviceAlarmQuery;
import io.github.lunasaw.gb28181.common.entity.query.DeviceConfigDownload;
import io.github.lunasaw.gb28181.common.entity.query.DeviceRecordQuery; | 3,792 | package io.github.lunasaw.gbproxy.client.transmit.request.message;
/**
* @author luna
* @date 2023/10/18
*/
public interface MessageProcessorClient {
/**
* 获取设备录像信息
* DeviceRecord
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param deviceRecordQuery 设备Id
* @return DeviceInfo
*/
DeviceRecord getDeviceRecord(DeviceRecordQuery deviceRecordQuery);
/**
* 获取设备信息
* DeviceStatus
* {@link DeviceStatusQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceStatus getDeviceStatus(String userId);
/**
* 获取设备信息
* DeviceInfo
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceInfo getDeviceInfo(String userId);
/**
* 获取设备通道信息
* {@link CatalogQueryMessageClientHandler}
*
* @param userId
* @return
*/
DeviceResponse getDeviceItem(String userId);
/**
* 语音广播通知
* {@link BroadcastNotifyMessageHandler}
*
* @param broadcastNotify
* @return
*/
void broadcastNotify(DeviceBroadcastNotify broadcastNotify);
/**
* 设备告警通知
*
* @param deviceAlarmQuery
* @return
*/ | package io.github.lunasaw.gbproxy.client.transmit.request.message;
/**
* @author luna
* @date 2023/10/18
*/
public interface MessageProcessorClient {
/**
* 获取设备录像信息
* DeviceRecord
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param deviceRecordQuery 设备Id
* @return DeviceInfo
*/
DeviceRecord getDeviceRecord(DeviceRecordQuery deviceRecordQuery);
/**
* 获取设备信息
* DeviceStatus
* {@link DeviceStatusQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceStatus getDeviceStatus(String userId);
/**
* 获取设备信息
* DeviceInfo
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceInfo getDeviceInfo(String userId);
/**
* 获取设备通道信息
* {@link CatalogQueryMessageClientHandler}
*
* @param userId
* @return
*/
DeviceResponse getDeviceItem(String userId);
/**
* 语音广播通知
* {@link BroadcastNotifyMessageHandler}
*
* @param broadcastNotify
* @return
*/
void broadcastNotify(DeviceBroadcastNotify broadcastNotify);
/**
* 设备告警通知
*
* @param deviceAlarmQuery
* @return
*/ | DeviceAlarmNotify getDeviceAlarmNotify(DeviceAlarmQuery deviceAlarmQuery); | 6 | 2023-10-11 06:56:28+00:00 | 8k |
1415181920/yamis-admin | cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/service/impl/AdminUsersServiceImpl.java | [
{
"identifier": "CommonPageRequest",
"path": "cocoyam-common/src/main/java/io/xiaoyu/common/req/CommonPageRequest.java",
"snippet": "@Slf4j\npublic class CommonPageRequest {\n\n private static final String PAGE_SIZE_PARAM_NAME = \"perPage\";\n\n private static final String PAGE_PARAM_NAME = \"page\";\n\n private static final Integer PAGE_SIZE_MAX_VALUE = 100;\n\n public static <T> PageResp<T> defaultPage() {\n return defaultPage(null);\n }\n\n public static <T> PageResp<T> defaultPage(List<OrderItem> orderItemList) {\n\n int perPage = 20;\n\n int page = 1;\n\n //每页条数\n String pageSizeString = CommonServletUtil.getParamFromRequest(PAGE_SIZE_PARAM_NAME);\n if (ObjectUtil.isNotEmpty(pageSizeString)) {\n try {\n perPage = Convert.toInt(pageSizeString);\n if(perPage > PAGE_SIZE_MAX_VALUE) {\n perPage = PAGE_SIZE_MAX_VALUE;\n }\n } catch (Exception e) {\n log.error(\">>> 分页条数转换异常:\", e);\n perPage = 20;\n }\n }\n\n //第几页\n String pageString = CommonServletUtil.getParamFromRequest(PAGE_PARAM_NAME);\n if (ObjectUtil.isNotEmpty(pageString)) {\n try {\n page = Convert.toInt(pageString);\n } catch (Exception e) {\n log.error(\">>> 分页页数转换异常:\", e);\n page = 1;\n }\n }\n\n\n PageResp<T> objectPage = new PageResp<>(page, perPage);\n if (ObjectUtil.isNotEmpty(orderItemList)) {\n objectPage.setOrders(orderItemList);\n }\n return objectPage;\n }\n}"
},
{
"identifier": "BaseService",
"path": "cocoyam-common/src/main/java/io/xiaoyu/common/basic/service/BaseService.java",
"snippet": "public class BaseService<M extends BaseMapperX<T>,T> extends ServiceImpl<M, T> implements IBaseService<T>{\n\n}"
},
{
"identifier": "CommonException",
"path": "cocoyam-common/src/main/java/io/xiaoyu/common/exception/CommonException.java",
"snippet": "@Getter\n@Setter\npublic class CommonException extends RuntimeException {\n\n private Integer code;\n\n private String msg;\n\n public CommonException() {\n super(\"服务器异常\");\n this.code = 500;\n this.msg = \"服务器异常\";\n }\n\n public CommonException(String msg, Object... arguments) {\n super(StrUtil.format(msg, arguments));\n this.code = 500;\n this.msg = StrUtil.format(msg, arguments);\n }\n\n public CommonException(Integer code, String msg, Object... arguments) {\n super(StrUtil.format(msg, arguments));\n this.code = code;\n this.msg = StrUtil.format(msg, arguments);\n }\n}"
},
{
"identifier": "AdminUsersEntity",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/entity/AdminUsersEntity.java",
"snippet": "@Data\n@TableName(\"admin_users\")\npublic class AdminUsersEntity extends CommonEntity {\n\n /**\n * \n */\n @TableId(type=IdType.AUTO)\n private Integer id;\n /**\n * \n */\n private String username;\n /**\n * \n */\n private String password;\n /**\n * \n */\n private String name;\n /**\n * \n */\n private String avatar;\n /**\n * \n */\n private String rememberToken;\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n @TableField(fill = FieldFill.INSERT)\n private Date createdAt;\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date updatedAt;\n\n\n}"
},
{
"identifier": "AdminUsersMapper",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/mapper/AdminUsersMapper.java",
"snippet": "@Mapper\n@Repository(\"sysAdminUsersMapper\")\npublic interface AdminUsersMapper extends BaseMapperX<AdminUsersEntity> {\n\n\n}"
},
{
"identifier": "AdminUsersQueryReq",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/req/AdminUsersQueryReq.java",
"snippet": "@Getter\n@Setter\npublic class AdminUsersQueryReq extends PageReq {\n\n @Override\n public String toString() {\n return \"AdminUsersQueryReq{\" +\n \"} \" + super.toString();\n }\n}"
},
{
"identifier": "AdminUsersQueryResp",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/resp/AdminUsersQueryResp.java",
"snippet": "public class AdminUsersQueryResp {\n\n /**\n * \n */\n @JsonSerialize(using= ToStringSerializer.class)\n @JsonProperty(\"id\")\n private Integer id;\n\n /**\n * \n */\n @JsonProperty(\"username\")\n private String username;\n\n /**\n * \n */\n @JsonProperty(\"password\")\n private String password;\n\n /**\n * \n */\n @JsonProperty(\"name\")\n private String name;\n\n /**\n * \n */\n @JsonProperty(\"avatar\")\n private String avatar;\n\n /**\n * \n */\n @JsonProperty(\"remember_token\")\n private String rememberToken;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n @JsonProperty(\"created_at\")\n private Date createdAt;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n @JsonProperty(\"updated_at\")\n private Date updatedAt;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\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 getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getRememberToken() {\n return rememberToken;\n }\n\n public void setRememberToken(String rememberToken) {\n this.rememberToken = rememberToken;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", username=\").append(username);\n sb.append(\", password=\").append(password);\n sb.append(\", name=\").append(name);\n sb.append(\", avatar=\").append(avatar);\n sb.append(\", rememberToken=\").append(rememberToken);\n sb.append(\", createdAt=\").append(createdAt);\n sb.append(\", updatedAt=\").append(updatedAt);\n sb.append(\"]\");\n return sb.toString();\n }\n}"
},
{
"identifier": "AdminUsersService",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/service/AdminUsersService.java",
"snippet": "public interface AdminUsersService extends IBaseService<AdminUsersEntity> {\n\n PageResp<AdminUsersEntity> queryList(AdminUsersQueryReq req);\n\n void add(AdminUsersAddReq adminUsersAddReq);\n\n void edit(AdminUsersEditReq adminUsersEditReq);\n\n AdminUsersQueryResp queryDetail(AdminUsersDetailReq adminUsersDetailReq);\n\n void delete(AdminUsersDetailReq adminUsersDetailReq);\n\n AdminUsersEntity queryEntity(int id);\n\n\n}"
},
{
"identifier": "AdminUsersAddReq",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/req/AdminUsersAddReq.java",
"snippet": "@Getter\n@Setter\npublic class AdminUsersAddReq {\n\n /**\n * \n */\n private Integer id;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String username;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String password;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String name;\n\n /**\n * \n */\n private String avatar;\n\n /**\n * \n */\n private String rememberToken;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date createdAt;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date updatedAt;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\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 getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getRememberToken() {\n return rememberToken;\n }\n\n public void setRememberToken(String rememberToken) {\n this.rememberToken = rememberToken;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", username=\").append(username);\n sb.append(\", password=\").append(password);\n sb.append(\", name=\").append(name);\n sb.append(\", avatar=\").append(avatar);\n sb.append(\", rememberToken=\").append(rememberToken);\n sb.append(\", createdAt=\").append(createdAt);\n sb.append(\", updatedAt=\").append(updatedAt);\n sb.append(\"]\");\n return sb.toString();\n }\n}"
},
{
"identifier": "AdminUsersEditReq",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/req/AdminUsersEditReq.java",
"snippet": "@Getter\n@Setter\npublic class AdminUsersEditReq {\n\n /**\n * \n */\n private Integer id;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String username;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String password;\n\n /**\n * \n */\n @NotBlank(message = \"【】不能为空\")\n private String name;\n\n /**\n * \n */\n private String avatar;\n\n /**\n * \n */\n private String rememberToken;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date createdAt;\n\n /**\n * \n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date updatedAt;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\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 getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public String getRememberToken() {\n return rememberToken;\n }\n\n public void setRememberToken(String rememberToken) {\n this.rememberToken = rememberToken;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", username=\").append(username);\n sb.append(\", password=\").append(password);\n sb.append(\", name=\").append(name);\n sb.append(\", avatar=\").append(avatar);\n sb.append(\", rememberToken=\").append(rememberToken);\n sb.append(\", createdAt=\").append(createdAt);\n sb.append(\", updatedAt=\").append(updatedAt);\n sb.append(\"]\");\n return sb.toString();\n }\n}"
},
{
"identifier": "AdminUsersDetailReq",
"path": "cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/req/AdminUsersDetailReq.java",
"snippet": "@Getter\n@Setter\npublic class AdminUsersDetailReq{\n\n\n @NotNull(message = \"id不能为空\")\n private Integer id;\n\n}"
},
{
"identifier": "PageResp",
"path": "cocoyam-common/src/main/java/io/xiaoyu/common/resp/PageResp.java",
"snippet": "@Getter\n@Setter\npublic class PageResp<T> extends Page<T>{\n\n /**\n * 当前页的列表\n */\n private List<T> items;\n /**\n * 当前页码\n */\n private long pageNum;\n /**\n * 每页条数\n */\n private long perPage;\n\n\n public PageResp(){\n super();\n }\n\n public PageResp(long page,long perPage,long total){\n super(page,perPage,total);\n this.pageNum = page;\n this.perPage = perPage;\n this.total = total;\n }\n\n public PageResp(long page,long perPage,long total,List<T> items){\n super(page,perPage,total);\n this.pageNum = page;\n this.perPage = perPage;\n this.total = total;\n this.items = items;\n }\n\n public PageResp(IPage<T> page){\n super(page.getCurrent(), page.getSize(), page.getTotal());\n this.items = page.getRecords();\n this.pageNum = page.getCurrent();\n this.perPage = page.getSize();\n this.total = page.getTotal();\n }\n\n public PageResp(long page,long perPage){\n super(page,perPage);\n this.pageNum = page;\n this.perPage = perPage;\n }\n\n @Override\n @JsonIgnore\n public long getSize() {\n return this.perPage;\n }\n\n @Override\n public PageResp<T> setSize(long size) {\n this.size = size;\n this.perPage = size;\n return this;\n }\n\n\n @Override\n @JsonIgnore\n public long getCurrent() {\n return this.pageNum;\n }\n\n @Override\n public PageResp<T> setCurrent(long current) {\n this.current = current;\n this.pageNum = current;\n return this;\n }\n\n @Override\n @JsonIgnore\n public List<T> getRecords() {\n return this.records;\n }\n\n @Override\n public PageResp<T> setRecords(List<T> records) {\n this.records = records;\n this.items = records;\n return this;\n }\n\n}"
}
] | import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.xiaoyu.common.req.CommonPageRequest;
import io.xiaoyu.common.basic.service.BaseService;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.ObjectUtil;
import io.xiaoyu.common.exception.CommonException;
import io.xiaoyu.sys.modular.admin.entity.AdminUsersEntity;
import io.xiaoyu.sys.modular.admin.mapper.AdminUsersMapper;
import io.xiaoyu.sys.modular.admin.req.AdminUsersQueryReq;
import io.xiaoyu.sys.modular.admin.resp.AdminUsersQueryResp;
import io.xiaoyu.sys.modular.admin.service.AdminUsersService;
import io.xiaoyu.sys.modular.admin.req.AdminUsersAddReq;
import io.xiaoyu.sys.modular.admin.req.AdminUsersEditReq;
import io.xiaoyu.sys.modular.admin.req.AdminUsersDetailReq;
import io.xiaoyu.common.resp.PageResp;
import org.springframework.stereotype.Service;
import javax.annotation.Resource; | 4,431 | package io.xiaoyu.sys.modular.admin.service.impl;
@Service
public class AdminUsersServiceImpl extends BaseService<AdminUsersMapper,AdminUsersEntity> implements AdminUsersService{
| package io.xiaoyu.sys.modular.admin.service.impl;
@Service
public class AdminUsersServiceImpl extends BaseService<AdminUsersMapper,AdminUsersEntity> implements AdminUsersService{
| public PageResp<AdminUsersEntity> queryList(AdminUsersQueryReq req) { | 11 | 2023-10-09 06:04:30+00:00 | 8k |
Swofty-Developments/Continued-Slime-World-Manager | swoftyworldmanager-nms/src/main/java/net/swofty/swm/nms/craft/CraftSlimeWorld.java | [
{
"identifier": "UnknownWorldException",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/UnknownWorldException.java",
"snippet": "public class UnknownWorldException extends SlimeException {\n\n public UnknownWorldException(String world) {\n super(\"Unknown world \" + world);\n }\n}"
},
{
"identifier": "WorldAlreadyExistsException",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/WorldAlreadyExistsException.java",
"snippet": "public class WorldAlreadyExistsException extends SlimeException {\n\n public WorldAlreadyExistsException(String world) {\n super(\"World \" + world + \" already exists!\");\n }\n}"
},
{
"identifier": "SlimeLoader",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/loaders/SlimeLoader.java",
"snippet": "public interface SlimeLoader {\n\n /**\n * Load a world's data file. In case {@code readOnly} is false,\n * the world automatically gets locked so no other server\n * can access it in write-mode.\n *\n * @param worldName The name of the world.\n * @param readOnly If false, a {@link WorldInUseException} should be thrown when the world is locked.\n * @return The world's data file, contained inside a byte array.\n * @throws UnknownWorldException if the world cannot be found.\n * @throws WorldInUseException if the world is locked\n * @throws IOException if the world could not be obtained.\n */\n byte[] loadWorld(String worldName, boolean readOnly) throws UnknownWorldException, WorldInUseException, IOException;\n\n /**\n * Checks whether or not a world exists\n * inside the data source.\n *\n * @param worldName The name of the world.\n * @return <code>true</code> if the world exists inside the data source, <code>false</code> otherwhise.\n * @throws IOException if the world could not be obtained.\n */\n boolean worldExists(String worldName) throws IOException;\n\n /**\n * Returns the current saved world names.\n *\n * @return a list containing all the world names\n * @throws IOException if the list could not be obtained\n */\n List<String> listWorlds() throws IOException;\n\n /**\n * Saves the world's data file. This method will also\n * lock the world, in case it's not locked already.\n *\n * @param worldName The name of the world.\n * @param serializedWorld The world's data file, contained inside a byte array.\n * @param lock Whether or not the world should be relocked.\n * @throws IOException if the world could not be saved.\n */\n void saveWorld(String worldName, byte[] serializedWorld, boolean lock) throws IOException;\n\n /**\n * Unlocks a world.\n *\n * @param worldName The name of the world.\n * @throws UnknownWorldException if the world could not be found.\n * @throws IOException if the world could not be locked/unlocked.\n */\n void unlockWorld(String worldName) throws UnknownWorldException, IOException;\n\n /**\n * Checks whether or not a world is locked.\n *\n * @param worldName The name of the world.\n * @return <code>true</code> if the world is locked, <code>false</code> otherwhise.\n * @throws UnknownWorldException if the world could not be found.\n * @throws IOException if the world could not be obtained.\n */\n boolean isWorldLocked(String worldName) throws UnknownWorldException, IOException;\n\n /**\n * Deletes a world from the data source.\n *\n * @param worldName name of the world\n * @throws UnknownWorldException if the world could not be found.\n * @throws IOException if the world could not be deleted.\n */\n void deleteWorld(String worldName) throws UnknownWorldException, IOException;\n\n}"
},
{
"identifier": "SlimeFormat",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/utils/SlimeFormat.java",
"snippet": "public class SlimeFormat {\n\n /** First bytes of every SRF file **/\n public static final byte[] SLIME_HEADER = new byte[] { -79, 11 };\n\n /** Latest version of the SRF that SWM supports **/\n public static final byte SLIME_VERSION = 10;\n}"
},
{
"identifier": "SlimeChunk",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/SlimeChunk.java",
"snippet": "public interface SlimeChunk {\n\n /**\n * Returns the name of the world this chunk belongs to.\n *\n * @return The name of the world of this chunk.\n */\n String getWorldName();\n\n /**\n * Returns the X coordinate of the chunk.\n *\n * @return X coordinate of the chunk.\n */\n int getX();\n\n /**\n * Returns the Z coordinate of the chunk.\n *\n * @return Z coordinate of the chunk.\n */\n int getZ();\n\n /**\n * Returns all the sections of the chunk.\n *\n * @return A {@link SlimeChunkSection} array.\n */\n SlimeChunkSection[] getSections();\n\n /**\n * Returns the height maps of the chunk. A\n * {@link com.flowpowered.nbt.IntArrayTag} containing the height\n * map will be stored inside here by the name of 'heightMap'.\n *\n * @return A {@link CompoundTag} containing all the height maps of the chunk.\n */\n CompoundTag getHeightMaps();\n\n /**\n * Returns all the biomes of the chunk. Every\n * <code>int</code> inside the array will contain two biomes,\n * and should be converted into a <code>byte[]</code>.\n *\n * @return A <code>int[]</code> containing all the biomes of the chunk.\n */\n int[] getBiomes();\n\n /**\n * Returns all the tile entities of the chunk.\n *\n * @return A {@link CompoundTag} containing all the tile entities of the chunk.\n */\n List<CompoundTag> getTileEntities();\n\n /**\n * Returns all the entities of the chunk.\n *\n * @return A {@link CompoundTag} containing all the entities of the chunk.\n */\n List<CompoundTag> getEntities();\n}"
},
{
"identifier": "SlimeChunkSection",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/SlimeChunkSection.java",
"snippet": "public interface SlimeChunkSection {\n\n /**\n * Returns all the blocks of the chunk section\n *\n * @return A <code>byte[]</code> with all the blocks of a chunk section.\n */\n byte[] getBlocks();\n\n /**\n * Returns the data of all the blocks of the chunk section\n *\n * @return A {@link NibbleArray} containing all the blocks of a chunk section.\n */\n NibbleArray getData();\n\n /**\n * Returns the block light data.\n *\n * @return A {@link NibbleArray} with the block light data.\n */\n NibbleArray getBlockLight();\n\n /**\n * Returns the sky light data.\n *\n * @return A {@link NibbleArray} containing the sky light data.\n */\n NibbleArray getSkyLight();\n}"
},
{
"identifier": "SlimeWorld",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/SlimeWorld.java",
"snippet": "public interface SlimeWorld {\n\n /**\n * Returns the name of the world.\n *\n * @return The name of the world.\n */\n String getName();\n\n /**\n * Returns the {@link SlimeLoader} used\n * to load and store the world.\n *\n * @return The {@link SlimeLoader} used to load and store the world.\n */\n SlimeLoader getLoader();\n\n /**\n * Returns the chunk that belongs to the coordinates specified.\n *\n * @param x X coordinate.\n * @param z Z coordinate.\n *\n * @return The {@link SlimeChunk} that belongs to those coordinates.\n */\n SlimeChunk getChunk(int x, int z);\n\n /**\n * Returns the extra data of the world. Inside this {@link CompoundTag}\n * can be stored any information to then be retrieved later, as it's\n * saved alongside the world data.\n *\n * @return A {@link CompoundTag} containing the extra data of the world.\n */\n CompoundTag getExtraData();\n\n /**\n * Returns a {@link Collection} with every world map, serialized\n * in a {@link CompoundTag} object.\n *\n * @return A {@link Collection} containing every world map.\n */\n Collection<CompoundTag> getWorldMaps();\n\n /**\n * Standardized method to Bukkit unload.\n *\n * @param save Whether or not to save the world\n * @param fallBack String name of the world to fall players back to\n */\n void unloadWorld(boolean save, String fallBack);\n\n /**\n * Standardized method to Bukkit unload.\n *\n * @param save Whether or not to save the world\n */\n default void unloadWorld(boolean save) {\n unloadWorld(save, null);\n }\n\n /**\n * Returns the property map.\n *\n * @return A {@link SlimePropertyMap} object containing all the properties of the world.\n */\n SlimePropertyMap getPropertyMap();\n\n /**\n * Returns whether or not read-only is enabled.\n *\n * @return true if read-only is enabled, false otherwise.\n */\n boolean isReadOnly();\n\n /**\n * Returns a clone of the world with the given name. This world will never be\n * stored, as the <code>readOnly</code> property will be set to true.\n *\n * @param worldName The name of the cloned world.\n *\n * @return The clone of the world.\n *\n * @throws IllegalArgumentException if the name of the world is the same as the current one or is <code>null</code>.\n */\n SlimeWorld clone(String worldName);\n\n /**\n * Returns a clone of the world with the given name. The world will be\n * automatically stored inside the provided data source.\n *\n * @param worldName The name of the cloned world.\n * @param loader The {@link SlimeLoader} used to store the world or <code>null</code> if the world is temporary.\n *\n * @return The clone of the world.\n *\n * @throws IllegalArgumentException if the name of the world is the same as the current one or is <code>null</code>.\n * @throws WorldAlreadyExistsException if there's already a world with the same name inside the provided data source.\n * @throws IOException if the world could not be stored.\n */\n SlimeWorld clone(String worldName, SlimeLoader loader) throws WorldAlreadyExistsException, IOException;\n\n /**\n * Returns a clone of the world with the given name. The world will be\n * automatically stored inside the provided data source.\n *\n * @param worldName The name of the cloned world.\n * @param loader The {@link SlimeLoader} used to store the world or <code>null</code> if the world is temporary.\n * @param lock whether or not SWM should lock the world. If false, SWM will not let you load this world for security reasons.\n *\n * @return The clone of the world.\n *\n * @throws IllegalArgumentException if the name of the world is the same as the current one or is <code>null</code>.\n * @throws WorldAlreadyExistsException if there's already a world with the same name inside the provided data source.\n * @throws IOException if the world could not be stored.\n */\n SlimeWorld clone(String worldName, SlimeLoader loader, boolean lock) throws WorldAlreadyExistsException, IOException;\n\n /**\n * Returns whether or not this world is locked and, therefore, can be loaded on the server by\n * using the {@link SlimePlugin#generateWorld(SlimeWorld)} method.\n *\n * @return true if the world is locked, false otherwise\n */\n boolean isLocked();\n}"
},
{
"identifier": "SlimePropertyMap",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/properties/SlimePropertyMap.java",
"snippet": "@RequiredArgsConstructor()\npublic class SlimePropertyMap {\n\n @Getter(value = AccessLevel.PRIVATE)\n private final CompoundMap properties;\n\n public SlimePropertyMap() {\n this(new CompoundMap());\n }\n\n /**\n * Return the current value of the given property\n *\n * @param property The slime property\n * @return The current value\n */\n public <T> T getValue(SlimeProperty<T> property) {\n if(properties.containsKey(property.getNbtName())) {\n return property.readValue(properties.get(property.getNbtName()));\n } else {\n return property.getDefaultValue();\n }\n }\n\n /**\n * Update the value of the given property\n *\n * @param property The slime property\n * @param value The new value\n * @throws IllegalArgumentException if the value fails validation.\n */\n public <T> void setValue(SlimeProperty<T> property, T value) {\n if (property.getValidator() != null && !property.getValidator().apply(value)) {\n throw new IllegalArgumentException(\"'\" + value + \"' is not a valid property value.\");\n }\n\n property.writeValue(properties, value);\n }\n\n /**\n * @deprecated Use setValue()\n */\n @Deprecated\n public void setInt(SlimeProperty<Integer> property, int value) {\n setValue(property, value);\n }\n\n /**\n * @deprecated Use setValue()\n */\n @Deprecated\n public void setBoolean(SlimeProperty<Boolean> property, boolean value) {\n setValue(property, value);\n }\n\n /**\n * @deprecated Use setValue()\n */\n @Deprecated\n public void setString(SlimeProperty<String> property, String value) {\n setValue(property, value);\n }\n\n /**\n * Copies all values from the specified {@link SlimePropertyMap}.\n * If the same property has different values on both maps, the one\n * on the providen map will be used.\n *\n * @param propertyMap A {@link SlimePropertyMap}.\n */\n public void merge(SlimePropertyMap propertyMap) {\n properties.putAll(propertyMap.properties);\n }\n\n /**\n * Returns a {@link CompoundTag} containing every property set in this map.\n *\n * @return A {@link CompoundTag} with all the properties stored in this map.\n */\n public CompoundTag toCompound() {\n return new CompoundTag(\"properties\", properties);\n }\n\n public static SlimePropertyMap fromCompound(CompoundTag compound) {\n return new SlimePropertyMap(compound.getValue());\n }\n\n @Override\n public String toString() {\n return \"SlimePropertyMap\" + properties;\n }\n}"
},
{
"identifier": "SlimeProperties",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/world/properties/SlimeProperties.java",
"snippet": "public class SlimeProperties {\n\n /**\n * The X coordinate of the world spawn\n */\n public static final SlimeProperty<Integer> SPAWN_X = new SlimePropertyInt(\"spawnX\", 0);\n\n /**\n * The Y coordinate of the world spawn\n */\n public static final SlimeProperty<Integer> SPAWN_Y = new SlimePropertyInt(\"spawnY\", 255);\n\n /**\n * The Z coordinate of the world spawn\n */\n public static final SlimeProperty<Integer> SPAWN_Z = new SlimePropertyInt(\"spawnZ\", 0);\n\n /**\n * The difficulty set for the world\n */\n public static final SlimeProperty<String> DIFFICULTY = new SlimePropertyString(\"difficulty\", \"peaceful\", (value) ->\n value.equalsIgnoreCase(\"peaceful\") || value.equalsIgnoreCase(\"easy\")\n || value.equalsIgnoreCase(\"normal\") || value.equalsIgnoreCase(\"hard\")\n );\n\n /**\n * Whether monsters are allowed to spawn at night or in the dark\n */\n public static final SlimeProperty<Boolean> ALLOW_MONSTERS = new SlimePropertyBoolean(\"allowMonsters\", true);\n\n /**\n * Whether peaceful animals are allowed to spawn\n */\n public static final SlimeProperty<Boolean> ALLOW_ANIMALS = new SlimePropertyBoolean(\"allowAnimals\", true);\n\n /**\n * Whether PVP combat is allowed\n */\n public static final SlimeProperty<Boolean> PVP = new SlimePropertyBoolean(\"pvp\", true);\n\n /**\n * The environment of the world\n */\n public static final SlimeProperty<String> ENVIRONMENT = new SlimePropertyString(\"environment\", \"normal\", (value) ->\n value.equalsIgnoreCase(\"normal\") || value.equalsIgnoreCase(\"nether\") || value.equalsIgnoreCase(\"the_end\")\n );\n\n /**\n * The type of world\n */\n public static final SlimeProperty<String> WORLD_TYPE = new SlimePropertyString(\"worldtype\", \"default\", (value) ->\n value.equalsIgnoreCase(\"default\") || value.equalsIgnoreCase(\"flat\") || value.equalsIgnoreCase(\"large_biomes\")\n || value.equalsIgnoreCase(\"amplified\") || value.equalsIgnoreCase(\"customized\")\n || value.equalsIgnoreCase(\"debug_all_block_states\") || value.equalsIgnoreCase(\"default_1_1\")\n );\n\n /**\n * The default biome generated in empty chunks\n */\n public static final SlimeProperty<Boolean> LOAD_ON_STARTUP = new SlimePropertyBoolean(\"loadOnStartup\", true);\n}"
}
] | import com.flowpowered.nbt.CompoundMap;
import com.flowpowered.nbt.CompoundTag;
import com.flowpowered.nbt.ListTag;
import com.flowpowered.nbt.TagType;
import com.flowpowered.nbt.stream.NBTInputStream;
import com.flowpowered.nbt.stream.NBTOutputStream;
import com.github.luben.zstd.Zstd;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import net.swofty.swm.api.exceptions.UnknownWorldException;
import net.swofty.swm.api.exceptions.WorldAlreadyExistsException;
import net.swofty.swm.api.loaders.SlimeLoader;
import net.swofty.swm.api.utils.SlimeFormat;
import net.swofty.swm.api.world.SlimeChunk;
import net.swofty.swm.api.world.SlimeChunkSection;
import net.swofty.swm.api.world.SlimeWorld;
import net.swofty.swm.api.world.properties.SlimePropertyMap;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.*;
import java.util.stream.Collectors;
import static net.swofty.swm.api.world.properties.SlimeProperties.*; | 5,013 | package net.swofty.swm.nms.craft;
@Getter
@Setter
@AllArgsConstructor
public class CraftSlimeWorld implements SlimeWorld {
private SlimeLoader loader;
private final String name;
private final Map<Long, SlimeChunk> chunks;
private final CompoundTag extraData;
private final List<CompoundTag> worldMaps;
private SlimePropertyMap propertyMap;
private final boolean readOnly;
private final boolean locked;
@Override
public SlimeChunk getChunk(int x, int z) {
synchronized (chunks) {
Long index = (((long) z) * Integer.MAX_VALUE + ((long) x));
return chunks.get(index);
}
}
@Override
public void unloadWorld(boolean save, String fallBack) {
World world = Bukkit.getWorld(name);
// Teleport all players outside the world before unloading it
List<Player> players = world.getPlayers();
if (!players.isEmpty()) {
World fallbackWorld = null;
if (fallBack != null) {
fallbackWorld = Bukkit.getWorld(fallBack);
} else {
fallbackWorld = Bukkit.getWorlds().get(0);
}
Location spawnLocation = fallbackWorld.getSpawnLocation();
while (spawnLocation.getBlock().getType() != Material.AIR || spawnLocation.getBlock().getRelative(BlockFace.UP).getType() != Material.AIR) {
spawnLocation.add(0, 1, 0);
}
for (Player player : players) {
player.teleport(spawnLocation);
}
}
if (!Bukkit.unloadWorld(world, save)) {
throw new IllegalStateException("Failed to unload world " + name + ".");
} else {
try {
loader.unlockWorld(name);
} catch (UnknownWorldException | IOException e) {
throw new RuntimeException(e);
}
}
}
public void updateChunk(SlimeChunk chunk) {
if (!chunk.getWorldName().equals(getName())) {
throw new IllegalArgumentException("Chunk (" + chunk.getX() + ", " + chunk.getZ() + ") belongs to world '"
+ chunk.getWorldName() + "', not to '" + getName() + "'!");
}
synchronized (chunks) {
chunks.put(((long) chunk.getZ()) * Integer.MAX_VALUE + ((long) chunk.getX()), chunk);
}
}
@Override
public SlimeWorld clone(String worldName) {
try {
return clone(worldName, null); | package net.swofty.swm.nms.craft;
@Getter
@Setter
@AllArgsConstructor
public class CraftSlimeWorld implements SlimeWorld {
private SlimeLoader loader;
private final String name;
private final Map<Long, SlimeChunk> chunks;
private final CompoundTag extraData;
private final List<CompoundTag> worldMaps;
private SlimePropertyMap propertyMap;
private final boolean readOnly;
private final boolean locked;
@Override
public SlimeChunk getChunk(int x, int z) {
synchronized (chunks) {
Long index = (((long) z) * Integer.MAX_VALUE + ((long) x));
return chunks.get(index);
}
}
@Override
public void unloadWorld(boolean save, String fallBack) {
World world = Bukkit.getWorld(name);
// Teleport all players outside the world before unloading it
List<Player> players = world.getPlayers();
if (!players.isEmpty()) {
World fallbackWorld = null;
if (fallBack != null) {
fallbackWorld = Bukkit.getWorld(fallBack);
} else {
fallbackWorld = Bukkit.getWorlds().get(0);
}
Location spawnLocation = fallbackWorld.getSpawnLocation();
while (spawnLocation.getBlock().getType() != Material.AIR || spawnLocation.getBlock().getRelative(BlockFace.UP).getType() != Material.AIR) {
spawnLocation.add(0, 1, 0);
}
for (Player player : players) {
player.teleport(spawnLocation);
}
}
if (!Bukkit.unloadWorld(world, save)) {
throw new IllegalStateException("Failed to unload world " + name + ".");
} else {
try {
loader.unlockWorld(name);
} catch (UnknownWorldException | IOException e) {
throw new RuntimeException(e);
}
}
}
public void updateChunk(SlimeChunk chunk) {
if (!chunk.getWorldName().equals(getName())) {
throw new IllegalArgumentException("Chunk (" + chunk.getX() + ", " + chunk.getZ() + ") belongs to world '"
+ chunk.getWorldName() + "', not to '" + getName() + "'!");
}
synchronized (chunks) {
chunks.put(((long) chunk.getZ()) * Integer.MAX_VALUE + ((long) chunk.getX()), chunk);
}
}
@Override
public SlimeWorld clone(String worldName) {
try {
return clone(worldName, null); | } catch (WorldAlreadyExistsException | IOException ignored) { | 1 | 2023-10-08 10:54:28+00:00 | 8k |
calicosun258/5c-client-N | src/main/java/fifthcolumn/n/copenheimer/CopeService.java | [
{
"identifier": "NMod",
"path": "src/main/java/fifthcolumn/n/NMod.java",
"snippet": "public class NMod implements ModInitializer {\n\n // You can set this to false to enable cope service. DO THIS AT YOUR OWN RISK due to security reasons as the mod would connect to servers on the internet.\n public static boolean COPE_OFFLINE_MODE = true;\n\n private static final Pattern STRIP_PATTERN = Pattern.compile(\"(?<!<@)[&§](?i)[0-9a-fklmnorx]\");\n private static NMod INSTANCE;\n public static final CopeService copeService = new CopeService();\n public static final Identifier CAPE_TEXTURE = new Identifier(\"nc:cape.png\");\n public static final Identifier cockSound = new Identifier(\"nc:cock\");\n public static final Identifier shotgunSound = new Identifier(\"nc:shot\");\n public static SoundEvent shotgunSoundEvent;\n public static SoundEvent cockSoundEvent;\n public static ProfileCache profileCache;\n public static GenericNames genericNames;\n private CopeMultiplayerScreen multiplayerScreen;\n\n public void onInitialize() {\n MinecraftClient mc = MinecraftClient.getInstance();\n INSTANCE = new NMod();\n ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {\n copeService.clearTranslations();\n copeService.startUpdating();\n copeService.setLastServerInfo(mc.getCurrentServerEntry());\n });\n ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> {\n copeService.clearTranslations();\n copeService.stopUpdating();\n copeService.setDefaultSession();\n genericNames.clear();\n });\n copeService.setDefaultSession(mc.getSession());\n CollarLogin.refreshSession();\n Registry.register(Registries.SOUND_EVENT, shotgunSound, shotgunSoundEvent);\n Registry.register(Registries.SOUND_EVENT, cockSound, cockSoundEvent);\n }\n\n public static CopeService getCopeService() {\n return copeService;\n }\n\n public static CopeMultiplayerScreen getMultiplayerScreen() {\n return INSTANCE.multiplayerScreen;\n }\n\n public static CopeMultiplayerScreen getOrCreateMultiplayerScreen(Screen parent) {\n if (INSTANCE.multiplayerScreen == null) {\n INSTANCE.multiplayerScreen = new CopeMultiplayerScreen(parent, copeService);\n }\n\n return INSTANCE.multiplayerScreen;\n }\n\n public static void setMultiplayerScreen(CopeMultiplayerScreen multiplayerScreen) {\n INSTANCE.multiplayerScreen = multiplayerScreen;\n }\n\n public static boolean is2b2t() {\n ServerInfo serverEntry = MeteorClient.mc.getCurrentServerEntry();\n return serverEntry != null && serverEntry.address.contains(\"2b2t.org\");\n }\n\n static {\n shotgunSoundEvent = SoundEvent.of(shotgunSound);\n cockSoundEvent = SoundEvent.of(cockSound);\n profileCache = new ProfileCache();\n genericNames = new GenericNames();\n }\n\n public static class GenericNames {\n private final Map<UUID, String> names = new HashMap<>();\n\n public String getName(UUID uuid) {\n this.names.computeIfAbsent(uuid, (k) -> NameGenerator.name(uuid));\n return this.names.get(uuid);\n }\n\n public void clear() {\n this.names.clear();\n }\n }\n}"
},
{
"identifier": "CollarLogin",
"path": "src/main/java/fifthcolumn/n/collar/CollarLogin.java",
"snippet": "public final class CollarLogin {\n private static final UUID COPE_GROUP_ID = UUID.fromString(\"fe2b0ae3-8984-414b-8a5f-e972736bb77c\");\n private static final Logger LOGGER = LoggerFactory.getLogger(CollarLogin.class);\n private static final Gson GSON = new Gson();\n private static final MinecraftClient mc = MinecraftClient.getInstance();\n\n public static String getMembershipToken() {\n try {\n return CollarSettings.read().membershipToken;\n } catch (IOException var1) {\n LOGGER.error(\"Unable to read Collar group membership token\", var1);\n throw new IllegalStateException(var1);\n }\n }\n\n public static boolean refreshSession() {\n if(NMod.COPE_OFFLINE_MODE)\n return false;\n\n RESTClient client = createClient();\n\n CollarSettings settings;\n try {\n settings = CollarSettings.read();\n } catch (Throwable var3) {\n LOGGER.error(\"Unable to read Collar settings\", var3);\n return false;\n }\n\n LoginResult loginResult = loginAndSave(settings.email, settings.password);\n if (loginResult.success) {\n return client.validateGroupMembershipToken(settings.membershipToken, COPE_GROUP_ID).isPresent();\n } else {\n LOGGER.error(\"Collar group membership validation unsuccessful\");\n return false;\n }\n }\n\n public static LoginResult loginAndSave(String email, String password) {\n if(NMod.COPE_OFFLINE_MODE)\n return new LoginResult(false, \"Login failed. Cope service is disabled\");\n\n RESTClient client = createClient();\n return client.login(LoginRequest.emailAndPassword(email, password)).map((loginResponse) -> {\n return loginResponse.token;\n }).map((token) -> {\n return client.createGroupMembershipToken(token, COPE_GROUP_ID).map((resp) -> {\n CollarSettings settings = new CollarSettings();\n settings.email = email;\n settings.password = password;\n settings.membershipToken = resp.token;\n\n try {\n settings.save();\n } catch (IOException var5) {\n LOGGER.error(\"Could not save collar settings\");\n return new LoginResult(false, var5.getMessage());\n }\n\n return new LoginResult(true, (String)null);\n }).orElse(new LoginResult(false, \"Login failed\"));\n }).orElse(new LoginResult(false, \"Login failed\"));\n }\n\n private static RESTClient createClient() {\n return new RESTClient(\"https://api.collarmc.com\");\n }\n\n public static final class CollarSettings {\n public String email;\n public String password;\n public String membershipToken;\n\n public void save() throws IOException {\n File file = new File(CollarLogin.mc.runDirectory, \"collar.json\");\n String contents = CollarLogin.GSON.toJson(this);\n Files.writeString(file.toPath(), contents);\n }\n\n public static CollarSettings read() throws IOException {\n File file = new File(CollarLogin.mc.runDirectory, \"collar.json\");\n String contents = Files.readString(file.toPath());\n return CollarLogin.GSON.fromJson(contents, CollarSettings.class);\n }\n }\n\n public static final class LoginResult {\n public final boolean success;\n public final String reason;\n\n public LoginResult(boolean success, String reason) {\n this.success = success;\n this.reason = reason;\n }\n }\n}"
},
{
"identifier": "GrieferUpdateEvent",
"path": "src/main/java/fifthcolumn/n/events/GrieferUpdateEvent.java",
"snippet": "public class GrieferUpdateEvent {\n public final List<CopeService.Griefer> griefers;\n\n public GrieferUpdateEvent(List<CopeService.Griefer> griefers) {\n this.griefers = griefers;\n }\n}"
},
{
"identifier": "BanEvasion",
"path": "src/main/java/fifthcolumn/n/modules/BanEvasion.java",
"snippet": "public class BanEvasion extends Module {\n private final SettingGroup sgGeneral;\n public ServerInfo lastServer;\n private final Setting<Boolean> addSpacesToName;\n public final Setting<Boolean> evadeAndReconnect;\n\n public BanEvasion() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Ban Evasion\", \"Options for evading bans\");\n this.sgGeneral = this.settings.getDefaultGroup();\n this.addSpacesToName = this.sgGeneral.add(new BoolSetting.Builder()\n .name(\"add spaces to name\")\n .description(\"makes it easy to evade bans\")\n .defaultValue(false)\n .build());\n this.evadeAndReconnect = this.sgGeneral.add(new BoolSetting.Builder()\n .name(\"Toggle from evade and reconnect button\")\n .description(\"makes it easy to evade bans\")\n .defaultValue(true).build());\n MeteorClient.EVENT_BUS.subscribe(new StaticListener());\n }\n\n public static boolean isSpacesToNameEnabled() {\n BanEvasion banEvasion = Modules.get().get(BanEvasion.class);\n return banEvasion != null && banEvasion.isActive() && banEvasion.addSpacesToName.get();\n }\n\n private class StaticListener {\n @EventHandler\n private void onConnectToServer(ServerConnectEndEvent event) {\n BanEvasion.this.lastServer = BanEvasion.this.mc.isInSingleplayer() ? null : BanEvasion.this.mc.getCurrentServerEntry();\n }\n }\n}"
},
{
"identifier": "GrieferTracer",
"path": "src/main/java/fifthcolumn/n/modules/GrieferTracer.java",
"snippet": "public class GrieferTracer extends Module {\n private final SettingGroup sgGeneral;\n private final Setting<SettingColor> playersColor;\n\n public GrieferTracer() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Griefer Tracer\", \"Tracers to fellow Griefers. Disabled on 2b2t.org.\");\n this.sgGeneral = this.settings.getDefaultGroup();\n this.playersColor = this.sgGeneral.add(((ColorSetting.Builder)((ColorSetting.Builder)(new ColorSetting.Builder()).name(\"players-colors\")).description(\"The griefers color.\")).defaultValue(new SettingColor(205, 205, 205, 127)).build());\n }\n\n @EventHandler\n private void onRender(Render3DEvent event) {\n Iterator var2 = NMod.getCopeService().griefers().iterator();\n\n while(var2.hasNext()) {\n CopeService.Griefer entity = (CopeService.Griefer)var2.next();\n if (entity.location != null) {\n System.out.println(entity.playerName + \" is at \" + entity.location);\n Color color = (Color)this.playersColor.get();\n double x = entity.location.x;\n double y = entity.location.y;\n double z = entity.location.z;\n event.renderer.line(RenderUtils.center.x, RenderUtils.center.y, RenderUtils.center.z, x, y, z, color);\n }\n }\n\n }\n}"
},
{
"identifier": "LarpModule",
"path": "src/main/java/fifthcolumn/n/modules/LarpModule.java",
"snippet": "public class LarpModule extends Module {\n private final SettingGroup sgGeneral = this.settings.getDefaultGroup();\n\n public final Setting<String> alias = this.sgGeneral.add(new StringSetting.Builder()\n .name(\"player uid\")\n .description(\"player uuid to larp as\")\n .defaultValue(\"24b82429-15f2-4d7f-91f6-d277a1858949\")\n .build());\n\n public final Setting<String> aliasName = this.sgGeneral.add(new StringSetting.Builder()\n .name(\"player name\")\n .description(\"player name to larp as\")\n .defaultValue(\"orsond\").build());\n\n public LarpModule() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Larping\", \"Make all griefers larp as another player\");\n }\n\n public static @Nullable String modifyPlayerNameInstances(String text) {\n\n for (CopeService.Griefer entity : NMod.getCopeService().griefers()) {\n if (entity.playerNameAlias != null) {\n Optional<GameProfile> profile = NMod.profileCache.findPlayerName(entity.playerNameAlias);\n if (profile.isPresent()) {\n text = StringUtils.replace(text, entity.playerName, entity.playerNameAlias);\n }\n }\n }\n\n if (MeteorClient.mc != null && MeteorClient.mc.player != null) {\n LarpModule larpModule = Modules.get().get(LarpModule.class);\n if (larpModule.isActive()) {\n String aliasName = larpModule.aliasName.get();\n text = StringUtils.replace(text, MeteorClient.mc.player.getEntityName(), aliasName);\n }\n }\n\n return text;\n }\n\n public static Optional<String> getPlayerEntityName(PlayerEntity player) {\n if (MeteorClient.mc.player != null && player.getGameProfile().getId().equals(MeteorClient.mc.player.getUuid())) {\n LarpModule larpModule = Modules.get().get(LarpModule.class);\n if (larpModule.isActive()) {\n UUID uuid = UUID.fromString(larpModule.alias.get());\n Optional<GameProfile>profile = NMod.profileCache.findByUUID(uuid);\n if (profile.isPresent()) {\n return profile.map(GameProfile::getName);\n }\n }\n } else {\n for (CopeService.Griefer griefer : NMod.getCopeService().griefers()) {\n if (player.getGameProfile().getId().equals(griefer.playerId)) {\n Optional<GameProfile> profile = NMod.profileCache.findByUUID(griefer.playerId);\n if (profile.isPresent()) {\n return profile.map(GameProfile::getName);\n }\n }\n }\n }\n\n return Optional.empty();\n }\n}"
},
{
"identifier": "StreamerMode",
"path": "src/main/java/fifthcolumn/n/modules/StreamerMode.java",
"snippet": "public class StreamerMode extends Module {\n private final SettingGroup sgGeneral;\n private final Setting<Boolean> hideServerInfo;\n private final Setting<Boolean> hideAccount;\n private final Setting<Boolean> generifyPlayerNames;\n private final Setting<Integer> addFakePlayers;\n private final Setting<String> spoofServerBrand;\n public final Setting<Boolean> useRandomIpOffset;\n\n public StreamerMode() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Streamer mode\", \"Hides sensitive info from stream viewers\");\n this.sgGeneral = this.settings.getDefaultGroup();\n this.hideServerInfo = this.sgGeneral.add((new BoolSetting.Builder()).name(\"hide server info\").defaultValue(true).build());\n this.hideAccount = this.sgGeneral.add((new BoolSetting.Builder()).name(\"hide Logged in account text\").defaultValue(true).build());\n this.generifyPlayerNames = this.sgGeneral.add(new BoolSetting.Builder().name(\"use a generic name for non-griefers\")\n .defaultValue(true).build());\n this.addFakePlayers = this.sgGeneral.add(new IntSetting.Builder()\n .name(\"add fake players to tablist\")\n .sliderRange(0, 10).defaultValue(5)\n .build());\n this.spoofServerBrand = this.sgGeneral.add((new StringSetting.Builder()).name(\"spoof server brand\").description(\"Change server brand label in F3, blank to disable.\").defaultValue(\"Paper devs are ops\").build());\n this.useRandomIpOffset = this.sgGeneral.add((new BoolSetting.Builder()).name(\"use a random ip header offset\").defaultValue(true).build());\n }\n\n @EventHandler\n public void onMessage(PacketEvent.Receive event) {\n if (event.packet instanceof GameMessageS2CPacket packet) {\n if (packet.content().getString().contains(\"join\") && isGenerifyNames()) {\n event.cancel();\n Text text = Text.literal(\"A player has joined the game\").formatted(Formatting.YELLOW);\n this.mc.inGameHud.getChatHud().addMessage(text);\n }\n }\n\n }\n\n public static boolean isStreaming() {\n return Modules.get().get(StreamerMode.class).isActive();\n }\n\n public static boolean isHideServerInfoEnabled() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.hideServerInfo.get();\n }\n\n public static boolean isHideAccountEnabled() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.hideAccount.get();\n }\n\n public static boolean isGenerifyNames() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.generifyPlayerNames.get();\n }\n\n public static int addFakePlayers() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() ? streamerMode.addFakePlayers.get() : 0;\n }\n\n public static String spoofServerBrand() {\n return Modules.get().get(StreamerMode.class).spoofServerBrand.get();\n }\n\n public static @Nullable String anonymizePlayerNameInstances(String text) {\n if (MeteorClient.mc != null && MeteorClient.mc.player != null && MeteorClient.mc.getNetworkHandler() != null && isGenerifyNames()) {\n\n for (PlayerListEntry player : MeteorClient.mc.getNetworkHandler().getPlayerList()) {\n if (player.getProfile() != null) {\n String fakeName = NMod.genericNames.getName(player.getProfile().getId());\n text = StringUtils.replace(text, player.getProfile().getName(), fakeName);\n if (player.getDisplayName() != null) {\n text = StringUtils.replace(text, player.getDisplayName().getString(), fakeName);\n }\n }\n }\n }\n\n return text;\n }\n\n public static Optional<String> getPlayerEntityName(PlayerEntity player) {\n return isGenerifyNames() && MeteorClient.mc.getNetworkHandler() != null && !player.getGameProfile().getId().equals(MeteorClient.mc.player.getUuid()) && MeteorClient.mc.getNetworkHandler() != null && isGenerifyNames() ? Optional.of(NMod.genericNames.getName(player.getGameProfile().getId())) : Optional.empty();\n }\n}"
},
{
"identifier": "WaypointSync",
"path": "src/main/java/fifthcolumn/n/modules/WaypointSync.java",
"snippet": "public class WaypointSync extends Module {\n public WaypointSync() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Waypoint Sync\", \"Syncs your waypoints. Disabled on 2b2t.org.\");\n }\n\n @EventHandler\n public void spawnPosition(PlayerSpawnPositionEvent event) {\n this.mc.execute(() -> {\n Waypoints waypoints = Waypoints.get();\n waypoints.add((new Waypoint.Builder()).name(\"Spawn\").pos(event.blockPos()).build());\n waypoints.save();\n });\n }\n\n @EventHandler\n private void onPlayerSeen(SpawnPlayerEvent event) {\n this.mc.world.getPlayers().stream().filter((player) -> {\n return player.getGameProfile().getId().equals(event.uuid());\n }).findFirst().ifPresent((player) -> {\n long count = NMod.getCopeService().griefers().stream().filter((griefer) -> {\n return griefer.playerId.equals(event.uuid());\n }).count();\n if (count <= 0L) {\n Waypoints waypoints = Waypoints.get();\n String playerName = \"Player \" + player.getEntityName();\n Waypoint existingWaypoint = waypoints.get(playerName);\n if (existingWaypoint == null) {\n Waypoint.Builder waypointBuilder = new Waypoint.Builder();\n waypointBuilder.name(playerName);\n waypointBuilder.pos(event.blockPos());\n waypointBuilder.icon(\"5c\");\n Waypoint waypoint = waypointBuilder.build();\n waypoints.add(waypoint);\n waypoints.save();\n }\n }\n });\n }\n\n @EventHandler\n public void griefersUpdated(GrieferUpdateEvent event) {\n if (Modules.get().get(WaypointSync.class).isActive()) {\n ServerInfo currentServer = this.mc.getCurrentServerEntry();\n if (currentServer != null && this.mc.player != null) {\n Map<String, CopeService.Waypoint> remoteWaypoints = event.griefers.stream().filter((griefer) -> {\n return !griefer.playerName.equalsIgnoreCase(this.mc.player.getEntityName());\n }).filter((griefer) -> {\n return griefer.serverAddress.equalsIgnoreCase(currentServer.address);\n }).flatMap((griefer) -> {\n return griefer.waypoints.stream();\n }).collect(Collectors.toMap((waypoint) -> {\n return waypoint.name;\n }, (waypoint) -> {\n return waypoint;\n }, (waypoint, waypoint2) -> {\n return waypoint;\n }));\n this.mc.execute(() -> {\n Waypoints waypoints = Waypoints.get();\n boolean waypointUpdated = false;\n Iterator var3 = remoteWaypoints.entrySet().iterator();\n\n while(true) {\n CopeService.Waypoint remoteWaypoint;\n Waypoint existingWaypoint;\n do {\n if (!var3.hasNext()) {\n if (waypointUpdated) {\n waypoints.save();\n }\n\n return;\n }\n\n Map.Entry<String, CopeService.Waypoint> entry = (Map.Entry)var3.next();\n String s = (String)entry.getKey();\n remoteWaypoint = (CopeService.Waypoint)entry.getValue();\n existingWaypoint = waypoints.get(remoteWaypoint.name);\n } while(existingWaypoint != null && ((String)existingWaypoint.name.get()).equals(remoteWaypoint.name));\n\n Waypoint.Builder waypointBuilder = new Waypoint.Builder();\n waypointBuilder.name(remoteWaypoint.name);\n waypointBuilder.pos(BlockPosUtils.from(remoteWaypoint.position));\n waypointBuilder.icon(\"5c\");\n if (remoteWaypoint.position.dimension.equals(\"OVERWORLD\")) {\n waypointBuilder = waypointBuilder.dimension(Dimension.Nether);\n } else if (remoteWaypoint.position.dimension.equals(\"END\")) {\n waypointBuilder = waypointBuilder.dimension(Dimension.End);\n } else {\n waypointBuilder = waypointBuilder.dimension(Dimension.Overworld);\n }\n\n Waypoint waypoint = waypointBuilder.build();\n waypoints.add(waypoint);\n waypointUpdated = true;\n }\n });\n }\n }\n }\n\n static {\n try {\n InputStream inputStream = WaypointSync.class.getResourceAsStream(\"/assets/nc/5c.png\");\n\n try {\n Waypoints.get().icons.put(\"5c\", new NativeImageBackedTexture(NativeImage.read(Objects.requireNonNull(inputStream))));\n } catch (Throwable var4) {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (Throwable var3) {\n var4.addSuppressed(var3);\n }\n }\n\n throw var4;\n }\n\n inputStream.close();\n\n } catch (IOException var5) {\n throw new RuntimeException(\"did not load 5c icon\");\n }\n }\n}"
}
] | import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fifthcolumn.n.NMod;
import fifthcolumn.n.collar.CollarLogin;
import fifthcolumn.n.events.GrieferUpdateEvent;
import fifthcolumn.n.modules.BanEvasion;
import fifthcolumn.n.modules.GrieferTracer;
import fifthcolumn.n.modules.LarpModule;
import fifthcolumn.n.modules.StreamerMode;
import fifthcolumn.n.modules.WaypointSync;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import meteordevelopment.meteorclient.MeteorClient;
import meteordevelopment.meteorclient.mixin.MinecraftClientAccessor;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.systems.waypoints.Waypoints;
import meteordevelopment.meteorclient.utils.world.Dimension;
import net.minecraft.SharedConstants;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.util.Session;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.world.World;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 6,837 | private ScheduledFuture<?> backgroundActiveRefresh;
private final ConcurrentHashMap<String, Griefer> griefers = new ConcurrentHashMap();
private final LoadingCache<TranslateRequest, CompletableFuture<Optional<TranslateResponse>>> translationCache;
public CopeService() {
this.translationCache = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterAccess(1L, TimeUnit.HOURS).build(new CacheLoader<>() {
public CompletableFuture<Optional<TranslateResponse>> load(TranslateRequest req) throws Exception {
CompletableFuture<Optional<TranslateResponse>> resp = new CompletableFuture();
CopeService.this.executor.execute(() -> {
try {
String content = CopeService.this.post("http://cope.fifthcolumnmc.com/api/text/translate", req);
Optional<TranslateResponse> translateResponse = Optional.ofNullable(CopeService.GSON.fromJson(content, TranslateResponse.class));
resp.complete(translateResponse);
} catch (Throwable var5) {
CopeService.LOGGER.error("CopeService Translate Error", var5);
resp.complete(Optional.empty());
}
});
return resp;
}
});
}
public List<Griefer> griefers() {
return new ArrayList(this.griefers.values());
}
public void find(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.currentFindRequest.skip = 0;
this.doFind(resultConsumer);
}
public void findMore(BiConsumer<List<Server>, List<Server>> resultConsumer) {
FindServersRequest var2 = this.currentFindRequest;
var2.skip = var2.skip + this.currentFindRequest.limit;
this.doFind(resultConsumer);
}
private void doFind(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.loading.set(true);
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/find", this.currentFindRequest);
FindServersResponse servers = GSON.fromJson(content, FindServersResponse.class);
this.loading.set(false);
resultConsumer.accept(servers.searchResult, servers.activeServers);
} catch (Throwable var4) {
LOGGER.error("CopeService Find Error", var4);
this.loading.set(false);
}
});
}
public void update(UpdateServerRequest req, Consumer<Server> serverConsumer) {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/update", req);
serverConsumer.accept(GSON.fromJson(content, Server.class));
} catch (Throwable var4) {
LOGGER.error("CopeService Update Error", var4);
}
});
}
public void findHistoricalPlayers(Consumer<List<ServerPlayer>> playersConsumer) {
this.createFindPlayersRequest().ifPresent((req) -> {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/findPlayers", req);
playersConsumer.accept(GSON.fromJson(content, (new TypeToken<ArrayList<ServerPlayer>>() {
}).getType()));
} catch (Throwable var4) {
LOGGER.error("CopeService FindPlayers Error", var4);
}
});
});
}
public CompletableFuture<Optional<TranslateResponse>> translate(TranslateRequest request) {
return this.translationCache.getUnchecked(request);
}
public void getAccount(Consumer<GetAccountResponse> consumer) {
this.executor.execute(() -> {
String response = this.httpGet("http://cope.fifthcolumnmc.com/api/accounts/alt");
consumer.accept(GSON.fromJson(response, GetAccountResponse.class));
});
}
public void useNewAlternateAccount(Consumer<Session> sessionConsumer) {
this.getAccount((resp) -> {
String username = BanEvasion.isSpacesToNameEnabled() ? " " + resp.username + " " : resp.username;
Session session = new Session(username, resp.uuid, resp.token, Optional.empty(), Optional.empty(), Session.AccountType.MSA);
((MinecraftClientAccessor)MeteorClient.mc).setSession(session);
MeteorClient.mc.getSessionProperties().clear();
MeteorClient.mc.execute(() -> {
sessionConsumer.accept(session);
});
});
}
private void setActive(ActiveServerRequest req) {
try {
String body = this.post("http://cope.fifthcolumnmc.com/api/servers/active", req);
ActiveServerResponse resp = GSON.fromJson(body, ActiveServerResponse.class);
resp.griefers.forEach((griefer) -> {
this.griefers.put(griefer.profileName, griefer);
});
MeteorClient.EVENT_BUS.post(new GrieferUpdateEvent(resp.griefers));
} catch (Throwable var4) {
LOGGER.error("CopeService Active Server Error", var4);
}
}
private String post(String url, Object req) { | package fifthcolumn.n.copenheimer;
public final class CopeService {
private static final Logger LOGGER = LoggerFactory.getLogger(CopeService.class);
private static final String BASE_URL = "http://cope.fifthcolumnmc.com/";
private static final Long backgroundRefreshIntervalSeconds = 5L;
private static final Gson GSON = new Gson();
private final HttpClient clientDelegate = HttpClient.newBuilder().build();
public final FindServersRequest currentFindRequest = defaultFindRequest();
public final Executor executor = Executors.newFixedThreadPool(3, (r) -> {
Thread thread = new Thread(r);
thread.setName("CopeService");
return thread;
});
public AtomicBoolean loading = new AtomicBoolean(false);
public final ScheduledExecutorService backgroundActiveExecutorService = new ScheduledThreadPoolExecutor(1);
private ServerInfo currentServer;
private ServerInfo serverInfo;
private Session defaultSession;
private ScheduledFuture<?> backgroundActiveRefresh;
private final ConcurrentHashMap<String, Griefer> griefers = new ConcurrentHashMap();
private final LoadingCache<TranslateRequest, CompletableFuture<Optional<TranslateResponse>>> translationCache;
public CopeService() {
this.translationCache = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterAccess(1L, TimeUnit.HOURS).build(new CacheLoader<>() {
public CompletableFuture<Optional<TranslateResponse>> load(TranslateRequest req) throws Exception {
CompletableFuture<Optional<TranslateResponse>> resp = new CompletableFuture();
CopeService.this.executor.execute(() -> {
try {
String content = CopeService.this.post("http://cope.fifthcolumnmc.com/api/text/translate", req);
Optional<TranslateResponse> translateResponse = Optional.ofNullable(CopeService.GSON.fromJson(content, TranslateResponse.class));
resp.complete(translateResponse);
} catch (Throwable var5) {
CopeService.LOGGER.error("CopeService Translate Error", var5);
resp.complete(Optional.empty());
}
});
return resp;
}
});
}
public List<Griefer> griefers() {
return new ArrayList(this.griefers.values());
}
public void find(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.currentFindRequest.skip = 0;
this.doFind(resultConsumer);
}
public void findMore(BiConsumer<List<Server>, List<Server>> resultConsumer) {
FindServersRequest var2 = this.currentFindRequest;
var2.skip = var2.skip + this.currentFindRequest.limit;
this.doFind(resultConsumer);
}
private void doFind(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.loading.set(true);
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/find", this.currentFindRequest);
FindServersResponse servers = GSON.fromJson(content, FindServersResponse.class);
this.loading.set(false);
resultConsumer.accept(servers.searchResult, servers.activeServers);
} catch (Throwable var4) {
LOGGER.error("CopeService Find Error", var4);
this.loading.set(false);
}
});
}
public void update(UpdateServerRequest req, Consumer<Server> serverConsumer) {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/update", req);
serverConsumer.accept(GSON.fromJson(content, Server.class));
} catch (Throwable var4) {
LOGGER.error("CopeService Update Error", var4);
}
});
}
public void findHistoricalPlayers(Consumer<List<ServerPlayer>> playersConsumer) {
this.createFindPlayersRequest().ifPresent((req) -> {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/findPlayers", req);
playersConsumer.accept(GSON.fromJson(content, (new TypeToken<ArrayList<ServerPlayer>>() {
}).getType()));
} catch (Throwable var4) {
LOGGER.error("CopeService FindPlayers Error", var4);
}
});
});
}
public CompletableFuture<Optional<TranslateResponse>> translate(TranslateRequest request) {
return this.translationCache.getUnchecked(request);
}
public void getAccount(Consumer<GetAccountResponse> consumer) {
this.executor.execute(() -> {
String response = this.httpGet("http://cope.fifthcolumnmc.com/api/accounts/alt");
consumer.accept(GSON.fromJson(response, GetAccountResponse.class));
});
}
public void useNewAlternateAccount(Consumer<Session> sessionConsumer) {
this.getAccount((resp) -> {
String username = BanEvasion.isSpacesToNameEnabled() ? " " + resp.username + " " : resp.username;
Session session = new Session(username, resp.uuid, resp.token, Optional.empty(), Optional.empty(), Session.AccountType.MSA);
((MinecraftClientAccessor)MeteorClient.mc).setSession(session);
MeteorClient.mc.getSessionProperties().clear();
MeteorClient.mc.execute(() -> {
sessionConsumer.accept(session);
});
});
}
private void setActive(ActiveServerRequest req) {
try {
String body = this.post("http://cope.fifthcolumnmc.com/api/servers/active", req);
ActiveServerResponse resp = GSON.fromJson(body, ActiveServerResponse.class);
resp.griefers.forEach((griefer) -> {
this.griefers.put(griefer.profileName, griefer);
});
MeteorClient.EVENT_BUS.post(new GrieferUpdateEvent(resp.griefers));
} catch (Throwable var4) {
LOGGER.error("CopeService Active Server Error", var4);
}
}
private String post(String url, Object req) { | if(NMod.COPE_OFFLINE_MODE) | 0 | 2023-10-14 19:18:35+00:00 | 8k |
dadegrande99/HikeMap | app/src/main/java/com/usi/hikemap/ui/viewmodel/ProfileViewModel.java | [
{
"identifier": "AuthenticationResponse",
"path": "app/src/main/java/com/usi/hikemap/model/AuthenticationResponse.java",
"snippet": "public class AuthenticationResponse {\n\n private boolean success;\n private String message;\n\n public AuthenticationResponse() {\n\n }\n\n public boolean isSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n @NonNull\n @Override\n public String toString() {\n return \"AuthenticationResponse{\" +\n \"success=\" + success +\n \", message='\" + message + '\\'' +\n '}';\n }\n\n}"
},
{
"identifier": "Route",
"path": "app/src/main/java/com/usi/hikemap/model/Route.java",
"snippet": "public class Route implements Parcelable {\n\n private int id, subRoute;\n private String timestamp, idRoute;\n private double altitude, longitude, latitude;\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 getIdRoute() {\n return idRoute;\n }\n\n public void setIdRoute(String idRoute) {\n this.idRoute = idRoute;\n }\n\n public int getSubRoute() {\n return subRoute;\n }\n\n public void setSubRoute(int subRoute) {\n this.subRoute = subRoute;\n }\n\n public String getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(String timestamp) {\n this.timestamp = timestamp;\n }\n\n public double getAltitude() {\n return altitude;\n }\n\n public void setAltitude(double altitude) {\n this.altitude = altitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n public void setLongitude(double longitude) {\n this.longitude = longitude;\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 Route(int id, String idRoute, int subRoute, String timestamp, double altitude, double longitude, double latitude) {\n this.id = id;\n this.idRoute = idRoute;\n this.subRoute = subRoute;\n this.timestamp = timestamp;\n this.altitude = altitude;\n this.longitude = longitude;\n this.latitude = latitude;\n }\n\n @Override\n public String toString() {\n return \"Route{\" +\n \"id=\" + id +\n \", idRoute=\" + idRoute +\n \", subRoute=\" + subRoute +\n \", timestamp='\" + timestamp + '\\'' +\n \", altitude=\" + altitude +\n \", longitude=\" + longitude +\n \", latitude=\" + latitude +\n '}';\n }\n\n protected Route(Parcel in) {\n id = in.readInt();\n idRoute = in.readString();\n subRoute = in.readInt();\n timestamp = in.readString();\n altitude = in.readDouble();\n longitude = in.readDouble();\n latitude = in.readDouble();\n }\n\n public static final Creator<Route> CREATOR = new Creator<Route>() {\n @Override\n public Route createFromParcel(Parcel in) {\n return new Route(in);\n }\n\n @Override\n public Route[] newArray(int size) {\n return new Route[size];\n }\n };\n\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int i) {\n parcel.writeInt(this.id);\n parcel.writeString(this.idRoute);\n parcel.writeInt(this.subRoute);\n parcel.writeString(this.timestamp);\n parcel.writeDouble(this.altitude);\n parcel.writeDouble(this.longitude);\n parcel.writeDouble(this.latitude);\n\n }\n}"
},
{
"identifier": "User",
"path": "app/src/main/java/com/usi/hikemap/model/User.java",
"snippet": "public class User implements Parcelable {\n\n private String birthdate;\n\n private String sex;\n private String name, surname, username, password, auth, userId, provider;\n private String image, path;\n\n private String height, weight;\n\n public User(String name, String surname, String username, String auth, String password, String userId,\n String provider, String image, String path, String height, String weight, String birthdate, String sex){\n this.name = name;\n this.surname = surname;\n this.username = username;\n this.auth = auth;\n this.password = password;\n this.userId = userId;\n this.provider = provider;\n this.image = image;\n this.path = path;\n this.height = height;\n this.weight = weight;\n this.birthdate = birthdate;\n this.sex = sex;\n }\n\n public User() {\n }\n\n public String getHeight() {\n return height;\n }\n\n public void setHeight(String height) {\n this.height = height;\n }\n\n public String getWeight() {\n return weight;\n }\n\n public void setWeight(String weight) {\n this.weight = weight;\n }\n\n protected User(Parcel in) {\n name = in.readString();\n surname = in.readString();\n username = in.readString();\n auth = in.readString();\n password = in.readString();\n userId = in.readString();\n provider = in.readString();\n image = in.readString();\n path = in.readString();\n height = in.readString();\n weight = in.readString();\n birthdate = in.readString();\n sex = in.readString();\n }\n\n public static final Creator<User> CREATOR = new Creator<User>() {\n @Override\n public User createFromParcel(Parcel in) {\n return new User(in);\n }\n\n @Override\n public User[] newArray(int size) {\n return new User[size];\n }\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 getBirthdate() {\n return birthdate;\n }\n\n public void setBirthdate(String birthdate) {\n this.birthdate = birthdate;\n }\n\n public String getSurname() {\n return surname;\n }\n\n public void setSurname(String surname) {\n this.surname = surname;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAuth() {\n return auth;\n }\n\n public void setAuth(String auth) {\n this.auth = auth;\n }\n\n @Exclude\n public String getUserId() {\n return userId;\n }\n\n @Exclude\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public String getProvider() {\n return provider;\n }\n\n public void setProvider(String provider) {\n this.provider = provider;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getSex() {\n return sex;\n }\n\n public void setSex(String sex) {\n this.sex = sex;\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"name='\" + name + '\\'' +\n \", surname='\" + surname + '\\'' +\n \", username='\" + username + '\\'' +\n \", password='\" + password + '\\'' +\n \", auth='\" + auth + '\\'' +\n \", userId='\" + userId + '\\'' +\n \", provider='\" + provider + '\\'' +\n \", image='\" + image + '\\'' +\n \", path='\" + path + '\\'' +\n \", path='\" + height + '\\'' +\n \", path='\" + weight + '\\'' +\n \", path='\" + birthdate + '\\'' +\n '}';\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int i) {\n parcel.writeString(this.name);\n parcel.writeString(this.surname);\n parcel.writeString(this.username);\n parcel.writeString(this.auth);\n parcel.writeString(this.password);\n parcel.writeString(this.userId);\n parcel.writeString(this.provider);\n parcel.writeString(this.image);\n parcel.writeString(this.path);\n\n parcel.writeString(this.height);\n parcel.writeString(this.weight);\n parcel.writeString(this.birthdate);\n\n }\n}"
},
{
"identifier": "IManagerRepository",
"path": "app/src/main/java/com/usi/hikemap/repository/IManagerRepository.java",
"snippet": "public interface IManagerRepository {\n\n\n MutableLiveData<User> readUser(String userId);\n MutableLiveData<AuthenticationResponse> readImage(String userId);\n MutableLiveData<AuthenticationResponse> deleteAccount(String userId);\n\n MutableLiveData<AuthenticationResponse> writeImage(Uri profileUri);\n\n MutableLiveData<AuthenticationResponse> updateData (Map<String, Object> data);\n\n MutableLiveData<AuthenticationResponse> updateRoute(String userId, List<Route> route);\n\n MutableLiveData<List<Route>> readRoutes(String userId);\n\n MutableLiveData<List<Route>> readRoute(String routeId);\n\n}"
},
{
"identifier": "ManagerRepository",
"path": "app/src/main/java/com/usi/hikemap/repository/ManagerRepository.java",
"snippet": "public class ManagerRepository implements IManagerRepository {\n\n private static FirebaseAuth fAuth;\n private static FirebaseDatabase fDatabase;\n private static DatabaseReference fReference;\n private static StorageReference fPhotoReference, fStorageReference;\n private static FirebaseStorage fStore;\n\n private final MutableLiveData<AuthenticationResponse> mAuthenticationResponse;\n private final MutableLiveData<User> mUserLiveData;\n private final MutableLiveData<Route> mRouteLiveData;\n private final MutableLiveData<List<Route>> mRouteLiveDataL;\n private String userId, path;\n\n private static final String TAG = \"ManageRepository\";\n\n public ManagerRepository(Application application) {\n fAuth = FirebaseAuth.getInstance();\n fDatabase = FirebaseDatabase.getInstance(FIREBASE_DATABASE_URL);\n fStore = FirebaseStorage.getInstance();\n\n mAuthenticationResponse = new MutableLiveData<>();\n mUserLiveData = new MutableLiveData<>();\n mRouteLiveData = new MutableLiveData<>();\n mRouteLiveDataL = new MutableLiveData<>();\n }\n\n\n @Override\n public MutableLiveData<User> readUser(String userId) {\n fReference = fDatabase.getReference();\n fReference.child(USER_COLLECTION).child(userId).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {\n @Override\n public void onComplete(@NonNull Task<DataSnapshot> task) {\n if (task.isSuccessful()) {\n User user = new User(task.getResult().child(\"name\").getValue(String.class),task.getResult().child(\"surname\").getValue(String.class),\n task.getResult().child(\"username\").getValue(String.class), task.getResult().child(\"auth\").getValue(String.class),\n task.getResult().child(\"password\").getValue(String.class), task.getResult().child(\"userId\").getValue(String.class),\n task.getResult().child(\"account provider\").getValue(String.class), task.getResult().child(\"image\").getValue(String.class),\n task.getResult().child(\"path\").getValue(String.class), task.getResult().child(\"height\").getValue(String.class),\n task.getResult().child(\"weight\").getValue(String.class), task.getResult().child(\"birthdate\").getValue(String.class), task.getResult().child(\"gendre\").getValue(String.class));\n\n Log.d(TAG, \"onComplete: readUser: \" + task.getResult().getValue(User.class));\n mUserLiveData.postValue(user);\n //mUserLiveData.postValue(task.getResult().getValue(User.class)); //bisogna avere un costruttore vuoto nella classe user\n }\n else {\n Log.d(TAG, \"Error getting data\", task.getException());\n mUserLiveData.postValue(null);\n }\n }\n });\n\n return mUserLiveData;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> readImage(String uId) {\n fPhotoReference = fStore.getReference().child(\"profile_picture/\" + uId);\n fPhotoReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {\n @Override\n public void onSuccess(Uri uri) {\n\n path = uri.toString();\n Map<String, Object> data = new HashMap<>();\n data.put(\"path\", path);\n\n updateData(data);\n\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(true);\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> writeImage(Uri profileUri) {\n\n fStorageReference = fStore.getReference().child(\"profile_picture\").child(FirebaseAuth.getInstance().getUid());\n fStorageReference.putFile(profileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {\n @Override\n public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setMessage(taskSnapshot.toString());\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> updateData(Map<String, Object> data) {\n userId = fAuth.getCurrentUser().getUid();\n fReference = fDatabase.getReference().child(USER_COLLECTION).child(userId);\n fReference.updateChildren(data).addOnSuccessListener(new OnSuccessListener<Void>() {\n @Override\n public void onSuccess(Void unused) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(true);\n mAuthenticationResponse.postValue(authenticationResponse);\n Log.d(TAG, \"data update \" + userId);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(false);\n mAuthenticationResponse.postValue(authenticationResponse);\n Log.d(TAG, \"onFailure: data not update\");\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> deleteAccount(String userId) {\n\n fReference = fDatabase.getReference().child(USER_COLLECTION).child(userId);\n\n // Remove the user from the database\n fReference.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {\n @Override\n public void onSuccess(Void unused) {\n fAuth.getCurrentUser().delete();\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(true);\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(true);\n mAuthenticationResponse.postValue(authenticationResponse);\n }\n });\n\n return mAuthenticationResponse;\n\n }\n\n @Override\n public MutableLiveData<AuthenticationResponse> updateRoute(String userId, List<Route> route) {\n\n Map<String, Object> data = new HashMap();\n data.put(route.get(0).getIdRoute(), route);\n \n fReference = fDatabase.getReference().child(USER_COLLECTION).child(userId).child(\"routes\");\n\n fReference.updateChildren(data).addOnSuccessListener(new OnSuccessListener<Void>() {\n @Override\n public void onSuccess(Void unused) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(true);\n mAuthenticationResponse.postValue(authenticationResponse);\n Log.d(TAG, \"onCreate: Data update \" + userId);\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n AuthenticationResponse authenticationResponse = new AuthenticationResponse();\n authenticationResponse.setSuccess(false);\n mAuthenticationResponse.postValue(authenticationResponse);\n Log.d(TAG, \"onFailure: Data not update\");\n }\n });\n return mAuthenticationResponse;\n }\n\n @Override\n public MutableLiveData<List<Route>> readRoutes(String userId) {\n fReference = fDatabase.getReference();\n\n // Assuming that \"routes\" is a child node under the user's ID\n DatabaseReference routesReference = fReference.child(USER_COLLECTION).child(userId).child(\"routes\");\n\n routesReference.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot dataSnapshot) {\n List<Route> routes = new ArrayList<>();\n\n for (DataSnapshot routeSnapshot : dataSnapshot.getChildren()) {\n // Iterate through the children of \"routes\"\n for (DataSnapshot subRouteSnapshot : routeSnapshot.getChildren()) {\n Integer id = subRouteSnapshot.child(\"id\").getValue(Integer.class);\n String idRoute = subRouteSnapshot.child(\"idRoute\").getValue(String.class);\n Integer subRoute = subRouteSnapshot.child(\"subRoute\").getValue(Integer.class);\n String timestamp = subRouteSnapshot.child(\"timestamp\").getValue(String.class);\n Double altitude = subRouteSnapshot.child(\"altitude\").getValue(Double.class);\n Double latitude = subRouteSnapshot.child(\"latitude\").getValue(Double.class);\n Double longitude = subRouteSnapshot.child(\"longitude\").getValue(Double.class);\n\n // Check for null values before invoking methods\n if (id != null && idRoute != null && subRoute != null && timestamp != null\n && altitude != null && latitude != null && longitude != null) {\n\n Route route = new Route(id, idRoute, subRoute, timestamp, altitude, latitude, longitude);\n routes.add(route);\n Log.d(TAG, \"onDataChange: Route added: \" + route.toString());\n } else {\n // Handle the case when any value is null\n Log.d(TAG, \"One or more values are null\");\n }\n }\n }\n\n Log.d(TAG, \"onDataChange: readRoutes: \" + routes);\n // Post the list of routes to the LiveData\n mRouteLiveDataL.postValue(routes);\n }\n\n @Override\n public void onCancelled(@NonNull DatabaseError databaseError) {\n Log.d(TAG, \"Error getting data\", databaseError.toException());\n mRouteLiveDataL.postValue(null);\n }\n });\n\n return mRouteLiveDataL;\n }\n\n @Override\n public MutableLiveData<List<Route>> readRoute(String routeId) {\n fReference = fDatabase.getReference();\n userId = fAuth.getCurrentUser().getUid();\n\n // Assuming that \"routes\" is a child node under the user's ID\n Log.d(\"ProvaHikeDetails\", \"userId: \" + userId);\n DatabaseReference routesReference = fReference.child(USER_COLLECTION).child(userId).child(\"routes\").child(routeId);\n\n routesReference.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot dataSnapshot) {\n List<Route> routes = new ArrayList<>();\n\n for (DataSnapshot subRouteSnapshot : dataSnapshot.getChildren()) {\n Integer id = subRouteSnapshot.child(\"id\").getValue(Integer.class);\n String idRoute = subRouteSnapshot.child(\"idRoute\").getValue(String.class);\n Integer subRoute = subRouteSnapshot.child(\"subRoute\").getValue(Integer.class);\n String timestamp = subRouteSnapshot.child(\"timestamp\").getValue(String.class);\n Double altitude = subRouteSnapshot.child(\"altitude\").getValue(Double.class);\n Double latitude = subRouteSnapshot.child(\"latitude\").getValue(Double.class);\n Double longitude = subRouteSnapshot.child(\"longitude\").getValue(Double.class);\n\n // Check for null values before invoking methods\n if (id != null && idRoute != null && subRoute != null && timestamp != null\n && altitude != null && latitude != null && longitude != null) {\n\n Route route = new Route(id, idRoute, subRoute, timestamp, altitude, latitude, longitude);\n routes.add(route);\n Log.d(TAG, \"onDataChange: Route added: \" + route.toString());\n } else {\n // Handle the case when any value is null\n Log.d(TAG, \"One or more values are null\");\n }\n }\n\n Log.d(TAG, \"onDataChange: readRoutes: \" + routes);\n // Post the list of routes to the LiveData\n mRouteLiveDataL.postValue(routes);\n }\n\n @Override\n public void onCancelled(@NonNull DatabaseError databaseError) {\n Log.d(TAG, \"Error getting data\", databaseError.toException());\n mRouteLiveDataL.postValue(null);\n }\n });\n\n return mRouteLiveDataL;\n }\n\n}"
}
] | import android.app.Application;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.usi.hikemap.model.AuthenticationResponse;
import com.usi.hikemap.model.Route;
import com.usi.hikemap.model.User;
import com.usi.hikemap.repository.IManagerRepository;
import com.usi.hikemap.repository.ManagerRepository;
import java.util.List;
import java.util.Map; | 5,111 | package com.usi.hikemap.ui.viewmodel;
public class ProfileViewModel extends AndroidViewModel {
private MutableLiveData<AuthenticationResponse> mAuthenticationResponse; | package com.usi.hikemap.ui.viewmodel;
public class ProfileViewModel extends AndroidViewModel {
private MutableLiveData<AuthenticationResponse> mAuthenticationResponse; | private MutableLiveData<User> mUserLiveData; | 2 | 2023-10-09 14:23:22+00:00 | 8k |
zyyzyykk/kkTerminal | terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Consumer/WebSocketServer.java | [
{
"identifier": "AppConfig",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Config/AppConfig.java",
"snippet": "@Component\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AppConfig {\n\n /**\n * 欢迎语\n */\n @Value(\"${kk.welcome:}\")\n private String welcome;\n\n /**\n * github源地址\n */\n @Value(\"${kk.source:}\")\n private String source;\n\n\n /**\n * 艺术字标题\n */\n @Value(\"${kk.title:}\")\n private String title;\n\n /**\n * ssh连接最大超时时间 ms\n */\n @Value(\"${kk.ssh-max-timeout:}\")\n private Integer SshMaxTimeout;\n\n /**\n * websocket最大空闲超时 ms\n */\n @Value(\"${kk.max-idle-timeout:}\")\n private Integer MaxIdleTimeout;\n\n\n}"
},
{
"identifier": "MessageInfoTypeRnum",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Constants/Enum/MessageInfoTypeRnum.java",
"snippet": "public enum MessageInfoTypeRnum {\n\n USER_TEXT(0,\"用户输入的文本\"),\n\n SIZE_CHANGE(1,\"改变虚拟终端大小\"),\n\n\n HEART_BEAT(2,\"进行心跳续约\");\n\n private Integer state;\n\n private String desc;\n\n MessageInfoTypeRnum(Integer state, String desc) {\n this.state = state;\n this.desc = desc;\n }\n\n public static MessageInfoTypeRnum getByState(Integer state) {\n for (MessageInfoTypeRnum item : MessageInfoTypeRnum.values()) {\n if (item.getState().equals(state)) {\n return item;\n }\n }\n return null;\n }\n\n public Integer getState() {\n return state;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n}"
},
{
"identifier": "ResultCodeEnum",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Constants/Enum/ResultCodeEnum.java",
"snippet": "public enum ResultCodeEnum {\n CONNECT_FAIL(-1,\"连接服务器失败!\"),\n\n CONNECT_SUCCESS(0,\"连接服务器成功!\"),\n\n OUT_TEXT(1,\"输出到终端屏幕的文本\");\n private Integer state;\n private String desc;\n\n ResultCodeEnum(Integer state, String desc) {\n this.state = state;\n this.desc = desc;\n }\n\n public static ResultCodeEnum getByState(Integer state) {\n for (ResultCodeEnum item : ResultCodeEnum.values()) {\n if (item.getState().equals(state)) {\n return item;\n }\n }\n return null;\n }\n\n public Integer getState() {\n return state;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n}"
},
{
"identifier": "EnvInfo",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Pojo/EnvInfo.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class EnvInfo {\n private String server_ip;\n\n private Integer server_port;\n\n private String server_user;\n\n private String server_password;\n\n}"
},
{
"identifier": "MessageInfo",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Pojo/MessageInfo.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MessageInfo {\n\n private Integer type;\n\n private String content;\n\n private Integer rows;\n\n private Integer cols;\n}"
},
{
"identifier": "Result",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Result/Result.java",
"snippet": "@Component\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n // 状态\n private String status;\n\n // 响应码\n private Integer code;\n\n // 状态信息\n private String info;\n\n // 返回数据\n private String data;\n\n // 失败返回\n public static Result setFail(Integer code, String info)\n {\n Result result = new Result();\n result.setStatus(\"warning\");\n result.setCode(code);\n result.setInfo(info);\n result.setData(null);\n\n return result;\n }\n\n // 成功返回\n public static Result setSuccess(Integer code, String info, Map<String,Object> data) {\n Result result = new Result();\n result.setStatus(\"success\");\n result.setCode(code);\n result.setInfo(info);\n try {\n if(null == data) result.setData(null);\n else result.setData(AesUtil.aesEncrypt(JSON.toJSONString(data)));\n } catch (Exception e) {\n System.out.println(\"加密异常\");\n result.setData(null);\n }\n\n return result;\n }\n\n // 错误返回\n public static Result setError(Integer code,String info)\n {\n Result result = new Result();\n result.setStatus(\"error\");\n result.setCode(code);\n result.setInfo(info);\n result.setData(null);\n\n return result;\n }\n\n\n public static Result setError(Integer code, String info, Map<String,Object> data) {\n Result result = new Result();\n result.setStatus(\"error\");\n result.setCode(code);\n result.setInfo(info);\n try {\n if(null == data) result.setData(null);\n else result.setData(AesUtil.aesEncrypt(JSON.toJSONString(data)));\n } catch (Exception e) {\n System.out.println(\"加密异常\");\n result.setData(null);\n }\n\n return result;\n }\n\n\n}"
},
{
"identifier": "AesUtil",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Utils/AesUtil.java",
"snippet": "public class AesUtil {\n\n // 密钥 (需要前端和后端保持一致)\n private static final String SECRET_KEY = \"P5P1SIqVe6kaOxMX\";\n\n // 加密算法\n private static final String ALGORITHMSTR = \"AES/ECB/PKCS5Padding\";\n\n /**\n * aes解密\n * @param encrypt 内容\n * @return\n * @throws Exception\n */\n public static String aesDecrypt(String encrypt) {\n try {\n return aesDecrypt(encrypt, SECRET_KEY);\n } catch (Exception e) {\n e.printStackTrace();\n return \"\";\n }\n }\n\n /**\n * aes加密\n * @param content\n * @return\n * @throws Exception\n */\n public static String aesEncrypt(String content) {\n try {\n return aesEncrypt(content, SECRET_KEY);\n } catch (Exception e) {\n e.printStackTrace();\n return \"\";\n }\n }\n\n /**\n * 将byte[]转为各种进制的字符串\n * @param bytes byte[]\n * @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制\n * @return 转换后的字符串\n */\n public static String binary(byte[] bytes, int radix){\n return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数\n }\n\n /**\n * base 64 encode\n * @param bytes 待编码的byte[]\n * @return 编码后的base 64 code\n */\n public static String base64Encode(byte[] bytes){\n return Base64.encodeBase64String(bytes);\n }\n\n /**\n * base 64 decode\n * @param base64Code 待解码的base 64 code\n * @return 解码后的byte[]\n * @throws Exception\n */\n public static byte[] base64Decode(String base64Code) throws Exception{\n return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);\n }\n\n\n /**\n * AES加密\n * @param content 待加密的内容\n * @param encryptKey 加密密钥\n * @return 加密后的byte[]\n * @throws Exception\n */\n public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {\n KeyGenerator kgen = KeyGenerator.getInstance(\"AES\");\n kgen.init(128);\n Cipher cipher = Cipher.getInstance(ALGORITHMSTR);\n cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), \"AES\"));\n\n return cipher.doFinal(content.getBytes(\"utf-8\"));\n }\n\n\n /**\n * AES加密为base 64 code\n * @param content 待加密的内容\n * @param encryptKey 加密密钥\n * @return 加密后的base 64 code\n * @throws Exception\n */\n public static String aesEncrypt(String content, String encryptKey) throws Exception {\n return base64Encode(aesEncryptToBytes(content, encryptKey));\n }\n\n /**\n * AES解密\n * @param encryptBytes 待解密的byte[]\n * @param decryptKey 解密密钥\n * @return 解密后的String\n * @throws Exception\n */\n public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {\n KeyGenerator kgen = KeyGenerator.getInstance(\"AES\");\n kgen.init(128);\n\n Cipher cipher = Cipher.getInstance(ALGORITHMSTR);\n cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), \"AES\"));\n byte[] decryptBytes = cipher.doFinal(encryptBytes);\n return new String(decryptBytes);\n }\n\n\n /**\n * 将base 64 code AES解密\n * @param encryptStr 待解密的base 64 code\n * @param decryptKey 解密密钥\n * @return 解密后的string\n * @throws Exception\n */\n public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {\n return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);\n }\n}"
},
{
"identifier": "FileUtil",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Utils/FileUtil.java",
"snippet": "public class FileUtil {\n\n public static final String folderBasePath = System.getProperty(\"user.dir\") + \"/src/main/resources/static/file\";\n\n /**\n * 文件片合并\n */\n public static void fileChunkMerge(String folderPath, String fileName, Integer chunks, Long totalSize) {\n File folder = new File(folderPath);\n // 获取暂存切片文件的文件夹中的所有文件\n File[] files = folder.listFiles();\n // 合并的文件\n File finalFile = new File(folderPath + \"/\" + fileName);\n InputStream inputStream = null;\n OutputStream outputStream = null;\n try {\n outputStream = new FileOutputStream(finalFile, true);\n\n List<File> list = new ArrayList<>();\n for (File file : files) {\n // 判断是否是文件对应的文件片\n if (StringUtil.isFileChunk(file.getName(),chunks,fileName)) {\n list.add(file);\n }\n }\n // 如果服务器上的切片数量和前端给的数量不匹配\n if (chunks != list.size()) {\n MyException myException = new MyException(\"文件片缺失\");\n myException.setResult(Result.setError(FileBlockStateEnum.UPLOAD_CHUNK_LOST.getState(), \"文件片缺失\"));\n throw myException;\n }\n // 根据切片文件的下标进行排序\n List<File> fileListCollect = list.parallelStream().sorted(((file1, file2) -> {\n Integer chunk1 = StringUtil.getFileChunkIndex(file1.getName());\n Integer chunk2 = StringUtil.getFileChunkIndex(file2.getName());\n return chunk1 - chunk2;\n })).collect(Collectors.toList());\n // 根据排序的顺序依次将文件合并到新的文件中\n for (File file : fileListCollect) {\n inputStream = new FileInputStream(file);\n int len = 0;\n byte[] bytes = new byte[2 * 1024 * 1024];\n while ((len = inputStream.read(bytes)) != -1) {\n outputStream.write(bytes, 0, len);\n }\n inputStream.close();\n outputStream.flush();\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (inputStream != null) inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n try {\n if (outputStream != null) outputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n // 产生的文件大小和前端一开始上传的文件不一致\n if (finalFile.length() != totalSize) {\n MyException myException = new MyException(\"上传文件大小不一致\");\n myException.setResult(Result.setError(FileBlockStateEnum.UPLOAD_SIZE_DIFF.getState(), \"上传文件大小不一致\"));\n throw myException;\n }\n\n }\n\n /**\n * 删除文件夹\n */\n public static void tmpFloderDelete(File directory) {\n if (directory.isDirectory()) {\n File[] files = directory.listFiles();\n if (files != null) {\n for (File file : files) {\n tmpFloderDelete(file);\n }\n }\n }\n directory.delete();\n }\n\n}"
},
{
"identifier": "StringUtil",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Utils/StringUtil.java",
"snippet": "public class StringUtil {\n\n /**\n * 生成随机字符与数字\n */\n public static final String getRandomStr(Integer count)\n {\n return RandomStringUtils.random(count,true,true);\n }\n\n /**\n * 生成随机数\n */\n public static final String getRandomNumber(Integer count)\n {\n return RandomStringUtils.random(count,false,true);\n }\n\n /**\n * 判断是否为空\n */\n public static boolean isEmpty(String str) {\n\n if (null == str || \"\".equals(str) || \"null\".equals(str) || \"\\u0000\".equals(str)) {\n return true;\n } else if (\"\".equals(str.trim())) {\n return true;\n }\n return false;\n }\n\n /**\n * 判断参数1是否为参数2的前缀\n */\n public static boolean isPrefix(String a, String b) {\n if(a == null) return true;\n if(b == null) return false;\n\n int len_a = a.length();\n int len_b = b.length();\n\n if(len_a > len_b) return false;\n\n for(int i=len_a-1;i>=0;i--) if(a.charAt(i) != b.charAt(i)) return false;\n\n return true;\n }\n\n /**\n * 获取最后一个'/'后面的字串\n */\n public static String getEndStr(String str) {\n int lastIndex = str.lastIndexOf(\"/\");\n if (lastIndex != -1) {\n return str.substring(lastIndex + 1);\n } else {\n return str;\n }\n }\n\n /**\n * 将字符串的'@'转为'/'\n */\n public static String changeStr(String str) {\n String result = \"\";\n for (int i=0;i<str.length();i++) {\n if(str.charAt(i) != '@') result += str.charAt(i);\n else result += '/';\n }\n\n return result;\n }\n\n /**\n * 判断分片文件名\n */\n public static Boolean isFileChunk(String chunkFileName, Integer chunks, String originFileName) {\n int index = chunkFileName.lastIndexOf(\"-\");\n if(index != -1) {\n String fileName = chunkFileName.substring(0,index);\n int chunk = Integer.parseInt(chunkFileName.substring(index + 1));\n if(!originFileName.equals(fileName)) return false;\n if(chunk < 1 || chunk > chunks) return false;\n return true;\n }\n\n return false;\n }\n\n /**\n * 获取文件片片号\n */\n public static Integer getFileChunkIndex(String chunkFileName) {\n int index = chunkFileName.lastIndexOf(\"-\");\n if(index != -1) {\n return Integer.parseInt(chunkFileName.substring(index + 1));\n }\n\n return 1;\n }\n\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.lalyos.jfiglet.FigletFont;
import com.kkbpro.terminal.Config.AppConfig;
import com.kkbpro.terminal.Constants.Enum.MessageInfoTypeRnum;
import com.kkbpro.terminal.Constants.Enum.ResultCodeEnum;
import com.kkbpro.terminal.Pojo.EnvInfo;
import com.kkbpro.terminal.Pojo.MessageInfo;
import com.kkbpro.terminal.Result.Result;
import com.kkbpro.terminal.Utils.AesUtil;
import com.kkbpro.terminal.Utils.FileUtil;
import com.kkbpro.terminal.Utils.StringUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; | 4,690 | package com.kkbpro.terminal.Consumer;
@Component
@ServerEndpoint("/socket/ssh/{env}") // 注意不要以'/'结尾
public class WebSocketServer {
public static ConcurrentHashMap<String, SSHClient> sshClientMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, EnvInfo> envInfoMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> fileUploadingMap = new ConcurrentHashMap<>();
private static AppConfig appConfig;
private Session sessionSocket = null;
private String sshKey = null;
private SSHClient sshClient;
private net.schmizz.sshj.connection.channel.direct.Session.Shell shell = null;
private InputStream shellInputStream;
private OutputStream shellOutputStream;
private Thread shellOutThread;
@Autowired
public void setAppConfig(AppConfig appConfig) {
WebSocketServer.appConfig = appConfig;
}
@OnOpen
public void onOpen(Session sessionSocket, @PathParam("env") String env) throws IOException {
EnvInfo envInfo =
JSONObject.parseObject(AesUtil.aesDecrypt(StringUtil.changeStr(env)),EnvInfo.class);
// 建立 web-socket 连接
this.sessionSocket = sessionSocket;
// 设置最大空闲超时(上线后失效???)
sessionSocket.setMaxIdleTimeout(appConfig.getMaxIdleTimeout());
// 与服务器建立连接
String host = envInfo.getServer_ip();
int port = envInfo.getServer_port();
String user_name = envInfo.getServer_user();
String password = envInfo.getServer_password();
sshClient = new SSHClient();
try {
sshClient.setConnectTimeout(appConfig.getSshMaxTimeout());
sshClient.addHostKeyVerifier(new PromiscuousVerifier()); // 不验证主机密钥
sshClient.connect(host,port);
sshClient.authPassword(user_name, password); // 使用用户名和密码进行身份验证
} catch (Exception e) {
e.printStackTrace(); | package com.kkbpro.terminal.Consumer;
@Component
@ServerEndpoint("/socket/ssh/{env}") // 注意不要以'/'结尾
public class WebSocketServer {
public static ConcurrentHashMap<String, SSHClient> sshClientMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, EnvInfo> envInfoMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> fileUploadingMap = new ConcurrentHashMap<>();
private static AppConfig appConfig;
private Session sessionSocket = null;
private String sshKey = null;
private SSHClient sshClient;
private net.schmizz.sshj.connection.channel.direct.Session.Shell shell = null;
private InputStream shellInputStream;
private OutputStream shellOutputStream;
private Thread shellOutThread;
@Autowired
public void setAppConfig(AppConfig appConfig) {
WebSocketServer.appConfig = appConfig;
}
@OnOpen
public void onOpen(Session sessionSocket, @PathParam("env") String env) throws IOException {
EnvInfo envInfo =
JSONObject.parseObject(AesUtil.aesDecrypt(StringUtil.changeStr(env)),EnvInfo.class);
// 建立 web-socket 连接
this.sessionSocket = sessionSocket;
// 设置最大空闲超时(上线后失效???)
sessionSocket.setMaxIdleTimeout(appConfig.getMaxIdleTimeout());
// 与服务器建立连接
String host = envInfo.getServer_ip();
int port = envInfo.getServer_port();
String user_name = envInfo.getServer_user();
String password = envInfo.getServer_password();
sshClient = new SSHClient();
try {
sshClient.setConnectTimeout(appConfig.getSshMaxTimeout());
sshClient.addHostKeyVerifier(new PromiscuousVerifier()); // 不验证主机密钥
sshClient.connect(host,port);
sshClient.authPassword(user_name, password); // 使用用户名和密码进行身份验证
} catch (Exception e) {
e.printStackTrace(); | sendMessage(sessionSocket,"连接服务器失败","fail", ResultCodeEnum.CONNECT_FAIL.getState()); | 2 | 2023-10-14 08:05:24+00:00 | 8k |
ZJU-ACES-ISE/chatunitest-core | src/main/java/zju/cst/aces/util/AskGPT.java | [
{
"identifier": "Config",
"path": "src/main/java/zju/cst/aces/api/config/Config.java",
"snippet": "@Getter\n@Setter\npublic class Config {\n public String date;\n public Gson GSON;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public List<String> classPaths;\n public Path promptPath;\n public String url;\n public String[] apiKeys;\n public Logger log;\n public String OS;\n public boolean stopWhenSuccess;\n public boolean noExecution;\n public boolean enableMultithreading;\n public boolean enableRuleRepair;\n public boolean enableMerge;\n public boolean enableObfuscate;\n public String[] obfuscateGroupIds;\n public int maxThreads;\n public int classThreads;\n public int methodThreads;\n public int testNumber;\n public int maxRounds;\n public int maxPromptTokens;\n public int maxResponseTokens;\n public int minErrorTokens;\n public int sleepTime;\n public int dependencyDepth;\n public Model model;\n public Double temperature;\n public int topP;\n public int frequencyPenalty;\n public int presencePenalty;\n public Path testOutput;\n public Path tmpOutput;\n public Path compileOutputPath;\n public Path parseOutput;\n public Path errorOutput;\n public Path classNameMapPath;\n public Path historyPath;\n public Path examplePath;\n public Path symbolFramePath;\n\n public String proxy;\n public String hostname;\n public String port;\n public OkHttpClient client;\n public static AtomicInteger sharedInteger = new AtomicInteger(0);\n public static Map<String, Map<String, String>> classMapping;\n public Validator validator;\n\n public static class ConfigBuilder {\n public String date;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public List<String> classPaths;\n public Path promptPath;\n public String url;\n public String[] apiKeys;\n public Logger log;\n public String OS = System.getProperty(\"os.name\").toLowerCase();\n public boolean stopWhenSuccess = true;\n public boolean noExecution = false;\n public boolean enableMultithreading = true;\n public boolean enableRuleRepair = true;\n public boolean enableMerge = true;\n public boolean enableObfuscate = false;\n public String[] obfuscateGroupIds;\n public int maxThreads = Runtime.getRuntime().availableProcessors() * 5;\n public int classThreads = (int) Math.ceil((double) this.maxThreads / 10);\n public int methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads);\n public int testNumber = 5;\n public int maxRounds = 5;\n public int maxPromptTokens = 2600;\n public int maxResponseTokens = 1024;\n public int minErrorTokens = 500;\n public int sleepTime = 0;\n public int dependencyDepth = 1;\n public Model model = Model.GPT_3_5_TURBO;\n public Double temperature = 0.5;\n public int topP = 1;\n public int frequencyPenalty = 0;\n public int presencePenalty = 0;\n public Path testOutput;\n public Path tmpOutput = Paths.get(System.getProperty(\"java.io.tmpdir\"), \"chatunitest-info\");\n public Path parseOutput;\n public Path compileOutputPath;\n public Path errorOutput;\n public Path classNameMapPath;\n public Path historyPath;\n public Path examplePath;\n public Path symbolFramePath;\n public String proxy = \"null:-1\";\n public String hostname = \"null\";\n public String port = \"-1\";\n public OkHttpClient client = new OkHttpClient.Builder()\n .connectTimeout(5, TimeUnit.MINUTES)\n .writeTimeout(5, TimeUnit.MINUTES)\n .readTimeout(5, TimeUnit.MINUTES)\n .build();\n public Validator validator;\n\n public ConfigBuilder(Project project) {\n this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"yyyy_MM_dd_HH_mm_ss\")).toString();\n this.project = project;\n this.log = new LoggerImpl();\n\n this.maxPromptTokens = this.model.getDefaultConfig().getContextLength() * 2 / 3;\n this.maxResponseTokens = 1024;\n this.minErrorTokens = this.maxPromptTokens * 1 / 3 - this.maxResponseTokens;\n if (this.minErrorTokens < 0) {\n this.minErrorTokens = 512;\n }\n\n Project parent = project.getParent();\n while(parent != null && parent.getBasedir() != null) {\n this.tmpOutput = this.tmpOutput.resolve(parent.getArtifactId());\n parent = parent.getParent();\n }\n this.tmpOutput = this.tmpOutput.resolve(project.getArtifactId());\n this.compileOutputPath = this.tmpOutput.resolve(\"build\");\n this.parseOutput = this.tmpOutput.resolve(\"class-info\");\n this.errorOutput = this.tmpOutput.resolve(\"error-message\");\n this.classNameMapPath = this.tmpOutput.resolve(\"classNameMapping.json\");\n this.historyPath = this.tmpOutput.resolve(\"history\" + this.date);\n this.symbolFramePath = this.tmpOutput.resolve(\"symbolFrames.json\");\n this.testOutput = project.getBasedir().toPath().resolve(\"chatunitest-tests\");\n this.validator = new ValidatorImpl(this.testOutput, this.compileOutputPath,\n this.project.getBasedir().toPath().resolve(\"target\"), this.classPaths);\n }\n\n public ConfigBuilder maxThreads(int maxThreads) {\n if (maxThreads <= 0) {\n this.maxThreads = Runtime.getRuntime().availableProcessors() * 5;\n } else {\n this.maxThreads = maxThreads;\n }\n this.classThreads = (int) Math.ceil((double) this.maxThreads / 10);\n this.methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads);\n if (this.stopWhenSuccess == false) {\n this.methodThreads = (int) Math.ceil((double) this.methodThreads / this.testNumber);\n }\n return this;\n }\n\n public ConfigBuilder proxy(String proxy) {\n setProxy(proxy);\n return this;\n }\n\n public ConfigBuilder tmpOutput(Path tmpOutput) {\n this.tmpOutput = tmpOutput;\n Project parent = project.getParent();\n while(parent != null && parent.getBasedir() != null) {\n this.tmpOutput = this.tmpOutput.resolve(parent.getArtifactId());\n parent = parent.getParent();\n }\n this.tmpOutput = this.tmpOutput.resolve(project.getArtifactId());\n this.compileOutputPath = this.tmpOutput.resolve(\"build\");\n this.parseOutput = this.tmpOutput.resolve(\"class-info\");\n this.errorOutput = this.tmpOutput.resolve(\"error-message\");\n this.classNameMapPath = this.tmpOutput.resolve(\"classNameMapping.json\");\n this.historyPath = this.tmpOutput.resolve(\"history\" + this.date);\n this.symbolFramePath = this.tmpOutput.resolve(\"symbolFrames.json\");\n this.validator = new ValidatorImpl(this.testOutput, this.compileOutputPath,\n this.project.getBasedir().toPath().resolve(\"target\"), this.classPaths);\n return this;\n }\n\n public ConfigBuilder project(Project project) {\n this.project = project;\n return this;\n }\n\n public ConfigBuilder promptPath(File promptPath) {\n if (promptPath != null) {\n this.promptPath = promptPath.toPath();\n }\n return this;\n }\n\n public ConfigBuilder parser(JavaParser parser) {\n this.parser = parser;\n return this;\n }\n\n public ConfigBuilder parserFacade(JavaParserFacade parserFacade) {\n this.parserFacade = parserFacade;\n return this;\n }\n\n public ConfigBuilder classPaths(List<String> classPaths) {\n this.classPaths = classPaths;\n this.validator = new ValidatorImpl(this.testOutput, this.compileOutputPath,\n this.project.getBasedir().toPath().resolve(\"target\"), this.classPaths);\n return this;\n }\n\n public ConfigBuilder log(Logger log) {\n this.log = log;\n return this;\n }\n\n public ConfigBuilder OS(String OS) {\n this.OS = OS;\n return this;\n }\n\n public ConfigBuilder stopWhenSuccess(boolean stopWhenSuccess) {\n this.stopWhenSuccess = stopWhenSuccess;\n return this;\n }\n\n public ConfigBuilder noExecution(boolean noExecution) {\n this.noExecution = noExecution;\n return this;\n }\n\n public ConfigBuilder enableMultithreading(boolean enableMultithreading) {\n this.enableMultithreading = enableMultithreading;\n return this;\n }\n\n public ConfigBuilder enableRuleRepair(boolean enableRuleRepair) {\n this.enableRuleRepair = enableRuleRepair;\n return this;\n }\n\n public ConfigBuilder enableMerge(boolean enableMerge) {\n this.enableMerge = enableMerge;\n return this;\n }\n\n public ConfigBuilder enableObfuscate(boolean enableObfuscate) {\n this.enableObfuscate = enableObfuscate;\n return this;\n }\n\n public ConfigBuilder obfuscateGroupIds(String[] obfuscateGroupIds) {\n this.obfuscateGroupIds = obfuscateGroupIds;\n return this;\n }\n\n public ConfigBuilder classThreads(int classThreads) {\n this.classThreads = classThreads;\n return this;\n }\n\n public ConfigBuilder methodThreads(int methodThreads) {\n this.methodThreads = methodThreads;\n return this;\n }\n\n public ConfigBuilder url(String url) {\n if (!this.model.getModelName().contains(\"gpt-4\") && !this.model.getModelName().contains(\"gpt-3.5\") && url.equals(\"https://api.openai.com/v1/chat/completions\")) {\n throw new RuntimeException(\"Invalid url for model: \" + this.model + \". Please configure the url in plugin configuration.\");\n }\n this.url = url;\n this.model.getDefaultConfig().setUrl(url);\n return this;\n }\n\n public ConfigBuilder apiKeys(String[] apiKeys) {\n this.apiKeys = apiKeys;\n return this;\n }\n\n public ConfigBuilder testNumber(int testNumber) {\n this.testNumber = testNumber;\n return this;\n }\n\n public ConfigBuilder maxRounds(int maxRounds) {\n this.maxRounds = maxRounds;\n return this;\n }\n\n public ConfigBuilder maxPromptTokens(int maxPromptTokens) {\n this.maxPromptTokens = maxPromptTokens;\n return this;\n }\n\n public ConfigBuilder maxResponseTokens(int maxResponseTokens) {\n this.maxResponseTokens = maxResponseTokens;\n return this;\n }\n\n public ConfigBuilder minErrorTokens(int minErrorTokens) {\n this.minErrorTokens = minErrorTokens;\n return this;\n }\n\n public ConfigBuilder sleepTime(int sleepTime) {\n this.sleepTime = sleepTime;\n return this;\n }\n\n public ConfigBuilder dependencyDepth(int dependencyDepth) {\n this.dependencyDepth = dependencyDepth;\n return this;\n }\n\n public ConfigBuilder model(String model) {\n this.model = Model.fromString(model);\n this.maxPromptTokens = this.model.getDefaultConfig().getContextLength() * 2 / 3;\n this.maxResponseTokens = 1024;\n this.minErrorTokens = this.maxPromptTokens * 1 / 2 - this.maxResponseTokens;\n if (this.minErrorTokens < 0) {\n this.minErrorTokens = 512;\n }\n return this;\n }\n\n public ConfigBuilder temperature(Double temperature) {\n this.temperature = temperature;\n return this;\n }\n\n public ConfigBuilder topP(int topP) {\n this.topP = topP;\n return this;\n }\n\n public ConfigBuilder frequencyPenalty(int frequencyPenalty) {\n this.frequencyPenalty = frequencyPenalty;\n return this;\n }\n\n public ConfigBuilder presencePenalty(int presencePenalty) {\n this.presencePenalty = presencePenalty;\n return this;\n }\n\n public ConfigBuilder testOutput(Path testOutput) {\n if (testOutput == null) {\n this.testOutput = project.getBasedir().toPath().resolve(\"chatunitest-tests\");\n } else {\n this.testOutput = testOutput;\n Project parent = project.getParent();\n while(parent != null && parent.getBasedir() != null) {\n this.testOutput = this.testOutput.resolve(parent.getArtifactId());\n parent = parent.getParent();\n }\n this.testOutput = this.testOutput.resolve(project.getArtifactId());\n }\n return this;\n }\n\n public ConfigBuilder compileOutputPath(Path compileOutputPath) {\n this.compileOutputPath = compileOutputPath;\n return this;\n }\n\n public ConfigBuilder parseOutput(Path parseOutput) {\n this.parseOutput = parseOutput;\n return this;\n }\n\n public ConfigBuilder errorOutput(Path errorOutput) {\n this.errorOutput = errorOutput;\n return this;\n }\n\n public ConfigBuilder classNameMapPath(Path classNameMapPath) {\n this.classNameMapPath = classNameMapPath;\n return this;\n }\n\n public ConfigBuilder examplePath(Path examplePath) {\n this.examplePath = examplePath;\n return this;\n }\n\n public ConfigBuilder symbolFramePath(Path symbolFramePath) {\n this.symbolFramePath = symbolFramePath;\n return this;\n }\n\n public ConfigBuilder hostname(String hostname) {\n this.hostname = hostname;\n return this;\n }\n\n public ConfigBuilder port(String port) {\n this.port = port;\n return this;\n }\n\n public ConfigBuilder client(OkHttpClient client) {\n this.client = client;\n return this;\n }\n\n public void setProxy(String proxy) {\n this.proxy = proxy;\n setProxyStr();\n if (!hostname.equals(\"null\") && !port.equals(\"-1\")) {\n setClinetwithProxy();\n } else {\n setClinet();\n }\n }\n\n public void setProxyStr() {\n this.hostname = this.proxy.split(\":\")[0];\n this.port = this.proxy.split(\":\")[1];\n }\n\n public void setClinet() {\n this.client = new OkHttpClient.Builder()\n .connectTimeout(5, TimeUnit.MINUTES)\n .writeTimeout(5, TimeUnit.MINUTES)\n .readTimeout(5, TimeUnit.MINUTES)\n .build();\n }\n\n public void setClinetwithProxy() {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.hostname, Integer.parseInt(this.port)));\n this.client = new OkHttpClient.Builder()\n .connectTimeout(5, TimeUnit.MINUTES)\n .writeTimeout(5, TimeUnit.MINUTES)\n .readTimeout(5, TimeUnit.MINUTES)\n .proxy(proxy)\n .build();\n }\n\n public void setValidator(Validator validator) {\n this.validator = validator;\n }\n\n public Config build() {\n Config config = new Config();\n config.setDate(this.date);\n config.setGSON(new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create());\n config.setProject(this.project);\n config.setParser(this.parser);\n config.setParserFacade(this.parserFacade);\n config.setClassPaths(this.classPaths);\n config.setPromptPath(this.promptPath);\n config.setUrl(this.url);\n config.setApiKeys(this.apiKeys);\n config.setOS(this.OS);\n config.setStopWhenSuccess(this.stopWhenSuccess);\n config.setNoExecution(this.noExecution);\n config.setEnableMultithreading(this.enableMultithreading);\n config.setEnableRuleRepair(this.enableRuleRepair);\n config.setEnableMerge(this.enableMerge);\n config.setEnableObfuscate(this.enableObfuscate);\n config.setObfuscateGroupIds(this.obfuscateGroupIds);\n config.setMaxThreads(this.maxThreads);\n config.setClassThreads(this.classThreads);\n config.setMethodThreads(this.methodThreads);\n config.setTestNumber(this.testNumber);\n config.setMaxRounds(this.maxRounds);\n config.setMaxPromptTokens(this.maxPromptTokens);\n config.setMaxResponseTokens(this.maxResponseTokens);\n config.setMinErrorTokens(this.minErrorTokens);\n config.setSleepTime(this.sleepTime);\n config.setDependencyDepth(this.dependencyDepth);\n config.setModel(this.model);\n config.setTemperature(this.temperature);\n config.setTopP(this.topP);\n config.setFrequencyPenalty(this.frequencyPenalty);\n config.setPresencePenalty(this.presencePenalty);\n config.setTestOutput(this.testOutput);\n config.setTmpOutput(this.tmpOutput);\n config.setCompileOutputPath(this.compileOutputPath);\n config.setParseOutput(this.parseOutput);\n config.setErrorOutput(this.errorOutput);\n config.setClassNameMapPath(this.classNameMapPath);\n config.setHistoryPath(this.historyPath);\n config.setExamplePath(this.examplePath);\n config.setSymbolFramePath(this.symbolFramePath);\n config.setProxy(this.proxy);\n config.setHostname(this.hostname);\n config.setPort(this.port);\n config.setClient(this.client);\n config.setLog(this.log);\n config.setValidator(this.validator);\n return config;\n }\n }\n\n public String getRandomKey() {\n Random rand = new Random();\n if (apiKeys.length == 0) {\n throw new RuntimeException(\"apiKeys is null!\");\n }\n String apiKey = apiKeys[rand.nextInt(apiKeys.length)];\n return apiKey;\n }\n\n public void print() {\n log.info(\"\\n========================== Configuration ==========================\\n\");\n log.info(\" Multithreading >>>> \" + this.isEnableMultithreading());\n if (this.isEnableMultithreading()) {\n log.info(\" - Class threads: \" + this.getClassThreads() + \", Method threads: \" + this.getMethodThreads());\n }\n log.info(\" Stop when success >>>> \" + this.isStopWhenSuccess());\n log.info(\" No execution >>>> \" + this.isNoExecution());\n log.info(\" Enable Merge >>>> \" + this.isEnableMerge());\n log.info(\" --- \");\n log.info(\" TestOutput Path >>> \" + this.getTestOutput());\n log.info(\" TmpOutput Path >>> \" + this.getTmpOutput());\n log.info(\" Prompt path >>> \" + this.getPromptPath());\n log.info(\" Example path >>> \" + this.getExamplePath());\n log.info(\" --- \");\n log.info(\" Model >>> \" + this.getModel());\n log.info(\" Url >>> \" + this.getUrl());\n log.info(\" MaxPromptTokens >>> \" + this.getMaxPromptTokens());\n log.info(\" MaxResponseTokens >>> \" + this.getMaxResponseTokens());\n log.info(\" MinErrorTokens >>> \" + this.getMinErrorTokens());\n log.info(\" MaxThreads >>> \" + this.getMaxThreads());\n log.info(\" TestNumber >>> \" + this.getTestNumber());\n log.info(\" MaxRounds >>> \" + this.getMaxRounds());\n log.info(\" MinErrorTokens >>> \" + this.getMinErrorTokens());\n log.info(\" MaxPromptTokens >>> \" + this.getMaxPromptTokens());\n log.info(\" SleepTime >>> \" + this.getSleepTime());\n log.info(\" DependencyDepth >>> \" + this.getDependencyDepth());\n log.info(\"\\n===================================================================\\n\");\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"identifier": "ModelConfig",
"path": "src/main/java/zju/cst/aces/api/config/ModelConfig.java",
"snippet": "@Data\npublic class ModelConfig {\n public String modelName;\n public String url;\n public int contextLength;\n public double temperature;\n public int frequencyPenalty;\n public int presencePenalty;\n\n private ModelConfig(Builder builder) {\n this.modelName = builder.modelName;\n this.url = builder.url;\n this.contextLength = builder.contextLength;\n this.temperature = builder.temperature;\n this.frequencyPenalty = builder.frequencyPenalty;\n this.presencePenalty = builder.presencePenalty;\n }\n\n public static class Builder {\n private String modelName = \"gpt-3.5-turbo\";\n private String url = \"https://api.openai.com/v1/chat/completions\";\n private int contextLength = 4096;\n private double temperature = 0.5;\n private int frequencyPenalty = 0;\n private int presencePenalty = 0;\n\n public Builder withModelName(String modelName) {\n this.modelName = modelName;\n return this;\n }\n\n public Builder withUrl(String url) {\n this.url = url;\n return this;\n }\n\n public Builder withContextLength(int contextLength) {\n this.contextLength = contextLength;\n return this;\n }\n\n public Builder withPresencePenalty(int penalty) {\n this.presencePenalty = penalty;\n return this;\n }\n\n public Builder withFrequencyPenalty(int penalty) {\n this.frequencyPenalty = penalty;\n return this;\n }\n\n public Builder withTemperature(double temperature) {\n this.temperature = temperature;\n return this;\n }\n\n public ModelConfig build() {\n return new ModelConfig(this);\n }\n }\n}"
},
{
"identifier": "Message",
"path": "src/main/java/zju/cst/aces/dto/Message.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class Message {\n private String role;\n private String content;\n private String name;\n\n public Message(String role, String content) {\n this.role = role;\n this.content = content;\n }\n\n public static Message of(String content) {\n\n return new Message(Message.Role.USER.getValue(), content);\n }\n\n public static Message ofSystem(String content) {\n\n return new Message(Role.SYSTEM.getValue(), content);\n }\n\n public static Message ofAssistant(String content) {\n\n return new Message(Role.ASSISTANT.getValue(), content);\n }\n\n @Getter\n @AllArgsConstructor\n public enum Role {\n\n SYSTEM(\"system\"),\n USER(\"user\"),\n ASSISTANT(\"assistant\"),\n ;\n private final String value;\n }\n\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import zju.cst.aces.api.config.Config;
import zju.cst.aces.api.config.ModelConfig;
import zju.cst.aces.dto.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects; | 5,459 | package zju.cst.aces.util;
public class AskGPT {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public Config config;
public AskGPT(Config config) {
this.config = config;
}
| package zju.cst.aces.util;
public class AskGPT {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public Config config;
public AskGPT(Config config) {
this.config = config;
}
| public Response askChatGPT(List<Message> messages) { | 2 | 2023-10-14 07:15:10+00:00 | 8k |
Nyayurn/Yutori-QQ | src/main/java/io/github/nyayurn/yutori/qq/listener/EventListenerContainer.java | [
{
"identifier": "Bot",
"path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Bot.java",
"snippet": "@Data\npublic class Bot {\n /**\n * QQ 号\n */\n private String id;\n private ChannelApi channelApi;\n private GuildApi guildApi;\n private GuildMemberApi guildMemberApi;\n private GuildRoleApi guildRoleApi;\n private LoginApi loginApi;\n private MessageApi messageApi;\n private UserApi userApi;\n\n public Bot(String platform, String selfId, PropertiesEntity properties) {\n this.id = selfId;\n this.channelApi = new ChannelApi(platform, selfId, properties);\n this.guildApi = new GuildApi(platform, selfId, properties);\n this.guildMemberApi = new GuildMemberApi(platform, selfId, properties);\n this.guildRoleApi = new GuildRoleApi(platform, selfId, properties);\n this.loginApi = new LoginApi(properties);\n this.messageApi = new MessageApi(platform, selfId, properties);\n this.userApi = new UserApi(platform, selfId, properties);\n }\n}"
},
{
"identifier": "GuildEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/guild/GuildEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class GuildEvent extends Event {\n /**\n * 群组信息\n */\n protected Guild guild;\n\n public GuildEvent(Integer id, Long timestamp, Guild guild) {\n super(id, timestamp);\n this.guild = guild;\n }\n\n public static GuildEvent parse(EventEntity event) {\n return new GuildEvent(event.getId(), event.getTimestamp(), Guild.parse(event));\n }\n}"
},
{
"identifier": "GuildMemberEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/guild/GuildMemberEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class GuildMemberEvent extends Event {\n /**\n * 群组信息\n */\n protected Guild guild;\n\n /**\n * 群成员信息\n */\n protected GuildMember member;\n\n public GuildMemberEvent(Integer id, Long timestamp, Guild guild, GuildMember member) {\n super(id, timestamp);\n this.guild = guild;\n this.member = member;\n }\n\n public static GuildMemberEvent parse(EventEntity event) {\n return new GuildMemberEvent(event.getId(), event.getTimestamp(), Guild.parse(event), GuildMember.parse(event, User.parse(event)));\n }\n}"
},
{
"identifier": "GuildRoleEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/guild/GuildRoleEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class GuildRoleEvent extends Event {\n /**\n * 群组信息\n */\n protected Guild guild;\n\n /**\n * 角色信息\n */\n protected GuildRole role;\n\n public GuildRoleEvent(Integer id, Long timestamp, Guild guild, GuildRole role) {\n super(id, timestamp);\n this.guild = guild;\n this.role = role;\n }\n\n public static GuildRoleEvent parse(EventEntity event) {\n return new GuildRoleEvent(event.getId(), event.getTimestamp(), Guild.parse(event), GuildRole.parse(event));\n }\n}"
},
{
"identifier": "GroupMessageEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/message/GroupMessageEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class GroupMessageEvent extends MessageEvent {\n /**\n * 群组信息\n */\n protected Guild guild;\n\n /**\n * 群成员卡片\n */\n protected String senderCard;\n\n public GroupMessageEvent(Integer id, Long timestamp, User user, Message message, Channel channel,\n List<BaseMessageElement> chain, Guild guild, String senderCard) {\n super(id, timestamp, user, message, channel, chain);\n this.guild = guild;\n this.senderCard = senderCard;\n }\n\n public static GroupMessageEvent parse(EventEntity event, List<BaseMessageElement> chain) {\n return new GroupMessageEvent(event.getId(), event.getTimestamp(), User.parse(event),\n Message.parse(event), Channel.parse(event), chain, Guild.parse(event), event.getMember().getName());\n }\n}"
},
{
"identifier": "MessageEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/message/MessageEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class MessageEvent extends UserEvent {\n /**\n * 消息信息\n */\n protected Message message;\n\n /**\n * 频道信息\n */\n protected Channel channel;\n\n /**\n * 消息链\n */\n protected List<BaseMessageElement> msgChain;\n\n public MessageEvent(Integer id, Long timestamp, User user, Message message, Channel channel, List<BaseMessageElement> chain) {\n super(id, timestamp, user);\n this.message = message;\n this.channel = channel;\n this.msgChain = chain;\n }\n}"
},
{
"identifier": "PrivateMessageEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/message/PrivateMessageEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class PrivateMessageEvent extends MessageEvent {\n public PrivateMessageEvent(Integer id, Long timestamp, User user, Message message, Channel channel,\n List<BaseMessageElement> chain) {\n super(id, timestamp, user, message, channel, chain);\n }\n\n public static PrivateMessageEvent parse(EventEntity event, List<BaseMessageElement> chain) {\n return new PrivateMessageEvent(event.getId(), event.getTimestamp(), User.parse(event),\n Message.parse(event), Channel.parse(event), chain);\n }\n}"
},
{
"identifier": "FriendRequestEvent",
"path": "src/main/java/io/github/nyayurn/yutori/qq/event/user/FriendRequestEvent.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class FriendRequestEvent extends UserEvent {\n public FriendRequestEvent(Integer id, Long timestamp, User user) {\n super(id, timestamp, user);\n }\n\n public static FriendRequestEvent parse(EventEntity event) {\n return new FriendRequestEvent(event.getId(), event.getTimestamp(), User.parse(event));\n }\n}"
},
{
"identifier": "GuildAddedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/GuildAddedListener.java",
"snippet": "public interface GuildAddedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildEvent event);\n}"
},
{
"identifier": "GuildRemovedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/GuildRemovedListener.java",
"snippet": "public interface GuildRemovedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildEvent event);\n}"
},
{
"identifier": "GuildRequestListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/GuildRequestListener.java",
"snippet": "public interface GuildRequestListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildEvent event);\n}"
},
{
"identifier": "GuildUpdatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/GuildUpdatedListener.java",
"snippet": "public interface GuildUpdatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildEvent event);\n}"
},
{
"identifier": "GuildMemberAddedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/member/GuildMemberAddedListener.java",
"snippet": "public interface GuildMemberAddedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildMemberEvent event);\n}"
},
{
"identifier": "GuildMemberRemovedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/member/GuildMemberRemovedListener.java",
"snippet": "public interface GuildMemberRemovedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildMemberEvent event);\n}"
},
{
"identifier": "GuildMemberRequestListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/member/GuildMemberRequestListener.java",
"snippet": "public interface GuildMemberRequestListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildMemberEvent event);\n}"
},
{
"identifier": "GuildMemberUpdatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/member/GuildMemberUpdatedListener.java",
"snippet": "public interface GuildMemberUpdatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildMemberEvent event);\n}"
},
{
"identifier": "GuildRoleCreatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/role/GuildRoleCreatedListener.java",
"snippet": "public interface GuildRoleCreatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildRoleEvent event);\n}"
},
{
"identifier": "GuildRoleDeletedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/role/GuildRoleDeletedListener.java",
"snippet": "public interface GuildRoleDeletedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildRoleEvent event);\n}"
},
{
"identifier": "GuildRoleUpdatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/guild/role/GuildRoleUpdatedListener.java",
"snippet": "public interface GuildRoleUpdatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, GuildRoleEvent event);\n}"
},
{
"identifier": "LoginAddedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/login/LoginAddedListener.java",
"snippet": "public interface LoginAddedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n */\n void onEvent(Bot bot);\n}"
},
{
"identifier": "LoginRemovedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/login/LoginRemovedListener.java",
"snippet": "public interface LoginRemovedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n */\n void onEvent(Bot bot);\n}"
},
{
"identifier": "LoginUpdatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/login/LoginUpdatedListener.java",
"snippet": "public interface LoginUpdatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n */\n void onEvent(Bot bot);\n}"
},
{
"identifier": "GroupMessageCreatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/created/GroupMessageCreatedListener.java",
"snippet": "public interface GroupMessageCreatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, GroupMessageEvent event, String msg);\n}"
},
{
"identifier": "MessageCreatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/created/MessageCreatedListener.java",
"snippet": "public interface MessageCreatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, MessageEvent event, String msg);\n}"
},
{
"identifier": "PrivateMessageCreatedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/created/PrivateMessageCreatedListener.java",
"snippet": "public interface PrivateMessageCreatedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, PrivateMessageEvent event, String msg);\n}"
},
{
"identifier": "GroupMessageDeletedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/deleted/GroupMessageDeletedListener.java",
"snippet": "public interface GroupMessageDeletedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, GroupMessageEvent event, String msg);\n}"
},
{
"identifier": "MessageDeletedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/deleted/MessageDeletedListener.java",
"snippet": "public interface MessageDeletedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, MessageEvent event, String msg);\n}"
},
{
"identifier": "PrivateMessageDeletedListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/message/deleted/PrivateMessageDeletedListener.java",
"snippet": "public interface PrivateMessageDeletedListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n * @param msg 过滤后的普通文本信息\n */\n void onEvent(Bot bot, PrivateMessageEvent event, String msg);\n}"
},
{
"identifier": "FriendRequestListener",
"path": "src/main/java/io/github/nyayurn/yutori/qq/listener/user/FriendRequestListener.java",
"snippet": "public interface FriendRequestListener {\n /**\n * 触发事件\n *\n * @param bot 机器人信息\n * @param event 事件信息\n */\n void onEvent(Bot bot, FriendRequestEvent event);\n}"
}
] | import io.github.nyayurn.yutori.qq.entity.event.Bot;
import io.github.nyayurn.yutori.qq.event.guild.GuildEvent;
import io.github.nyayurn.yutori.qq.event.guild.GuildMemberEvent;
import io.github.nyayurn.yutori.qq.event.guild.GuildRoleEvent;
import io.github.nyayurn.yutori.qq.event.message.GroupMessageEvent;
import io.github.nyayurn.yutori.qq.event.message.MessageEvent;
import io.github.nyayurn.yutori.qq.event.message.PrivateMessageEvent;
import io.github.nyayurn.yutori.qq.event.user.FriendRequestEvent;
import io.github.nyayurn.yutori.qq.listener.guild.GuildAddedListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildRemovedListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildRequestListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberAddedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberRemovedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberRequestListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleCreatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleDeletedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginAddedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginRemovedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.GroupMessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.MessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.PrivateMessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.GroupMessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.MessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.PrivateMessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.user.FriendRequestListener;
import lombok.Data;
import java.util.ArrayList;
import java.util.List; | 4,261 | /*
Copyright (c) 2023 Yurn
yutori-qq is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package io.github.nyayurn.yutori.qq.listener;
/**
* @author Yurn
*/
@Data
public class EventListenerContainer {
public final List<GuildAddedListener> onGuildAddedListenerDelegate = new ArrayList<>();
public final List<GuildUpdatedListener> onGuildUpdatedListenerDelegate = new ArrayList<>();
public final List<GuildRemovedListener> onGuildRemovedListenerDelegate = new ArrayList<>();
public final List<GuildRequestListener> onGuildRequestListenerDelegate = new ArrayList<>();
public final List<GuildMemberAddedListener> onGuildMemberAddedListenerDelegate = new ArrayList<>(); | /*
Copyright (c) 2023 Yurn
yutori-qq is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package io.github.nyayurn.yutori.qq.listener;
/**
* @author Yurn
*/
@Data
public class EventListenerContainer {
public final List<GuildAddedListener> onGuildAddedListenerDelegate = new ArrayList<>();
public final List<GuildUpdatedListener> onGuildUpdatedListenerDelegate = new ArrayList<>();
public final List<GuildRemovedListener> onGuildRemovedListenerDelegate = new ArrayList<>();
public final List<GuildRequestListener> onGuildRequestListenerDelegate = new ArrayList<>();
public final List<GuildMemberAddedListener> onGuildMemberAddedListenerDelegate = new ArrayList<>(); | public final List<GuildMemberUpdatedListener> onGuildMemberUpdatedListenerDelegate = new ArrayList<>(); | 15 | 2023-10-12 09:58:07+00:00 | 8k |
villainwtf/weave | src/main/java/wtf/villain/weave/builder/WeaveInstanceBuilder.java | [
{
"identifier": "Weave",
"path": "src/main/java/wtf/villain/weave/Weave.java",
"snippet": "public sealed interface Weave permits Weave.Impl {\n\n @NotNull\n static WeaveInstanceBuilder builder() {\n return new WeaveInstanceBuilder();\n }\n\n /**\n * Gets the underlying Retrofit client.\n *\n * @return the client\n */\n @NotNull\n TolgeeClient client();\n\n /**\n * Gets the underlying storage instance.\n * This is where all the supported languages and translations are cached.\n *\n * @return the storage instance\n */\n @NotNull\n Storage storage();\n\n /**\n * Refreshes the cache in the background.\n *\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n default CompletableFuture<Void> refresh() {\n return storage().refresh(client());\n }\n\n /**\n * Refreshes the cache for the given project in the background.\n *\n * @param projectId the ID of the project to refresh\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n default CompletableFuture<Project> refreshProject(int projectId) {\n return storage().refreshProject(client(), projectId);\n }\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project\n * @return the project\n */\n @NotNull\n default Project project(int id) {\n return storage().ensureProject(id);\n }\n\n /**\n * Closes the underlying client.\n */\n void dispose();\n\n record Impl(@NotNull TolgeeClient client,\n @NotNull Runnable clientShutdown,\n @NotNull Storage storage) implements Weave {\n @Override\n public void dispose() {\n clientShutdown.run();\n }\n }\n\n\n}"
},
{
"identifier": "TolgeeClient",
"path": "src/main/java/wtf/villain/weave/client/TolgeeClient.java",
"snippet": "public interface TolgeeClient {\n\n @NotNull\n @GET(\"/v2/projects/{id}/languages?size=2000\")\n Call<LanguagesResponse> getLanguages(@Path(\"id\") int id);\n\n @NotNull\n @GET(\"/v2/projects/{id}/translations/{language}?structureDelimiter\")\n Call<Map<String, Map<String, String>>> getTranslations(@Path(\"id\") int id, @Path(\"language\") String language);\n\n /**\n * Queries the list of supported languages for the given project.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @return a future that completes with the list of supported languages\n */\n @NotNull\n default CompletableFuture<List<LanguagesResponse.Language>> querySupportedLanguages(@NotNull TolgeeClient client, int projectId) {\n CompletableFuture<List<LanguagesResponse.Language>> future = new CompletableFuture<>();\n\n client.getLanguages(projectId).enqueue(new Callback<>() {\n @Override\n public void onResponse(@NotNull Call<LanguagesResponse> call, @NotNull Response<LanguagesResponse> response) {\n if (!response.isSuccessful()) {\n future.completeExceptionally(new RuntimeException(\"Unsuccessful request, status code is \" + response.code()));\n return;\n }\n\n LanguagesResponse data = response.body();\n\n if (data == null) {\n future.completeExceptionally(new RuntimeException(\"Invalid response body received\"));\n return;\n }\n\n future.complete(data.embedded().languages());\n }\n\n @Override\n public void onFailure(@NotNull Call<LanguagesResponse> call, @NotNull Throwable throwable) {\n future.completeExceptionally(new RuntimeException(\"Request failed\", throwable));\n }\n });\n\n return future;\n }\n\n /**\n * Queries the translations for the given project and language.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @param language the language\n * @return a future that completes with the translations\n */\n @NotNull\n default CompletableFuture<Map<String, Map<String, String>>> queryTranslations(@NotNull TolgeeClient client, int projectId, @NotNull String language) {\n CompletableFuture<Map<String, Map<String, String>>> future = new CompletableFuture<>();\n\n client.getTranslations(projectId, language).enqueue(new Callback<>() {\n @Override\n public void onResponse(@NotNull Call<Map<String, Map<String, String>>> call, @NotNull Response<Map<String, Map<String, String>>> response) {\n if (!response.isSuccessful()) {\n future.completeExceptionally(new RuntimeException(\"Unsuccessful request, status code is \" + response.code()));\n return;\n }\n\n Map<String, Map<String, String>> data = response.body();\n\n if (data == null) {\n future.completeExceptionally(new RuntimeException(\"Invalid response body received\"));\n return;\n }\n\n future.complete(data);\n }\n\n @Override\n public void onFailure(@NotNull Call<Map<String, Map<String, String>>> call, @NotNull Throwable throwable) {\n future.completeExceptionally(new RuntimeException(\"Request failed\", throwable));\n }\n });\n\n return future;\n }\n\n}"
},
{
"identifier": "Storage",
"path": "src/main/java/wtf/villain/weave/storage/Storage.java",
"snippet": "@Getter\n@RequiredArgsConstructor\npublic final class Storage {\n\n private final List<Integer> projectIds;\n private final List<PostProcessor> postProcessors;\n private final Map<Integer, Project> projects = new HashMap<>();\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project to get\n * @return the project with the given ID\n * @throws IllegalArgumentException if no such project exists\n */\n @NotNull\n public Project ensureProject(int id) {\n Project project = project(id);\n\n if (project == null) {\n throw new IllegalArgumentException(\"No project with ID \" + id);\n }\n\n return project;\n }\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project to get\n * @return the project with the given ID, or {@code null} if no such project exists\n */\n @Nullable\n public Project project(int id) {\n return projects.get(id);\n }\n\n /**\n * Refreshes the cache in the background.\n *\n * @param client the Tolgee client\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n public CompletableFuture<Void> refresh(@NotNull TolgeeClient client) {\n List<CompletableFuture<Void>> futures = projectIds.stream()\n .map(projectId -> refreshProject(client, projectId)\n .thenAccept(project -> projects.put(projectId, project)))\n .toList();\n\n return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new));\n }\n\n /**\n * Refreshes the cache of the given project in the background.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n public CompletableFuture<Project> refreshProject(@NotNull TolgeeClient client, int projectId) {\n CompletableFuture<Project> future = new CompletableFuture<>();\n\n int oldProjectVersion = Optional.ofNullable(projects.get(projectId))\n .map(Project::version)\n .orElse(0);\n\n WeaveProcessor processor = WeaveProcessor.of(postProcessors.toArray(PostProcessor[]::new));\n\n CompletableFuture<List<LanguagesResponse.Language>> languagesFuture = client.querySupportedLanguages(client, projectId);\n languagesFuture.whenComplete((languages, throwable) -> {\n if (throwable != null) {\n future.completeExceptionally(throwable);\n return;\n }\n\n if (languages.isEmpty()) {\n // If there are no languages, there won't be any translations either.\n future.complete(new Project(projectId, Map.of(), Map.of(), oldProjectVersion + 1));\n return;\n }\n\n Map<String, Map<String, Translation>> translations = new HashMap<>();\n\n List<CompletableFuture<Void>> languageFutures = languages.stream()\n .map(language -> client.queryTranslations(client, projectId, language.tag())\n .thenAccept(map -> {\n Map<String, String> keyToValue = map.get(language.tag());\n\n if (keyToValue == null) {\n // This should never happen since we're querying the translations for the given language.\n throw new IllegalStateException(\"No translations for language \" + language.tag());\n }\n\n Map<String, Translation> translationMap = new HashMap<>();\n\n keyToValue.forEach((key, value) -> {\n if (value == null) {\n // The value can be null if this key is not translated in the given language.\n // Example: \"en\" has \"hello\" -> \"Hello World!\", but \"de\" doesn't have this key translated yet.\n return;\n }\n\n // We iterate through each (translation key -> text) pair and add it to the map.\n translationMap.put(key, new Translation(value, processor));\n });\n\n translations.put(language.tag(), translationMap);\n }))\n .toList();\n\n CompletableFuture.allOf(languageFutures.toArray(CompletableFuture[]::new))\n .whenComplete((unused, throwable1) -> {\n if (throwable1 != null) {\n future.completeExceptionally(throwable1);\n return;\n }\n\n future.complete(new Project(\n projectId,\n languages.stream().collect(HashMap::new, (map, language) -> map.put(language.tag(), Language.findOrCreate(language.tag(), language.name())), HashMap::putAll),\n translations,\n oldProjectVersion + 1));\n });\n });\n\n return future;\n }\n\n}"
},
{
"identifier": "PostProcessor",
"path": "src/main/java/wtf/villain/weave/translation/process/PostProcessor.java",
"snippet": "@FunctionalInterface\npublic interface PostProcessor extends Function<Text, String> {\n\n /**\n * Returns a post-processor that returns its input unchanged.\n *\n * @return a post-processor that returns its input unchanged\n */\n @NotNull\n static PostProcessor identity() {\n return Text::text;\n }\n\n}"
},
{
"identifier": "Ensure",
"path": "src/main/java/wtf/villain/weave/util/Ensure.java",
"snippet": "public interface Ensure {\n\n /**\n * Checks that the specified object reference is not {@code null}.\n *\n * @param object the object reference to check for nullity\n * @param key the key to use in the exception message\n * @throws IllegalArgumentException if {@code object} is {@code null}\n */\n @Contract(\"null, _ -> fail\")\n static void argumentIsSet(@Nullable Object object, @NotNull String key) {\n that(object != null, key + \" must be set\");\n }\n\n /**\n * Checks that the given condition is true.\n *\n * @param condition the condition to check\n * @param message the message to use in the exception\n * @throws IllegalArgumentException if {@code condition} is {@code false}\n */\n static void that(boolean condition, @NotNull String message) {\n if (!condition) {\n throw new IllegalArgumentException(message);\n }\n }\n}"
}
] | import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import wtf.villain.weave.Weave;
import wtf.villain.weave.client.TolgeeClient;
import wtf.villain.weave.storage.Storage;
import wtf.villain.weave.translation.process.PostProcessor;
import wtf.villain.weave.util.Ensure;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture; | 3,702 | package wtf.villain.weave.builder;
public final class WeaveInstanceBuilder {
@Nullable
private String apiKey;
@Nullable
private String endpoint;
@NotNull
private final List<Integer> projectIds = new ArrayList<>();
@NotNull
private Duration connectTimeout = Duration.ofSeconds(30);
@NotNull
private Duration readTimeout = Duration.ofSeconds(30);
@NotNull
private Duration writeTimeout = Duration.ofSeconds(30);
@NotNull
private final List<PostProcessor> processors = new ArrayList<>();
/**
* Sets the API key to use for the Tolgee client.
*
* @param apiKey the API key
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder apiKey(@NotNull String apiKey) {
this.apiKey = apiKey;
return this;
}
/**
* Sets the endpoint to use for the Tolgee client.
*
* @param endpoint the endpoint
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder endpoint(@NotNull String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Adds the given project IDs to the Tolgee client.
*
* @param projectIds the project IDs
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProjects(int... projectIds) {
for (int projectId : projectIds) {
this.projectIds.add(projectId);
}
return this;
}
/**
* Sets the connect timeout for the Tolgee client.
*
* @param connectTimeout the connect timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder connectTimeout(@NotNull Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Sets the read timeout for the Tolgee client.
*
* @param readTimeout the read timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder readTimeout(@NotNull Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Sets the write timeout for the Tolgee client.
*
* @param writeTimeout the write timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder writeTimeout(@NotNull Duration writeTimeout) {
this.writeTimeout = writeTimeout;
return this;
}
/**
* Adds the given translation post processors to the Tolgee client.
*
* @param processors the translation post processors
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProcessors(@NotNull PostProcessor... processors) {
this.processors.addAll(Arrays.asList(processors));
return this;
}
/**
* Builds the Tolgee client synchronously.
*
* @return the Tolgee client
*/
@NotNull
public Weave build() {
return buildAsync().join();
}
/**
* Builds the Tolgee client asynchronously.
*
* @return a future that completes when the Tolgee client is built
*/
@NotNull
public CompletableFuture<Weave> buildAsync() {
Ensure.argumentIsSet(apiKey, "apiKey");
Ensure.argumentIsSet(endpoint, "endpoint");
Ensure.that(!projectIds.isEmpty(), "projectIds must contain at least one project ID");
Ensure.argumentIsSet(connectTimeout, "connectTimeout");
Ensure.argumentIsSet(readTimeout, "readTimeout");
Ensure.argumentIsSet(writeTimeout, "writeTimeout");
Ensure.that(connectTimeout.toMillis() > 0, "connectTimeout must be greater than zero");
Ensure.that(readTimeout.toMillis() > 0, "readTimeout must be greater than zero");
Ensure.that(writeTimeout.toMillis() > 0, "writeTimeout must be greater than zero");
CompletableFuture<Weave> future = new CompletableFuture<>();
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new TolgeeInterceptor(apiKey))
.connectTimeout(connectTimeout)
.readTimeout(readTimeout)
.writeTimeout(writeTimeout)
.build();
| package wtf.villain.weave.builder;
public final class WeaveInstanceBuilder {
@Nullable
private String apiKey;
@Nullable
private String endpoint;
@NotNull
private final List<Integer> projectIds = new ArrayList<>();
@NotNull
private Duration connectTimeout = Duration.ofSeconds(30);
@NotNull
private Duration readTimeout = Duration.ofSeconds(30);
@NotNull
private Duration writeTimeout = Duration.ofSeconds(30);
@NotNull
private final List<PostProcessor> processors = new ArrayList<>();
/**
* Sets the API key to use for the Tolgee client.
*
* @param apiKey the API key
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder apiKey(@NotNull String apiKey) {
this.apiKey = apiKey;
return this;
}
/**
* Sets the endpoint to use for the Tolgee client.
*
* @param endpoint the endpoint
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder endpoint(@NotNull String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Adds the given project IDs to the Tolgee client.
*
* @param projectIds the project IDs
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProjects(int... projectIds) {
for (int projectId : projectIds) {
this.projectIds.add(projectId);
}
return this;
}
/**
* Sets the connect timeout for the Tolgee client.
*
* @param connectTimeout the connect timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder connectTimeout(@NotNull Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Sets the read timeout for the Tolgee client.
*
* @param readTimeout the read timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder readTimeout(@NotNull Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Sets the write timeout for the Tolgee client.
*
* @param writeTimeout the write timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder writeTimeout(@NotNull Duration writeTimeout) {
this.writeTimeout = writeTimeout;
return this;
}
/**
* Adds the given translation post processors to the Tolgee client.
*
* @param processors the translation post processors
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProcessors(@NotNull PostProcessor... processors) {
this.processors.addAll(Arrays.asList(processors));
return this;
}
/**
* Builds the Tolgee client synchronously.
*
* @return the Tolgee client
*/
@NotNull
public Weave build() {
return buildAsync().join();
}
/**
* Builds the Tolgee client asynchronously.
*
* @return a future that completes when the Tolgee client is built
*/
@NotNull
public CompletableFuture<Weave> buildAsync() {
Ensure.argumentIsSet(apiKey, "apiKey");
Ensure.argumentIsSet(endpoint, "endpoint");
Ensure.that(!projectIds.isEmpty(), "projectIds must contain at least one project ID");
Ensure.argumentIsSet(connectTimeout, "connectTimeout");
Ensure.argumentIsSet(readTimeout, "readTimeout");
Ensure.argumentIsSet(writeTimeout, "writeTimeout");
Ensure.that(connectTimeout.toMillis() > 0, "connectTimeout must be greater than zero");
Ensure.that(readTimeout.toMillis() > 0, "readTimeout must be greater than zero");
Ensure.that(writeTimeout.toMillis() > 0, "writeTimeout must be greater than zero");
CompletableFuture<Weave> future = new CompletableFuture<>();
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new TolgeeInterceptor(apiKey))
.connectTimeout(connectTimeout)
.readTimeout(readTimeout)
.writeTimeout(writeTimeout)
.build();
| TolgeeClient tolgeeClient = new Retrofit.Builder() | 1 | 2023-10-09 13:46:52+00:00 | 8k |
jmdevall/opencodeplan | src/main/java/jmdevall/opencodeplan/domain/promptmaker/Context.java | [
{
"identifier": "Repository",
"path": "src/main/java/jmdevall/opencodeplan/application/port/out/repository/Repository.java",
"snippet": "public interface Repository {\n\n\tList<SourceFolder> getBuildPath();\n\t\n\tCuSource getCuSource();\n\n void save(String filepath, String newFileContent);\n}"
},
{
"identifier": "Fragment",
"path": "src/main/java/jmdevall/opencodeplan/domain/Fragment.java",
"snippet": "@Getter\n@Builder\npublic class Fragment {\n\n\t/**\n\tSimply extracting\n\tcode of the block 𝐵 loses information about relationship of 𝐵 with the surrounding code.\n\tKeeping the entire file on the other hand takes up prompt space and is often unnecessary.\n\tWe found the surrounding context is most helpful when a block belongs to a class. For such\n\tblocks, we sketch the enclosing class. That is, in addition to the code of block 𝐵, we also\n\tkeep declarations of the enclosing class and its members. As we discuss later, this sketched\n\trepresentation also helps us merge the LLM’s output into a source code file more easily.\n\t*/\n\tprivate Node prunedcu;\n\tprivate Node originalcu;\n\tprivate Node revised;\n\t\n\t/**\n\t * Fragment is like a copy of the Compilation Unit node but some of the child nodes that represent the method blocks has been\n\t * replaced with empty blocks because it is not of interest.\n\t * \n\t * @param cu\n\t * @param principalMethodBlock\n\t * @return\n\t */\n\tpublic static Fragment newFromPrunedCuNode(Node originalcu, NodeId affectedSubNode) {\n\t\treturn Fragment.builder()\n\t\t\t\t.originalcu(originalcu)\n\t\t\t\t.prunedcu(Fragment.extractCodeFragment(originalcu,Arrays.asList(affectedSubNode),null))\n\t\t\t\t.build();\n\t}\n\t\n\tpublic static Fragment newFromCuNode(Node cu) {\n\t\treturn Fragment.builder()\n\t\t\t\t.originalcu(cu)\n\t\t\t\t.prunedcu(cu)\n\t\t\t\t.build();\n\t}\n\t\n\n\tpublic static Node extractCodeFragment(Node root, List<NodeId> affectedBlocks, Node parent) {\n\t \n\t Stream<Node> consideredChildren=root.getChildren().stream();\n\t \n\t //other methods different to the affected: replace blockStmt with other empty \"SkipBlock\"\n\t if(root.isMethodDeclaration() && !root.getId().containsByPosition(\n\t \t\taffectedBlocks.stream()\n\t \t\t.collect(Collectors.toList()))\n\t ) {\n\t \tconsideredChildren=consideredChildren\n\t\t\t\t\t.map(c->{\n\t\t\t\t\t\t\treturn (c.getType().equals(\"BlockStmt\"))?\n\t\t\t\t\t\t\t\tFragment.skipedNode(c):c;\n\t\t\t\t\t});\n\t }\n\t \n\t Node newNode=root.newCopyWithoutChildren();\n\t \n\t List<Node> prunedChildren=consideredChildren\n\t \t\t.map(c->extractCodeFragment(c,affectedBlocks,newNode))\n\t \t\t.collect(Collectors.toList());\n\t\n\t newNode.setChildren(prunedChildren);\n\t \n\t return newNode;\n\t}\n\n\tpublic static Node skipedNode(Node c) {\n\t\treturn Node.builder()\n\t\t.id(c.getId())\n\t\t.type(\"SkipedBlockFragment\")\n\t\t.parent(c.parent)\n\t\t.children(Collections.emptyList())\n\t\t.rrange(c.getRrange())\n\t\t.content(\"\")\n\t\t.original(c)\n\t\t.build();\n\t}\n\t\n\n\tpublic String merge(String llmrevised){\n\t\tString originalCuPrompt = originalcu.prompt();\n\t\tList<String> original= DiffUtil.tolines(originalCuPrompt);\n\t\tString prunedCUPrompt = prunedcu.prompt();\n\t\tList<String> pruned = DiffUtil.tolines(prunedCUPrompt);\n\t\tList<String> revised= DiffUtil.tolines(llmrevised);\n\t\t\n\t\t\n\t\t//patchPrunedToOriginal should only have deltas of source=1 line and target= multiples lines because It's only method body deletions\n\t\tPatch<String> patchPrunedToOriginal=DiffUtils.diff(pruned, original);\n\t\t\n\t\tPatch<String> patchPrunedToRevised=DiffUtils.diff(pruned, revised);\n\t\t\n\t\tArrayList<String> prunedCopy=new ArrayList<String>(pruned);\n\t\tfor(AbstractDelta<String> delta:patchPrunedToOriginal.getDeltas()) {\n\n\t\t\tChunk<String> source=delta.getSource();\n\t\t\tint position=source.getPosition();\n\t\t\t\n\t\t\t//in this line it actually goes more than one line but do not alter the positions for the next patch \n\t\t\tString multilineHack=delta.getTarget().getLines().stream().collect(Collectors.joining(System.lineSeparator()));\n\t\t\tprunedCopy.remove(position);\n\t\t\tprunedCopy.add(position, multilineHack);\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tList<String> finalpatch = DiffUtils.patch(prunedCopy,patchPrunedToRevised);\n\t\t\treturn finalpatch.stream().collect(Collectors.joining(System.lineSeparator()));\n\t\t} catch (PatchFailedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\t\n\t\n\n\t\n\tpublic void setRevised(Node newFragment){\n\t\tthis.revised=newFragment;\n\t}\n\n\t/**\n\t * Compare original compilation unit with revised and gives a list of Clasified changes\n\t * @return\n\t */\n\tpublic List<ClasifiedChange> classifyChanges() {\n\t\tList<String> original= DiffUtil.tolines(originalcu.prompt());\n\t\tList<String> revisedCode = DiffUtil.tolines(revised.prompt());\n\t\t\n\t\tPatch<String> originalToRevised=DiffUtils.diff(original, revisedCode);\n\t\t\n\t\tList<ClasifiedChange> clasified=new ArrayList<ClasifiedChange>();\n\t\t\n\t\tfor(AbstractDelta<String> delta:originalToRevised.getDeltas()) {\n\n\t\t\tChunk<String> source=delta.getSource();\n\t\t\tChunk<String> target=delta.getTarget();\n\t\t\t\n\t\t\tint sourceLine=source.getPosition()+1;\n\t\t\tint targetLine=target.getPosition()+1;\n\t\t\t\n\t\t\tChangeType ct=fromDeltaType(delta.getType());\n\t\t\t\n\t\t\tList<Node> originalNodes=Collections.emptyList();\n\t\t\tList<Node> revisedNodes=Collections.emptyList();\n\t\t\t//con esto filtraríamos los nodos raiz de algun tipoTag que se han añadido en revised\n\t\t\tif(ct==ChangeType.ADD || ct==ChangeType.MODIFICATION) {\n\t\t\t\trevisedNodes=revised.toStream()\n\t\t\t\t\t.filter(n -> n.getId().getRange().containsLine(targetLine))\n\t\t\t\t\t.filter(n -> n.getNodeTypeTag()!=null && n.getParent()!=null)\n\t\t\t\t\t.filter(n -> n.getNodeTypeTag()!=n.getParent().getNodeTypeTag())\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\t\t\tif(ct==ChangeType.DELETION || ct==ChangeType.MODIFICATION) {\n\t\t\t\toriginalNodes=originalcu.toStream()\n\t\t\t\t.filter(n -> n.getId().getRange().containsLine(sourceLine))\n\t\t\t\t.filter(n -> n.getNodeTypeTag()!=null && n.getParent()!=null)\n\t\t\t\t.filter(n -> n.getNodeTypeTag()!=n.getParent().getNodeTypeTag()) \n\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\t\t\t\n\n\t\t\tList<String> contentsoriginal=originalNodes.stream().map(n->n.getContent()).collect(Collectors.toList());\n\t\t\tList<String> contentsrevised=revisedNodes.stream().map(n->n.getContent()).collect(Collectors.toList());\n\t\t\toriginalNodes.removeIf(n->contentsrevised.contains(n.getContent()));\n\t\t\trevisedNodes.removeIf(n->contentsoriginal.contains(n.getContent()));\n\t\t\t\n\t\t\t//al pillar los nodos también entran los nodos superiores, en este caso no nos interesa saber que cuando el cambio es en un método\n\t\t\toriginalNodes=filterMostRelevant(originalNodes);\n\t\t\trevisedNodes=filterMostRelevant(revisedNodes);\n\t\t\t\n\t\t\tOptional<NodeTypeTag> nodeTypeTag=Streams.concat(originalNodes.stream(),revisedNodes.stream())\n\t\t\t.map(n->n.getNodeTypeTag())\n\t\t\t.findFirst();\n\n\t\t\tif(nodeTypeTag.isPresent()) {\n\t\t\t\tCMI cmi=CMI.find(ct, nodeTypeTag.get());\n\t\t\t\tclasified.add(new ClasifiedChange(cmi, originalNodes, revisedNodes));\n\t\t\t}\n\t\t}\n\n\t\treturn clasified;\n\t}\n\t\n\tprivate List<Node> filterMostRelevant(List<Node> nodes){\n\t\t\n\t\tfor(NodeTypeTag nodeTypeTag:NodeTypeTag.values()) {\n\t\t\tList<Node> only=nodes.stream()\n\t\t\t\t\t.filter(n->n.getNodeTypeTag()==nodeTypeTag).collect(Collectors.toList());\n\t\t\tif(!only.isEmpty()) {\n\t\t\t\treturn only;\n\t\t\t}\n\t\t}\n\t\treturn Collections.emptyList();\n\t\t\n\t}\n\t\n\tprivate ChangeType fromDeltaType(DeltaType deltaType) {\n\t\tif(deltaType==DeltaType.INSERT) {\n\t\t\treturn ChangeType.ADD;\n\t\t}\n\t\tif(deltaType==DeltaType.DELETE) {\n\t\t\treturn ChangeType.DELETION;\n\t\t}\n\t\tif(deltaType==DeltaType.CHANGE) {\n\t\t\treturn ChangeType.MODIFICATION;\n\t\t}\n\t\tthrow new IllegalArgumentException();\n\t}\n\t\n}"
},
{
"identifier": "DependencyGraph",
"path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/DependencyGraph.java",
"snippet": "@Getter\n@Slf4j\npublic class DependencyGraph {\n\n\tprivate HashMap<String,Node> forest;\n\tprivate List<DependencyRelation> rels;\n\t\n public DependencyGraph(HashMap<String, Node> forest, List<DependencyRelation> rels) {\n\t\tsuper();\n\t\tthis.forest = forest;\n\t\tthis.rels = rels;\n\t}\n \n public Optional<Node> findByNodeId(NodeId nodeid) {\n \tif(!forest.containsKey(nodeid.getFile())) {\n \t\treturn Optional.empty();\n \t}\n \tNode cu=forest.get(nodeid.getFile()); //TODO: bug. el nodo de tipo field se ha recortado y no encuentra\n \tOptional<Node> findFirst = cu.toStream().filter(n->n.getId().equals(nodeid)).findFirst();\n \tif(findFirst.isEmpty()) {\n \t\tSystem.out.println(\"no encontrado\");\n \t}\n\t\treturn findFirst;\n }\n \n public Optional<Node> findFinalNodeContaining(NodeId nodeid){\n \tif(!forest.containsKey(nodeid.getFile())) {\n \t\treturn Optional.empty();\n \t}\n \tNode cu=forest.get(nodeid.getFile());\n \t\n\t\treturn cu.toStream()\n\t\t.filter(n->n.getId().getRange().contains(nodeid.getRange()))\n\t\t.filter(n->n.children.isEmpty())\n\t\t.findAny();\n }\n\n\tpublic DependencyGraph updateDependencyGraph(List<CMI> labels, Fragment fragment, Fragment newFragment, Node b) {\n // TODO:\n //return new DependencyGraph(this.r);\n \treturn null;\n }\n\n\n\t/*\n @Builder\n public static class ClassNode{\n String className;\n }\n \n @Builder\n public class MethodNode{\n String methodName;\n }*/\n}"
},
{
"identifier": "Node",
"path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/Node.java",
"snippet": "@Builder(toBuilder=true)\n@Getter\n@Slf4j\npublic class Node {\n private NodeId id;\n \n\tpublic String type;\n\tpublic Node parent;\n\tpublic List<Node> children;\n\t\n\tprivate IndexPosRange rrange;\n\tprivate String content;\n\t\n\t//skiped nodes keep the original node\n\tpublic Node original;\n\t\n\tpublic Node newCopyWithoutChildren() {\n\t\treturn Node.builder()\n\t\t.id(this.getId())\n\t\t.type(this.getType())\n\t\t.parent(this.getParent())\n\t\t.rrange(this.getRrange())\n\t\t.content(this.getContent())\n\t\t.original(this.original)\n\t\t.build();\n\t}\n\t\n\t\n\tpublic NodeTypeTag getNodeTypeTag(){\n\t\tif(this.type.equals(\"BlockStmt\")) {\n\t\t\treturn NodeTypeTag.BodyOfMethod;\n\t\t}\n\t\tif(this.type.equals(\"MethodDeclaration\")) {\n\t\t\treturn NodeTypeTag.SignatureOfMethod;\n\t\t}\n\t\tif(this.type.equals(\"ConstructorDeclaration\")) {\n\t\t\treturn NodeTypeTag.SignatureOfConstructor;\n\t\t}\t\t\n\t\tif(this.type.equals(\"FieldDeclaration\")) {\n\t\t\treturn NodeTypeTag.Field;\n\t\t}\n\t\tif(this.type.equals(\"ClassOrInterfaceDeclaration\")) {\n\t\t\treturn NodeTypeTag.DeclarationOfClass;\n\t\t}\n\t\tif(this.parent==null) {\n\t\t\treturn null;\t\n\t\t}\n\t\treturn this.parent.getNodeTypeTag();\n\t\t\n\t}\n\t\n\t/*\n\tprivate boolean findParentRecursive(String type) {\n\t\tif(this.type.equals(type)) {\n\t\t\treturn true;\n\t\t}\n\t\tif(this.parent==null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn parent.findParentRecursive(type);\n\t\t\n\t}*/\n\t\n\tpublic String debugRecursive() {\n\t\tStringBuffer sb=new StringBuffer(\"\");\n\t\tdebugRecursiveSb(sb,0);\n\t\treturn sb.toString();\n\t}\n\t\n\tpublic void debugRecursiveSb(StringBuffer sb, int level) {\n\t\t\n\t\t//String mycontent=\"\\n\"+this.getContent();\n\t\tString mycontent=\"\";\n\t\t\n \tif(this.getChildren().isEmpty()) {\n \tSystem.out.println(String.format(\"%s [%s]+[%s]: A%s R%s, [%s]\"\n \t\t\t,this.getLevel(level)\n \t\t\t,this.getType(), id.getFile()\n \t\t\t,this.id.getRange().toString()\n \t\t\t,this.rrange.toString()\n \t\t\t,mycontent));\n \t}\n \telse {\n \tSystem.out.println(String.format(\"%s [%s]+[%s]: A%s R[%s], [%s]\"\n \t\t\t,this.getLevel(level)\n \t\t\t,this.getType(), id.getFile()\n \t\t\t,this.id.getRange().toString()\n \t\t\t,this.rrange.toString()\n \t ,mycontent));\n \t}\n \t\n \t\n \tfor(Node child:this.getChildren()) {\n \t\tchild.debugRecursiveSb(sb,level+1);\n \t}\n }\n\t\n\tpublic Node getRootParent() {\n\t\tif(this.parent==null) {\n\t\t\treturn this;\n\t\t}\n\t\telse {\n\t\t\treturn this.parent.getRootParent();\n\t\t}\n\t}\n\t\n private String getLevel(int level) {\n \tStringBuffer sb=new StringBuffer(\"\");\n \t\n \tfor(int i=0;i<level;i++) {\n \t\tsb.append(\"-\");\n \t}\n \treturn sb.toString();\n }\n\t\n\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id);\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\tNode other = (Node) obj;\n\t\treturn Objects.equals(id, other.id);\n\t}\n\n\tpublic void setChildren(List<Node> children) {\n\t\tthis.children = children;\n\t}\n \n\tpublic IndexPosRange relativeRange() {\n\t\tif(parent==null) {\n\t\t\treturn this.rrange;\n\t\t}\n\t\telse { \n\t\t\tIndexPosRange arangeparent=parent.rrange;\n\t\t\treturn rrange.minus(arangeparent);\n\t\t}\n\t}\n\t\n\tpublic String prompt() {\n\t\treturn this.prompt(new StringBuffer(this.content));\n\t}\n\t\n public String prompt(StringBuffer sbpadre) {\n \tStringBuffer sbyo = new StringBuffer(content);\n \t\n \t//es necesario ordenador los hijos y hacer las sustituciones desde el final hasta el principio para que no se descuadre.\n \tArrayList<Node> consideredChildren=new ArrayList<Node>(this.children);\n \tconsideredChildren.sort((o1, o2) -> o2.relativeRange().getBegin() - o1.relativeRange().getBegin());\n \t\n \tfor(Node child:consideredChildren) {\n \t\tchild.prompt(sbyo);\n \t}\n \tIndexPosRange relativeRange = this.relativeRange();\n\t\tsbpadre.replace(relativeRange.getBegin(), relativeRange.getEnd(), sbyo.toString());\n \treturn sbpadre.toString();\n\n }\n\n public Stream<Node> toStream(){\n \tjava.util.stream.Stream.Builder<Node> s=Stream.<Node>builder();\n \taddRecursive(s);\n \treturn s.build();\n }\n \n\tprivate void addRecursive(java.util.stream.Stream.Builder<Node> s) {\n\t\ts.add(this);\n\t\tfor(Node child:children){\n\t\t\tchild.addRecursive(s);\n\t\t}\n\t}\n\t\n\tpublic boolean isMethodContaining(Node other){\n\t\treturn this.isMethodDeclaration() && this.id.containsByPosition(other.getId());\n\t}\n\n\tpublic boolean isMethodDeclaration() {\n\t\treturn this.type.equals(\"MethodDeclaration\");\n\t}\n}"
},
{
"identifier": "NodeId",
"path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/NodeId.java",
"snippet": "@Builder(toBuilder = true)\n@Getter\n@EqualsAndHashCode\npublic class NodeId {\n\t\n\t@NonNull\n\tprivate String file;\n\tprivate LineColRange range;\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"NodeId(file=\" + file + \", range=\" + range + \")\";\n\t}\n\t\n\tpublic boolean isSameFile(NodeId other){\n\t\treturn (this.getFile().equals(other.getFile()));\n\t}\n\t\n\tpublic boolean containsByPosition(NodeId other) {\n\t\treturn this.isSameFile(other) \n\t\t\t\t&& \n\t\t\t\tthis.getRange().contains(other.getRange());\n\t}\n\t\n\tpublic boolean containsByPosition(List<NodeId> others){\n\t\tfor(NodeId nodeid:others) {\n\t\t\tif(this.containsByPosition(nodeid)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\n\t\n\t\n}"
},
{
"identifier": "PlanGraph",
"path": "src/main/java/jmdevall/opencodeplan/domain/plangraph/PlanGraph.java",
"snippet": "public class PlanGraph {\n\n\tprivate ArrayList<Obligation> obligationRoots = new ArrayList<Obligation>();\n\n\tpublic void addPendingRoot(BI bi) {\n\t\tobligationRoots.add(Obligation.builder().b(bi.getB()).i(bi.getI()).cmi(null).status(Status.PENDING).build());\n\n\t}\n\n\tpublic Optional<Obligation> getNextPending() {\n\t\tfor (Obligation o : obligationRoots) {\n\t\t\tOptional<Obligation> found = o.findNextPendingRecursive();\n\t\t\tif (found.isPresent()) {\n\t\t\t\treturn found;\n\t\t\t}\n\t\t}\n\t\treturn Optional.empty();\n\t}\n\n\tpublic boolean hasNodesWithPendingStatus() {\n\t\tfor (Obligation o : obligationRoots) {\n\t\t\tif (o.isPendingRecursive()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic void markCompleted(Node b) {\n\t\tfor (Obligation o : obligationRoots) {\n\t\t\tif (o.searchRecursiveToMarkCompleted(b)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void addPendingChild(Node parent, Node child, CMIRelation cmi) {\n\t\tfor (Obligation o : obligationRoots) {\n\t\t\to.searchRecursiveToAddPendingChild(parent, child, cmi);\n\t\t}\n\t}\n\n\tpublic TemporalContext getTemporalContext(Node targetNode) {\n\t\tTemporalContext temporalContext = new TemporalContext();\n\t\t List<Obligation> visitedNodes = new ArrayList<>();\n\n\t\t// Recorrer todos los nodos raíz\n\t\tfor (Obligation root : obligationRoots) {\n\t\t\t// Llamar a la función recursiva para obtener el contexto temporal\n\t\t\tgetTemporalContextRecursive(root, targetNode, temporalContext,visitedNodes);\n\t\t}\n\n\t\treturn temporalContext;\n\t}\n\n\tprivate void getTemporalContextRecursive(Obligation currentNode, Node targetNode, TemporalContext temporalContext, List<Obligation> visitedNodes) {\n\t\t// Si el nodo actual es el nodo objetivo, agregar el contexto temporal\n\t\tif (currentNode.getB().equals(targetNode)) {\n\t\t\tfor(Obligation o:visitedNodes) {\n\t\t\t\tTemporalChange change=TemporalChange.builder()\n\t\t\t\t\t\t.fragment(o.getFragment())\n\t\t\t\t\t\t.cause(o.getCmi())\n\t\t\t\t\t\t.build();\n\t\t\t\t\t\t\n\t\t\t\ttemporalContext.addChange(change);\t\n\t\t\t}\n\t\t}else {\n\t\t\tvisitedNodes.add(currentNode);\n\n\t\t\t// Recorrer todos los hijos del nodo actual\n\t\t\tfor (Obligation child : currentNode.getChildrens()) {\n\t\t\t\t// Llamar a la función recursiva para los hijos del nodo actual\n\t\t\t\tgetTemporalContextRecursive(child, targetNode, temporalContext, new ArrayList<Obligation>(visitedNodes));\n\t\t\t}\n\t\t}\n\n\t}\n\n}"
},
{
"identifier": "TemporalContext",
"path": "src/main/java/jmdevall/opencodeplan/domain/plangraph/TemporalContext.java",
"snippet": "public class TemporalContext {\n private List<TemporalChange> changes = new ArrayList<>();\n\n public void addChange(TemporalChange temporalChange) {\n changes.add(temporalChange);\n }\n\n public List<TemporalChange> getChanges() {\n return changes;\n }\n}"
},
{
"identifier": "DependencyRelation",
"path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/DependencyRelation.java",
"snippet": "@Builder\n@Getter\npublic class DependencyRelation {\n\tNodeId origin;\n\tNodeId destiny;\n\tDependencyLabel label;\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Rel(origin=\" + origin + \", destiny=\" + destiny + \", label=\" + label + \")\";\n\t}\n}"
}
] | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jmdevall.opencodeplan.application.port.out.repository.Repository;
import jmdevall.opencodeplan.domain.Fragment;
import jmdevall.opencodeplan.domain.dependencygraph.DependencyGraph;
import jmdevall.opencodeplan.domain.dependencygraph.Node;
import jmdevall.opencodeplan.domain.dependencygraph.NodeId;
import jmdevall.opencodeplan.domain.plangraph.PlanGraph;
import jmdevall.opencodeplan.domain.plangraph.TemporalContext;
import jmdevall.opencodeplan.domain.dependencygraph.DependencyRelation;
import lombok.Getter; | 5,291 | package jmdevall.opencodeplan.domain.promptmaker;
/**
* The context of the edit
(line 38–41) consists of (a) spatial context, which contains related code such as methods
called from the block 𝐵, and
(b) temporal context, which contains the previous edits that
caused the need to edit the block 𝐵. The temporal context is formed by edits along the paths
from the root nodes of the plan graph to 𝐵.
*/
@Getter
public class Context {
private List<String> spatialContext; | package jmdevall.opencodeplan.domain.promptmaker;
/**
* The context of the edit
(line 38–41) consists of (a) spatial context, which contains related code such as methods
called from the block 𝐵, and
(b) temporal context, which contains the previous edits that
caused the need to edit the block 𝐵. The temporal context is formed by edits along the paths
from the root nodes of the plan graph to 𝐵.
*/
@Getter
public class Context {
private List<String> spatialContext; | private TemporalContext temporalContext; | 6 | 2023-10-14 18:27:18+00:00 | 8k |
eahau/douyin-openapi | generator/src/main/java/com/github/eahau/openapi/douyin/generator/parser/HtmlParser.java | [
{
"identifier": "DocField",
"path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/DocField.java",
"snippet": "@Getter\n@Setter\npublic class DocField {\n\n /**\n * 字段名称.\n */\n @SerializedName(value = \"name\", alternate = {\"key\"})\n private String name = \"\";\n\n /**\n * 字段类型.\n */\n private String type;\n\n public boolean isBinaryType() {\n return StringUtils.equalsAny(getType(), \"binary\", \"form-data\");\n }\n\n public String getType() {\n if (this.type != null) {\n return this.type;\n }\n if (StringUtils.equalsAnyIgnoreCase(getName(), \"content-type\", \"access-token\")) {\n setType(\"string\");\n return \"string\";\n }\n\n return Stream.of(getDefV(), getExample())\n .filter(Objects::nonNull)\n .map(v -> {\n String type;\n if (NumberUtils.isCreatable(v)) {\n type = \"number\";\n } else if (StringUtils.equalsAnyIgnoreCase(v, \"true\", \"false\")) {\n type = \"bool\";\n } else {\n type = \"string\";\n }\n\n setType(type);\n return type;\n })\n .findFirst()\n .orElse(\"struct\");\n }\n\n /**\n * 是否必传字段.\n */\n private boolean required;\n\n /**\n * 字段描述信息.\n */\n private String desc;\n\n /**\n * 字段默认值.\n */\n private String defV;\n\n /**\n * 最大长度.\n */\n private String maxLength;\n\n /**\n * 示例值.\n */\n private String example;\n\n @SerializedName(value = \"children\", alternate = {\"fields\"})\n private List<DocField> children = Lists.newLinkedList();\n\n private Map<String, List<DocField>> otherSchemas = Maps.newHashMap();\n\n public void addSchema(List<DocField> children) {\n final Map<String, List<DocField>> otherSchemas = getOtherSchemas();\n otherSchemas.put(getName() + (otherSchemas.size() + 1), children);\n }\n\n public List<DocField> flatChildren() {\n final List<DocField> children = getChildren();\n\n if (CollectionUtils.isEmpty(children)) {\n return Collections.emptyList();\n }\n\n final List<DocField> list = Lists.newLinkedList();\n\n for (final DocField docField : children) {\n if (CollectionUtils.isEmpty(docField.getChildren())) {\n list.add(docField);\n } else {\n list.addAll(docField.flatChildren());\n }\n }\n\n return list;\n }\n\n private DocField parent;\n\n public DocField getParent() {\n DocField parent = this.parent;\n\n while (parent != null) {\n if (parent.isObjectType()) {\n break;\n }\n parent = parent.getParent();\n }\n\n return parent;\n }\n\n public boolean isRootObject() {\n return getParent() == null;\n }\n\n public String getParentName() {\n DocField parent = getParent();\n if (parent == null) {\n return \"\";\n }\n\n final LinkedList<String> list = Lists.newLinkedList();\n while (parent != null) {\n String name = parent.getName();\n if (parent.getType().startsWith(\"[]\")) {\n name += \"[0]\";\n }\n list.addFirst(name);\n parent = parent.getParent();\n }\n\n return String.join(\".\", list);\n }\n\n public String getFullName() {\n String name = getName();\n if (getType().startsWith(\"[]\")) {\n name += \"[0]\";\n }\n return String.join(\".\", getParentName(), name);\n }\n\n public void setDesc(String value) {\n this.desc = value;\n if (StringUtils.equalsAnyIgnoreCase(getName(), \"content-type\")) {\n if (StringUtils.containsIgnoreCase(value, \"application/json\")) {\n setDefV(\"application/json\");\n setType(\"string\");\n }\n } else {\n Stream.<Pair<String, Consumer<String>>>of(\n Pair.of(\"示例\", this::setDesc),\n Pair.of(Misc.DEFAULT_VALUE_KEY, this::setDefV)\n )\n .forEach(pair -> {\n final String k = pair.getKey();\n final String key = k + \":\";\n\n final String regex = value.contains(key) ? key : (value.contains(k) ? k : null);\n if (regex == null) {\n return;\n }\n Arrays.stream(value.split(regex))\n .filter(StringUtils::isNotBlank)\n .map(it -> it.replace(\"\\\"\", \"\").trim())\n .findFirst()\n .ifPresent(pair.getValue());\n }\n );\n\n if (StringUtils.equalsAny(getName(), \"msg\") && getType().equals(\"string\")) {\n if (StringUtils.containsIgnoreCase(value, \"json\")) {\n /**\n * @see #isObjectType(String)\n */\n setType(\"Json Object\");\n }\n }\n }\n }\n\n public boolean isObjectType() {\n final String type = getType();\n return isObjectType(type) || !isPrimitiveType(type);\n }\n\n private static boolean isObjectType(String type) {\n return StringUtils.equalsAny(type, \"object\", \"struct\", \"strcut\", \"Json Object\");\n }\n\n public boolean isArrayType() {\n return StringUtils.containsAnyIgnoreCase(getType(), \"[]\", \"list\", \"array\");\n }\n\n public boolean isMapType() {\n return StringUtils.startsWithIgnoreCase(getType(), \"map\");\n }\n\n public boolean isArrayObject() {\n return isArrayType() && isObjectType(getLastParamType());\n }\n\n public boolean isArrayOrObject() {\n return isArrayType() || isObjectType();\n }\n\n private static final ImmutableMap<Predicate<String>, BiConsumer<DocField, String>> setters\n = ImmutableMap.<Predicate<String>, BiConsumer<DocField, String>>builder()\n .put(it -> StringUtils.equalsAny(it, \"\", \"参数\", \"属性\", \"参数名\", \"字段名\")\n || StringUtils.containsAny(it, \"名称\"),\n DocField::setName)\n .put(it -> it.contains(\"类型\"), DocField::setType)\n // 必须 必需 必填 必传\n .put(it -> it.contains(\"必\"), (it, v) -> it.setRequired(\"是\".equals(v) || \"true\".equalsIgnoreCase(v)))\n .put(it -> \"说明\".equals(it) || StringUtils.containsAny(it, \"描述\", \"备注\"), DocField::setDesc)\n .put(it -> it.contains(\"示例\"), DocField::setExample)\n .put(\"默认值\"::equals, DocField::setDefV)\n .put(\"最大长度\"::equals, DocField::setMaxLength)\n .build();\n\n public static BiConsumer<DocField, String> getByColumnName(String name) {\n for (final Entry<Predicate<String>, BiConsumer<DocField, String>> entry : setters.entrySet()) {\n if (entry.getKey().test(name)) {\n return entry.getValue();\n }\n }\n\n return null;\n }\n\n public boolean isUnknownTypeArray() {\n return StringUtils.equalsAnyIgnoreCase(getType(), \"[]\", \"list\", \"array\");\n }\n\n public Parameter toParameter(Supplier<Parameter> supplier) {\n return supplier.get()\n .name(getName())\n .description(getDesc())\n .example(getExample())\n .required(isRequired())\n .schema(toSchema());\n }\n\n private Schema schema;\n\n Schema toPrimitiveSchema(String type) {\n final Schema schema = toPrimitiveSchemaOrNull(type);\n if (schema == null) {\n throw new IllegalArgumentException(getName() + \" unknown type: \" + type);\n }\n\n return schema;\n }\n\n boolean isPrimitiveType(String type) {\n return toPrimitiveSchemaOrNull(type) != null;\n }\n\n Schema toPrimitiveSchemaOrNull(String type) {\n final String defV = getDefV();\n if (type.contains(\"bool\")) {\n return new BooleanSchema()._default(Boolean.parseBoolean(defV));\n }\n if (StringUtils.equalsAnyIgnoreCase(type, \"sting\", \"string\")) {\n return new StringSchema()._default(defV);\n }\n if (StringUtils.containsAny(type, \"int\", \"i32\")) {\n final IntegerSchema numberSchema = new IntegerSchema();\n if (NumberUtils.isCreatable(defV)) {\n numberSchema._default(NumberUtils.toInt(defV));\n }\n return numberSchema;\n }\n if (StringUtils.containsAny(type, \"i64\", \"int64\", \"long\")) {\n final IntegerSchema numberSchema = new IntegerSchema();\n numberSchema.type(\"integer\").format(\"int64\");\n if (NumberUtils.isCreatable(defV)) {\n numberSchema._default(NumberUtils.toLong(defV));\n }\n return numberSchema;\n }\n if (StringUtils.containsAny(type, \"float\", \"double\", \"number\")) {\n final Schema numberSchema = new Schema();\n numberSchema.type(\"number\").format(\"double\");\n if (NumberUtils.isCreatable(defV)) {\n numberSchema._default(NumberUtils.toDouble(defV));\n }\n return numberSchema;\n }\n if (isBinaryType()) {\n return new FileSchema();\n }\n\n return null;\n }\n\n String getLastParamType() {\n final String type = getType();\n StringTokenizer tokenizer = new StringTokenizer(type, \"[]<>(),\");\n\n String paramType = \"object\";\n while (tokenizer.hasMoreTokens()) {\n final String token = tokenizer.nextToken();\n if (!StringUtils.equalsAnyIgnoreCase(token, \"list\", \"array\")) {\n paramType = token;\n }\n }\n\n return paramType;\n }\n\n boolean isPrimitiveArrayType() {\n return isArrayType() && isPrimitiveType(getLastParamType());\n }\n\n Schema toObjectSchema() {\n final List<DocField> children = getChildren();\n final Schema schema;\n final DocField childField;\n if (children.size() == 1 && !(childField = children.get(0)).isObjectType() && !childField.isPrimitiveArrayType()) {\n schema = childField.toSchema();\n } else {\n final Map<String, Schema> properties = children\n .stream()\n .map(DocField::toSchema)\n // https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/data-analysis/component-analysis/component-overview-analysis\n // 离谱,竟然还有重名对象(字段数量不一样)所以用新的 schema(文档顺序)\n .collect(Collectors.toMap(Schema::getName, Function.identity(), (oldV, newV) -> newV));\n schema = new ObjectSchema().properties(properties);\n }\n\n return schema;\n }\n\n public Schema<?> toSchema() {\n\n if (this.schema == null) {\n\n final String type = getType();\n\n final String defV = getDefV();\n if (isArrayObject()) {\n setSchema(new ArraySchema().items(toObjectSchema())._default(defV));\n } else if (isArrayType()) {\n final String paramType = getLastParamType();\n final Schema schema = Optional.ofNullable(toPrimitiveSchemaOrNull(paramType))\n .orElseGet(this::toObjectSchema);\n setSchema(new ArraySchema().items(schema)._default(defV));\n } else if (isObjectType()) {\n setSchema(toObjectSchema()._default(\"{}\".equals(defV) ? null : defV));\n } else if (isMapType()) {\n final String paramType = getLastParamType();\n final Schema schema = Optional.ofNullable(toPrimitiveSchemaOrNull(paramType))\n .orElseGet(this::toObjectSchema);\n setSchema(new MapSchema().additionalProperties(schema)._default(defV));\n } else {\n setSchema(toPrimitiveSchema(type));\n }\n this.schema.name(getName()).example(getExample()).description(getDesc());\n }\n\n return schema;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj instanceof DocField) {\n return StringUtils.equals(getName(), ((DocField) obj).getName())\n && StringUtils.equals(getType(), ((DocField) obj).getType());\n }\n return false;\n }\n\n}"
},
{
"identifier": "GeneratorContent",
"path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/GeneratorContent.java",
"snippet": "@Slf4j\n@Getter\n@Builder\npublic class GeneratorContent {\n\n private final String title;\n\n private final String desc;\n\n private final HttpMethod method;\n\n @Singular(\"addServer\")\n private final List<Server> serverList;\n\n private final String path;\n\n String schemaPrefix;\n\n String getSchemaPrefix() {\n if (schemaPrefix == null) {\n final String[] pathArray = getPath().split(\"/\");\n final String path = String.join(\"_\", ArrayUtils.subarray(pathArray, pathArray.length - 2, pathArray.length));\n this.schemaPrefix = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, path);\n }\n return schemaPrefix;\n }\n\n private final String docPath;\n\n @Setter\n private String tag;\n\n private final Map<String, String> params;\n\n private final String requestJson;\n\n private final String responseJson;\n\n private final String errorResponseJson;\n\n @Default\n private final List<DocField> headFields = Collections.emptyList();\n\n @Default\n private final List<DocField> queryFields = Collections.emptyList();\n\n @Default\n private final List<DocField> bodyFields = Collections.emptyList();\n\n @Default\n private final List<DocField> respFields = Collections.emptyList();\n\n private final boolean respFieldNeedRebuild;\n\n private final boolean callback;\n\n @Default\n @Setter\n private Components components = new Components().schemas(Maps.newLinkedHashMap());\n\n RequestBody getRequestBody() {\n final List<DocField> bodyFields = getBodyFields();\n\n final String name;\n if (bodyFields.stream().anyMatch(DocField::isBinaryType)) {\n name = \"multipart/form-data\";\n } else {\n name = \"application/json\";\n }\n\n return new RequestBody()\n .required(!bodyFields.isEmpty())\n .description(getDesc())\n .content(\n new Content()\n .addMediaType(\n name,\n new MediaType()\n .schema(buildReqBodySchema())\n )\n );\n }\n\n Schema<Object> buildReqBodySchema() {\n final Schema<Object> responseSchema = new ObjectSchema().name(getSchemaPrefix() + \"Request\");\n\n getComponents().addSchemas(responseSchema.getName(), responseSchema);\n\n final Schema<Object> rootSchema = new ObjectSchema().$ref(responseSchema.getName());\n\n getBodyFields().forEach(docField -> {\n final Schema<?> schema = docField.toSchema();\n if (MapUtils.isNotEmpty(schema.getProperties()) || schema.getItems() != null) {\n addSchema(responseSchema, schema);\n } else {\n responseSchema.addProperty(docField.getName(), schema);\n }\n });\n\n return rootSchema;\n }\n\n Schema<Object> buildRespSchema() {\n\n final List<DocField> respFields = getRespFields();\n\n if (isRespFieldNeedRebuild()) {\n\n final Function<String, Object> pathReader = new Function<String, Object>() {\n\n final Supplier<DocumentContext> documentContext = Suppliers.memoize(() -> {\n try {\n return JsonPath.parse(getResponseJson());\n } catch (RuntimeException ignored) {\n return JsonPath\n .using(Configuration.defaultConfiguration().jsonProvider(new JsonSmartJsonProvider()))\n .parse(getResponseJson());\n }\n });\n\n @Override\n public Object apply(final String path) {\n final Object value = documentContext.get().read(path);\n if (value instanceof List) {\n if (((List<?>) value).isEmpty()) {\n return null;\n }\n }\n\n return value;\n }\n };\n\n final boolean hasOtherStructField = respFields.stream()\n .filter(it -> !StringUtils.equalsAny(it.getName(), \"extra\", \"data\"))\n .anyMatch(DocField::isObjectType);\n\n final Iterator<DocField> iterator = respFields.iterator();\n DocField lastStructDocField = null;\n\n while (iterator.hasNext()) {\n final DocField docField = iterator.next();\n final String name = docField.getName();\n if (docField.isArrayOrObject()) {\n Object value;\n if (!hasOtherStructField || (value = pathReader.apply(name)) != null) {\n lastStructDocField = docField;\n } else {\n\n lastStructDocField.getChildren().add(docField);\n docField.setParent(lastStructDocField);\n\n String fullName = docField.getFullName();\n value = pathReader.apply(fullName);\n if (value != null) {\n lastStructDocField = docField.isArrayOrObject() ? docField : docField.getParent();\n }\n }\n } else {\n if (hasOtherStructField && docField.getParent() == null) {\n docField.setParent(lastStructDocField);\n String fullName = docField.getFullName();\n Object value = pathReader.apply(fullName);\n\n // 文档 有的缺字段,和返回的 json 不一致\n if (value == null) {\n value = pathReader.apply(String.join(\".\", lastStructDocField.getParentName(), name));\n if (value != null) {\n lastStructDocField = lastStructDocField.getParent();\n }\n docField.setParent(lastStructDocField);\n }\n }\n\n if (lastStructDocField != null) {\n lastStructDocField.getChildren().add(docField);\n }\n\n }\n }\n }\n\n final Schema<Object> responseSchema = new ObjectSchema().name(getSchemaPrefix() + \"Response\");\n\n getComponents().addSchemas(responseSchema.getName(), responseSchema);\n\n final Schema<Object> rootSchema = new ObjectSchema().$ref(responseSchema.getName());\n\n respFields.forEach(docField -> {\n final Schema<?> schema = docField.toSchema();\n if (MapUtils.isNotEmpty(schema.getProperties()) || schema.getItems() != null) {\n addSchema(responseSchema, schema);\n } else {\n responseSchema.addProperty(docField.getName(), schema);\n }\n });\n\n return rootSchema;\n }\n\n void addSchema(Schema<?> parentSchema, Schema<?> schema) {\n final Schema<?> items = schema.getItems();\n\n final Map<String, Schema> properties = (items != null ? items : schema).getProperties();\n\n if (MapUtils.isEmpty(properties)) {\n return;\n }\n\n final String name = StringUtils.defaultIfBlank(schema.getName(), parentSchema.getName());\n\n String schemaFullName = getSchemaPrefix() + (CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name));\n\n // 通用的 extra 处理\n if (\"extra\".equals(name)) {\n schemaFullName = name;\n parentSchema.addProperty(name, new Schema().$ref(\"extra\"));\n }\n\n final Components components = getComponents();\n\n final Schema existSchema = components.getSchemas().get(schemaFullName);\n if (schema.equals(existSchema)) {\n parentSchema.addProperty(name, new Schema().$ref(existSchema.get$ref()));\n return;\n }\n\n if (schema instanceof ArraySchema) {\n // 当前字段是数组,修改为 ref\n parentSchema.addProperty(name,\n new ArraySchema()\n .example(schema.getExample())\n .description(schema.getDescription())\n .items(new Schema().$ref(schemaFullName))\n );\n\n // 并且将 ref 修改为 object\n schema = new ObjectSchema()\n .name(name)\n .properties(properties)\n .example(schema.getExample())\n .description(schema.getDescription());\n } else {\n parentSchema.addProperty(name, new ObjectSchema().$ref(schemaFullName));\n }\n\n components.addSchemas(schemaFullName, schema);\n\n for (final Schema value : properties.values()) {\n addSchema(schema, value);\n }\n\n }\n\n ApiResponses getApiResponses() {\n\n final Schema<Object> schema = buildRespSchema();\n\n return new ApiResponses()\n ._default(\n new ApiResponse()\n .description(getTitle())\n .content(\n new Content()\n .addMediaType(\"application/json\",\n new MediaType()\n .schema(schema)\n .addExamples(\"succeed\", new Example().value(getResponseJson()))\n .addExamples(\"failed\", new Example().value(getErrorResponseJson()))\n )\n )\n );\n }\n\n static final ConcurrentMap<String, String> operationCache = Maps.newConcurrentMap();\n\n String operationId() {\n final String path = getPath().replace('/', '_');\n final String methodName = getMethod().name().toLowerCase();\n\n // 候选的 operationId 中有 get post 等关键字,则删除该关键字\n final String operationId = Stream.of(HttpMethod.GET, HttpMethod.POST)\n .map(Enum::name)\n .filter(method -> StringUtils.containsIgnoreCase(path, method))\n .findFirst()\n .map(method -> path.toLowerCase().replace(method.toLowerCase(), \"\"))\n .map(it -> String.join(\"_\", methodName, it))\n .orElseGet(() -> String.join(\"_\", methodName, path));\n\n return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, operationId);\n }\n\n @SneakyThrows\n Operation getOperation() {\n\n final String docUrl = Misc.DOC_BASE_URL + getDocPath();\n final String desc = \"[\" + getTitle() + \"]\" + \"(\" + docUrl + \")\";\n\n final Operation operation = new Operation()\n .operationId(operationId())\n .addTagsItem(getTag())\n .description(desc);\n\n final List<DocField> queryFields = getQueryFields();\n\n if (CollectionUtils.isNotEmpty(queryFields)) {\n queryFields\n .stream()\n .map(it -> it.toParameter(QueryParameter::new))\n .forEach(operation::addParametersItem);\n }\n\n final List<DocField> headFields = getHeadFields();\n\n if (CollectionUtils.isNotEmpty(headFields)) {\n headFields.stream()\n .map(it -> it.toParameter(HeaderParameter::new))\n .forEach(operation::addParametersItem);\n }\n\n if (CollectionUtils.isNotEmpty(getBodyFields())) {\n operation.requestBody(getRequestBody());\n }\n\n operation.responses(getApiResponses());\n\n return operation;\n }\n\n public boolean accept() {\n // 不是 http api 文档\n if (getMethod() == null) {\n return false;\n }\n\n final String path = getPath();\n if (path == null || isCallback()) {\n// log.warn(\"docPath {}, path is null, ignored.\", Misc.DOC_BASE_URL + getDocPath());\n return false;\n }\n\n return true;\n }\n\n public PathItem toPathItem() {\n\n final PathItem pathItem = new PathItem();\n try {\n pathItem.operation(getMethod(), getOperation());\n } catch (Throwable e) {\n log.error(\"docPath {} , build Operation failed.\", Misc.DOC_BASE_URL + getDocPath(), e);\n throw e;\n }\n\n final List<Server> serverList = getServerList();\n if (CollectionUtils.isNotEmpty(serverList)) {\n pathItem.servers(serverList);\n }\n\n return pathItem;\n }\n\n}"
},
{
"identifier": "Misc",
"path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/Misc.java",
"snippet": "public interface Misc {\n\n String API_BASE_URL = \"https://open.douyin.com\";\n\n String DOC_BASE_URL = \"https://developer.open-douyin.com\";\n\n String DOC_URI = \"/docs/resource\";\n\n String DOC_LANGUAGE = \"zh-CN\";\n\n String DEFAULT_VALUE_KEY = \"固定值\";\n\n Gson GSON = new GsonBuilder().disableHtmlEscaping().create();\n\n}"
},
{
"identifier": "DocResponse",
"path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java",
"snippet": " @Getter\n @ToString\n @Setter\n class DocResponse {\n\n /**\n * content 类型,据观察 2=html.\n */\n private int type;\n\n private String title;\n\n private String keywords;\n\n private String description;\n\n private String content;\n\n private boolean isShowUpdateTime;\n\n private String updateTime;\n\n private String arcositeId;\n\n public String path;\n\n public boolean isJson() {\n return type == 1;\n }\n\n public boolean isMarkdownHeadHtmlBody() {\n return type == 2;\n }\n\n public GeneratorContent toGeneratorContext() {\n if (isJson()) {\n final ApiListResponse apiListResponse = ApiListResponse.fromJson(getContent());\n\n final String markdown = new JsonDocParser(apiListResponse.getOps()).toMarkdown();\n setContent(markdown);\n\n// return new MarkdownParser(this).parse();\n }\n\n // isMarkdownHeadHtmlBody\n return new HtmlParser(this).parse();\n }\n\n }"
}
] | import com.github.eahau.openapi.douyin.generator.DocField;
import com.github.eahau.openapi.douyin.generator.GeneratorContent;
import com.github.eahau.openapi.douyin.generator.GeneratorContent.GeneratorContentBuilder;
import com.github.eahau.openapi.douyin.generator.Misc;
import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.DocResponse;
import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.Streams;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configuration.Defaults;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
import com.vladsch.flexmark.ast.Heading;
import com.vladsch.flexmark.ast.HtmlBlock;
import com.vladsch.flexmark.ast.ListBlock;
import com.vladsch.flexmark.ast.Paragraph;
import com.vladsch.flexmark.ast.Text;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.servers.Server;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 7,071 | /*
* Copyright 2023 [email protected]
*
* 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.github.eahau.openapi.douyin.generator.parser;
@Slf4j
public class HtmlParser {
static final Parser PARSER = Parser.builder()
.extensions(Collections.singletonList(TablesExtension.create()))
.build();
static {
Configuration.setDefaults(
new Defaults() {
final JsonProvider jsonProvider = new GsonJsonProvider(Misc.GSON);
final MappingProvider mappingProvider = new GsonMappingProvider(Misc.GSON);
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public Set<Option> options() {
return EnumSet.of(Option.SUPPRESS_EXCEPTIONS);
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
}
);
}
final DocResponse response;
final com.vladsch.flexmark.util.ast.Document markdown;
| /*
* Copyright 2023 [email protected]
*
* 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.github.eahau.openapi.douyin.generator.parser;
@Slf4j
public class HtmlParser {
static final Parser PARSER = Parser.builder()
.extensions(Collections.singletonList(TablesExtension.create()))
.build();
static {
Configuration.setDefaults(
new Defaults() {
final JsonProvider jsonProvider = new GsonJsonProvider(Misc.GSON);
final MappingProvider mappingProvider = new GsonMappingProvider(Misc.GSON);
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public Set<Option> options() {
return EnumSet.of(Option.SUPPRESS_EXCEPTIONS);
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
}
);
}
final DocResponse response;
final com.vladsch.flexmark.util.ast.Document markdown;
| final GeneratorContentBuilder builder = GeneratorContent.builder(); | 1 | 2023-10-07 09:09:15+00:00 | 8k |
Aywen1/wispy | src/fr/nicolas/wispy/Panels/GamePanel.java | [
{
"identifier": "Runner",
"path": "src/fr/nicolas/wispy/Runner.java",
"snippet": "public class Runner implements Runnable {\n\n\tprivate boolean isRunning = false;\n\tprivate GamePanel gamePanel;\n\tprivate int maxFps = 80;\n\tprivate long waitTime = 4;\n\n\tpublic Runner(GamePanel gamePanel) {\n\t\tthis.gamePanel = gamePanel;\n\t\tstart();\n\t}\n\n\tprivate void start() {\n\t\tisRunning = true;\n\t\tnew Thread(this).start();\n\t}\n\n\tpublic void run() {\n\t\twhile (isRunning) {\n\t\t\tlong startTime, differenceTime;\n\t\t\tmaxFps = 1000 / maxFps;\n\n\t\t\twhile (isRunning) {\n\t\t\t\tstartTime = System.nanoTime();\n\n\t\t\t\tgamePanel.refresh();\n\t\t\t\tgamePanel.repaint();\n\t\t\t\t\n\t\t\t\tdifferenceTime = System.nanoTime() - startTime;\n\t\t\t\twaitTime = maxFps - differenceTime / 1000000;\n\n\t\t\t\tif (waitTime < 4) {\n\t\t\t\t\twaitTime = 4;\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(waitTime);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic long getWaitTime() {\n\t\treturn waitTime;\n\t}\n\t\n}"
},
{
"identifier": "MainFrame",
"path": "src/fr/nicolas/wispy/Frames/MainFrame.java",
"snippet": "public class MainFrame extends JFrame {\n\n\tprivate WPanel panel;\n\tpublic static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720;\n\n\tpublic MainFrame() {\n\t\tthis.setTitle(\"Wispy\");\n\t\tthis.setSize(INIT_WIDTH, INIT_HEIGHT);\n\t\tthis.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT));\n\t\tthis.setLocationRelativeTo(null);\n\t\tthis.setResizable(true);\n\t\tthis.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\tpanel = new MenuPanel(this.getBounds(), this);\n\n\t\tthis.addComponentListener(new ComponentListener() {\n\t\t\tpublic void componentResized(ComponentEvent e) {\n\t\t\t\tpanel.setFrameBounds(getBounds());\n\t\t\t}\n\n\t\t\tpublic void componentHidden(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentMoved(ComponentEvent e) {\n\t\t\t}\n\n\t\t\tpublic void componentShown(ComponentEvent e) {\n\t\t\t}\n\t\t});\n\n\t\tthis.setContentPane(panel);\n\n\t\tthis.setVisible(true);\n\t}\n\n\tpublic void newGame() {\n\t\tpanel = new GamePanel(this.getBounds(), true);\n\t\tthis.setContentPane(panel);\n\t\tthis.validate();\n\t\tpanel.requestFocus();\n\t}\n\n}"
},
{
"identifier": "Player",
"path": "src/fr/nicolas/wispy/Panels/Components/Game/Player.java",
"snippet": "public class Player extends Rectangle {\n\n\tprivate BufferedImage playerStopImg, playerWalk1Img, playerWalk2Img;\n\tprivate boolean isFalling = false, isJumping = false, isWalking = false, isToRight = true, canGoLeft = true,\n\t\t\tcanGoRight = true, canGoUp = true;\n\tprivate int jumpNum = 1, walkNum = 0;\n\tprivate GamePanel gamePanel;\n\n\tpublic Player(BufferedImage playerStopImg, BufferedImage playerWalk1Img, BufferedImage playerWalk2Img,\n\t\t\tGamePanel gamePanel) {\n\t\tthis.playerStopImg = playerStopImg;\n\t\tthis.playerWalk1Img = playerWalk1Img;\n\t\tthis.playerWalk2Img = playerWalk2Img;\n\t\tthis.gamePanel = gamePanel;\n\t\tthis.width = GamePanel.BLOCK_SIZE;\n\t\tthis.height = GamePanel.BLOCK_SIZE * 2;\n\t}\n\n\tpublic void refresh(int playerWidth, int playerHeight, int playerX, int playerY) {\n\t\tgamePanel.getMapManager().refreshPaintAllDisplayedBlocks(null, RefreshPaintMap.COLLISION, gamePanel.getWidth(),\n\t\t\t\tgamePanel.getHeight(), gamePanel.getNewBlockWidth(), gamePanel.getNewBlockHeight(), playerWidth,\n\t\t\t\tplayerHeight, playerX, playerY, gamePanel, null);\n\n\t\t// Déplacements\n\t\tif (isWalking) {\n\t\t\tif (isToRight && canGoRight) {\n\t\t\t\twalkNum++;\n\t\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\t\tif (canGoRight) {\n\t\t\t\t\t\tx += 1;\n\t\t\t\t\t\tgamePanel.getMapManager().refreshPaintAllDisplayedBlocks(null, RefreshPaintMap.COLLISION,\n\t\t\t\t\t\t\t\tgamePanel.getWidth(), gamePanel.getHeight(), gamePanel.getNewBlockWidth(),\n\t\t\t\t\t\t\t\tgamePanel.getNewBlockHeight(), playerWidth, playerHeight, playerX, playerY, gamePanel,\n\t\t\t\t\t\t\t\tnull);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!isToRight && canGoLeft) {\n\t\t\t\twalkNum++;\n\t\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\t\tif (canGoLeft) {\n\t\t\t\t\t\tx -= 1;\n\t\t\t\t\t\tgamePanel.getMapManager().refreshPaintAllDisplayedBlocks(null, RefreshPaintMap.COLLISION,\n\t\t\t\t\t\t\t\tgamePanel.getWidth(), gamePanel.getHeight(), gamePanel.getNewBlockWidth(),\n\t\t\t\t\t\t\t\tgamePanel.getNewBlockHeight(), playerWidth, playerHeight, playerX, playerY, gamePanel,\n\t\t\t\t\t\t\t\tnull);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (walkNum > 20) {\n\t\t\twalkNum = 1;\n\t\t}\n\n\t\t// Jump\n\t\tif (isJumping && canGoUp) {\n\t\t\tif (jumpNum != 15) {\n\t\t\t\tfor (int i = 0; i < 8 - jumpNum / 2; i++) {\n\t\t\t\t\tif (canGoUp) {\n\t\t\t\t\t\ty -= 1;\n\t\t\t\t\t\tgamePanel.getMapManager().refreshPaintAllDisplayedBlocks(null, RefreshPaintMap.COLLISION,\n\t\t\t\t\t\t\t\tgamePanel.getWidth(), gamePanel.getHeight(), gamePanel.getNewBlockWidth(),\n\t\t\t\t\t\t\t\tgamePanel.getNewBlockHeight(), playerWidth, playerHeight, playerX, playerY, gamePanel,\n\t\t\t\t\t\t\t\tnull);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tjumpNum++;\n\t\t\t} else {\n\t\t\t\tjumpNum = 1;\n\t\t\t\tisJumping = false;\n\t\t\t}\n\t\t}\n\n\t\tif (!canGoUp) {\n\t\t\tjumpNum = 1;\n\t\t\tisJumping = false;\n\t\t}\n\n\t\t// Gravité\n\t\tif (isFalling && !isJumping) {\n\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\tif (isFalling) {\n\t\t\t\t\ty += 1;\n\t\t\t\t\tgamePanel.getMapManager().refreshPaintAllDisplayedBlocks(null, RefreshPaintMap.COLLISION,\n\t\t\t\t\t\t\tgamePanel.getWidth(), gamePanel.getHeight(), gamePanel.getNewBlockWidth(),\n\t\t\t\t\t\t\tgamePanel.getNewBlockHeight(), playerWidth, playerHeight, playerX, playerY, gamePanel,\n\t\t\t\t\t\t\tnull);\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void paint(Graphics g, int x, int y, int width, int height) {\n\t\t// TODO: iswalking inutilisable car toujours faux donc frame playerStopImg n'est\n\t\t// pas affiché (toujours walk)\n\t\tif (isJumping) {\n\t\t\tdrawImg(g, playerWalk2Img, x, y, width, height);\n\t\t} else if (isFalling || !isWalking || !canGoRight || !canGoLeft) {\n\t\t\tdrawImg(g, playerStopImg, x, y, width, height);\n\t\t} else if (walkNum <= 10) {\n\t\t\tdrawImg(g, playerWalk1Img, x, y, width, height);\n\t\t} else if (!isJumping && !isFalling && walkNum <= 20) {\n\t\t\tdrawImg(g, playerWalk2Img, x, y, width, height);\n\t\t}\n\t}\n\n\tprivate void drawImg(Graphics g, BufferedImage img, int x, int y, int width, int height) {\n\t\tif (isToRight) {\n\t\t\tg.drawImage(img, x, y, width, height, null);\n\t\t} else {\n\t\t\tg.drawImage(img, x + width, y, -width, height, null);\n\t\t}\n\t}\n\n\tpublic void setFalling(boolean isFalling) {\n\t\tthis.isFalling = isFalling;\n\t}\n\n\tpublic void setWalking(boolean isWalking) {\n\t\tthis.isWalking = isWalking;\n\t}\n\n\tpublic void setToRight(boolean isToRight) {\n\t\tthis.isToRight = isToRight;\n\t}\n\n\tpublic void setJumping(boolean isJumping) {\n\t\tif (isJumping && !isFalling) {\n\t\t\tthis.isJumping = isJumping;\n\t\t}\n\t}\n\n\tpublic void setCanGoLeft(boolean canGoLeft) {\n\t\tthis.canGoLeft = canGoLeft;\n\t}\n\n\tpublic void setCanGoRight(boolean canGoRight) {\n\t\tthis.canGoRight = canGoRight;\n\t}\n\n\tpublic void setCanGoUp(boolean canGoUp) {\n\t\tthis.canGoUp = canGoUp;\n\t}\n\n}"
},
{
"identifier": "EscapeMenu",
"path": "src/fr/nicolas/wispy/Panels/Components/Menu/EscapeMenu.java",
"snippet": "public class EscapeMenu {\n\n\t// Escape menu in game\n\n\tpublic void paint(Graphics g, int frameHeight) {\n\t\tGraphics2D g2d = (Graphics2D) g;\n\t\tg2d.setColor(new Color(0, 0, 0, 200));\n\t\tg2d.fillRect(0, 0, 250, frameHeight);\n\t\tg2d.setColor(new Color(255, 255, 255, 200));\n\t\tg2d.setFont(new Font(\"Arial\", Font.PLAIN, 40));\n\t\tg2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);\n\t\tg2d.drawString(\"Options\", 20, 55);\n\t}\n\n}"
},
{
"identifier": "WPanel",
"path": "src/fr/nicolas/wispy/Panels/Components/Menu/WPanel.java",
"snippet": "public abstract class WPanel extends JPanel {\n\n\tprotected Rectangle frameBounds;\n\n\tpublic WPanel(Rectangle frameBounds) {\n\t\tthis.frameBounds = frameBounds;\n\t}\n\n\tpublic void setFrameBounds(Rectangle frameBounds) {\n\n\t}\n\n}"
},
{
"identifier": "MapManager",
"path": "src/fr/nicolas/wispy/Panels/Fonctions/MapManager.java",
"snippet": "public class MapManager {\n\n\tprivate int mapBLeftNum = -1, mapBCenterNum = 0, mapBRightNum = 1;\n\tprivate Block[][] mapBLeft, mapBRight, mapBCenter;\n\tprivate String worldName;\n\tprivate Player player;\n\tprivate boolean hasFoundFallingCollision = false, hasFoundUpCollision = false, hasFoundRightCollision = false,\n\t\t\thasFoundLeftCollision = false;\n\n\t// Random generation variables\n\tprivate int state = 0, changeStateNum = 5, currentNum = 0, lastY = 10, lastState = 0;\n\n\tpublic enum RefreshPaintMap {\n\t\tPAINT, COLLISION, SELECTION;\n\t}\n\n\tpublic MapManager(Player player) {\n\t\tthis.player = player;\n\t}\n\n\tpublic void loadWorld(String worldName) {\n\t\tthis.worldName = worldName;\n\t\tif (!new File(\"Wispy/worlds/\" + worldName).exists()) {\n\t\t\tnew File(\"Wispy/worlds/\" + worldName).mkdirs();\n\n\t\t\t// Génération des maps\n\t\t\tint mapSize = 2; // Nombre de maps crées à gauche et à droite des 3 maps centrales\n\t\t\t\t\t\t\t\t// Ainsi: nombre total de map = mapSize*2+3\n\n\t\t\tmapBLeftNum = -1;\n\t\t\tmapBLeft = generateMap(mapBLeftNum);\n\t\t\tsaveMap(mapBLeft, mapBLeftNum);\n\n\t\t\tmapBCenterNum = 0;\n\t\t\tmapBCenter = generateMap(mapBCenterNum);\n\t\t\tsaveMap(mapBCenter, mapBCenterNum);\n\n\t\t\tmapBRightNum = 1;\n\t\t\tmapBRight = generateMap(mapBRightNum);\n\t\t\tsaveMap(mapBRight, mapBRightNum);\n\n\t\t\tfor (int i = -2; i >= -mapSize - 1; i--) {\n\t\t\t\tsaveMap(generateMap(i), i);\n\t\t\t}\n\n\t\t\tfor (int i = 2; i <= mapSize + 1; i++) {\n\t\t\t\tsaveMap(generateMap(i), i);\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Chargement des maps (pour l'instant les 3 principales mais TODO: système pour\n\t\t\t// charger les coords du joueurs pour charger les 3 maps par rapport à sa\n\t\t\t// position)\n\n\t\t\tmapBLeftNum = -1;\n\t\t\tmapBLeft = loadMap(mapBLeftNum);\n\n\t\t\tmapBCenterNum = 0;\n\t\t\tmapBCenter = loadMap(mapBCenterNum);\n\n\t\t\tmapBRightNum = 1;\n\t\t\tmapBRight = loadMap(mapBRightNum);\n\n\t\t}\n\n\t\t// Player spawnpoint\n\t\tplayer.x = 0;\n\t\tplayer.y = getPlayerSpawnY();\n\t}\n\n\tpublic int getPlayerSpawnY() {\n\t\t// TODO: Système à refaire\n\t\tint y = 0;\n\t\twhile (mapBCenter[0][y] == null) {\n\t\t\ty++;\n\t\t}\n\t\treturn y;\n\t}\n\n\tpublic void newLoadingMapThread(Runner runner, GamePanel gamePanel) {\n\t\tThread loadNextMap = new Thread(new Runnable() {\n\n\t\t\tprivate void saveMap(Block[][] mapToSave, int num) {\n\t\t\t\ttry {\n\t\t\t\t\tObjectOutputStream objectOutputS = new ObjectOutputStream(\n\t\t\t\t\t\t\tnew FileOutputStream(\"Wispy/worlds/\" + worldName + \"/\" + num + \".wmap\"));\n\t\t\t\t\tobjectOutputS.writeObject(mapToSave);\n\t\t\t\t\tobjectOutputS.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprivate Block[][] loadMap(int num) {\n\t\t\t\tBlock[][] loadedMap = null;\n\t\t\t\ttry {\n\t\t\t\t\tObjectInputStream objectInputS = new ObjectInputStream(\n\t\t\t\t\t\t\tnew FileInputStream(\"Wispy/worlds/\" + worldName + \"/\" + num + \".wmap\"));\n\t\t\t\t\ttry {\n\t\t\t\t\t\tloadedMap = (Block[][]) objectInputS.readObject();\n\t\t\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tobjectInputS.close();\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\treturn loadedMap;\n\t\t\t}\n\n\t\t\tpublic void run() {\n\t\t\t\twhile (true) {\n\t\t\t\t\tint newX;\n\t\t\t\t\tif (mapBRight != null) {\n\t\t\t\t\t\tnewX = ((mapBRight.length / 2 + mapBRightNum * mapBRight.length) * gamePanel.getNewBlockWidth())\n\t\t\t\t\t\t\t\t- (int) (player.getX() * gamePanel.getNewBlockWidth() / GamePanel.BLOCK_SIZE);\n\t\t\t\t\t\tif (newX >= 0 && newX <= gamePanel.getWidth()) {\n\t\t\t\t\t\t\tsaveMap(mapBLeft, mapBLeftNum);\n\t\t\t\t\t\t\tmapBLeft = mapBCenter;\n\t\t\t\t\t\t\tmapBLeftNum = mapBCenterNum;\n\t\t\t\t\t\t\tmapBCenter = mapBRight;\n\t\t\t\t\t\t\tmapBCenterNum = mapBRightNum;\n\n\t\t\t\t\t\t\tif (new File(\"Wispy/worlds/\" + worldName + \"/\" + (mapBRightNum + 1) + \".wmap\").exists()) {\n\t\t\t\t\t\t\t\tmapBRightNum++;\n\t\t\t\t\t\t\t\tmapBRight = loadMap(mapBRightNum);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tmapBRight = null;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (mapBLeft != null) {\n\t\t\t\t\t\tnewX = ((mapBLeft.length / 2 + mapBLeftNum * mapBLeft.length) * gamePanel.getNewBlockWidth())\n\t\t\t\t\t\t\t\t- (int) (player.getX() * gamePanel.getNewBlockWidth() / GamePanel.BLOCK_SIZE);\n\t\t\t\t\t\tif (newX >= 0 && newX <= gamePanel.getWidth()) {\n\t\t\t\t\t\t\tsaveMap(mapBRight, mapBRightNum);\n\t\t\t\t\t\t\tmapBRight = mapBCenter;\n\t\t\t\t\t\t\tmapBRightNum = mapBCenterNum;\n\t\t\t\t\t\t\tmapBCenter = mapBLeft;\n\t\t\t\t\t\t\tmapBCenterNum = mapBLeftNum;\n\n\t\t\t\t\t\t\tif (new File(\"Wispy/worlds/\" + worldName + \"/\" + (mapBLeftNum - 1) + \".wmap\").exists()) {\n\t\t\t\t\t\t\t\tmapBLeftNum--;\n\t\t\t\t\t\t\t\tmapBLeft = loadMap(mapBLeftNum);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tmapBLeft = null;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tint waitTime = (int) runner.getWaitTime();\n\t\t\t\t\tif (waitTime < 4) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tThread.sleep(4);\n\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tThread.sleep(waitTime);\n\t\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tloadNextMap.start();\n\t}\n\n\tprivate void saveMap(Block[][] mapToSave, int num) {\n\t\ttry {\n\t\t\tObjectOutputStream objectOutputS = new ObjectOutputStream(\n\t\t\t\t\tnew FileOutputStream(\"Wispy/worlds/\" + worldName + \"/\" + num + \".wmap\"));\n\t\t\tobjectOutputS.writeObject(mapToSave);\n\t\t\tobjectOutputS.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate Block[][] loadMap(int num) {\n\t\tBlock[][] loadedMap = null;\n\t\ttry {\n\t\t\tObjectInputStream objectInputS = new ObjectInputStream(\n\t\t\t\t\tnew FileInputStream(\"Wispy/worlds/\" + worldName + \"/\" + num + \".wmap\"));\n\t\t\ttry {\n\t\t\t\tloadedMap = (Block[][]) objectInputS.readObject();\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tobjectInputS.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn loadedMap;\n\t}\n\n\tprivate Block[][] generateMap(int num) {\n\t\tBlock[][] mapToGenerate = new Block[82][100];\n\n\t\tint newY = 0;\n\n\t\tfor (int x = 0; x < mapToGenerate.length; x++) {\n\t\t\t// TODO: Algo de génération\n\t\t\t// TODO: Actuellement: génération map par map au lieu de l'ensemble des maps\n\t\t\t// d'un coup ... (problèmes si grottes, montagnes, bâtiments ...)\n\n\t\t\tif (random(1, 2) == 1) {\n\t\t\t\tif (state == 0) {\n\t\t\t\t\tnewY = random(lastY - 1, lastY + 1);\n\t\t\t\t} else if (state == 1) {\n\t\t\t\t\tif (random(1, 3) == 1) {\n\t\t\t\t\t\tnewY = random(lastY, lastY + 3);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewY = random(lastY, lastY + 2);\n\t\t\t\t\t}\n\t\t\t\t} else if (state == 2) {\n\t\t\t\t\tif (random(1, 3) == 1) {\n\t\t\t\t\t\tnewY = random(lastY, lastY - 3);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewY = random(lastY, lastY - 2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewY = lastY;\n\t\t\t}\n\n\t\t\tif (currentNum == changeStateNum) {\n\t\t\t\tcurrentNum = 0;\n\t\t\t\tchangeStateNum = random(3, 7);\n\n\t\t\t\tif (random(1, 3) == 1) {\n\t\t\t\t\tstate = random(1, 2);\n\t\t\t\t} else {\n\t\t\t\t\tstate = 0;\n\t\t\t\t}\n\n\t\t\t\tif (lastState == state) {\n\t\t\t\t\tif (random(1, 3) != 1) {\n\t\t\t\t\t\tif (state == 1) {\n\t\t\t\t\t\t\tstate = 2;\n\t\t\t\t\t\t} else if (state == 2) {\n\t\t\t\t\t\t\tstate = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlastState = state;\n\n\t\t\t} else {\n\t\t\t\tcurrentNum++;\n\t\t\t}\n\n\t\t\tif (newY > 25) { // Profondeur y max\n\t\t\t\tnewY = 25;\n\t\t\t} else if (newY < 10) { // Hauteur y max\n\t\t\t\tnewY = 10;\n\t\t\t}\n\n\t\t\tlastY = newY;\n\t\t\tmapToGenerate[x][newY] = new Block(BlockID.GRASS);\n\n\t\t\tfor (int y = newY + 1; y < mapToGenerate[0].length; y++) {\n\n\t\t\t\tif (y < newY + 3) {\n\t\t\t\t\tmapToGenerate[x][y] = new Block(BlockID.DIRT);\n\t\t\t\t} else {\n\t\t\t\t\tmapToGenerate[x][y] = new Block(BlockID.STONE);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn mapToGenerate;\n\n\t}\n\n\tprivate int random(int min, int max) {\n\t\treturn (int) (Math.random() * (max - min + 1) + min);\n\t}\n\n\tpublic void refreshPaintAllDisplayedBlocks(Graphics g, RefreshPaintMap mode, int width, int height,\n\t\t\tint newBlockWidth, int newBlockHeight, int playerX, int playerY, int playerWidth, int playerHeight,\n\t\t\tGamePanel gamePanel, Point mouseLocation) {\n\t\t// Si mode:\n\t\t// = 1: Paint\n\t\t// = 2: Test collisions\n\t\t// = 3: Block selection\n\t\trefreshPaintMapDisplayedBlocks(g, mode, mapBCenter, mapBCenterNum, width, height, newBlockWidth, newBlockHeight,\n\t\t\t\tgamePanel, playerWidth, playerHeight, playerX, playerY, mouseLocation);\n\t\trefreshPaintMapDisplayedBlocks(g, mode, mapBLeft, mapBLeftNum, width, height, newBlockWidth, newBlockHeight,\n\t\t\t\tgamePanel, playerWidth, playerHeight, playerX, playerY, mouseLocation);\n\t\trefreshPaintMapDisplayedBlocks(g, mode, mapBRight, mapBRightNum, width, height, newBlockWidth, newBlockHeight,\n\t\t\t\tgamePanel, playerWidth, playerHeight, playerX, playerY, mouseLocation);\n\n\t\thasFoundFallingCollision = false;\n\t\thasFoundUpCollision = false;\n\t\thasFoundRightCollision = false;\n\t\thasFoundLeftCollision = false;\n\t}\n\n\t// TODO: Fonction a réorganiser\n\tprivate void refreshPaintMapDisplayedBlocks(Graphics g, RefreshPaintMap mode, Block[][] mapB, int times, int width,\n\t\t\tint height, int newBlockWidth, int newBlockHeight, GamePanel gamePanel, int playerWidth, int playerHeight,\n\t\t\tint playerX, int playerY, Point mouseLocation) {\n\t\t// Voir modes dans la fonction \"refreshPaintAllDisplayedBlocks\"\n\n\t\tif (mapB != null) {\n\t\t\tfor (int x = 0; x < mapB.length; x++) {\n\t\t\t\tint newX = ((x + times * mapB.length) * newBlockWidth)\n\t\t\t\t\t\t- (int) (player.getX() / GamePanel.BLOCK_SIZE * newBlockWidth);\n\t\t\t\tif (newX >= -350 && newX <= width + 350) {\n\t\t\t\t\tfor (int y = 0; y < mapB[0].length; y++) {\n\t\t\t\t\t\tint newY = (y * newBlockHeight) - (int) (player.getY() / GamePanel.BLOCK_SIZE * newBlockHeight);\n\t\t\t\t\t\tif (newY >= -350 && newY <= height + 350) {\n\t\t\t\t\t\t\tif (mapB[x][y] != null) {\n\t\t\t\t\t\t\t\tif (mode == RefreshPaintMap.PAINT) {\n\t\t\t\t\t\t\t\t\t// Paint\n\t\t\t\t\t\t\t\t\tmapB[x][y].paint(g, newX, newY, newBlockWidth, newBlockHeight);\n\t\t\t\t\t\t\t\t} else if (mode == RefreshPaintMap.COLLISION) {\n\t\t\t\t\t\t\t\t\t// Test des collisions avec le joueur\n\t\t\t\t\t\t\t\t\tif (!hasFoundFallingCollision) {\n\t\t\t\t\t\t\t\t\t\tif (new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX, playerY + playerHeight))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight).contains(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew Point(playerX + playerWidth - 1, playerY + playerHeight))) {\n\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setFalling(false);\n\t\t\t\t\t\t\t\t\t\t\thasFoundFallingCollision = true;\n\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setFalling(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (!hasFoundUpCollision) {\n\t\t\t\t\t\t\t\t\t\tif (new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX, playerY - 1))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX + playerWidth - 1, playerY - 1))) {\n\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoUp(false);\n\t\t\t\t\t\t\t\t\t\t\thasFoundUpCollision = true;\n\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoUp(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (!hasFoundRightCollision) {\n\t\t\t\t\t\t\t\t\t\tif (new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX + playerWidth, playerY))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight).contains(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew Point(playerX + playerWidth, playerY + playerHeight - 1))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight).contains(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew Point(playerX + playerWidth, playerY + playerHeight / 2))) {\n\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoRight(false);\n\t\t\t\t\t\t\t\t\t\t\thasFoundRightCollision = true;\n\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoRight(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (!hasFoundLeftCollision) {\n\t\t\t\t\t\t\t\t\t\tif (new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX - 1, playerY))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX - 1, playerY + playerHeight - 1))\n\t\t\t\t\t\t\t\t\t\t\t\t|| new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.contains(new Point(playerX - 1, playerY + playerHeight / 2))) {\n\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoLeft(false);\n\t\t\t\t\t\t\t\t\t\t\thasFoundLeftCollision = true;\n\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tgamePanel.getPlayer().setCanGoLeft(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (mode == RefreshPaintMap.SELECTION) {\n\t\t\t\t\t\t\t\t\t// Block selection\n\t\t\t\t\t\t\t\t\tif (new Rectangle(newX, newY, newBlockWidth, newBlockHeight)\n\t\t\t\t\t\t\t\t\t\t\t.contains(mouseLocation)) {\n\t\t\t\t\t\t\t\t\t\tg.setColor(new Color(255, 255, 255, 50));\n\t\t\t\t\t\t\t\t\t\tg.drawRect(newX, newY, newBlockWidth, newBlockHeight);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (newY > 0) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (newX > 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}"
},
{
"identifier": "RefreshPaintMap",
"path": "src/fr/nicolas/wispy/Panels/Fonctions/MapManager.java",
"snippet": "public enum RefreshPaintMap {\n\tPAINT, COLLISION, SELECTION;\n}"
}
] | import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import fr.nicolas.wispy.Runner;
import fr.nicolas.wispy.Frames.MainFrame;
import fr.nicolas.wispy.Panels.Components.Game.Player;
import fr.nicolas.wispy.Panels.Components.Menu.EscapeMenu;
import fr.nicolas.wispy.Panels.Components.Menu.WPanel;
import fr.nicolas.wispy.Panels.Fonctions.MapManager;
import fr.nicolas.wispy.Panels.Fonctions.MapManager.RefreshPaintMap; | 6,914 | package fr.nicolas.wispy.Panels;
public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {
public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;
private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; | package fr.nicolas.wispy.Panels;
public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {
public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;
private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; | private Runner runner; | 0 | 2023-10-13 13:10:56+00:00 | 8k |
PfauMC/CyanWorld | cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/commands/CmdNbt.java | [
{
"identifier": "ItemBuilder",
"path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/api/ItemBuilder.java",
"snippet": "public class ItemBuilder {\n public ItemStack itemStack;\n public ItemMeta itemMeta;\n\n public ItemBuilder(ItemStack itemStack) {\n this.itemStack = itemStack;\n this.itemMeta = itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material) {\n this.itemStack = new ItemStack(material);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material, int amount) {\n this.itemStack = new ItemStack(material, amount);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder(Material material, int amount, int dura) {\n new ItemBuilder(material, amount, (short) dura);\n }\n\n public ItemBuilder(Material material, int amount, short dura) {\n this.itemStack = new ItemStack(material, amount, dura);\n this.itemMeta = this.itemStack.getItemMeta();\n }\n\n public ItemBuilder name(String name) {\n this.itemMeta.setDisplayName(name != null ? \"\\u00a7f\" + name : null);\n return this;\n }\n\n public ItemBuilder locname(String locname) {\n this.itemMeta.setLocalizedName(locname);\n return this;\n }\n\n public ItemBuilder amount(int amount) {\n this.itemStack.setAmount(amount);\n return this;\n }\n\n public ItemBuilder dura(int dura) {\n return this.dura((short) dura);\n }\n\n public ItemBuilder dura(short dura) {\n this.itemStack.setDurability(dura);\n return this;\n }\n\n public ItemBuilder lore(List<String> lore) {\n this.itemMeta.setLore(lore);\n return this;\n }\n\n public ItemBuilder unbreakable(boolean unbreakable) {\n this.itemMeta.setUnbreakable(unbreakable);\n return this;\n }\n\n public ItemBuilder enchant(Enchantment enchant, int lvl) {\n this.itemStack.addUnsafeEnchantment(enchant, lvl);\n return this;\n }\n\n public /* varargs */ ItemBuilder itemflag(ItemFlag... itemFlags) {\n this.itemMeta.addItemFlags(itemFlags);\n return this;\n }\n\n public ItemStack build() {\n this.itemStack.setItemMeta(this.itemMeta);\n return this.itemStack;\n }\n}"
},
{
"identifier": "WorldManager",
"path": "cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/WorldManager.java",
"snippet": "public class WorldManager {\n\n public static PotionEffect lobbyspeed = new PotionEffect(PotionEffectType.SPEED, 99999, 2);\n\n public static World generateEmptyWorld(String name, int size, boolean autoSave) {\n new WorldCreator(name)\n .type(WorldType.FLAT)\n .seed(0)\n .generatorSettings(\"3;minecraft:air\")\n .generateStructures(false)\n .createWorld();\n World world = server.getWorld(name);\n world.setGameRuleValue(\"doMobSpawning\", \"false\");\n world.setGameRuleValue(\"doDaylightCycle\", \"false\");\n world.setGameRuleValue(\"doWeatherCycle\", \"false\");\n WorldBorder worldBorder = world.getWorldBorder();\n worldBorder.setCenter(0.5, 0.5);\n worldBorder.setWarningDistance(0);\n worldBorder.setSize(size + 1);\n world.setAutoSave(autoSave);\n world.setPVP(false);\n return world;\n }\n\n public static World generateWorld(String name, WorldType worldType, long seed, String generatorSettings, boolean generateStructures, int size, boolean autoSave) {\n new WorldCreator(name)\n .type(worldType)\n .seed(seed)\n .generatorSettings(generatorSettings)\n .generateStructures(generateStructures)\n .createWorld();\n World world = server.getWorld(name);\n world.setGameRuleValue(\"doMobSpawning\", \"false\");\n world.setGameRuleValue(\"doDaylightCycle\", \"false\");\n world.setGameRuleValue(\"doWeatherCycle\", \"false\");\n WorldBorder worldBorder = world.getWorldBorder();\n worldBorder.setCenter(0.5, 0.5);\n worldBorder.setWarningDistance(0);\n worldBorder.setSize(size + 1);\n world.setAutoSave(autoSave);\n world.setPVP(false);\n return world;\n }\n\n public static World teleportToWorld(Player player, String worldname) {\n if (worldname == null) {\n System.out.print(\"CyanUniverse.WorldManager::teleportToWorld - worldname is null\");\n return null;\n }\n if (player == null) {\n System.out.print(\"CyanUniverse.WorldManager::teleportToWorld - player is null\");\n return null;\n }\n World world = server.getWorld(worldname);\n\n //int size = Utils.playerIsDonator(worldname.split(\"#\")[0]) ? 256 : 128;\n\n String playeruuid = player.getUniqueId().toString();\n String ownername = worldscfg.getString(worldname + \".owner\", \"?\");\n String worlddisplayname = CyanUniverse.worldscfg.getString(worldname + \".name\", \"Мир #\" + worldname.split(\"#\")[1] + \" \" + ownername);\n\n int size = worldscfg.getInt(worldname + \".size\", (Utils.playerIsDonator(playeruuid) ? 512 : 256));\n\n boolean initworld = worldname.startsWith(playeruuid);\n\n TextComponent header = new TextComponent(\"§2KiwiServer\");\n TextComponent footer = new TextComponent(\"Мир \" + ownername);\n\n if (worldname.startsWith(playeruuid)) player.setAllowFlight(true);\n else player.setAllowFlight(false);\n player.getInventory().clear();\n player.getScoreboardTags().remove(\"keepInventory\");\n\n CodeEventHandler codeEventHandler = Coding.codeMap.get(world);\n\n switch (worldscfg.getString(worldname + \".type\")) {\n case \"building\": {\n footer = new TextComponent(\"Строительство: \" + worlddisplayname + \"\\n§rАвтор: \" + ownername);\n if (world == null) {\n world = WorldManager.generateEmptyWorld(worldname, size, true);\n codeEventHandler = new CodeEventHandler(world);\n }\n Scoreboard sb = CyanUniverse.worldScoreboardMap.get(world);\n if (initworld) {\n sb = server.getScoreboardManager().getNewScoreboard();\n CyanUniverse.worldScoreboardMap.put(world, sb);\n world.getWorldBorder().setSize(size + 1);\n world.getWorldBorder().setCenter(0.5, 0.5);\n world.setAutoSave(true);\n }\n player.setScoreboard(sb != null ? sb : CyanUniverse.server.getScoreboardManager().getMainScoreboard());\n if (worldname.startsWith(playeruuid)) player.setGameMode(GameMode.CREATIVE);\n else player.setGameMode(GameMode.ADVENTURE);\n player.teleport(world.getSpawnLocation().add(0.5, 0, 0.5));\n player.getInventory().setItem(8, ItemsList.worldscompass);\n player.getInventory().setItem(7, ItemsList.deco);\n player.setExp(0);\n player.setLevel(CyanEcoManager.getEco(player));\n break;\n }\n case \"coding\": {\n footer = new TextComponent(\"Кодинг: \" + worlddisplayname + \"\\n§rАвтор: \" + ownername);\n if (world == null) {\n world = WorldManager.generateEmptyWorld(worldname, size, true);\n codeEventHandler = new CodeEventHandler(world);\n }\n if (initworld) {\n Scoreboard sb = server.getScoreboardManager().getNewScoreboard();\n CyanUniverse.worldScoreboardMap.put(world, sb);\n world.getWorldBorder().setCenter(1050, 1050);\n world.getWorldBorder().setSize(100);\n world.setAutoSave(true);\n world.setPVP(false);\n Block endchest = new Location(world, 1000, 0, 1000).getBlock();\n Block endchest1 = new Location(world, 1099, 0, 1099).getBlock();\n if (endchest1.getType() != Material.ENDER_CHEST) {\n for (int x = 1000; x < 1100; x++) {\n int linenumber = 0;\n for (int z = 1000; z < 1100; z++) {\n Block block = world.getBlockAt(x, 0, z);\n if (x % 2 == 1 && z % 3 == 2) {\n if (x == 1001) {\n block.setType(Material.COMMAND_REPEATING);\n block.setData((byte) 5);\n Utils.createHolo(\"Строка \" + linenumber, block.getLocation().add(0.5, 2, 0.5));\n linenumber++;\n } else {\n block.setType(Material.COMMAND_CHAIN);\n block.setData((byte) 5);\n }\n } else block.setType(Material.GLASS);\n }\n }\n endchest.setType(Material.ENDER_CHEST);\n endchest1.setType(Material.ENDER_CHEST);\n }\n }\n\n Coding.giveCodingKit(player);\n if (worldname.startsWith(playeruuid)) {\n player.setGameMode(GameMode.ADVENTURE);\n player.sendMessage(\" \\n§b§lДобро пожаловать в Кодинг!\" +\n \"\\n§rДля быстрого переключения между режимами используйте команды:\\n§b/mode play§r, §b/mode code§r, §b/mode build\" +\n \"\\n§rДля дюпа предметов команда: §b/dupe\" +\n \"\\n§rВыдать права кодинга игроку: §b/code ник\" +\n \"\\n \");\n } else {\n player.setGameMode(GameMode.SPECTATOR);\n }\n Utils.healthUpPlayer(player);\n player.setAllowFlight(true);\n player.teleport(new Location(world, 1001.5, 3, 1000.5));\n break;\n }\n case \"playing\": {\n footer = new TextComponent(worlddisplayname + \"\\n§rАвтор: \" + ownername);\n if (world == null) {\n world = WorldManager.generateEmptyWorld(worldname, size, false);\n codeEventHandler = new CodeEventHandler(world);\n }\n if (initworld) {\n Scoreboard sb = server.getScoreboardManager().getNewScoreboard();\n CyanUniverse.worldScoreboardMap.put(world, sb);\n world.getWorldBorder().setSize(size + 1);\n world.getWorldBorder().setCenter(0.5, 0.5);\n world.setAutoSave(false);\n if (codeEventHandler == null) codeEventHandler = new CodeEventHandler(world);\n codeEventHandler.compile();\n }\n player.setAllowFlight(false);\n Utils.healthUpPlayer(player);\n player.setGameMode(GameMode.ADVENTURE);\n player.teleport(world.getSpawnLocation().add(0.5, 0, 0.5));\n codeEventHandler.runCode(\"СобытиеИгрока_Вход\", UUID.randomUUID(), player, null);\n codeEventHandler.runCode(\"Планировщик_Цикл\", null, null, null);\n break;\n }\n }\n worldscfg.set(worldname + \".lastvisit\", System.currentTimeMillis());\n player.setPlayerListHeaderFooter(header, footer);\n Utils.healthUpPlayer(player);\n player.getInventory().setHeldItemSlot(0);\n if (!worldname.startsWith(playeruuid)) {\n List<String> playedbefore = worldscfg.getStringList(worldname + \".playedbefore\");\n if (!playedbefore.contains(playeruuid)) {\n playedbefore.add(playeruuid);\n worldscfg.set(worldname + \".playedbefore\", playedbefore);\n world.getPlayers().forEach(players -> players.sendMessage(player.getDisplayName() + \" §7зашёл в мир впервые\"));\n Player owner = server.getPlayer(UUID.fromString(worldname.split(\"#\")[0]));\n if (owner != null && owner.isOnline()) {\n CyanEcoManager.addEco(owner, 1, true);\n owner.sendMessage(\"§b+1 монетка\");\n }\n } else {\n world.getPlayers().forEach(players -> players.sendMessage(player.getDisplayName() + \" §7зашёл в мир\"));\n }\n }\n return world;\n }\n\n public static void teleportToLobby(Player player) {\n player.teleport(lobby.getSpawnLocation().add(0.5, 0, 0.5));\n server.getScheduler().scheduleSyncDelayedTask(plugin, () -> {\n if (player.isOnline()) {\n player.setScoreboard(CyanUniverse.worldScoreboardMap.get(lobby));\n player.setGameMode(GameMode.ADVENTURE);\n player.getInventory().clear();\n player.getInventory().setItem(0, ItemsList.worldscompass);\n player.getInventory().setItem(1, ItemsList.myworlds);\n player.setHealth(20);\n player.setFoodLevel(20);\n player.setFireTicks(0);\n player.setFallDistance(0);\n player.getActivePotionEffects().forEach(PotionEffect -> player.removePotionEffect(PotionEffect.getType()));\n player.setExp(0);\n player.setLevel(CyanEcoManager.getEco(player));\n player.getInventory().setHeldItemSlot(0);\n player.sendTitle(\" \", \" \", 20, 20, 20);\n player.addPotionEffect(lobbyspeed);\n Utils.updatePerWorldTab(player.getWorld());\n if (Utils.playerIsDonator(player) || Utils.playerIsModer(player) || player.isOp() == true) {\n player.setAllowFlight(true);\n } else player.setAllowFlight(false);\n }\n }, 5);\n\n TextComponent header = new TextComponent(\"§2KiwiServer\");\n TextComponent footer = new TextComponent(\"Лобби\");\n player.setPlayerListHeaderFooter(header, footer);\n }\n\n public static void generateWorld(Player player, String worldname, Material type) {\n int size = Utils.playerIsDonator(player) ? 512 : 256;\n World world = WorldManager.generateEmptyWorld(worldname, size, true);\n world.setTime(0);\n com.sk89q.worldedit.world.World faweworld = FaweAPI.getWorld(worldname);\n\n switch (type) {\n case GRASS: {\n try (EditSession session = WorldEdit.getInstance().newEditSession(faweworld)) {\n session.setBlocks((Region) new CuboidRegion(BlockVector3.at(-(size / 2), 0, -(size / 2)), BlockVector3.at((size / 2), 0, (size / 2))), BlockTypes.BEDROCK.getDefaultState());\n session.setBlocks((Region) new CuboidRegion(BlockVector3.at(-(size / 2), 1, -(size / 2)), BlockVector3.at((size / 2), 2, (size / 2))), BlockTypes.DIRT.getDefaultState());\n session.setBlocks((Region) new CuboidRegion(BlockVector3.at(-(size / 2), 3, -(size / 2)), BlockVector3.at((size / 2), 3, (size / 2))), BlockTypes.GRASS.getDefaultState());\n }\n break;\n }\n case GLASS: {\n try (EditSession session = WorldEdit.getInstance().newEditSession(faweworld)) {\n session.setBlocks((Region) new CuboidRegion(BlockVector3.at(-3, 16, -3), BlockVector3.at(3, 16, 3)), BlockTypes.STONE.getDefaultState());\n }\n world.getBlockAt(0, 16, 0).setType(Material.COBBLESTONE);\n break;\n }\n }\n\n world.setSpawnLocation(0, world.getHighestBlockYAt(0, 0), 0);\n world.setGameRuleValue(\"doFireTick\", \"false\");\n world.setGameRuleValue(\"keepInventory\", \"true\");\n world.setGameRuleValue(\"doTileDrops\", \"false\");\n world.setGameRuleValue(\"doMobLoot\", \"false\");\n worldscfg.set(worldname + \".type\", \"building\");\n worldscfg.set(worldname + \".owner\", player.getDisplayName());\n worldscfg.set(worldname + \".allowenter\", \"all\");\n worldscfg.set(worldname + \".votecount\", 0);\n worldscfg.set(worldname + \".votescore\", 0d);\n WorldManager.teleportToWorld(player, worldname);\n }\n\n public static void loadPlayerWorlds(Player player) {\n\n }\n\n public static void purgeOldWorlds(int days, boolean delete) {\n long timeNow = System.currentTimeMillis();\n server.broadcastMessage(\"[CyanUniverse] Удаление старых миров!\");\n StringBuilder sb = new StringBuilder();\n sb.append(\"[CyanUniverse] Будут удалены миры игроков: \");\n final int[] count = {0};\n worldscfg.getKeys(false).forEach(worldName -> {\n if (Utils.playerIsDonator(worldName.split(\"#\")[0])) return;\n Long lastseen = timeNow - worldscfg.getLong(worldName + \".lastvisit\");\n if (!(lastseen > 86400000 * days)) return;\n try {\n sb.append(worldscfg.getString(worldName + \".owner\")).append(\", \");\n FileUtils.deleteDirectory(new File(server.getWorldContainer(), worldName + \"/playerdata\"));\n if (delete) {\n worldscfg.set(worldName, null);\n FileUtils.deleteDirectory(new File(server.getWorldContainer(), worldName));\n\n }\n\n count[0]++;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n });\n CyanUniverse.saveCfgs();\n long timeAfterPurge = System.currentTimeMillis();\n if (delete)\n server.broadcastMessage(\"[CyanUniverse] Удалено \" + count[0] + \" миров за \" + (timeAfterPurge - timeNow) + \"мс\");\n if (count[0] != 0) server.broadcastMessage(sb.toString());\n }\n\n public static String getWorldType(World world) {\n if (world == lobby) return \"lobby\";\n return worldscfg.getString(world.getName() + \".type\");\n }\n}"
},
{
"identifier": "NbtItemMenu",
"path": "cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/menus/nbt/item/NbtItemMenu.java",
"snippet": "public class NbtItemMenu extends CustomMenu {\n public static ItemStack[] contents;\n private ItemBuilder itemBuilder;\n\n public NbtItemMenu(ItemBuilder itemBuilder) {\n super(server, 3, \"Редактор NBT - Предмет\");\n this.itemBuilder = itemBuilder;\n initItems();\n }\n\n public void initItems() {\n if (contents != null) {\n this.inventory.setContents(contents);\n } else {\n this.inventory.setItem(3, new ItemBuilder(Material.BOOK).name(\"Название\").build());\n this.inventory.setItem(4, new ItemBuilder(Material.ENDER_PEARL).name(\"Описание\").build());\n contents = this.inventory.getContents();\n }\n\n this.inventory.setItem(10, itemBuilder.build());\n calculateUnbreakable();\n\n }\n\n @Override\n public void onClick(InventoryClickEvent event) {\n event.setCancelled(true);\n if (event.getClickedInventory().getHolder() != this) return;\n ItemStack item = event.getCurrentItem();\n if (item == null || item.getType() == Material.AIR) return;\n Player player = (Player) event.getWhoClicked();\n switch (event.getSlot()) {\n case 10: { //Предмет\n player.getInventory().addItem(item);\n break;\n }\n case 3: { //Название\n player.openInventory(new NbtItemNameMenu(itemBuilder).getInventory());\n break;\n }\n case 4: { //Описание\n player.openInventory(new NbtItemLore(itemBuilder).getInventory());\n break;\n }\n case 5: {\n if (this.inventory.getItem(10).getItemMeta().isUnbreakable()) {\n this.inventory.setItem(10, itemBuilder.unbreakable(false).build());\n } else {\n this.inventory.setItem(10, itemBuilder.unbreakable(true).build());\n }\n calculateUnbreakable();\n break;\n }\n }\n }\n\n public void calculateUnbreakable() {\n if (this.inventory.getItem(10).getItemMeta().isUnbreakable()) {\n inventory.setItem(5, new ItemBuilder(Material.GOLD_PICKAXE).enchant(Enchantment.DIG_SPEED, 1).itemflag(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS).name(\"§aНеразрушимость - Вкл\").build());\n } else {\n inventory.setItem(5, new ItemBuilder(Material.GOLD_PICKAXE).name(\"§cНеразрушимость - Выкл\").itemflag(ItemFlag.HIDE_ATTRIBUTES).build());\n }\n }\n}"
}
] | import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import ru.cyanworld.cyan1dex.api.ItemBuilder;
import ru.cyanworld.cyanuniverse.WorldManager;
import ru.cyanworld.cyanuniverse.menus.nbt.item.NbtItemMenu;
import java.util.*; | 5,558 | package ru.cyanworld.cyanuniverse.commands;
public class CmdNbt extends Command {
public static List<String> blacklist = Arrays.asList("ru.cyanworld.cyanuniverse.coding.number", "ru.cyanworld.cyanuniverse.coding.effect", "ru.cyanworld.cyanuniverse.coding.location");
public static Set<Player> selectmob = new HashSet<>();
public static Map<Player, Entity> selectedmob = new HashMap<>();
public CmdNbt() {
super
(
"nbt",
"Редактор NBT",
"/nbt",
new ArrayList<>()
);
Bukkit.getCommandMap().register(getName(), this);
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
switch (WorldManager.getWorldType(player.getWorld())) {
case "coding": {
if (player.getGameMode() != GameMode.ADVENTURE) {
sender.sendMessage("Вы не можете редактировать NBT без прав кодинга");
return true;
}
break;
}
case "building": {
if (player.getGameMode() != GameMode.CREATIVE) {
sender.sendMessage("Вы не можете редактировать NBT без прав строительства");
return true;
}
break;
}
default: {
sender.sendMessage("Редактор работает только в режиме кодинга или строительства");
return true;
}
}
if (args.length < 1) {
sender.sendMessage("/nbt item");
return true;
}
switch (args[0]) {
case "item": {
ItemStack item = player.getInventory().getItemInMainHand();
if (item == null || item.getType() == Material.AIR) {
sender.sendMessage("Возьмите предмет в руки и попробуйте снова");
return true;
} | package ru.cyanworld.cyanuniverse.commands;
public class CmdNbt extends Command {
public static List<String> blacklist = Arrays.asList("ru.cyanworld.cyanuniverse.coding.number", "ru.cyanworld.cyanuniverse.coding.effect", "ru.cyanworld.cyanuniverse.coding.location");
public static Set<Player> selectmob = new HashSet<>();
public static Map<Player, Entity> selectedmob = new HashMap<>();
public CmdNbt() {
super
(
"nbt",
"Редактор NBT",
"/nbt",
new ArrayList<>()
);
Bukkit.getCommandMap().register(getName(), this);
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
switch (WorldManager.getWorldType(player.getWorld())) {
case "coding": {
if (player.getGameMode() != GameMode.ADVENTURE) {
sender.sendMessage("Вы не можете редактировать NBT без прав кодинга");
return true;
}
break;
}
case "building": {
if (player.getGameMode() != GameMode.CREATIVE) {
sender.sendMessage("Вы не можете редактировать NBT без прав строительства");
return true;
}
break;
}
default: {
sender.sendMessage("Редактор работает только в режиме кодинга или строительства");
return true;
}
}
if (args.length < 1) {
sender.sendMessage("/nbt item");
return true;
}
switch (args[0]) {
case "item": {
ItemStack item = player.getInventory().getItemInMainHand();
if (item == null || item.getType() == Material.AIR) {
sender.sendMessage("Возьмите предмет в руки и попробуйте снова");
return true;
} | ItemBuilder itemBuilder = new ItemBuilder(item); | 0 | 2023-10-08 17:50:55+00:00 | 8k |
vaaako/Vakraft | src/main/java/com/magenta/main/Renderer.java | [
{
"identifier": "Camera",
"path": "src/main/java/com/magenta/engine/Camera.java",
"snippet": "public class Camera {\n\tprivate final Window window;\n\t// private int width, height;\n\n\t// Camera movement vectors\n\tprivate Vector3f position = new Vector3f(0.0f, 0.0f, 0.0f);\n\tprivate Vector3f rotation = new Vector3f((float) Math.TAU / 4, 0.0f, 0.0f);\n\n\t// Camera config\n\tprivate final float fovDeg, sensitivity;\n\tprivate final float nearPlane = 0.01f, farPlane = 100.0f;\n\n\tpublic Camera(Window window, float fovDeg, float sensitivity) {\n\t\tthis.window = window;\n\t\tthis.fovDeg = fovDeg;\n\t\tthis.sensitivity = sensitivity;\n\n\t\t// width = window.getWidth();\n\t\t// height = window.getHeight();\n\t}\n\n\tpublic void setRotation(float x, float y, float z) {\n\t\trotation.x = x;\n\t\trotation.y = y;\n\t\trotation.z = z;\n\t}\n\n\tpublic void setPosition(float x, float y, float z) {\n\t\tposition.x = x;\n\t\tposition.y = y;\n\t\tposition.z = z;\n\t}\n\n\tpublic void moveRotation(double xpos, double ypos) {\n\t\t// rotation.x -= xpos * sensitivity;\n\t\trotation.x += xpos * sensitivity;\n\t\trotation.y += ypos * sensitivity;\n\t\t// rotation.z += offsetZ;\n\n\t\t// Avoid 360º spin (Y only duurh)\n\t\trotation.y = Math.max((float) (-Math.TAU / 4),\n\t\t\tMath.min((float) (Math.TAU / 4), rotation.y)\n\t\t);\n\t}\n\t\n\tpublic void movePosition(float offsetX, float offsetY, float offsetZ, float speed) {\n\t\tfloat angle = (float)(rotation.x - Math.atan2(offsetZ, offsetX) + (Math.TAU / 4));\n\t\tif(offsetX != 0.0f || offsetZ != 0.0f) {\n\t\t\tposition.x += (float) Math.cos(angle) * speed * 0.1f;\n\t\t\tposition.z += (float) Math.sin(angle) * speed * 0.1f;\n\t\t}\n\n\t\tposition.y += offsetY * 0.1f;\n\t}\n\n\tpublic float getNearPlane() {\n\t\treturn nearPlane;\n\t}\n\n\tpublic float getFarPlane() {\n\t\treturn farPlane;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn window.getWidth();\n\t}\n\n\tpublic int getHeight() {\n\t\treturn window.getHeight();\n\t}\n\n\tpublic Vector3f getRotation() {\n\t\treturn rotation;\n\t}\n\n\tpublic Vector3f getPosition() {\n\t\treturn position;\n\t}\n\t\n\tpublic float getFovDeg() {\n\t\treturn fovDeg;\n\t}\n\n\tpublic float getSensitivity() {\n\t\treturn sensitivity;\n\t}\n}"
},
{
"identifier": "Window",
"path": "src/main/java/com/magenta/engine/Window.java",
"snippet": "public class Window {\n\tprivate String title;\n\tprivate int width, height;\n\tprivate long windowHandle;\n\tprivate boolean vSync;\n\n\n\tpublic Window(String title, int width, int height, boolean vSync) {\n\t\tthis.title = title;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.vSync = vSync;\n\t}\n\n\tpublic void initGLFW() {\n\t\tGLFWErrorCallback.createPrint(System.err).set(); // Errors to System.err\n\t\t\n\t\tif(!GLFW.glfwInit()) throw new IllegalStateException(\"Unable to initialize GLFW\");\n\t\t\t\t\n\t\tGLFW.glfwDefaultWindowHints();\n\t\tGLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);\n\t\tGLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_TRUE);\n\t\t\n\t\twindowHandle = GLFW.glfwCreateWindow(width, height, title, NULL, NULL);\n\t\tif(windowHandle == NULL) throw new IllegalStateException(\"Unable to create GLFW Window\");\n\n\t\t// Calback\n\t\t// On resizing window, adjust viewport\n\t\tGLFW.glfwSetFramebufferSizeCallback(windowHandle, (window, width, height) -> {\n\t\t\t// Tells OpenGL size of rendering window\n\t\t\tSystem.out.println(\"Resizing to: \" + width + \"x\" + height);\n\n\t\t\t// int aspect = width/height;\n\t\t\t// GL11.glViewport(0, 0, width * aspect, height * aspect); // Rendering startX, startX, width and height\n\t\t\tGL11.glViewport(0, 0, width, height); // Rendering startX, startX, width and height\n\n\t\t\tthis.width = width;\n\t\t\tthis.height = height;\n\t\t});\n\n\n\t\t// Get the thread stack and push a new frame\n\t\t// This is just to center the window\n\t\ttry (MemoryStack stack = MemoryStack.stackPush()) {\n\t\t\tIntBuffer pWidth = stack.mallocInt(1); // int*\n\t\t\tIntBuffer pHeight = stack.mallocInt(1); // int*\n\t\t\t\n\t\t\tGLFW.glfwGetWindowSize(windowHandle, pWidth, pHeight);\n\n\t\t\t// Get the resolution of the primary monitor\n\t\t\tGLFWVidMode vidmode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());\n\t\t\t\n\t\t\t// Set window position to center of screen\n\t\t\tGLFW.glfwSetWindowPos(windowHandle,\n\t\t\t\t(vidmode.width() - pWidth.get(0)) / 2,\n\t\t\t\t(vidmode.height() - pHeight.get(0)) / 2\n\t\t\t);\n\t\t\t\n\t\t} // The stack frame is popped automatically\n\n\t\tGLFW.glfwMakeContextCurrent(windowHandle); // Make the OpenGL context current\n\t\t\n\t\tif(vSync) GLFW.glfwSwapInterval(1); // Enable V-Sync\n\t\tGLFW.glfwShowWindow(windowHandle); // Make window visible\n\n\t\t// Begining of the start\n\t\tGL.createCapabilities(); // Finishes the initializing process\t\n\t\tGL11.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set the clear color\n\t\t\n\t\tGL11.glEnable(GL11.GL_DEPTH_TEST); // Enable 3D depth\n\t\tGL11.glEnable(GL11.GL_CULL_FACE); // Don't show inside faces\n\t\t\n\t\t// Translucent\n\t\tGL11.glEnable(GL11.GL_BLEND);\n\t}\n\n\n\t// This //\n\tpublic long getWindowHandle() {\n\t\treturn windowHandle;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic boolean isvSync() {\n\t\treturn vSync;\n\t}\n\n\tpublic void setClearColor(float r, float g, float b, float alpha) {\n\t\tGL11.glClearColor(r, g, b, alpha);\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t\tGLFW.glfwSetWindowTitle(windowHandle, title);\n\t}\n\n\tpublic void setvSync(boolean vSync) {\n\t\tthis.vSync = vSync;\n\t}\n\n\n\n\n\t// GLFW //\n\tpublic boolean windowShouldClose() {\n\t\treturn GLFW.glfwWindowShouldClose(windowHandle);\n\t}\n\n\tpublic void update() {\n\t\tGLFW.glfwSwapBuffers(windowHandle); // Swap front buffers to back buffers (clean screen basically)\n\t\tGLFW.glfwPollEvents(); // Window events (close, resize etc)\n\t}\n\n\tpublic void destroy() {\n\t\t// Free the window callbacks and destroy the window\n\t\tCallbacks.glfwFreeCallbacks(windowHandle);\n\t\tGLFW.glfwDestroyWindow(windowHandle);\n\n\t\t// Terminate GLFW and free the error callback\n\t\tGLFW.glfwTerminate();\n\t\tGLFW.glfwSetErrorCallback(null).free();\n\t}\n}"
},
{
"identifier": "Aim",
"path": "src/main/java/com/magenta/game/Aim.java",
"snippet": "public class Aim {\n\n\t// Mesh\n\tprivate final float[] vertices;\n\tprivate final int[] indices;\n\n\t// Format\n\tprivate final float size = 0.01f; // Radius (if circle)\n\tprivate final int segments = 10; // Number of segments to approximate a circle\n\n\t// Programs\n\tprivate final Mesh mesh;\n\tprivate final ShaderProgram shaderProgram;\n\n\t// Matrices\n\t// Matrix4f projectionMatrix = new Matrix4f().ortho2D(-1, 1, -1, 1);\n\t// Matrix4f modelMatrix = new Matrix4f().translate(0, 0, 0);\n\t// Matrix4f modelViewProjection = new Matrix4f(projectionMatrix).mul(modelMatrix);\n\n\n\tpublic enum AimType {\n\t\tSQUARE, CIRCLE;\n\t}\n\n\tpublic Aim(AimType type) {\n\t\tif(type == AimType.SQUARE) {\n\t\t\tvertices = new float[] {\n\t\t\t\t-size, -size, 0.0f, // Bottom-left\n\t\t\t\t size, -size, 0.0f, // Bottom-right\n\t\t\t\t size, size, 0.0f, // Top-right\n\t\t\t\t-size, size, 0.0f // Top-left\n\t\t\t};\n\n\t\t\tindices = new int[] {\n\t\t\t\t0, 1, 2, // Upper triangle\n\t\t\t\t0, 2, 3 // Bottom triangle\n\t\t\t};\n\t\t} else {\n\t\t\tvertices = new float[(segments + 1) * 3];\n\t\t\tindices = new int[segments * 3];\n\n\t\t\tfor (int i = 0; i <= segments; i++) {\n\t\t\t\tfloat angle = (float) Math.toRadians(360.0f / segments * i);\n\t\t\t\t// float angle = (float) (2 * Math.PI * i / segments);\n\t\t\t\tvertices[i * 3] = (float) (size * Math.cos(angle));\n\t\t\t\tvertices[i * 3 + 1] = (float) (size * Math.sin(angle));\n\t\t\t\tvertices[i * 3 + 2] = 0.0f;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < segments; i++) {\n\t\t\t\tindices[i * 3] = 0;\n\t\t\t\tindices[i * 3 + 1] = i + 1;\n\t\t\t\tindices[i * 3 + 2] = i + 2;\n\t\t\t}\n\t\t}\n\n\n\t\tmesh = MeshLoader.createMesh(vertices, indices);\n\t\tshaderProgram = new ShaderProgram(\"aim/vertex.glsl\", \"aim/fragment.glsl\");\n\t}\n\n\tpublic void render() {\n\t\tshaderProgram.use();\n\n\t\t// Set the MVP matrix in your shader program\n\t\t// int matrixLocation = GL20.glGetUniformLocation(shaderProgram.getProgramID(), \"MVP\");\n\t\t// FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);\n\t\t// modelViewProjection.get(matrixBuffer);\n\t\t// GL20.glUniformMatrix4fv(matrixLocation, false, matrixBuffer);\n\n\t\tGL30.glBindVertexArray(mesh.getVaoID());\n\t\tGL11.glDrawElements(GL11.GL_TRIANGLES, indices.length, GL11.GL_UNSIGNED_INT, 0);\n\t}\n}"
},
{
"identifier": "World",
"path": "src/main/java/com/magenta/game/World.java",
"snippet": "public class World {\n\tprivate TextureManager texManager;\n\tprivate LinkedList<BlockType> blockTypes = new LinkedList<>();\n\tprivate Map<Vector3f, Chunk> chunks = new LinkedHashMap<>();\n\n\tprivate final int WORLD_SIZE = 8; // this * this = WORLD_SIZE\n\tprivate final int WORLD_CENTER = WORLD_SIZE / 2; // Used to spawn at the center of the world\n\n\tpublic World() {\n\t\ttexManager = new TextureManager(16, 16, 256);\n\t\tSystem.out.println(\"Loading textures...\");\n\n\t\t// Add blocks from file\n\t\tnew BlockLoader(\"blocks.vk\").loadContent(blockTypes, texManager); // Load all blocks from file\n\t\ttexManager.generateMipmap();\n\n\t\tTimer timer = new Timer();\n\t\tSystem.out.println(\"\\n\\nGenerating world...\");\n\n\t\t// Generate chunk randomly\n\t\t// generateChunk(0, 0);\n\t\tfor(int wx = 0; wx < WORLD_SIZE; wx++) { // wx -> World's x\n\t\t\tfor(int wz = 0; wz < WORLD_SIZE; wz++) {\n\t\t\t\t// float x = (float) Math.floor((wx - 1)) / Chunk.CHUNK_SIZE);\n\t\t\t\t// float z = (float) Math.floor((wz - 1)) / Chunk.CHUNK_SIZE);\n\n\t\t\t\t// Chunk currentChunk = new Chunk(this, new Vector3f(x, 0, z)); // Y: -1 = Start at -1 (camera spawns at Y:0)\n\t\t\t\tChunk currentChunk = new Chunk(this, new Vector3f(wx - WORLD_CENTER, -1, wz - WORLD_CENTER)); // Y: -1 = Start at -1 (camera spawns at Y:0)\n\t\t\t\tchunks.put(currentChunk.getChunkPosition(), currentChunk); // Add to chunks list\n\t\t\t}\n\t\t}\n\n\n\t\tSystem.out.println(\"=> Generated world in: \" + (float) timer.getElapsedTime() + \" seconds\");\t\n\t\tSystem.out.println(\"\\n=> Loading world...\");\n\n\t\t// Load world (render all chunk meshes)\n\t\tfor(Chunk chunk : chunks.values()) {\n\t\t\tchunk.updateMesh();\n\t\t}\n\n\t\tfloat elapsed = (float) timer.getElapsedTime();\n\t\tSystem.out.println(\"=> Loaded world in: \" + elapsed + \" seconds\");\n\t\tSystem.out.println(\"Average: \" + elapsed / chunks.size() + \" per chunk\\n\");\n\t}\n\t\n\tprivate void loadChunk(int wx, int wz) {\n\t\tfloat x = (float) Math.floor((wx - 1) / Chunk.CHUNK_SIZE);\n\t\tfloat z = (float) Math.floor((wz - 1) / Chunk.CHUNK_SIZE);\n\n\t\tChunk currentChunk = new Chunk(this, new Vector3f(x, 0, z)); // Y: -1 = Start at -1 (camera spawns at Y:0)\n\t\tchunks.put(currentChunk.getChunkPosition(), currentChunk); // Add to chunks list\n\t}\n\n\tprivate void generateChunk(int wx, int wz) {\n\t\t// if chunk loaded blablabla\n\t\t// else generate\n\t}\n\n\t// private Chunk getChunk(float x, float z) {\n\t// \t// Convert to chunk coordinates\n\t// \tfloat nx = (float) Math.floor((x - 1) / Chunk.CHUNK_SIZE);\n\t// \tfloat nz = (float) Math.floor((z - 1) / Chunk.CHUNK_SIZE);\n\n\t// \tChunk chunk = chunks.get(nx);\n\t// \tif(chunk != null) return chunk.get(nz);\n\t// \treturn null;\n\t// }\n\n\n\n\n\n\n\n\n\n\tpublic Vector3f getChunkPosition(Vector3f position) {\n\t\treturn new Vector3f(\n\t\t\t(float) Math.floor(position.x / Chunk.CHUNK_SIZE),\n\t\t\t(float) Math.floor(position.y / Chunk.CHUNK_HEIGHT),\n\t\t\t(float) Math.floor(position.z / Chunk.CHUNK_SIZE)\n\t\t);\n\t}\n\n\tpublic Vector3f getLocalPosition(Vector3f position) {\n\t\tVector3f chunk = getChunkPosition(position);\n\t\treturn new Vector3f(\n\t\t\tposition.x - (chunk.x * Chunk.CHUNK_SIZE),\n\t\t\tposition.y - (chunk.y * Chunk.CHUNK_HEIGHT),\n\t\t\tposition.z - (chunk.z * Chunk.CHUNK_SIZE)\n\t\t);\n\t}\n\n\t// Get the index in the BlockManager array of the block at a certain position\n\tpublic int getBlockInChunk(float x, float y, float z) {\n\t\t// Get the chunk in wich the block it's position\n\t\tVector3f chunkPosition = getChunkPosition(new Vector3f(x, y, z));\n\n\t\t// Return \"air\" if the chunk doens't exist\n\t\tif(chunks.get(chunkPosition) == null)\n\t\t\treturn 0;\n\n\t\t// Get the relative position of the block in the chunk\n\t\tVector3f temp = getLocalPosition(new Vector3f(x, y, z));\n\t\treturn chunks.get(chunkPosition).getBlock((int) temp.x, (int) temp.y, (int) temp.z);\n\t\t// return the block number at the local position in the correct chunk\n\t}\n\n\tpublic int getBlockInChunk(Vector3f position) {\n\t\treturn getBlockInChunk(position.x, position.y, position.z);\n\t}\n\n\t// Get block type and check if it's opaque or not\n\tpublic boolean isOpaqueBlock(Vector3f position) {\n\t\t// Air counts as a transparent block, so test for that or not\n\t\tint blockTypeID = getBlockInChunk(position.x, position.y, position.z);\n\t\tif(blockTypes.get(blockTypeID) != null) // Block exists\n\t\t\treturn !blockTypes.get(blockTypeID).isTransparent(); // Not transparent = Opaque\n\t\treturn false; // Air\n\t}\n\n\tpublic boolean isOpaqueBlock(float x, float y, float z) {\n\t\treturn isOpaqueBlock(new Vector3f(x, y, z));\n\t}\n\n\n\t// public int getBlock(Vector3f position) {\n\t// \tVector3f chunkPosition = getChunkPosition(position);\n\t\t\n\t// \t// If no chunks exist at this position, create a new one\n\t// \tChunk currentChunk;\n\t// \tif(!chunks.containsKey(chunkPosition)) {\n\t// \t\tcurrentChunk = new Chunk(this, chunkPosition);\n\t// \t\tchunks.put(chunkPosition, currentChunk);\n\t// \t} else {\n\t// \t\tcurrentChunk = chunks.get(chunkPosition);\n\t// \t}\t\n\n\t// \t// No point updating mesh if the block is the same\n\t// \tVector3f localPosition = getLocalPosition(position);\n\t// \tint lx = (int) localPosition.x;\n\t// \tint ly = (int) localPosition.y;\n\t// \tint lz = (int) localPosition.z;\n\n\t// \treturn currentChunk.getBlocks()[lx][ly][lz];\n\t// }\n\n\t// Set number to 0 (air) to remove block\n\tpublic void setBlock(Vector3f position, int number) {\n\t\tVector3f chunkPosition = getChunkPosition(position);\n\t\t\n\t\t// If no chunks exist at this position, create a new one\n\t\tChunk currentChunk;\n\t\tif(!chunks.containsKey(chunkPosition)) {\n\t\t\t// No point in creating a whole new chunk if we're not gonna be adding anything\n\t\t\tif(number == 0) return;\n\n\t\t\tcurrentChunk = new Chunk(this, chunkPosition);\n\t\t\tchunks.put(chunkPosition, currentChunk);\n\t\t} else {\n\t\t\tcurrentChunk = chunks.get(chunkPosition);\n\t\t}\n\n\t\t\n\n\t\t// No point updating mesh if the block is the same\n\t\tint lastBlockNumber = getBlockInChunk(position.x, position.y, position.z);\n\t\tif(lastBlockNumber == number) return;\n\n\t\tVector3f localPosition = getLocalPosition(position);\n\t\tint lx = (int) localPosition.x;\n\t\tint ly = (int) localPosition.y;\n\t\tint lz = (int) localPosition.z;\n\n\t\tcurrentChunk.getBlocks()[lx][ly][lz] = number;\n\n\t\tint cx = (int) chunkPosition.x;\n\t\tint cy = (int) chunkPosition.y;\n\t\tint cz = (int) chunkPosition.z;\n\n\t\t// Check if position is located at chunk border\n\t\tif(lx == (Chunk.CHUNK_SIZE - 1))\n\t\t\ttryUpdateChunkMesh(cx + 1, cy, cz);\n\t\tif(lx == 0)\n\t\t\ttryUpdateChunkMesh(cx - 1, cy, cz);\n\n\t\tif(ly == (Chunk.CHUNK_SIZE - 1))\n\t\t\ttryUpdateChunkMesh(cx, cy + 1, cz);\n\t\tif(ly == 0)\n\t\t\ttryUpdateChunkMesh(cx, cy - 1, cz);\n\n\t\tif(lz == (Chunk.CHUNK_HEIGHT - 1))\n\t\t\ttryUpdateChunkMesh(cx, cy, cz + 1);\n\t\tif(lz == 0)\n\t\t\ttryUpdateChunkMesh(cx, cy, cz - 1);\t\n\n\t\tcurrentChunk.updateMesh(); // Render updated block\n\t}\n\n\tpublic void tryUpdateChunkMesh(float x, float y, float z) {\n\t\tVector3f chunkPosition = new Vector3f(x, y, z);\n\t\tif(chunks.containsKey(chunkPosition))\n\t\t\tchunks.get(chunkPosition).updateMesh();\n\t}\n\n\n\n\t// public int getBlockIDByName(String name) {\n\t// \treturn trackBlocks.get(name);\n\t// }\n\n\t// public String getBlockNameByID(int id) {\n\t// \treturn blockTypes.get(id).getName();\n\t// }\n\n\tpublic LinkedList<BlockType> getBlockTypes() {\n\t\treturn blockTypes;\n\t}\n\n\tpublic Map<Vector3f, Chunk> getChunks() {\n\t\treturn chunks;\n\t}\n\n\tpublic TextureManager getTexManager() {\n\t\treturn texManager;\n\t}\n\n\n\n\t// Render all chunks\n\tpublic void render() {\n\t\tfor(Chunk chunk : chunks.values()) {\n\t\t\tchunk.draw();\n\t\t}\n\t}\n}"
},
{
"identifier": "ShaderProgram",
"path": "src/main/java/com/magenta/render/ShaderProgram.java",
"snippet": "public class ShaderProgram {\n\tprivate int programID;\n\n\tpublic ShaderProgram(String vert, String frag) {\n\t\tint vertexID = loadShader(vert, GL20.GL_VERTEX_SHADER); // Load vertex shader\n\t\tint fragmentID = loadShader(frag, GL20.GL_FRAGMENT_SHADER); // Load fragment shader\n\t\tprogramID = GL20.glCreateProgram(); // Create shader program\n\n\t\t// Bind shader on shader program\n\t\tGL20.glAttachShader(programID, vertexID);\n\t\tGL20.glAttachShader(programID, fragmentID);\n\n\t\t// Bind all\n\t\tGL20.glLinkProgram(programID);\n\t\tGL20.glValidateProgram(programID);\n\n\t\t// Get all the Uniform variables within the shader\n\t\tGL20.glDeleteShader(vertexID);\n\t\tGL20.glDeleteShader(fragmentID);\n\t}\n\n\t// Get some uniform from shader\n\tpublic int findUniform(String name) {\n\t\treturn GL20.glGetUniformLocation(programID, name);\n\t}\n\n// Example of matrix\n// float[] matrixData = {\n// 1.0f, 0.0f, 0.0f, 0.0f,\n// 0.0f, 1.0f, 0.0f, 0.0f,\n// 0.0f, 0.0f, 1.0f, 0.0f,\n// 0.0f, 0.0f, 0.0f, 1.0f\n// };\n\n\n\tpublic void uniformMatrix(int location, Matrix4f matrix) {\n\t\tFloatBuffer buffer = BufferUtils.createFloatBuffer(16); // Create a FloatBuffer to hold the matrix data\n\t\tmatrix.get(buffer); // Copy the matrix data into the buffer\n\t\tGL30.glUniformMatrix4fv(location, false, buffer);\n\t}\n\n\tprivate int loadShader(String file, int type) {\n\t\t// Takes the data that BufferedReader is taking from Shader file and loading everythign into the String shaderSouce as one string of code to send to GLSL\n\t\tStringBuilder shaderSource = new StringBuilder();\n\n\t\t// Read file\n\t\ttry {\n\t\t\t// BufferedReader reader = new BufferedReader(new FileReader(\"/shaders/\"+file));\n\t\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(ShaderProgram.class.getClassLoader().getResourceAsStream(\"shaders/\"+file)));\n\n\t\t\tString line;\n\t\t\twhile((line = reader.readLine()) != null)\n\t\t\t\tshaderSource.append(line).append(\"\\n\"); // Get lines\n\n\t\t\treader.close(); // Close reader\n\t\t} catch (IOException e){\n\t\t\tSystem.err.println(\"Can't read file\");\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(-1);\n\t\t}\n\n\t\t// return shaderSource.toString();\n\n\t\tint shaderProgram = GL20.glCreateShader(type); // Type is any of the shader types: Vertex, Geometry or Fragment\n\t\tGL20.glShaderSource(shaderProgram, shaderSource); // With shaderProgram set, send shaderSource\n\t\tGL20.glCompileShader(shaderProgram); // Compile shader and sends it off to the CPU\n\n\t\t// Handle any GLSL error\n\t\tif(GL20.glGetShaderi(shaderProgram, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {\n\t\t\tSystem.err.println(\"\\n=> Couldn't compile \" + file);\n\t\t\tSystem.err.println(GL20.glGetShaderInfoLog(shaderProgram, 512));\n\t\t\tSystem.err.println(\"=> Couldn't compile the shader of type: \" + ((type == 35632) ? \"Fragment Shader\" : \"Vertex Shader\"));\n\t\t\tSystem.exit(-1);\n\t\t}\n\n\t\treturn shaderProgram;\n\t}\n\n\tpublic int getProgramID() {\n\t return programID;\n\t}\n\n\tpublic void use() {\n\t\tGL20.glUseProgram(programID);\n\t}\n\n\tpublic void delete() {\n\t\t// Going back to default render mode\n\t\tGL20.glDeleteProgram(programID);\n\t\t// GL20.glUseProgram(0);\n\t}\n}"
}
] | import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import com.magenta.engine.Camera;
import com.magenta.engine.Window;
import com.magenta.game.Aim;
import com.magenta.game.World;
import com.magenta.render.ShaderProgram; | 6,557 | package com.magenta.main;
public class Renderer {
private ShaderProgram shaderProgram;
private final Window window;
// Matrices //
// Render Matrices
private Matrix4f mvMatrix, pMatrix;
// Camera
private final Camera camera;
private final float nearPlane, farPlane;
// Matrices
private Vector3f position;
private Vector3f rotation;
// Aim
private final Aim aim;
// This is just for view a single block
// private final TextureManager texManager = new TextureManager(16, 16, 256);
// private final BlockType blockType = new BlockType(BlocksEnum.AHIRO, texManager);
// private final int[] indices = {0, 0, 0};
// private final Mesh mesh = new MeshLoader(blockType.getVertexPositions(), indices, blockType.getTexCoords(), blockType.getShadingValues());
public Renderer(Window window, Camera camera) {
this.window = window;
this.camera = camera;
// Matrices //
// Consts
nearPlane = camera.getNearPlane();
farPlane = camera.getFarPlane();
// Render
mvMatrix = new Matrix4f();
pMatrix = new Matrix4f();
// Camera position/rotation
position = new Vector3f();
rotation = new Vector3f();
// Aim
aim = new Aim(Aim.AimType.CIRCLE);
}
public void init() {
// Load shaders
shaderProgram = new ShaderProgram("vertex.glsl", "fragment.glsl");
}
private void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear frame buffer of Color and Depth (Depth: 3D)
}
| package com.magenta.main;
public class Renderer {
private ShaderProgram shaderProgram;
private final Window window;
// Matrices //
// Render Matrices
private Matrix4f mvMatrix, pMatrix;
// Camera
private final Camera camera;
private final float nearPlane, farPlane;
// Matrices
private Vector3f position;
private Vector3f rotation;
// Aim
private final Aim aim;
// This is just for view a single block
// private final TextureManager texManager = new TextureManager(16, 16, 256);
// private final BlockType blockType = new BlockType(BlocksEnum.AHIRO, texManager);
// private final int[] indices = {0, 0, 0};
// private final Mesh mesh = new MeshLoader(blockType.getVertexPositions(), indices, blockType.getTexCoords(), blockType.getShadingValues());
public Renderer(Window window, Camera camera) {
this.window = window;
this.camera = camera;
// Matrices //
// Consts
nearPlane = camera.getNearPlane();
farPlane = camera.getFarPlane();
// Render
mvMatrix = new Matrix4f();
pMatrix = new Matrix4f();
// Camera position/rotation
position = new Vector3f();
rotation = new Vector3f();
// Aim
aim = new Aim(Aim.AimType.CIRCLE);
}
public void init() {
// Load shaders
shaderProgram = new ShaderProgram("vertex.glsl", "fragment.glsl");
}
private void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear frame buffer of Color and Depth (Depth: 3D)
}
| public void render(World world) { | 3 | 2023-10-08 04:08:22+00:00 | 8k |
Aywen1/improvident | src/fr/nicolas/main/panels/NBase.java | [
{
"identifier": "MainFrame",
"path": "src/fr/nicolas/main/frames/MainFrame.java",
"snippet": "public class MainFrame extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n\tprivate NBackground bg;\n\tprivate NLeftBar leftBar;\n\tprivate NTitle titlePanel;\n\tprivate NBase base;\n\tprivate String[] categories = { \"Accueil\", \"Cours écrits\", \"Cours vidéos\", \"Compréhension écrite\",\n\t\t\t\"Compréhension orale\", \"Points\", \"Paramètres\" };\n\n\tprivate Point mouseLocation = new Point(0, 0);\n\n\tpublic MainFrame(Point location) {\n\t\tString path = \"Improvident/Categories/\";\n\t\tif (!(new File(path).exists())) {\n\t\t\tfor (int i = 1; i < categories.length; i++) {\n\t\t\t\tnew File(path + categories[i]).mkdirs();\n\t\t\t\tif (categories[i] != \"Points\" && categories[i] != \"Paramètres\") {\n\t\t\t\t\tnewFile(path + categories[i] + \"/À faire\", false);\n\t\t\t\t\tnewFile(path + categories[i] + \"/À revoir\", false);\n\t\t\t\t\tnewFile(path + categories[i] + \"/Archivés\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewFile(\"Improvident/Categories/Points/points\", true);\n\t\t}\n\n\t\tthis.setTitle(\"Improvident\");\n\t\tthis.setSize(800, 500);\n\t\tthis.setLocationRelativeTo(null);\n\t\tthis.setResizable(false);\n\t\tthis.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tthis.setIconImage(new ImageIcon(\"res/icon.png\").getImage());\n\t\tthis.setLocation(location);\n\n\t\tthis.addMouseListener(this);\n\t\tthis.addMouseMotionListener(this);\n\t\tthis.addMouseWheelListener(this);\n\t\tthis.setFocusable(true);\n\n\t\tinit();\n\n\t\tthis.setVisible(true);\n\t}\n\n\tprivate void newFile(String path, boolean valueTo0) {\n\t\ttry {\n\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(path)));\n\t\t\tif (valueTo0) {\n\t\t\t\tbufferedWriter.write(\"0\");\n\t\t\t} else {\n\t\t\t\tbufferedWriter.write(\"\");\n\t\t\t}\n\t\t\tbufferedWriter.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate void init() {\n\t\tbg = new NBackground(0);\n\t\tleftBar = new NLeftBar(categories, this);\n\t\ttitlePanel = new NTitle(this);\n\t\tbase = new NBase(this);\n\n\t\tthis.setContentPane(bg);\n\n\t\tbg.add(leftBar);\n\t\tbg.add(titlePanel);\n\t\tbg.add(base);\n\n\t\tleftBar.setBounds(0, 0, 42, getHeight());\n\t\ttitlePanel.setBounds(42, 0, getWidth(), 60);\n\t\tbase.setBounds(42, 60, getWidth(), getHeight());\n\t}\n\n\tpublic NTitle getTitlePanel() {\n\t\treturn titlePanel;\n\t}\n\n\tpublic NBase getBase() {\n\t\treturn base;\n\t}\n\n\t// MouseListener\n\n\tpublic void mouseClicked(MouseEvent e) {\n\t}\n\n\tpublic void mouseEntered(MouseEvent e) {\n\t}\n\n\tpublic void mouseExited(MouseEvent e) {\n\t}\n\n\tpublic void mousePressed(MouseEvent e) {\n\t}\n\n\tpublic void mouseReleased(MouseEvent e) {\n\t\tif (e.getButton() == MouseEvent.BUTTON1) {\n\n\t\t\tleftBar.mouseClick(mouseLocation);\n\t\t\tbase.mouseClick(mouseLocation, false);\n\t\t\ttitlePanel.mouseClick(mouseLocation);\n\n\t\t} else if (e.getButton() == MouseEvent.BUTTON2) {\n\t\t\tbase.mouseClick(mouseLocation, true);\n\t\t}\n\n\t\tbg.repaint();\n\t}\n\n\t// MouseMotionListener\n\n\tpublic void mouseDragged(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tleftBar.mouseMove(mouseLocation);\n\t\tbase.mouseMove(mouseLocation);\n\n\t\tbg.repaint();\n\t}\n\n\tpublic void mouseMoved(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tleftBar.mouseMove(mouseLocation);\n\t\tbase.mouseMove(mouseLocation);\n\t\ttitlePanel.mouseMove(mouseLocation);\n\n\t\tbg.repaint();\n\t}\n\n\t// MouseWheelListener\n\n\tpublic void mouseWheelMoved(MouseWheelEvent e) {\n\t\tleftBar.mouseWheelMoved(mouseLocation, e.getWheelRotation());\n\n\t\tbg.repaint();\n\t}\n\n}"
},
{
"identifier": "NCategoryPanel",
"path": "src/fr/nicolas/main/panels/categories/NCategoryPanel.java",
"snippet": "public abstract class NCategoryPanel extends JPanel {\n\n\tpublic NCategoryPanel() {\n\t\tsetLayout(null);\n\t}\n\t\n\tpublic abstract void mouseMove(Point mouseLocation);\n\t\n\tpublic abstract void mouseClick(Point mouseLocation, boolean middleClick);\n\t\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t}\n\t\n}"
},
{
"identifier": "NHome",
"path": "src/fr/nicolas/main/panels/categories/NHome.java",
"snippet": "public class NHome extends NCategoryPanel {\n\n\tprivate NButtonImg buttonChrono15m, buttonChrono30m, buttonChrono45m, buttonChrono1h, buttonChrono1h30m,\n\t\t\tbuttonChronoStop;\n\tprivate boolean isButtonChronoStopShowed = false, canStop = false;\n\tprivate NChrono chrono;\n\tprivate MainFrame mainFrame;\n\n\tpublic NHome(MainFrame mainFrame) {\n\t\tthis.mainFrame = mainFrame;\n\n\t\tbuttonChrono15m = new NButtonImg(\"chrono/chrono15m\", new Rectangle(10 + 60, 15 + 86, 158, 37));\n\t\tbuttonChrono15m.setBounds(25, 15, 158, 37);\n\t\tthis.add(buttonChrono15m);\n\t\tbuttonChrono30m = new NButtonImg(\"chrono/chrono30m\", new Rectangle(10 + 60, 60 + 86, 158, 37));\n\t\tbuttonChrono30m.setBounds(25, 60, 158, 37);\n\t\tthis.add(buttonChrono30m);\n\t\tbuttonChrono45m = new NButtonImg(\"chrono/chrono45m\", new Rectangle(10 + 60, 105 + 86, 158, 37));\n\t\tbuttonChrono45m.setBounds(25, 105, 158, 37);\n\t\tthis.add(buttonChrono45m);\n\t\tbuttonChrono1h = new NButtonImg(\"chrono/chrono1h\", new Rectangle(10 + 60, 150 + 86, 158, 37));\n\t\tbuttonChrono1h.setBounds(25, 150, 158, 37);\n\t\tthis.add(buttonChrono1h);\n\t\tbuttonChrono1h30m = new NButtonImg(\"chrono/chrono1h30m\", new Rectangle(10 + 60, 195 + 86, 158, 37));\n\t\tbuttonChrono1h30m.setBounds(25, 195, 158, 37);\n\t\tthis.add(buttonChrono1h30m);\n\t\tbuttonChronoStop = new NButtonImg(\"chrono/chronoStop\", new Rectangle(10 + 60, 15 + 86, 176, 190));\n\t\tbuttonChronoStop.setBounds(16, 6, 176, 190);\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tif (!isButtonChronoStopShowed) {\n\t\t\tbuttonChrono15m.mouseMove(mouseLocation);\n\t\t\tbuttonChrono30m.mouseMove(mouseLocation);\n\t\t\tbuttonChrono45m.mouseMove(mouseLocation);\n\t\t\tbuttonChrono1h.mouseMove(mouseLocation);\n\t\t\tbuttonChrono1h30m.mouseMove(mouseLocation);\n\t\t}\n\n\t\tif (isButtonChronoStopShowed) {\n\t\t\tbuttonChronoStop.mouseMove(mouseLocation);\n\t\t\tif (!buttonChronoStop.isHovered()) {\n\t\t\t\tcanStop = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tif (!isButtonChronoStopShowed) {\n\t\t\tif (buttonChrono15m.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tshowButtonChronoStop();\n\t\t\t\tchrono = new NChrono(mainFrame, 15);\n\t\t\t} else if (buttonChrono30m.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tshowButtonChronoStop();\n\t\t\t\tchrono = new NChrono(mainFrame, 30);\n\t\t\t} else if (buttonChrono45m.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tshowButtonChronoStop();\n\t\t\t\tchrono = new NChrono(mainFrame, 45);\n\t\t\t} else if (buttonChrono1h.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tshowButtonChronoStop();\n\t\t\t\tchrono = new NChrono(mainFrame, 60);\n\t\t\t} else if (buttonChrono1h30m.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tshowButtonChronoStop();\n\t\t\t\tchrono = new NChrono(mainFrame, 90);\n\t\t\t}\n\t\t}\n\n\t\tif (isButtonChronoStopShowed && canStop) {\n\t\t\tif (buttonChronoStop.mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tint confirm = JOptionPane.showConfirmDialog(null,\n\t\t\t\t\t\t\"Voulez-vous vraiment arrêter le chrono et ne gagner aucun point ?\", \"Arrêt du chrono\",\n\t\t\t\t\t\tJOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);\n\n\t\t\t\tif (confirm == JOptionPane.OK_OPTION) {\n\t\t\t\t\tremoveButtonChronoStop();\n\t\t\t\t\tchrono.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void removeButtonChronoStop() {\n\t\tthis.remove(buttonChronoStop);\n\t\tthis.add(buttonChrono15m);\n\t\tthis.add(buttonChrono30m);\n\t\tthis.add(buttonChrono45m);\n\t\tthis.add(buttonChrono1h);\n\t\tthis.add(buttonChrono1h30m);\n\t\tisButtonChronoStopShowed = false;\n\t}\n\n\tprivate void showButtonChronoStop() {\n\t\tif (!isButtonChronoStopShowed) {\n\t\t\tthis.remove(buttonChrono15m);\n\t\t\tthis.remove(buttonChrono30m);\n\t\t\tthis.remove(buttonChrono45m);\n\t\t\tthis.remove(buttonChrono1h);\n\t\t\tthis.remove(buttonChrono1h30m);\n\t\t\tthis.add(buttonChronoStop);\n\t\t\tcanStop = false;\n\t\t\tisButtonChronoStopShowed = true;\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t\tg.setColor(new Color(255, 255, 255, 50));\n\t\tif (isButtonChronoStopShowed) {\n\t\t\tg.drawRect(15, 5, 177, 191);\n\t\t} else {\n\t\t\tg.drawRect(15, 5, 177, 236);\n\t\t}\n\t}\n\n}"
},
{
"identifier": "NPoints",
"path": "src/fr/nicolas/main/panels/categories/NPoints.java",
"snippet": "public class NPoints extends NCategoryPanel {\n\n\tprivate MainFrame mainFrame;\n\tprivate ArrayList<NButtonImg> buttonList = new ArrayList<NButtonImg>();\n\tprivate ArrayList<NButtonImg> buttonCategoryList = new ArrayList<NButtonImg>();\n\tprivate ArrayList<String> blockCategoryList = new ArrayList<String>();\n\tprivate ArrayList<String> nameList = new ArrayList<String>();\n\tprivate ArrayList<String> commandList = new ArrayList<String>();\n\tprivate ArrayList<Integer> pointsList = new ArrayList<Integer>();\n\tprivate CardLayout cardLayout = new CardLayout();\n\tprivate JPanel items = new JPanel(), blocs = new JPanel(), vegetaux = new JPanel(), mineraies = new JPanel(),\n\t\t\tdivers = new JPanel(), bonus = new JPanel();\n\n\tprivate String[] categories = { \"Blocs\", \"Végétaux\", \"Mineraies\", \"Divers\", \"Bonus\" };\n\tprivate String openCategory = \"Blocs\", mapPath;\n\n\tpublic NPoints(MainFrame mainFrame) {\n\t\tthis.mainFrame = mainFrame;\n\n\t\tthis.setLayout(new BorderLayout());\n\t\titems.setLayout(cardLayout);\n\t\tblocs.setLayout(null);\n\t\tvegetaux.setLayout(null);\n\t\tmineraies.setLayout(null);\n\t\tdivers.setLayout(null);\n\t\tbonus.setLayout(null);\n\n\t\titems.add(blocs, \"Blocs\");\n\t\titems.add(vegetaux, \"Végétaux\");\n\t\titems.add(mineraies, \"Mineraies\");\n\t\titems.add(divers, \"Divers\");\n\t\titems.add(bonus, \"Bonus\");\n\n\t\tint x2 = 25;\n\t\tfor (int i = 0; i < categories.length; i++) {\n\t\t\tNButtonImg category = new NButtonImg(\"category2\", new Rectangle(x2 + 45, 4 + 86, 125, 28), 3);\n\t\t\tcategory.setName(categories[i]);\n\t\t\tcategory.setBounds(x2, 4, 125, 28);\n\n\t\t\tbuttonCategoryList.add(category);\n\t\t\tthis.add(category);\n\n\t\t\tx2 += 145;\n\n\t\t\tString blockName = \"\";\n\t\t\tint x = 8, y = 40;\n\t\t\ttry {\n\t\t\t\tBufferedReader bufferedReader = new BufferedReader(new FileReader(\"res/list\" + categories[i] + \".txt\"));\n\n\t\t\t\twhile (blockName != null) {\n\t\t\t\t\tblockName = bufferedReader.readLine();\n\t\t\t\t\tif (blockName != null) {\n\t\t\t\t\t\tNButtonImg icon = new NButtonImg(\"item\", new Rectangle(x + 45, y + 86, 180, 35), 2);\n\t\t\t\t\t\tbuttonList.add(icon);\n\n\t\t\t\t\t\tif (categories[i] == \"Blocs\") {\n\t\t\t\t\t\t\tblocs.add(icon);\n\t\t\t\t\t\t} else if (categories[i] == \"Végétaux\") {\n\t\t\t\t\t\t\tvegetaux.add(icon);\n\t\t\t\t\t\t} else if (categories[i] == \"Mineraies\") {\n\t\t\t\t\t\t\tmineraies.add(icon);\n\t\t\t\t\t\t} else if (categories[i] == \"Divers\") {\n\t\t\t\t\t\t\tdivers.add(icon);\n\t\t\t\t\t\t} else if (categories[i] == \"Bonus\") {\n\t\t\t\t\t\t\tbonus.add(icon);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString command = bufferedReader.readLine();\n\t\t\t\t\t\tString quantity = bufferedReader.readLine();\n\n\t\t\t\t\t\tif (categories[i] == \"Bonus\") {\n\t\t\t\t\t\t\tcommandList.add(command);\n\t\t\t\t\t\t\ticon.setName(blockName + \" [\" + quantity + \"pts]\");\n\t\t\t\t\t\t\tpointsList.add(Integer.parseInt(quantity));\n\t\t\t\t\t\t\tnameList.add(blockName);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (command.contains(\"spawn_egg\")) {\n\t\t\t\t\t\t\t\tcommandList.add(\"give @p spawn_egg 1 0 {EntityTag:{id:\"\n\t\t\t\t\t\t\t\t\t\t+ command.replace(\"spawn_egg \", \"\") + \"}}\");\n\t\t\t\t\t\t\t} else if (command.contains(\" \")) {\n\t\t\t\t\t\t\t\tcommandList.add(\"give @p \" + command.split(\" \")[0] + \" \" + quantity + \" \"\n\t\t\t\t\t\t\t\t\t\t+ command.split(\" \")[1]);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcommandList.add(\"give @p \" + command + \" \" + quantity);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ticon.setName(blockName + \" (\" + quantity + \")\");\n\t\t\t\t\t\t\tpointsList.add(10);\n\t\t\t\t\t\t\tnameList.add(blockName + \" (\" + quantity + \")\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ticon.setBounds(x, y, 180, 35);\n\n\t\t\t\t\t\tblockCategoryList.add(categories[i]);\n\n\t\t\t\t\t\tx += 185;\n\t\t\t\t\t\tif (x >= 744) {\n\t\t\t\t\t\t\tx = 8;\n\t\t\t\t\t\t\ty += 45;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbufferedReader.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\t\n\t\t\tbuttonCategoryList.get(0).setSelected(true);\n\t\t}\n\n\t\tblocs.add(new NBackground(2));\n\t\tvegetaux.add(new NBackground(2));\n\t\tmineraies.add(new NBackground(2));\n\t\tdivers.add(new NBackground(2));\n\t\tbonus.add(new NBackground(2));\n\n\t\tthis.add(items, BorderLayout.CENTER);\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tbuttonList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tbuttonCategoryList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t}\n\n\tpublic void mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tif (buttonList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tif (blockCategoryList.get(i) == openCategory) {\n\t\t\t\t\tif (mainFrame.getTitlePanel().getPoints() >= pointsList.get(i)) {\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(\n\t\t\t\t\t\t\t\t\tnew FileWriter(new File(mapPath + \"/data/functions/join/join1.mcfunction\"), true));\n\n\t\t\t\t\t\t\tbufferedWriter.write(commandList.get(i) + \"\\n\");\n\t\t\t\t\t\t\tif (blockCategoryList.get(i) == \"Bonus\") {\n\t\t\t\t\t\t\t\tbufferedWriter.write(\n\t\t\t\t\t\t\t\t\t\t\"tellraw @a {\\\"text\\\":\\\" + \" + nameList.get(i) + \"\\\",\\\"color\\\":\\\"yellow\\\"}\\n\");\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbufferedWriter.write(\n\t\t\t\t\t\t\t\t\t\t\"tellraw @a {\\\"text\\\":\\\" + \" + nameList.get(i) + \"\\\",\\\"color\\\":\\\"green\\\"}\\n\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbufferedWriter.close();\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString newPoints = \"\" + (mainFrame.getTitlePanel().getPoints() - pointsList.get(i));\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(\n\t\t\t\t\t\t\t\t\tnew FileWriter(new File(\"Improvident/Categories/Points/points\")));\n\t\t\t\t\t\t\tbufferedWriter.write(newPoints);\n\t\t\t\t\t\t\tbufferedWriter.close();\n\t\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmainFrame.getTitlePanel().reloadPoints();\n\t\t\t\t\t\tmainFrame.getTitlePanel().showConfirmItemsButton();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tif (buttonCategoryList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tcardLayout.show(items, categories[i]);\n\t\t\t\topenCategory = categories[i];\n\t\t\t\tfor (int i2 = 0; i2 < buttonCategoryList.size(); i2++) {\n\t\t\t\t\tbuttonCategoryList.get(i2).setSelected(false);\n\t\t\t\t}\n\t\t\t\tbuttonCategoryList.get(i).setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t}\n\n\tpublic void setMapPath(String mapPath) {\n\t\tthis.mapPath = mapPath;\n\t}\n\n}"
},
{
"identifier": "NSettings",
"path": "src/fr/nicolas/main/panels/categories/NSettings.java",
"snippet": "public class NSettings extends NCategoryPanel {\n\n\tprivate NButtonImg buttonSavePath;\n\tprivate NLabel labelInfoPath = new NLabel(\"(Aucune map enregistrée)\", 16);\n\tprivate JFileChooser fileChooser = new JFileChooser();\n\tprivate NPoints points;\n\n\tpublic NSettings() {\n\t\tfileChooser.setDialogTitle(\"Sauvegarder le chemin de la map\");\n\t\tfileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n\n\t\tbuttonSavePath = new NButtonImg(\"savePath\", new Rectangle(85, 92, 158, 37));\n\t\tbuttonSavePath.setBounds(40, 6, 158, 37);\n\n\t\tlabelInfoPath.setBounds(35, 48, 400, 20);\n\n\t\tadd(buttonSavePath);\n\t\tadd(labelInfoPath);\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tbuttonSavePath.mouseMove(mouseLocation);\n\t}\n\n\tpublic void mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tif (buttonSavePath.mouseClick(mouseLocation, middleClick)) {\n\t\t\tint fileChooserValue = fileChooser.showOpenDialog(this);\n\t\t\tif (fileChooserValue == JFileChooser.APPROVE_OPTION) {\n\t\t\t\ttry {\n\t\t\t\t\tBufferedWriter bufferedWriter = new BufferedWriter(\n\t\t\t\t\t\t\tnew FileWriter(new File(\"Improvident/Categories/Paramètres/mapPath\")));\n\n\t\t\t\t\tpoints.setMapPath(fileChooser.getSelectedFile().getPath());\n\n\t\t\t\t\tbufferedWriter.write(fileChooser.getSelectedFile().getPath() + \"\\n\");\n\t\t\t\t\tbufferedWriter.write(fileChooser.getSelectedFile().getName());\n\n\t\t\t\t\tbufferedWriter.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t\tlabelInfoPath.setText(\"(Map enregistrée: \" + fileChooser.getSelectedFile().getName() + \")\");\n\t\t\t\tJOptionPane.showMessageDialog(null, \"Le chemin de la map a bien été sauvegardée !\",\n\t\t\t\t\t\t\"Chemin de la map sauvegardée\", JOptionPane.INFORMATION_MESSAGE);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t}\n\n\tpublic void setPoints(NPoints points) {\n\t\tthis.points = points;\n\t\tif (new File(\"Improvident/Categories/Paramètres/mapPath\").exists()) {\n\t\t\ttry {\n\t\t\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\t\t\tnew FileReader(\"Improvident/Categories/Paramètres/mapPath\"));\n\t\t\t\tpoints.setMapPath(bufferedReader.readLine());\n\n\t\t\t\tlabelInfoPath.setText(\"(Map enregistrée: \" + bufferedReader.readLine() + \")\");\n\n\t\t\t\tbufferedReader.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\t\n}"
},
{
"identifier": "NDefault",
"path": "src/fr/nicolas/main/panels/categories/NDefault.java",
"snippet": "public class NDefault extends NCategoryPanel {\n\n\tprivate ArrayList<NButtonImg> buttonList;\n\tprivate ArrayList<NButtonImg> buttonCategoryList;\n\tprivate ArrayList<Integer> categoryList;\n\tprivate ArrayList<String> urlList;\n\tprivate CardLayout cardLayout = new CardLayout();\n\tprivate JPanel items = new JPanel(), aFaire = new JPanel(), aRevoir = new JPanel(), archives = new JPanel();\n\n\tprivate String[] categories = { \"À faire\", \"À revoir\", \"Archivés\" };\n\tprivate int openCategory = 0;\n\tprivate NButtonImg buttonAdd;\n\tprivate String name;\n\n\tpublic NDefault(String name) {\n\t\tthis.name = name;\n\n\t\tload();\n\t}\n\n\tpublic void load() {\n\t\tif (new File(\"Improvident/Categories/Cours écrits/À faire\").exists()) {\n\n\t\t\tbuttonList = new ArrayList<NButtonImg>();\n\t\t\tbuttonCategoryList = new ArrayList<NButtonImg>();\n\t\t\tcategoryList = new ArrayList<Integer>();\n\t\t\turlList = new ArrayList<String>();\n\t\t\tthis.removeAll();\n\t\t\taFaire.removeAll();\n\t\t\taRevoir.removeAll();\n\t\t\tarchives.removeAll();\n\n\t\t\tint x2 = 76;\n\t\t\tfor (int i = 0; i < categories.length; i++) {\n\t\t\t\tint y = 42, xNum = 1;\n\n\t\t\t\ttry {\n\t\t\t\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\t\t\t\tnew FileReader(\"Improvident/Categories/\" + name + \"/\" + categories[i]));\n\n\t\t\t\t\tString buttonName = \"\";\n\n\t\t\t\t\twhile (buttonName != null) {\n\t\t\t\t\t\tbuttonName = bufferedReader.readLine();\n\t\t\t\t\t\tif (buttonName != null) {\n\n\t\t\t\t\t\t\tNButtonImg button;\n\t\t\t\t\t\t\tif (xNum == 1) {\n\t\t\t\t\t\t\t\tbutton = new NButtonImg(\"category3\", new Rectangle(15 + 45, y + 86, 354, 25), 5);\n\t\t\t\t\t\t\t\tbutton.setBounds(15, y, 354, 25);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbutton = new NButtonImg(\"category3Inverted\", new Rectangle(383 + 45, y + 86, 354, 25),\n\t\t\t\t\t\t\t\t\t\t5);\n\t\t\t\t\t\t\t\tbutton.setBounds(383, y, 354, 25);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbutton.setName(buttonName);\n\n\t\t\t\t\t\t\tif (categories[i] == \"À faire\") {\n\t\t\t\t\t\t\t\taFaire.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(0);\n\t\t\t\t\t\t\t} else if (categories[i] == \"À revoir\") {\n\t\t\t\t\t\t\t\taRevoir.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(1);\n\t\t\t\t\t\t\t} else if (categories[i] == \"Archivés\") {\n\t\t\t\t\t\t\t\tarchives.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(2);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbuttonList.add(button);\n\t\t\t\t\t\t\turlList.add(bufferedReader.readLine());\n\n\t\t\t\t\t\t\tif (xNum == 1) {\n\t\t\t\t\t\t\t\txNum = 2;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\txNum = 1;\n\t\t\t\t\t\t\t\ty += 32;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferedReader.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t\tNButtonImg category = new NButtonImg(\"category\", new Rectangle(x2 + 45, 4 + 86, 150, 28), 4);\n\t\t\t\tcategory.setName(categories[i]);\n\t\t\t\tcategory.setBounds(x2, 4, 150, 28);\n\n\t\t\t\tbuttonCategoryList.add(category);\n\t\t\t\tthis.add(category);\n\n\t\t\t\tx2 += 225;\n\t\t\t}\n\t\t}\n\n\t\taFaire.setLayout(null);\n\t\taRevoir.setLayout(null);\n\t\tarchives.setLayout(null);\n\n\t\taFaire.add(new NBackground(2));\n\t\taRevoir.add(new NBackground(2));\n\t\tarchives.add(new NBackground(2));\n\n\t\tbuttonAdd = new NButtonImg(\"add\", new Rectangle(15 + 45, 5 + 86, 26, 26), 5);\n\t\tbuttonAdd.setBounds(15, 5, 26, 26);\n\t\tthis.add(buttonAdd);\n\n\t\tthis.setLayout(new BorderLayout());\n\t\titems.setLayout(cardLayout);\n\n\t\titems.add(aFaire, \"À faire\");\n\t\titems.add(aRevoir, \"À revoir\");\n\t\titems.add(archives, \"Archivés\");\n\n\t\tthis.add(items, BorderLayout.CENTER);\n\n\t\tselect(openCategory);\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tbuttonList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tbuttonCategoryList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t\tbuttonAdd.mouseMove(mouseLocation);\n\t}\n\n\tpublic void mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tif (buttonList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tif (categoryList.get(i) == openCategory) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tDesktop.getDesktop().browse(URI.create(urlList.get(i)));\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buttonList.get(i).middleClick(mouseLocation, middleClick)) {\n\t\t\t\tif (categoryList.get(i) == openCategory) {\n\t\t\t\t\tnew EditFrame(this.getLocationOnScreen(),\n\t\t\t\t\t\t\t\"Improvident/Categories/\" + name + \"/\",\n\t\t\t\t\t\t\tcategories[openCategory],urlList.get(i), this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tif (buttonCategoryList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tselect(i);\n\t\t\t}\n\t\t}\n\t\tif (buttonAdd.mouseClick(mouseLocation, middleClick)) {\n\t\t\tnew NewFrame(this.getLocationOnScreen(), \"Improvident/Categories/\" + name + \"/\" + categories[openCategory],\n\t\t\t\t\tthis);\n\t\t}\n\t}\n\n\tprivate void select(int i) {\n\t\tcardLayout.show(items, categories[i]);\n\t\topenCategory = i;\n\t\tfor (int i2 = 0; i2 < buttonCategoryList.size(); i2++) {\n\t\t\tbuttonCategoryList.get(i2).setSelected(false);\n\t\t}\n\t\tbuttonCategoryList.get(i).setSelected(true);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t}\n\n}"
}
] | import java.awt.CardLayout;
import java.awt.Point;
import javax.swing.JPanel;
import fr.nicolas.main.frames.MainFrame;
import fr.nicolas.main.panels.categories.NCategoryPanel;
import fr.nicolas.main.panels.categories.NHome;
import fr.nicolas.main.panels.categories.NPoints;
import fr.nicolas.main.panels.categories.NSettings;
import fr.nicolas.main.panels.categories.NDefault; | 6,860 | package fr.nicolas.main.panels;
public class NBase extends JPanel {
private NCategoryPanel[] panels;
private int currentPanelNumber = 0;
private CardLayout cardLayout;
public NBase(MainFrame mainFrame) { | package fr.nicolas.main.panels;
public class NBase extends JPanel {
private NCategoryPanel[] panels;
private int currentPanelNumber = 0;
private CardLayout cardLayout;
public NBase(MainFrame mainFrame) { | panels = new NCategoryPanel[] { new NHome(mainFrame), new NDefault("Cours écrits"), | 5 | 2023-10-13 10:30:31+00:00 | 8k |
Kelwinkxps13/Projeto_POO_Swing | UrnaEletronica/src/br/edu/view/Urna.java | [
{
"identifier": "ConexaoDAO",
"path": "UrnaEletronica/src/br/edu/bancodedados/ConexaoDAO.java",
"snippet": "public class ConexaoDAO{\r\n public Connection conexaodao(){\r\n Connection conn = null;\r\n // 192.168.18.165\r\n try {\r\n String url = \"jdbc:mysql://sql10.freesqldatabase.com:3306/sql10669860?user=sql10669860&password=dPvlAtAmq6\";\r\n conn = DriverManager.getConnection(url);\r\n } catch (SQLException erro) {\r\n JOptionPane.showMessageDialog(null, \"ConexaoDao \"+erro);\r\n }\r\n \r\n return conn;\r\n }\r\n\r\n}"
},
{
"identifier": "User",
"path": "UrnaEletronica/src/br/edu/bancodedados/User.java",
"snippet": "public class User {\r\n \r\n protected String nome;\r\n protected String senha;\r\n protected String email;\r\n\r\n public String getNome() {\r\n return nome;\r\n }\r\n\r\n public void setNome(String nome) {\r\n this.nome = nome;\r\n }\r\n\r\n public String getSenha() {\r\n return senha;\r\n }\r\n\r\n public void setSenha(String senha) {\r\n this.senha = senha;\r\n }\r\n\r\n public String getEmail() {\r\n return email;\r\n }\r\n\r\n public void setEmail(String email) {\r\n this.email = email;\r\n }\r\n\r\n /*\r\n String nome = campoNome.getText();\r\n String senha = campoSenha.getText();\r\n \r\n PreparedStatement pstm;\r\n \r\n Connection conn;\r\n String sql = \"insert into login (nome_usuario, senha_usuario) values(?, ?)\";\r\n \r\n conn = new ConexaoDAO().conexaodao();\r\n \r\n \r\n try {\r\n pstm = conn.prepareStatement(sql);\r\n \r\n \r\n \r\n } catch (SQLException erro) {\r\n JOptionPane.showMessageDialog(null, erro);\r\n }\r\n */\r\n\r\n \r\n}\r"
},
{
"identifier": "UsuarioDAO",
"path": "UrnaEletronica/src/br/edu/bancodedados/UsuarioDAO.java",
"snippet": "public class UsuarioDAO {\r\n Connection conn;\r\n \r\n\r\n public ResultSet autenticacaoUsuario(User objusuariodto) {\r\n conn = new ConexaoDAO().conexaodao();\r\n\r\n try {\r\n String sql = (\"SELECT * FROM usuarios WHERE email = ? AND senha = ?\");\r\n\r\n PreparedStatement pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getEmail());\r\n pstm.setString(2, objusuariodto.getSenha());\r\n\r\n ResultSet rs = pstm.executeQuery();\r\n return rs;\r\n\r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (autenticação): \" + error);\r\n return null;\r\n }\r\n\r\n }\r\n \r\n \r\n public void cadastrarUsuario(UsuarioDTO objusuariodto) {\r\n PreparedStatement pstm;\r\n String sql = \"insert into usuarios (nome, email, senha, votosA, votosB, votosC, votosBranco, votosNulo, votosEx) values (?,?,?,0,0,0,0,0,0)\";\r\n\r\n conn = new ConexaoDAO().conexaodao();\r\n\r\n try {\r\n \r\n pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getCriar_nome_usuario());\r\n pstm.setString(2, objusuariodto.getCriar_email_usuario());\r\n pstm.setString(3, objusuariodto.getCriar_senha_usuario());\r\n\r\n pstm.execute();\r\n pstm.close();\r\n\r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (cadastrar)\" + error);\r\n }\r\n }\r\n \r\n \r\n \r\n \r\n \r\n public ResultSet checarUsuarioExistente(UsuarioDTO objusuariodto) {\r\n conn = new ConexaoDAO().conexaodao();\r\n \r\n try {\r\n String sql = \"select * from usuarios where email = ?\";\r\n \r\n PreparedStatement pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getCriar_email_usuario());\r\n \r\n ResultSet rs = pstm.executeQuery();\r\n return rs;\r\n \r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (checagem): \" + error);\r\n return null;\r\n }\r\n }\r\n \r\n}\r"
}
] | import br.edu.bancodedados.ConexaoDAO;
import br.edu.bancodedados.User;
import br.edu.bancodedados.UsuarioDAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.lang.Integer;
import static java.lang.Integer.parseInt; | 4,350 | jButton14.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jButton14.setForeground(new java.awt.Color(0, 0, 0));
jButton14.setText("Voltar para o Login");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton14)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(10, 10, 10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton14)))
.addContainerGap(15, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
Login login = new Login();
login.setVisible(true);
dispose();
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
texto += "1";
campoText.setText(texto);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
texto += "2";
campoText.setText(texto);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
texto += "3";
campoText.setText(texto);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
texto += "4";
campoText.setText(texto);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
texto += "5";
campoText.setText(texto);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
texto += "6";
campoText.setText(texto);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
texto += "7";
campoText.setText(texto);
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
texto += "8";
campoText.setText(texto);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
texto += "9";
campoText.setText(texto);
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
texto += "0";
campoText.setText(texto);
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
texto = "";
campoText.setText(texto);
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
if(texto.equals("12")){
try { | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package br.edu.view;
/**
*
* @author Windows
*/
public class Urna extends javax.swing.JFrame {
Connection conn;
String nome = null;
String senha = null;
String email = null;
String votosA = null;
String votosB = null;
String votosC = null;
String votosBB = null;
String votosNull = null;
String votosEx = null;
/**
* Creates new form Urna
*/
private String texto = "";
public Urna() {
initComponents();
setLocationRelativeTo(null);
}
/**
* 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() {
jPanel6 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
campoText = new javax.swing.JTextField();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jPanel7 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jButton14 = new javax.swing.JButton();
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jLabel8.setText("jLabel8");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Urna Eletrônica");
setResizable(false);
jPanel3.setBackground(new java.awt.Color(255, 238, 209));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/resourses/JUSTIÇA ELEITORAL.png"))); // NOI18N
jPanel5.setBackground(new java.awt.Color(0, 0, 0));
jButton1.setBackground(new java.awt.Color(51, 51, 51));
jButton1.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("2");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(51, 51, 51));
jButton2.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton2.setForeground(new java.awt.Color(255, 255, 255));
jButton2.setText("1");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(51, 51, 51));
jButton3.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton3.setForeground(new java.awt.Color(255, 255, 255));
jButton3.setText("8");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setBackground(new java.awt.Color(51, 51, 51));
jButton4.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 255, 255));
jButton4.setText("3");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setBackground(new java.awt.Color(51, 51, 51));
jButton5.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton5.setForeground(new java.awt.Color(255, 255, 255));
jButton5.setText("6");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setBackground(new java.awt.Color(51, 51, 51));
jButton6.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton6.setForeground(new java.awt.Color(255, 255, 255));
jButton6.setText("5");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setBackground(new java.awt.Color(51, 51, 51));
jButton7.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton7.setForeground(new java.awt.Color(255, 255, 255));
jButton7.setText("4");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setBackground(new java.awt.Color(51, 51, 51));
jButton8.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton8.setForeground(new java.awt.Color(255, 255, 255));
jButton8.setText("7");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton9.setBackground(new java.awt.Color(51, 51, 51));
jButton9.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton9.setForeground(new java.awt.Color(255, 255, 255));
jButton9.setText("9");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton10.setBackground(new java.awt.Color(51, 51, 51));
jButton10.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton10.setForeground(new java.awt.Color(255, 255, 255));
jButton10.setText("0");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
campoText.setEditable(false);
campoText.setBackground(new java.awt.Color(255, 255, 255));
campoText.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
campoText.setForeground(new java.awt.Color(0, 0, 0));
campoText.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jButton11.setBackground(new java.awt.Color(255, 255, 255));
jButton11.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton11.setForeground(new java.awt.Color(0, 0, 0));
jButton11.setText("Branco");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton12.setBackground(new java.awt.Color(204, 0, 0));
jButton12.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton12.setForeground(new java.awt.Color(255, 255, 255));
jButton12.setText("Corrigir");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jButton13.setBackground(new java.awt.Color(0, 153, 0));
jButton13.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton13.setForeground(new java.awt.Color(255, 255, 255));
jButton13.setText("Confirmar");
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(campoText)))
.addContainerGap(77, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton13)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(campoText, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(56, 56, 56))
);
jPanel7.setBackground(new java.awt.Color(204, 204, 204));
jLabel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 0));
jLabel1.setText("Eleições 2023");
jLabel3.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 0));
jLabel3.setText("Partido dos Trabalhadores (PT)");
jLabel4.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 0, 0));
jLabel4.setText("Presidente: Luis Inácio Lula da Silva");
jLabel5.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 0, 0));
jLabel5.setText("Vice-presidente: Geraldo Alckmin");
jLabel7.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 0, 0));
jLabel7.setText("Número eleitoral: 13");
jLabel9.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(0, 0, 0));
jLabel9.setText("Partido Liberal (PL)");
jLabel10.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(0, 0, 0));
jLabel10.setText("Número eleitoral: 22");
jLabel11.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(0, 0, 0));
jLabel11.setText("Vice-presidente: Walter Souza Braga Netto");
jLabel12.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel12.setForeground(new java.awt.Color(0, 0, 0));
jLabel12.setText("Presidente: Jair Messias Bolsonaro");
jLabel13.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel13.setForeground(new java.awt.Color(0, 0, 0));
jLabel13.setText("Partido Democrático Trabalhista (PDT)");
jLabel14.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel14.setForeground(new java.awt.Color(0, 0, 0));
jLabel14.setText("Número eleitoral: 12");
jLabel15.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel15.setForeground(new java.awt.Color(0, 0, 0));
jLabel15.setText("Presidente: Ciro Gomes");
jLabel16.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel16.setForeground(new java.awt.Color(0, 0, 0));
jLabel16.setText("Vice-presidente: Ana Paula Matos");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jLabel1))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addComponent(jLabel10)
.addComponent(jLabel12)))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel3)
.addComponent(jLabel9)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel5)))
.addComponent(jLabel13)))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15)
.addComponent(jLabel14)
.addComponent(jLabel16))))
.addContainerGap(148, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(30, 30, 30)
.addComponent(jLabel3)
.addGap(0, 0, 0)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addGap(37, 37, 37)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11)
.addGap(36, 36, 36)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel16)
.addContainerGap(78, Short.MAX_VALUE))
);
jButton14.setBackground(new java.awt.Color(255, 255, 255));
jButton14.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jButton14.setForeground(new java.awt.Color(0, 0, 0));
jButton14.setText("Voltar para o Login");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton14)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(10, 10, 10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton14)))
.addContainerGap(15, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
Login login = new Login();
login.setVisible(true);
dispose();
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
texto += "1";
campoText.setText(texto);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
texto += "2";
campoText.setText(texto);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
texto += "3";
campoText.setText(texto);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
texto += "4";
campoText.setText(texto);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
texto += "5";
campoText.setText(texto);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
texto += "6";
campoText.setText(texto);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
texto += "7";
campoText.setText(texto);
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
texto += "8";
campoText.setText(texto);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
texto += "9";
campoText.setText(texto);
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
texto += "0";
campoText.setText(texto);
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
texto = "";
campoText.setText(texto);
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
if(texto.equals("12")){
try { | conn = new ConexaoDAO().conexaodao(); | 0 | 2023-10-10 18:25:35+00:00 | 8k |
ljjy1/discord-mj-java | src/main/java/com/github/dmj/service/DiscordService.java | [
{
"identifier": "DiscordMjJavaException",
"path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java",
"snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n */\n private int errorCode;\n\n /**\n * 错误信息.\n */\n private String errorMsg;\n\n\n public DiscordMjJavaException(Throwable e){\n super(e);\n }\n\n public DiscordMjJavaException(int errorCode,String errorMsg){\n this.errorCode = errorCode;\n this.errorMsg = errorMsg;\n }\n\n public DiscordMjJavaException(int errorCode,String errorMsg,Object...params){\n this.errorCode = errorCode;\n this.errorMsg = StrUtil.format(errorMsg,params);\n }\n\n public DiscordMjJavaException(String errorMsg){\n this.errorCode = 400;\n this.errorMsg = errorMsg;\n }\n\n public DiscordMjJavaException(String errorMsg,Object...params){\n this.errorCode = 400;\n this.errorMsg = StrUtil.format(errorMsg,params);\n }\n\n}"
},
{
"identifier": "TaskQueue",
"path": "src/main/java/com/github/dmj/queue/TaskQueue.java",
"snippet": "@Slf4j\npublic class TaskQueue {\n\n /**\n * key存储账户key 任务队列\n */\n private static final Map<String,LinkedBlockingQueue<DiscordTask>> taskQueueMap = new ConcurrentHashMap<>();\n /**\n * key存储账户key 等待队列\n */\n private static final Map<String,LinkedBlockingQueue<DiscordTask>> waitQueueMap = new ConcurrentHashMap<>();\n\n\n private static ExecutorService runExecutorService;\n private static ExecutorService waitToRunExecutorService;\n\n private TaskQueue() {\n }\n\n private static class TaskQueueHolder{\n private static final TaskQueue INSTANCE = new TaskQueue();\n\n static {\n DiscordProperties discordProperties = DiscordPropertiesAutoConfig.discordProperties;\n Iterator<Map.Entry<String, DiscordAccountProperties>> iterator = discordProperties.getAccount().entrySet().iterator();\n while (iterator.hasNext()){\n Map.Entry<String, DiscordAccountProperties> next = iterator.next();\n String key = next.getKey();\n DiscordAccountProperties discordAccountProperties = next.getValue();\n int waitSize = discordAccountProperties.getWaitSize();\n int concurSize = discordAccountProperties.getConcurSize();\n LinkedBlockingQueue<DiscordTask> taskQueue = new LinkedBlockingQueue<>(concurSize);\n LinkedBlockingQueue<DiscordTask> waitQueue = new LinkedBlockingQueue<>(waitSize);\n taskQueueMap.put(key,taskQueue);\n waitQueueMap.put(key,waitQueue);\n\n }\n //创建一个跟随配置账户数量的线程池\n runExecutorService = Executors.newFixedThreadPool(taskQueueMap.size());\n\n waitToRunExecutorService = Executors.newFixedThreadPool(taskQueueMap.size());\n\n //执行任务启动\n INSTANCE.runTask();\n\n //同步等待任务到运行任务\n INSTANCE.waitToRunTask();\n }\n }\n\n public static TaskQueue getInstance(){\n return TaskQueue.TaskQueueHolder.INSTANCE;\n }\n\n\n /**\n * 给某个账户增加任务\n * @param userKey\n * @param function\n * @param param\n */\n public <T,S> void putTask(String userKey,Function<T,S> function, T param){\n LinkedBlockingQueue<DiscordTask> waitTasks = waitQueueMap.get(userKey);\n //判断队列是否已经满了 offer返回false表示队列已经达到初始设置的大小 不会进行扩容\n if(!waitTasks.offer(new DiscordTask(function, param))){\n throw new DiscordMjJavaException(\"The current account userKey:{} waiting queue is full, please try again later\",userKey);\n }\n }\n\n\n /**\n * 运行任务\n */\n public void runTask(){\n for (LinkedBlockingQueue<DiscordTask> taskQueue : taskQueueMap.values()) {\n runExecutorService.submit(() -> {\n while (true){\n //阻塞获取队列元素 执行任务\n DiscordTask take = taskQueue.take();\n try {\n take.run();\n } catch (Exception e) {\n log.error(\"任务:{} 运行异常:{}\", JSONUtil.toJsonStr(take),e.getMessage(),e);\n }\n }\n });\n }\n }\n\n /**\n * 将等待队列任务推入运行队列\n */\n public void waitToRunTask(){\n Iterator<Map.Entry<String, LinkedBlockingQueue<DiscordTask>>> iterator = waitQueueMap.entrySet().iterator();\n while (iterator.hasNext()){\n Map.Entry<String, LinkedBlockingQueue<DiscordTask>> next = iterator.next();\n String key = next.getKey();\n LinkedBlockingQueue<DiscordTask> waitQueue = next.getValue();\n LinkedBlockingQueue<DiscordTask> taskQueue = taskQueueMap.get(key);\n\n waitToRunExecutorService.submit(() -> {\n while (true){\n //判断任务队列是否满了\n if(taskQueue.remainingCapacity() != 0){\n DiscordTask take = waitQueue.take();\n taskQueue.offer(take);\n }else{\n //休眠1000毫秒 避免任务队列taskQueue一直满 一直循环\n Thread.sleep(1000);\n }\n }\n });\n }\n\n\n }\n\n\n\n\n\n\n\n\n\n\n}"
},
{
"identifier": "DiscordApi",
"path": "src/main/java/com/github/dmj/service/api/DiscordApi.java",
"snippet": "@Slf4j\npublic class DiscordApi {\n\n /**\n * 连接超时时间 单位毫秒\n */\n private final Integer connectTimeOut = 5000;\n\n\n private final String uploadAttachmentUrl;\n private final String sendMessageUrl;\n\n private final String triggerUrl = Constants.TRIGGER_URL;\n\n private final DiscordAccountProperties discordAccountProperties;\n\n\n private final DiscordProxyProperties discordProxyProperties;\n\n private final Cache<String, String> cache;\n\n\n private final String version = \"1118961510123847772\";\n private final String id = \"938956540159881230\";\n private final String applicationId = \"936929561302675456\";\n private final String sessionId = \"7adb7b9360a4ee4fea41aecad803f1d9\";\n\n public DiscordApi(DiscordAccountProperties discordAccountProperties,DiscordProxyProperties discordProxyProperties) {\n this.discordAccountProperties = discordAccountProperties;\n this.discordProxyProperties = discordProxyProperties;\n uploadAttachmentUrl = StrUtil.format(Constants.UPLOAD_ATTACHMENT_URL, discordAccountProperties.getChannelId());\n sendMessageUrl = StrUtil.format(Constants.SEND_MESSAGE_URL, discordAccountProperties.getChannelId());\n\n cache = CacheBuilder.newBuilder()\n //设置最大500容量\n .maximumSize(10)\n // 根据写入时间设置6个小时逐出\n .expireAfterWrite(6, TimeUnit.HOURS)\n .build();\n }\n\n\n\n private String getUserToken(){\n if(StrUtil.isNotBlank(discordAccountProperties.getUserToken())){\n return discordAccountProperties.getUserToken();\n }\n if(StrUtil.hasBlank(discordAccountProperties.getUser(),discordAccountProperties.getPassword())){\n throw new DiscordMjJavaException(\"请确认是否正确配置了账号token或者账号密码 [Check whether the account token or password is correctly configured]\");\n }\n\n //从缓存中获取token\n String userToken = cache.getIfPresent(\"userToken\");\n if(StrUtil.isBlank(userToken)){\n\n HttpRequest post = HttpUtil.createPost(Constants.LOGIN).timeout(connectTimeOut)\n .header(\"Content-Type\", \"application/json\");\n //判断是否使用代理 与是否请求 discord.com的网站\n if (discordProxyProperties.isEnable() && StrUtil.containsAnyIgnoreCase(Constants.LOGIN, \"discord.com\")) {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(discordProxyProperties.getAddress(), discordProxyProperties.getPort()));\n post.setProxy(proxy);\n }\n\n Map<String, Object> paramsMap = new HashMap<>();\n paramsMap.put(\"gift_code_sku_id\",null);\n paramsMap.put(\"login\",discordAccountProperties.getUser());\n paramsMap.put(\"login_source\",null);\n paramsMap.put(\"password\",discordAccountProperties.getPassword());\n paramsMap.put(\"undelete\",null);\n HttpResponse response = null;\n try {\n response = post.body(JSONUtil.toJsonStr(paramsMap)).execute();\n int status = response.getStatus();\n if(status != 200){\n throw new DiscordMjJavaException(\"调用登录API不成功,状态:{}\",status);\n }\n String body = response.body();\n if(StrUtil.isBlank(body)){\n throw new DiscordMjJavaException(\"调用登录API不成功,响应body为空\");\n }\n //获取响应token\n JSONObject jsonObject = JSONUtil.parseObj(body);\n String token = jsonObject.getStr(\"token\");\n if(StrUtil.isBlank(token)){\n throw new DiscordMjJavaException(\"调用登录API不成功,响应body内token为空\");\n }\n userToken = token;\n //存入缓存\n cache.put(\"userToken\",userToken);\n } catch (Exception e) {\n throw new DiscordMjJavaException(\"discord登录异常:{}\",e.getMessage());\n } finally {\n if (response != null) {\n response.close();\n }\n }\n }\n return userToken;\n }\n\n\n\n /**\n * 封装get统一请求头和参数\n *\n * @return\n */\n public HttpRequest requestGet(String url) {\n HttpRequest get = HttpUtil.createGet(url).timeout(connectTimeOut)\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", getUserToken());\n //判断是否使用代理 与是否请求 discord.com的网站\n if (discordProxyProperties.isEnable() && StrUtil.containsAnyIgnoreCase(url, \"discord.com\")) {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(discordProxyProperties.getAddress(), discordProxyProperties.getPort()));\n get.setProxy(proxy);\n }\n\n return get;\n }\n\n /**\n * 封装post统一请求头和参数\n *\n * @return\n */\n public HttpRequest requestPostJson(String url) {\n HttpRequest post = HttpUtil.createPost(url).timeout(connectTimeOut)\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", getUserToken());\n //判断是否使用代理 与是否请求 discord.com的网站\n if (discordProxyProperties.isEnable() && StrUtil.containsAnyIgnoreCase(url, \"discord.com\")) {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(discordProxyProperties.getAddress(), discordProxyProperties.getPort()));\n post.setProxy(proxy);\n }\n return post;\n }\n\n /**\n * 封装post统一请求头和参数\n *\n * @return\n */\n public HttpRequest requestPostForm(String url) {\n HttpRequest post = HttpUtil.createPost(url).timeout(connectTimeOut)\n .header(\"Content-Type\", \"multipart/form-data\")\n .header(\"Authorization\", getUserToken());\n //判断是否使用代理 与是否请求 discord.com的网站\n if (discordProxyProperties.isEnable() && StrUtil.containsAnyIgnoreCase(url, \"discord.com\")) {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(discordProxyProperties.getAddress(), discordProxyProperties.getPort()));\n post.setProxy(proxy);\n }\n return post;\n }\n\n @NotNull\n private Map<String, Object> getTriggerParams(Integer type, Map<String, Object> data) {\n Map<String, Object> params = new HashMap<>();\n params.put(\"type\", type);\n params.put(\"application_id\", applicationId);\n params.put(\"session_id\", sessionId);\n params.put(\"guild_id\", discordAccountProperties.getGuildId());\n params.put(\"channel_id\", discordAccountProperties.getChannelId());\n params.put(\"data\", data);\n return params;\n }\n\n /**\n * 文生图/ 图生图\n *\n * @param triggerImagineInRequest\n * @return\n */\n public String triggerImagine(ImagineInRequest triggerImagineInRequest) {\n HttpRequest postRequest = requestPostForm(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"version\", version);\n dataMap.put(\"id\", id);\n dataMap.put(\"name\", \"imagine\");\n dataMap.put(\"type\", 1);\n List<Map<String, Object>> options = new ArrayList<>();\n Map<String, Object> option = new HashMap<>();\n option.put(\"type\", 3);\n option.put(\"name\", \"prompt\");\n option.put(\"value\", triggerImagineInRequest.getPrompt());\n options.add(option);\n dataMap.put(\"options\", options);\n dataMap.put(\"attachments\", new ArrayList<>());\n ;\n Map<String, Object> params = getTriggerParams(2, dataMap);\n postRequest.form(\"payload_json\", JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 图片细节增强\n *\n * @param upscaleVariationRequest\n * @return\n */\n public String triggerUpscale(UpscaleVariationRequest upscaleVariationRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::upsample::{}::{}\", upscaleVariationRequest.getIndex(), upscaleVariationRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", upscaleVariationRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 图片细节变化\n *\n * @param upscaleVariationRequest\n * @return\n */\n public String triggerVariation(UpscaleVariationRequest upscaleVariationRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::variation::{}::{}\", upscaleVariationRequest.getIndex(), upscaleVariationRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", upscaleVariationRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 图片重绘\n */\n public String triggerReset(ResetRequest resetRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::reroll::0::{}::SOLO\", resetRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", resetRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n /**\n * 单张图片 微改变Subtle\n */\n public String triggerSoloLowVariation(SoloVariationRequest soloVariationRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::low_variation::1::{}::SOLO\", soloVariationRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", soloVariationRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 单张图片 较大改变Strong\n */\n public String triggerSoloHighVariation(SoloVariationRequest soloVariationRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::high_variation::1::{}::SOLO\", soloVariationRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", soloVariationRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 单张图片 进行缩小操作zoomout(2x:50 1.5X 75)\n */\n public String triggerZoomOut(ZoomOutRequest zoomOutRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::Outpaint::{}::1::{}::SOLO\", zoomOutRequest.getZoomout(), zoomOutRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", zoomOutRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n\n /**\n * 单张图片 图片进行某方向的扩展 (left/right/up/down)\n */\n public String triggerExpand(ExpandRequest expandRequest) {\n HttpRequest postRequest = requestPostJson(triggerUrl);\n HttpResponse response = null;\n try {\n Map<String, Object> dataMap = new HashMap<>();\n dataMap.put(\"component_type\", 2);\n String customId = StrUtil.format(\"MJ::JOB::pan_{}::1::{}::SOLO\", expandRequest.getDirection(), expandRequest.getMsgHash());\n dataMap.put(\"custom_id\", customId);\n\n Map<String, Object> params = getTriggerParams(3, dataMap);\n params.put(\"message_flags\", 0);\n params.put(\"message_id\", expandRequest.getMsgId());\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n return null;\n }\n\n /**\n * 上传文件 返回服务器文件名和 文件上传连接(用户上传的url)\n * @param file\n * @param fileName\n * @return\n */\n public Map<String,String> uploadFile(File file, String fileName) {\n HttpRequest postRequest = requestPostJson(uploadAttachmentUrl);\n HttpResponse response = null;\n HttpResponse response2 = null;\n Map<String,String> returnMap = new HashMap<>();\n try {\n Map<String, Object> params = new HashMap<>();\n ArrayList<Map<String, Object>> files = new ArrayList<>();\n\n Map<String, Object> fileMap = new HashMap<>();\n fileMap.put(\"filename\", fileName);\n fileMap.put(\"file_size\", file.length());\n fileMap.put(\"id\", \"0\");\n files.add(fileMap);\n params.put(\"files\", files);\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n\n if(response.getStatus() != 200){\n throw new DiscordMjJavaException(\"预上传文件到discord状态异常 [The pre-upload file to discord is abnormal. Procedure]\");\n }\n\n String body = response.body();\n if(StrUtil.isBlank(body)){\n throw new DiscordMjJavaException(\"预上传文件到discord 返回体为空 [The return body of a pre-uploaded file to discord is empty]\");\n }\n System.out.println(body);\n\n JSONObject jsonObject = JSONUtil.parseObj(body);\n JSONArray attachments = jsonObject.getJSONArray(\"attachments\");\n if(attachments.isEmpty()){\n throw new DiscordMjJavaException(\"预上传文件到discord 返回的attachments为空 [The attachments returned for pre-uploading files to discord are empty]\");\n }\n JSONObject attachment = attachments.getJSONObject(0);\n String uploadUrl = attachment.getStr(\"upload_url\");\n String uploadFilename = attachment.getStr(\"upload_filename\");\n\n //上传文件\n // 构建 HTTP 请求\n HttpRequest putRequest = HttpRequest.put(uploadUrl).timeout(30000);\n putRequest.header(\"Content-Type\",\"image/png\");\n // 设置请求体为文件内容\n putRequest.body(FileUtil.readBytes(file));\n\n // 发送请求并获取响应\n response2 = putRequest.execute();\n\n if(response2.getStatus() != 200){\n throw new DiscordMjJavaException(\"上传文件到discord状态异常 [The upload file to discord is abnormal. Procedure]\");\n }\n returnMap.put(\"uploadUrl\",uploadUrl);\n returnMap.put(\"uploadFilename\",uploadFilename);\n return returnMap;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n if (response2 != null) {\n response2.close();\n }\n }\n }\n\n\n /**\n * 通过文件名 获取文件地址链接\n */\n public String message(String uploadFilename){\n HttpRequest postRequest = requestPostJson(sendMessageUrl);\n HttpResponse response = null;\n try {\n\n Map<String, Object> params = new HashMap<>();\n params.put(\"content\",\"\");\n params.put(\"nonce\",\"\");\n params.put(\"channel_id\",\"1105829904790065223\");\n params.put(\"type\",0);\n params.put(\"sticker_ids\",new ArrayList<>());\n\n List<Map<String,Object>> attachments = new ArrayList<>();\n Map<String,Object> attachment = new HashMap<>();\n\n attachment.put(\"id\",\"0\");\n String[] split = uploadFilename.split(\"/\");\n attachment.put(\"filename\",split[split.length-1]);\n attachment.put(\"uploaded_filename\",uploadFilename);\n attachments.add(attachment);\n params.put(\"attachments\",attachments);\n\n postRequest.body(JSONUtil.toJsonStr(params));\n response = postRequest.execute();\n\n if(response.getStatus() != 200){\n throw new DiscordMjJavaException(\"获取文件链接状态异常 [The file link status is abnormal. Procedure]\");\n }\n\n String body = response.body();\n if(StrUtil.isBlank(body)){\n throw new DiscordMjJavaException(\"获取文件链接状态异常 返回体为空 [Obtain file link status Abnormal Return box is empty]\");\n }\n System.out.println(body);\n\n JSONObject jsonObject = JSONUtil.parseObj(body);\n JSONArray attachmentsArr = jsonObject.getJSONArray(\"attachments\");\n if(attachmentsArr.isEmpty()){\n throw new DiscordMjJavaException(\"获取文件链接 返回的attachments为空 [The attachments returned for the document link are empty]\");\n }\n JSONObject attachmentObj = attachmentsArr.getJSONObject(0);\n return attachmentObj.getStr(\"url\");\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n throw new RuntimeException(e);\n } finally {\n // 手动关闭连接\n if (response != null) {\n response.close();\n }\n }\n }\n\n\n\n\n\n}"
},
{
"identifier": "UniqueUtil",
"path": "src/main/java/com/github/dmj/util/UniqueUtil.java",
"snippet": "public class UniqueUtil {\n\n public static Integer generateUniqueId() {\n int digits = 9; // 指定生成的位数\n // 生成11位数的随机纯数字字符串\n String randomNumber = RandomUtil.randomNumbers(digits);\n if(randomNumber.charAt(0) == '0'){\n //如果第一位是0 随机切换到1-9\n Random random = new Random();\n int randomOne = random.nextInt(9) + 1;\n randomNumber = randomOne +randomNumber.substring(1);\n }\n return Integer.parseInt(randomNumber);\n }\n}"
}
] | import cn.hutool.core.util.StrUtil;
import com.github.dmj.error.DiscordMjJavaException;
import com.github.dmj.model.*;
import com.github.dmj.queue.TaskQueue;
import com.github.dmj.service.api.DiscordApi;
import com.github.dmj.util.UniqueUtil;
import java.io.File;
import java.net.URLConnection;
import java.util.Map; | 6,859 | package com.github.dmj.service;
/**
* @author ljjy1
* @classname DiscordService
* @description API接口服务
* @date 2023/10/11 16:31
*/
public class DiscordService {
private final Map<String, DiscordApi> discordApiMap;
public DiscordService(Map<String, DiscordApi> discordApiMap) {
this.discordApiMap = discordApiMap;
}
/**
* 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine
*/
public Integer imagine(ImagineInRequest request){
request.check();
String userKey = request.getUserKey();
DiscordApi discordApi = discordApiMap.get(userKey);
if(discordApi == null){
throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey);
}
Integer triggerId = request.getTriggerId();
//加入队列 | package com.github.dmj.service;
/**
* @author ljjy1
* @classname DiscordService
* @description API接口服务
* @date 2023/10/11 16:31
*/
public class DiscordService {
private final Map<String, DiscordApi> discordApiMap;
public DiscordService(Map<String, DiscordApi> discordApiMap) {
this.discordApiMap = discordApiMap;
}
/**
* 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine
*/
public Integer imagine(ImagineInRequest request){
request.check();
String userKey = request.getUserKey();
DiscordApi discordApi = discordApiMap.get(userKey);
if(discordApi == null){
throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey);
}
Integer triggerId = request.getTriggerId();
//加入队列 | TaskQueue.getInstance().putTask(userKey,discordApi::triggerImagine,request); | 1 | 2023-10-11 01:12:39+00:00 | 8k |
weizen-w/Educational-Management-System-BE | src/main/java/de/ait/ems/services/GroupsService.java | [
{
"identifier": "from",
"path": "src/main/java/de/ait/ems/dto/GroupDto.java",
"snippet": "public static GroupDto from(Group group) {\n return GroupDto.builder()\n .id(group.getId())\n .name(group.getName())\n .courseId(group.getCourse().getId())\n .archived(group.getArchived())\n .link_template(group.getLinkTemplate())\n .build();\n}"
},
{
"identifier": "from",
"path": "src/main/java/de/ait/ems/dto/UserDto.java",
"snippet": "public static UserDto from(User user) {\n return UserDto.builder()\n .id(user.getId())\n .password(user.getHashPassword())\n .firstName(user.getFirstName())\n .lastName(user.getLastName())\n .email(user.getEmail())\n .role(user.getRole().toString())\n .state(user.getState().name())\n .photoLink(user.getPhotoLink())\n .build();\n}"
},
{
"identifier": "GroupDto",
"path": "src/main/java/de/ait/ems/dto/GroupDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Schema(name = \"Group\", description = \"Group of entity User (admin, students and teachers)\")\npublic class GroupDto {\n\n @Schema(description = \"Group ID\", example = \"1\")\n private Long id;\n @Schema(description = \"Group name\", example = \"Cohort-26\")\n private String name;\n @Schema(description = \"Group course ID\", example = \"1\")\n private Long courseId;\n @Schema(description = \"Link template\", example =\n \"https://raw.githubusercontent.com/ait-tr/cohort25/main/back_end/lesson_0x0/theory.md or \"\n + \"https://raw.githubusercontent.com/ait-tr/cohort25/main/back_end/lesson_000/theory.md when QA\")\n private String link_template;\n @Schema(description = \"Group is archived\", example = \"false\")\n private Boolean archived;\n\n public static GroupDto from(Group group) {\n return GroupDto.builder()\n .id(group.getId())\n .name(group.getName())\n .courseId(group.getCourse().getId())\n .archived(group.getArchived())\n .link_template(group.getLinkTemplate())\n .build();\n }\n\n public static List<GroupDto> from(List<Group> groups) {\n return groups\n .stream()\n .map(GroupDto::from)\n .collect(Collectors.toList());\n }\n}"
},
{
"identifier": "NewGroupDto",
"path": "src/main/java/de/ait/ems/dto/NewGroupDto.java",
"snippet": "@Data\n@Schema(name = \"New group\")\npublic class NewGroupDto {\n\n @Schema(description = \"Group name\", example = \"Cohort-26\")\n @NotNull(message = \"Must not be null\")\n @NotBlank(message = \"Must not be blank\")\n @NotEmpty(message = \"Must not be empty\")\n @Size(max = 50, message = \"Size must be in the range from 0 to 50\")\n private String name;\n @Schema(description = \"Course ID\", example = \"1\")\n @NotNull(message = \"Must not be null\")\n @Min(value = 1, message = \"Can't be zero or negative\")\n private Long courseId;\n}"
},
{
"identifier": "UpdateGroupDto",
"path": "src/main/java/de/ait/ems/dto/UpdateGroupDto.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Schema(name = \"Update group\", description = \"Data for updating the group\")\npublic class UpdateGroupDto {\n\n @Pattern(regexp = \"^$|^(?!\\\\s+$).+\", message = \"Must not be blank or contain only spaces\")\n @Size(min = 1, max = 50, message = \"Size must be in the range from 1 to 50\")\n @Schema(description = \"Group name\", example = \"Cohort-26\")\n private String name;\n @Min(value = 1, message = \"Can't be zero or negative\")\n @Schema(description = \"Group course ID\", example = \"1\")\n private Long courseId;\n @Schema(description = \"Link template\", example =\n \"https://raw.githubusercontent.com/ait-tr/cohort25/main/back_end/lesson_0X/theory.md\")\n private String link_template;\n @Schema(description = \"Group is archived\", example = \"true\")\n private Boolean archived;\n}"
},
{
"identifier": "UserDto",
"path": "src/main/java/de/ait/ems/dto/UserDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Schema(name = \"User\", description = \"User Description\")\npublic class UserDto {\n\n @Schema(description = \"User ID\", example = \"1\")\n private Long id;\n @Schema(description = \"User password\", example = \"qwerty007\")\n private String password;\n @Schema(description = \"User first name\", example = \"Max\")\n private String firstName;\n @Schema(description = \"User last name\", example = \"Musterman\")\n private String lastName;\n @Schema(description = \"e-mail\", example = \"[email protected]\")\n private String email;\n @Schema(description = \"User role\", example = \"STUDENT\")\n private String role;\n @Schema(description = \"User state\", example = \"CONFIRMED\")\n private String state;\n @Schema(description = \"User photo\")\n private String photoLink;\n\n public static UserDto from(User user) {\n return UserDto.builder()\n .id(user.getId())\n .password(user.getHashPassword())\n .firstName(user.getFirstName())\n .lastName(user.getLastName())\n .email(user.getEmail())\n .role(user.getRole().toString())\n .state(user.getState().name())\n .photoLink(user.getPhotoLink())\n .build();\n }\n\n public static List<UserDto> from(List<User> users) {\n return users.stream()\n .map(UserDto::from)\n .collect(Collectors.toList());\n }\n}"
},
{
"identifier": "RestException",
"path": "src/main/java/de/ait/ems/exceptions/RestException.java",
"snippet": "public class RestException extends RuntimeException {\n\n private final HttpStatus status;\n\n public RestException(HttpStatus status, String message) {\n super(message);\n this.status = status;\n }\n\n public HttpStatus getStatus() {\n return status;\n }\n}"
},
{
"identifier": "EntityMapper",
"path": "src/main/java/de/ait/ems/mapper/EntityMapper.java",
"snippet": "@Component\npublic class EntityMapper {\n\n private final ModelMapper modelMapper;\n\n public EntityMapper() {\n this.modelMapper = new ModelMapper();\n }\n\n public AttendanceDto convertToDto(Attendance attendance) {\n return modelMapper.map(attendance, AttendanceDto.class);\n }\n\n public LessonDto convertToDto(Lesson lesson) {\n return modelMapper.map(lesson, LessonDto.class);\n }\n\n public SubmissionDto convertToDto(Submission submission) {\n return modelMapper.map(submission, SubmissionDto.class);\n }\n\n public CommentDto convertToDto(Comment comment) {\n return modelMapper.map(comment, CommentDto.class);\n }\n\n public UserDto convertToDto(User user) {\n return modelMapper.map(user, UserDto.class);\n }\n\n}"
},
{
"identifier": "Course",
"path": "src/main/java/de/ait/ems/models/Course.java",
"snippet": "@Getter\n@Setter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@Entity\n@Table(name = \"course\")\npublic class Course {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"course_id\")\n private Long id;\n @Column(name = \"course_name\", length = 200, nullable = false)\n private String name;\n @Column(name = \"archived\", nullable = false)\n @ColumnDefault(\"false\")\n private Boolean archived;\n\n @Override\n public final boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (object == null) {\n return false;\n }\n Class<?> oEffectiveClass = object instanceof HibernateProxy\n ? ((HibernateProxy) object).getHibernateLazyInitializer()\n .getPersistentClass() : object.getClass();\n Class<?> thisEffectiveClass = this instanceof HibernateProxy\n ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass() : this.getClass();\n if (thisEffectiveClass != oEffectiveClass) {\n return false;\n }\n Course course = (Course) object;\n return getId() != null && Objects.equals(getId(), course.getId());\n }\n\n @Override\n public final int hashCode() {\n return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass().hashCode() : getClass().hashCode();\n }\n}"
},
{
"identifier": "Group",
"path": "src/main/java/de/ait/ems/models/Group.java",
"snippet": "@Getter\n@Setter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@Entity\n@Table(name = \"student_group\")\npublic class Group {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"group_id\")\n private Long id;\n @Column(name = \"group_name\", length = 50, nullable = false)\n private String name;\n @ManyToOne\n @JoinColumn(name = \"course_id\", nullable = false)\n @ToString.Exclude\n private Course course;\n @Column(name = \"archived\", nullable = false)\n @ColumnDefault(\"false\")\n private Boolean archived;\n @Column(name = \"link_template\")\n private String linkTemplate;\n\n @Override\n public final boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (object == null) {\n return false;\n }\n Class<?> oEffectiveClass = object instanceof HibernateProxy\n ? ((HibernateProxy) object).getHibernateLazyInitializer()\n .getPersistentClass() : object.getClass();\n Class<?> thisEffectiveClass = this instanceof HibernateProxy\n ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass() : this.getClass();\n if (thisEffectiveClass != oEffectiveClass) {\n return false;\n }\n Group group = (Group) object;\n return getId() != null && Objects.equals(getId(), group.getId());\n }\n\n @Override\n public final int hashCode() {\n return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass().hashCode() : getClass().hashCode();\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/de/ait/ems/models/User.java",
"snippet": "@Getter\n@Setter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@Entity\n@Table(name = \"account\")\npublic class User {\n\n public enum Role {\n ADMIN, STUDENT, TEACHER\n }\n\n public enum State {\n NOT_CONFIRMED, CONFIRMED, DELETED, BANNED\n }\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"account_id\")\n private Long id;\n @Column(name = \"hash_password\", length = 100, nullable = false)\n private String hashPassword;\n @Column(name = \"first_name\", length = 50, nullable = false)\n private String firstName;\n @Column(name = \"last_name\", length = 50, nullable = false)\n private String lastName;\n @Column(name = \"email\", unique = true, nullable = false)\n private String email;\n @Column(name = \"role\", nullable = false)\n @Enumerated(value = EnumType.STRING)\n private Role role;\n @Column(name = \"account_state\", nullable = false)\n @Enumerated(value = EnumType.STRING)\n private State state;\n @Column(name = \"photo_link\")\n private String photoLink;\n\n @OneToMany(mappedBy = \"user\")\n @Exclude\n private Set<ConfirmationCode> codes;\n\n\n @Override\n public final boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (object == null) {\n return false;\n }\n Class<?> oEffectiveClass = object instanceof HibernateProxy\n ? ((HibernateProxy) object).getHibernateLazyInitializer()\n .getPersistentClass() : object.getClass();\n Class<?> thisEffectiveClass = this instanceof HibernateProxy\n ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass() : this.getClass();\n if (thisEffectiveClass != oEffectiveClass) {\n return false;\n }\n User user = (User) object;\n return getId() != null && Objects.equals(getId(), user.getId());\n }\n\n @Override\n public final int hashCode() {\n return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass().hashCode() : getClass().hashCode();\n }\n}"
},
{
"identifier": "UserGroup",
"path": "src/main/java/de/ait/ems/models/UserGroup.java",
"snippet": "@Getter\n@Setter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@Entity\n@Table(name = \"account_group\")\npublic class UserGroup {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"account_group_id\")\n private Long id;\n @ManyToOne\n @JoinColumn(name = \"account_id\", nullable = false)\n @ToString.Exclude\n private User user;\n @ManyToOne\n @JoinColumn(name = \"group_id\", nullable = false)\n @ToString.Exclude\n private Group group;\n @JoinColumn(name = \"main_group\", nullable = false)\n private Boolean mainGroup;\n\n @Override\n public final boolean equals(Object object) {\n if (this == object) {\n return true;\n }\n if (object == null) {\n return false;\n }\n Class<?> oEffectiveClass = object instanceof HibernateProxy\n ? ((HibernateProxy) object).getHibernateLazyInitializer()\n .getPersistentClass() : object.getClass();\n Class<?> thisEffectiveClass = this instanceof HibernateProxy\n ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass() : this.getClass();\n if (thisEffectiveClass != oEffectiveClass) {\n return false;\n }\n UserGroup userGroup = (UserGroup) object;\n return getId() != null && Objects.equals(getId(), userGroup.getId());\n }\n\n @Override\n public final int hashCode() {\n return this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer()\n .getPersistentClass().hashCode() : getClass().hashCode();\n }\n}"
},
{
"identifier": "CoursesRepository",
"path": "src/main/java/de/ait/ems/repositories/CoursesRepository.java",
"snippet": "public interface CoursesRepository extends JpaRepository<Course, Long> {\n\n}"
},
{
"identifier": "GroupsRepository",
"path": "src/main/java/de/ait/ems/repositories/GroupsRepository.java",
"snippet": "public interface GroupsRepository extends JpaRepository<Group, Long> {\n\n}"
},
{
"identifier": "UserGroupsRepository",
"path": "src/main/java/de/ait/ems/repositories/UserGroupsRepository.java",
"snippet": "public interface UserGroupsRepository extends JpaRepository<UserGroup, Long> {\n\n List<UserGroup> findByUserId(Long id);\n\n List<UserGroup> findByGroupId(Long groupId);\n\n List<UserGroup> findByGroupAndMainGroup(Group group, boolean b);\n}"
},
{
"identifier": "AuthenticatedUser",
"path": "src/main/java/de/ait/ems/security/details/AuthenticatedUser.java",
"snippet": "public class AuthenticatedUser implements UserDetails {\n\n private final User user;\n\n public AuthenticatedUser(User user) {\n this.user = user;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return Collections.singleton(new SimpleGrantedAuthority(user.getRole().toString()));\n }\n\n @Override\n public String getPassword() {\n return user.getHashPassword();\n }\n\n @Override\n public String getUsername() {\n return user.getEmail();\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return !user.getState().equals(User.State.BANNED);\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return user.getState().equals(User.State.CONFIRMED);\n }\n\n public Long getId() {\n return this.user.getId();\n }\n}"
}
] | import static de.ait.ems.dto.GroupDto.from;
import static de.ait.ems.dto.UserDto.from;
import de.ait.ems.dto.GroupDto;
import de.ait.ems.dto.NewGroupDto;
import de.ait.ems.dto.UpdateGroupDto;
import de.ait.ems.dto.UserDto;
import de.ait.ems.exceptions.RestException;
import de.ait.ems.mapper.EntityMapper;
import de.ait.ems.models.Course;
import de.ait.ems.models.Group;
import de.ait.ems.models.User;
import de.ait.ems.models.UserGroup;
import de.ait.ems.repositories.CoursesRepository;
import de.ait.ems.repositories.GroupsRepository;
import de.ait.ems.repositories.UserGroupsRepository;
import de.ait.ems.security.details.AuthenticatedUser;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; | 4,137 | package de.ait.ems.services;
/**
* 14/10/2023 EducationalManagementSystem
*
* @author Wladimir Weizen
*/
@RequiredArgsConstructor
@Service
public class GroupsService {
private final GroupsRepository groupsRepository;
private final CoursesRepository coursesRepository;
private final UserGroupsRepository userGroupsRepository;
private final EntityMapper entityMapper;
| package de.ait.ems.services;
/**
* 14/10/2023 EducationalManagementSystem
*
* @author Wladimir Weizen
*/
@RequiredArgsConstructor
@Service
public class GroupsService {
private final GroupsRepository groupsRepository;
private final CoursesRepository coursesRepository;
private final UserGroupsRepository userGroupsRepository;
private final EntityMapper entityMapper;
| public GroupDto addGroup(NewGroupDto newGroup) { | 3 | 2023-10-07 16:00:02+00:00 | 8k |
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom | src/UI/LevelCompleted.java | [
{
"identifier": "Gamestate",
"path": "src/gamestates/Gamestate.java",
"snippet": "public enum Gamestate {\n PLAYING, MENU, OPTIONS, QUIT;\n public static Gamestate state = MENU;\n}"
},
{
"identifier": "Playing",
"path": "src/gamestates/Playing.java",
"snippet": "public class Playing extends State implements Statemethods {\n private Player player;\n private LevelManager levelManager;\n private EnemyManager enemyManager;\n private PauseOverlay pauseOverlay;\n private GameOverOverlay gameOverOverlay;\n private LevelCompleted levelCompleted;\n private ObjectManager objectManager;\n private boolean paused = false ;\n \n private int xLvlOffset;\n\tprivate int leftBorder = (int) (0.2 * Game.GAME_WIDTH);\n\tprivate int rightBorder = (int) (0.8 * Game.GAME_WIDTH);\n\tprivate int maxLvlOffsetX;\n\t\n\t//new modify for the multiple background\n\tpublic int currentLevelIndex = 0; \n\tprivate BufferedImage backgroundImg, smallcloudImg;\n\tprivate int[] smallCloudsPos;\n\tprivate Random rnd = new Random();\n\t\n\tprivate boolean gameOver;\n\tprivate boolean lvlCompleted;\n\tprivate boolean playerDying;\n\t\n\n public Playing(Game game) {\n super(game);\n initClasses();\n \n\t\t// Setting the background playing and all the environment in the background\n backgroundImg = LoadSave.GetSpriteAtlas(LoadSave.PLAYING_BG_IMG_MAP1); // default background will be background1\n smallcloudImg = LoadSave.GetSpriteAtlas(LoadSave.WHITE_SMALL_CLOUDS); // default small clouds\n smallCloudsPos = new int[8];\n\t\tfor (int i = 0; i < smallCloudsPos.length; i++)\n\t\t\tsmallCloudsPos[i] = (int) (90 * Game.SCALE) + rnd.nextInt((int) (100 * Game.SCALE));\n calcLvlOffset();\n\t\tloadStartLevel();\n }\n \n private void loadStartLevel() {\n\t\tenemyManager.loadEnemies(levelManager.getCurrentLevel());\n\t\tobjectManager.loadObjects(levelManager.getCurrentLevel());\n\t}\n\n\tprivate void calcLvlOffset() {\n\t\tmaxLvlOffsetX = levelManager.getCurrentLevel().getLvlOffset();\n\t}\n\t\n\tpublic void loadNextLevel() {\n\t\t// resetAll();\n\t\tlevelManager.loadNextLevel();\n\t\tplayer.setSpawn(levelManager.getCurrentLevel().getPlayerSpawn());\n\t\tresetAll();\n\n\t\t// Set background based on the current level index\n switch (currentLevelIndex) {\n case 0:\n setBackgroundImage(LoadSave.GetSpriteAtlas(LoadSave.PLAYING_BG_IMG_MAP2));\n setSmallCloudImage(LoadSave.GetSpriteAtlas(LoadSave.BLACK_SMALL_CLOUDS));\n break;\n case 1:\n setBackgroundImage(LoadSave.GetSpriteAtlas(LoadSave.PLAYING_BG_IMG_MAP3));\n setSmallCloudImage(LoadSave.GetSpriteAtlas(LoadSave.GREY_SMALL_CLOUDS));\n break;\n \n }\n \n currentLevelIndex++; // Increment the current level index for the next level\n\t}\n\t\n private void initClasses() {\n levelManager = new LevelManager(game);\n enemyManager = new EnemyManager(this);\n objectManager = new ObjectManager(this);\n \n player = new Player(200, 200, (int) (140 * Game.SCALE), (int) (102 * Game.SCALE),this);\n player.loadLvlData(levelManager.getCurrentLevel().getLevelData());\n player.setSpawn(levelManager.getCurrentLevel().getPlayerSpawn());\n \n pauseOverlay = new PauseOverlay(this);\n gameOverOverlay = new GameOverOverlay(this);\n levelCompleted = new LevelCompleted(this);\n }\n\n @Override\n public void update() {\n \tif (paused) {\n\t\t\tpauseOverlay.update();\n\t\t} else if (lvlCompleted) {\n\t\t\tlevelCompleted.update();\n\t\t} else if (gameOver) {\n\t\t\tgameOverOverlay.update();\n\n\t\t} else if (playerDying) {\n\t\t\tplayer.update();\n\t\t} else {\n\t\t\tlevelManager.update();\n\t\t\tobjectManager.update(levelManager.getCurrentLevel().getLevelData(), player);\n\t\t\tplayer.update();\n\t\t\tenemyManager.update(levelManager.getCurrentLevel().getLevelData(), player);\n\t\t\tcheckCloseToBorder();\n\t\t}\n \n }\n\n private void checkCloseToBorder() {\n \tint playerX = (int) player.getHitbox().x;\n\t\tint diff = playerX - xLvlOffset;\n\n\t\tif (diff > rightBorder)\n\t\t\txLvlOffset += diff - rightBorder;\n\t\telse if (diff < leftBorder)\n\t\t\txLvlOffset += diff - leftBorder;\n\n\t\tif (xLvlOffset > maxLvlOffsetX)\n\t\t\txLvlOffset = maxLvlOffsetX;\n\t\telse if (xLvlOffset < 0)\n\t\t\txLvlOffset = 0;\n\t\t\n\t}\n\n\t//setBackgroundImage() method\n public void setBackgroundImage(BufferedImage backgroundImage) {\n // Set the background image for the playing state\n this.backgroundImg = backgroundImage;\n }\n \n //setSmallCloudImage() method\n public void setSmallCloudImage(BufferedImage smallcloudImage) {\n // Set the cloud image for the playing state\n this.smallcloudImg = smallcloudImage;\n }\n\n\t@Override\n public void draw(Graphics g) {\n\t\t//new modify for drawing the background\n\t\tif (backgroundImg != null) {\n\t\t\tg.drawImage(backgroundImg, 0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT, null);\n\t\t}\n\t\t\n\t\t//drawing big clouds\n\t\tdrawBigClouds(g);\n\n levelManager.draw(g, xLvlOffset);\n player.render(g, xLvlOffset);\n enemyManager.draw(g,xLvlOffset);\n objectManager.draw(g, xLvlOffset);\n\n if (paused) {\n \tg.setColor(new Color(0, 0, 0, 170));\n\t\t\tg.fillRect(0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT);\n\t\t\tpauseOverlay.draw(g);\n }else if(gameOver)\n \tgameOverOverlay.draw(g); \n else if (lvlCompleted)\n\t\t\tlevelCompleted.draw(g);\n }\n\t\n\t// drawClouds method()\n\tprivate void drawBigClouds(Graphics g) {\n\t\tfor (int i = 0; i < smallCloudsPos.length; i++) // for loop to make the small cloud randomly throught all the map\n\t\t\tg.drawImage(smallcloudImg, SMALL_CLOUD_WIDTH * 4 * i - (int) (xLvlOffset * 0.7), smallCloudsPos[i], SMALL_CLOUD_WIDTH, SMALL_CLOUD_HEIGHT, null);\n\t}\n\t\n\tpublic void resetAll() {\n\t\tgameOver = false;\n\t\tpaused = false;\n\t\tlvlCompleted = false;\n\t\tplayerDying = false;\n\t\tplayer.resetAll();\n\t\tenemyManager.resetAllEnemies();\n\t\tobjectManager.resetAllObjects();\n\t}\n\t\n\t\n\tpublic void setGameOver(boolean gameOver) {\n\t\tthis.gameOver = gameOver;\n\t}\n\t\n\tpublic void checkObjectHit(Rectangle2D.Float attackBox) {\n\t\tobjectManager.checkObjectHit(attackBox);\n\t}\n\t\n\tpublic void checkEnemyHit(Rectangle2D.Float attackBox) {\n\t\tenemyManager.checkEnemyHit(attackBox);\n\t}\n\n\tpublic void checkPotionTouched(Rectangle2D.Float hitbox) {\n\t\tobjectManager.checkObjectTouched(hitbox);\n\t}\n\tpublic void checkSpikesTouched(Player p) {\n\t\tobjectManager.checkSpikesTouched(p);\n\t}\n\t\n @Override\n public void mouseClicked(MouseEvent e) {\n \tif(!gameOver)\n \t\tif (e.getButton() == MouseEvent.BUTTON1)\n \t\t\tplayer.setAttacking(true);\n }\n \n @Override\n public void keyPressed(KeyEvent e) {\n \tif (gameOver)\n \t\tgameOverOverlay.keyPressed(e);\n \telse\n \t\tswitch (e.getKeyCode()) {\n case KeyEvent.VK_A:\n player.setLeft(true);\n break;\n case KeyEvent.VK_D:\n player.setRight(true);\n break;\n case KeyEvent.VK_SPACE:\n player.setJump(true);\n break;\n case KeyEvent.VK_ESCAPE:\n paused = !paused;\n break;\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n \tif(!gameOver)\n \t\tswitch (e.getKeyCode()) {\n case KeyEvent.VK_A:\n player.setLeft(false);\n break;\n case KeyEvent.VK_D:\n player.setRight(false);\n break;\n case KeyEvent.VK_SPACE:\n player.setJump(false);\n break;\n \n }\n\n }\n\n public void mouseDragged(MouseEvent e) {\n \tif(!gameOver)\n \t\tif (paused)\n pauseOverlay.mouseDragged(e); \n }\n\n @Override\n public void mousePressed(MouseEvent e) {\n \tif (!gameOver) {\n\t\t\tif (paused)\n\t\t\t\tpauseOverlay.mousePressed(e);\n\t\t\telse if (lvlCompleted)\n\t\t\t\tlevelCompleted.mousePressed(e);\n \t}\telse\n\t\t\tgameOverOverlay.mousePressed(e);\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n \tif (!gameOver) {\n\t\t\tif (paused)\n\t\t\t\tpauseOverlay.mouseReleased(e);\n\t\t\telse if (lvlCompleted)\n\t\t\t\tlevelCompleted.mouseReleased(e);\n\t\t}\telse\n\t\t\tgameOverOverlay.mouseReleased(e);\n }\n\n @Override\n public void mouseMoved(MouseEvent e) {\n \tif (!gameOver) {\n\t\t\tif (paused)\n\t\t\t\tpauseOverlay.mouseMoved(e);\n\t\t\telse if (lvlCompleted)\n\t\t\t\tlevelCompleted.mouseMoved(e);\n\t\t}\telse\n\t\t\tgameOverOverlay.mouseMoved(e);\n }\n\n\n public void unpauseGame() {\n paused = false;\n }\n\n public void windowFocusLost() {\n player.resetDirBooleans();\n }\n\n public Player getPlayer() {\n return player;\n }\n \n public EnemyManager getEnemyManager() {\n\t\treturn enemyManager;\n\t}\n \n public void setLevelCompleted(boolean levelCompleted) {\n\t\tthis.lvlCompleted = levelCompleted;\n\t\tif(levelCompleted)\n\t\t\tgame.getAudioPlayer().lvlCompleted();\n\t}\n\n\tpublic void setMaxLvlOffset(int lvlOffset) {\n\t\tthis.maxLvlOffsetX = lvlOffset;\n\t}\n\tpublic ObjectManager getObjectManager() {\n\t\treturn objectManager;\n\t}\n\tpublic LevelManager getLevelManager() {\n\t\treturn levelManager;\n\t}\n\tpublic void setPlayerDying (boolean playerDying) {\n\t\tthis.playerDying = playerDying;\n\t}\n}"
},
{
"identifier": "Game",
"path": "src/main/Game.java",
"snippet": "public class Game implements Runnable {\n\n\tprivate GameWindow gameWindow;\n\tprivate GamePanel gamePanel;\n\tprivate Thread gameThread;\n\tprivate final int FPS_SET = 120;\n\tprivate final int UPS_SET = 200;\n\n\tprivate Playing playing;\n\tprivate Menu menu;\n\tprivate GameOptions gameOptions;\n\tprivate AudioOptions audioOptions;\n\tprivate AudioPlayer audioPlayer;\n\t\n\tpublic final static int TILES_DEFAULT_SIZE = 32;\n\tpublic final static float SCALE = 1f;\n\tpublic final static int TILES_IN_WIDTH = 26;\n\tpublic final static int TILES_IN_HEIGHT = 14;\n\tpublic final static int TILES_SIZE = (int) (TILES_DEFAULT_SIZE * SCALE);\n\tpublic final static int GAME_WIDTH = TILES_SIZE * TILES_IN_WIDTH;\n\tpublic final static int GAME_HEIGHT = TILES_SIZE * TILES_IN_HEIGHT;\n\n\tpublic Game() {\n\t\t\n\t\tLoadSave.GetAllLevels();\n\t\tinitClasses();\n\n\t\tgamePanel = new GamePanel(this);\n\t\tgameWindow = new GameWindow(gamePanel);\n\t\tgamePanel.setFocusable(true);\n\t\tgamePanel.requestFocus();\n\n\t\tstartGameLoop();\n\t}\n\n\tprivate void initClasses() {\n\t\taudioOptions = new AudioOptions(this);\n\t\taudioPlayer = new AudioPlayer();\n\t\tmenu = new Menu(this);\n\t\tplaying = new Playing(this);\n\t\tgameOptions = new GameOptions(this);\n\t}\n\n\tprivate void startGameLoop() {\n\t\tgameThread = new Thread(this);\n\t\tgameThread.start();\n\t}\n\n\tpublic void update() {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tmenu.update();\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tplaying.update();\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgameOptions.update();\n\t\t\t\tbreak;\n\t\t\tcase QUIT:\n\t\t\tdefault:\n\t\t\t\tSystem.exit(0);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic void render(Graphics g) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tmenu.draw(g);\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tplaying.draw(g);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgameOptions.draw(g);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void run() {\n\n\t\tdouble timePerFrame = 1000000000.0 / FPS_SET;\n\t\tdouble timePerUpdate = 1000000000.0 / UPS_SET;\n\n\t\tlong previousTime = System.nanoTime();\n\n\t\tint frames = 0;\n\t\tint updates = 0;\n\t\tlong lastCheck = System.currentTimeMillis();\n\n\t\tdouble deltaU = 0;\n\t\tdouble deltaF = 0;\n\n\t\twhile (true) {\n\t\t\tlong currentTime = System.nanoTime();\n\n\t\t\tdeltaU += (currentTime - previousTime) / timePerUpdate;\n\t\t\tdeltaF += (currentTime - previousTime) / timePerFrame;\n\t\t\tpreviousTime = currentTime;\n\n\t\t\tif (deltaU >= 1) {\n\t\t\t\tupdate();\n\t\t\t\tupdates++;\n\t\t\t\tdeltaU--;\n\t\t\t}\n\n\t\t\tif (deltaF >= 1) {\n\t\t\t\tgamePanel.repaint();\n\t\t\t\tframes++;\n\t\t\t\tdeltaF--;\n\t\t\t}\n\n\t\t\tif (System.currentTimeMillis() - lastCheck >= 1000) {\n\t\t\t\tlastCheck = System.currentTimeMillis();\n\t\t\t\tSystem.out.println(\"FPS: \" + frames + \" | UPS: \" + updates);\n\t\t\t\tframes = 0;\n\t\t\t\tupdates = 0;\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void windowFocusLost() {\n\t\tif (Gamestate.state == Gamestate.PLAYING)\n\t\t\tplaying.getPlayer().resetDirBooleans();\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\tpublic Playing getPlaying() {\n\t\treturn playing;\n\t}\n\tpublic GameOptions getGameOptions() {\n\t\treturn gameOptions;\n\t}\n\tpublic AudioOptions getAudioOptions() {\n\t\treturn audioOptions;\n\t}\n\tpublic AudioPlayer getAudioPlayer() {\n\t\treturn audioPlayer;\n\t}\n}"
},
{
"identifier": "LoadSave",
"path": "src/utilz/LoadSave.java",
"snippet": "public class LoadSave {\n\n\tpublic static final String PLAYER_ATLAS = \"player_sprites_sheet.png\";\n\tpublic static final String LEVEL_ATLAS = \"outside_sprites.png\";\n\tpublic static final String MENU_BUTTONS = \"button_atlas.png\";\n\tpublic static final String MENU_BACKGROUND = \"menu_background.png\";\n\tpublic static final String PAUSE_BACKGROUND = \"pause_menu.png\";\n\tpublic static final String SOUND_BUTTONS = \"sound_button.png\";\n\tpublic static final String URM_BUTTONS = \"urm_buttons.png\";\n\tpublic static final String VOLUME_BUTTONS = \"volume_buttons.png\";\n\n\t//constants variables for the background \n\tpublic static final String PLAYING_BG_IMG_MAP1 = \"playing_bg_img_map1.png\";\n\tpublic static final String PLAYING_BG_IMG_MAP2 = \"playing_bg_img_map2.png\";\n\tpublic static final String PLAYING_BG_IMG_MAP3 = \"playing_bg_img_map3.png\";\n\n\t//constants variables for the environment\n\tpublic static final String WHITE_SMALL_CLOUDS = \"white_small_clouds.png\";\n\tpublic static final String BLACK_SMALL_CLOUDS = \"black_small_clouds.png\";\n\tpublic static final String GREY_SMALL_CLOUDS = \"grey_small_clouds.png\";\n\t\n\tpublic static final String CARNIVOROUS_SPRITE = \"carnivorous.png\";\n\tpublic static final String TURTLE_SPRITE = \"Battle_Turtle.png\";\n\tpublic static final String BIG_BLOATED_SPRITE = \"Big_Bloated.png\";\n\t\n\tpublic static final String HEALTH_POWER_BAR = \"health_power_bar.png\";\n\tpublic static final String LEVEL_COMPLETED = \"completed_sprite.png\";\n\t\n\tpublic static final String POTION = \"potions_sprites.png\";\n\tpublic static final String CONTAINER = \"objects_sprites.png\";\n\tpublic static final String TRAP = \"trap_atlas.png\";\n\tpublic static final String CANNON_ATLAS = \"cannon_atlas.png\";\n\tpublic static final String CANNON_BALL = \"ball.png\";\n\tpublic static final String DEATH_SCREEN = \"death_screen.png\";\n\tpublic static final String OPTIONS_MENU = \"options_background.png\";\n\n\n\n\tpublic static BufferedImage GetSpriteAtlas(String fileName) {\n\t BufferedImage img = null;\n\t try {\n\t InputStream is = LoadSave.class.getResourceAsStream(\"/\" + fileName);\n\t if (is != null) {\n\t img = ImageIO.read(is);\n\t } else {\n\t System.out.println(\"Failed to find file: \" + fileName);\n\t }\n\t } catch (IOException e) {\n\t e.printStackTrace();\n\t }\n\t return img;\n\t}\n\t\n\t\n\tpublic static BufferedImage[] GetAllLevels() {\n\t\tURL url = LoadSave.class.getResource(\"/Lvls\");\n\t\tFile file = null;\n\n\t\ttry {\n\t\t\tfile = new File(url.toURI());\n\t\t} catch (URISyntaxException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tFile[] files = file.listFiles();\n\t\tFile[] filesSorted = new File[files.length];\n\n\t\tfor (int i = 0; i < filesSorted.length; i++)\n\t\t\tfor (int j = 0; j < files.length; j++) {\n\t\t\t\tif (files[j].getName().equals((i + 1) + \".png\"))\n\t\t\t\t\tfilesSorted[i] = files[j];\n\n\t\t\t}\n\n\t\tBufferedImage[] imgs = new BufferedImage[filesSorted.length];\n\n\t\tfor (int i = 0; i < imgs.length; i++)\n\t\t\ttry {\n\t\t\t\timgs[i] = ImageIO.read(filesSorted[i]);\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\treturn imgs;\n\t}\n\t\n\t\n\t\n\n\n}"
},
{
"identifier": "URMButtons",
"path": "src/utilz/Constants.java",
"snippet": "public static class URMButtons {\n\tpublic static final int URM_DEFAULT_SIZE = 56;\n\tpublic static final int URM_SIZE = (int) (URM_DEFAULT_SIZE * Game.SCALE);\n\n}"
}
] | import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import gamestates.Gamestate;
import gamestates.Playing;
import main.Game;
import utilz.LoadSave;
import static utilz.Constants.UI.URMButtons.*; | 5,013 | package UI;
public class LevelCompleted {
private Playing playing;
private UrmButton menu, next;
private BufferedImage img;
private int bgX, bgY, bgW, bgH;
public LevelCompleted(Playing playing) {
this.playing = playing;
initImg();
initButtons();
}
private void initButtons() {
int menuX = (int) (330 * Game.SCALE);
int nextX = (int) (445 * Game.SCALE);
int y = (int) (195 * Game.SCALE);
next = new UrmButton(nextX, y, URM_SIZE, URM_SIZE, 0);
menu = new UrmButton(menuX, y, URM_SIZE, URM_SIZE, 2);
}
private void initImg() {
img = LoadSave.GetSpriteAtlas(LoadSave.LEVEL_COMPLETED);
bgW = (int) (img.getWidth() * Game.SCALE);
bgH = (int) (img.getHeight() * Game.SCALE);
bgX = Game.GAME_WIDTH / 2 - bgW / 2;
bgY = (int) (75 * Game.SCALE);
}
public void draw(Graphics g) {
g.setColor(new Color(0, 0, 0, 200));
g.fillRect(0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT);
g.drawImage(img, bgX, bgY, bgW, bgH, null);
next.draw(g);
menu.draw(g);
}
public void update() {
next.update();
menu.update();
}
private boolean isIn(UrmButton b, MouseEvent e) {
return b.getBounds().contains(e.getX(), e.getY());
}
public void mouseMoved(MouseEvent e) {
next.setMouseOver(false);
menu.setMouseOver(false);
if (isIn(menu, e))
menu.setMouseOver(true);
else if (isIn(next, e))
next.setMouseOver(true);
}
public void mouseReleased(MouseEvent e) {
if (isIn(menu, e)) {
if (menu.isMousePressed()) {
playing.resetAll(); | package UI;
public class LevelCompleted {
private Playing playing;
private UrmButton menu, next;
private BufferedImage img;
private int bgX, bgY, bgW, bgH;
public LevelCompleted(Playing playing) {
this.playing = playing;
initImg();
initButtons();
}
private void initButtons() {
int menuX = (int) (330 * Game.SCALE);
int nextX = (int) (445 * Game.SCALE);
int y = (int) (195 * Game.SCALE);
next = new UrmButton(nextX, y, URM_SIZE, URM_SIZE, 0);
menu = new UrmButton(menuX, y, URM_SIZE, URM_SIZE, 2);
}
private void initImg() {
img = LoadSave.GetSpriteAtlas(LoadSave.LEVEL_COMPLETED);
bgW = (int) (img.getWidth() * Game.SCALE);
bgH = (int) (img.getHeight() * Game.SCALE);
bgX = Game.GAME_WIDTH / 2 - bgW / 2;
bgY = (int) (75 * Game.SCALE);
}
public void draw(Graphics g) {
g.setColor(new Color(0, 0, 0, 200));
g.fillRect(0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT);
g.drawImage(img, bgX, bgY, bgW, bgH, null);
next.draw(g);
menu.draw(g);
}
public void update() {
next.update();
menu.update();
}
private boolean isIn(UrmButton b, MouseEvent e) {
return b.getBounds().contains(e.getX(), e.getY());
}
public void mouseMoved(MouseEvent e) {
next.setMouseOver(false);
menu.setMouseOver(false);
if (isIn(menu, e))
menu.setMouseOver(true);
else if (isIn(next, e))
next.setMouseOver(true);
}
public void mouseReleased(MouseEvent e) {
if (isIn(menu, e)) {
if (menu.isMousePressed()) {
playing.resetAll(); | playing.setGamestate(Gamestate.MENU); | 0 | 2023-10-07 12:07:45+00:00 | 8k |
whykang/Trajectory-extraction | app/src/main/java/com/wang/tracker/MainActivity.java | [
{
"identifier": "LogRecorder",
"path": "app/src/main/java/com/wang/tracker/log/LogRecorder.java",
"snippet": "public class LogRecorder {\n Context context = null;\n public static LogRecorder instance;\n\n static String STORAGE_PATH = \"\";\n\n public LogRecorder(Context context) {\n this.context = context;\n STORAGE_PATH = context.getExternalFilesDir(\"log\").toString();\n }\n\n public static synchronized LogRecorder getInstance() {\n if (instance != null) return instance;\n return null;\n }\n\n public static synchronized LogRecorder getInstance(Context context) {\n if (instance != null) return instance;\n instance = new LogRecorder(context);\n return instance;\n }\n\n\n public int e(String TAG, String msg) {\n writeFile(String.valueOf(new Date().getTime()) + '-' + TAG, msg);\n Log.e(TAG, STORAGE_PATH);\n return 0;\n }\n\n\n public void i(String TAG, String msg) {\n writeFile(String.valueOf(new Date().getTime()) + '-' + TAG, msg);\n Log.i(TAG, msg);\n }\n\n public void writeFile(String fileName, String content) {\n File path = new File(STORAGE_PATH);\n if (!path.exists()) path.mkdir();\n File file = new File(STORAGE_PATH + File.separator + fileName);\n FileOutputStream fos = null;\n OutputStreamWriter osw = null;\n try {\n if (!file.exists()) {\n boolean hasFile = file.createNewFile();\n fos = new FileOutputStream(file);\n } else {\n fos = new FileOutputStream(file, true);\n }\n osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);\n osw.write(content);\n osw.write(\"\\r\\n\");\n } catch (Exception e) {\n } finally {\n // 关闭流\n try {\n if (osw != null) {\n osw.close();\n }\n if (fos != null) {\n fos.close();\n }\n } catch (IOException e) {\n }\n }\n }\n}"
},
{
"identifier": "StepPosition",
"path": "app/src/main/java/com/wang/tracker/pojo/StepPosition.java",
"snippet": "public class StepPosition {\n private Long time;\n private Float dx;\n private Float dy;\n\n public StepPosition(Long time, Float dx, Float dy) {\n this.time = time;\n this.dx = dx;\n this.dy = dy;\n }\n\n public Float getDx() {\n return dx;\n }\n\n public void setDx(float x) {\n\n this.dx=x;\n // return dx;\n }\n\n public void setDy(float y) {\n\n this.dy=y;\n // return dx;\n }\n\n public Float getDy() {\n return dy;\n }\n\n public long getTime() {\n return time;\n }\n\n @Override\n public String toString() {\n return \"StepPosition{\" +\n \"time=\" + time +\n \", dx=\" + dx +\n \", dy=\" + dy +\n '}';\n }\n}"
},
{
"identifier": "StepEventHandler",
"path": "app/src/main/java/com/wang/tracker/sensor/StepEventHandler.java",
"snippet": "public class StepEventHandler {\n private final Handler activityHandler;\n\n private final Handler activityHandler1;\n\n private List<Float> angles=new ArrayList<Float>();\n private Context context;\n\n public StepEventHandler(Handler activityHandler, Handler activityHandler1, Context con) {\n\n\n this.activityHandler = activityHandler;\n this.activityHandler1 = activityHandler1;\n this.context=con;\n\n }\n\n /**\n * Calculate the direction and distance of this step\n * Of course, the numbers are relative\n * */\n public void onStep() {\n float angle = (float) OrientationData.getInstance().getAzimuth();\n\n angles.add(angle);\n\n\n float ang=angle;\n\n SharedPreferences dataBase =context. getSharedPreferences(\"Sha\", context.MODE_PRIVATE);\n SharedPreferences.Editor edit = dataBase.edit();\n int phclnum=dataBase.getInt(\"phcl\", 3);\n\n if(angles.size()>200)\n {\n angles.clear();\n }\n\n if(angles.size()>phclnum)\n {\n ang=pro(angles,phclnum);\n }\n\n\n float distance = getStepSize();\n //StepPosition stepPosition = new StepPosition(new Date().getTime(), (float) -Math.cos(angle) * distance, (float) -Math.sin(angle) * distance);\n\n StepPosition stepPosition = new StepPosition(new Date().getTime(), (float) Math.sin(ang) * distance, (float) Math.cos(ang) * distance);\n Message message = new Message();\n Message message1 = new Message();\n message.obj = stepPosition;\n message.arg1= (int) distance;\n// LogRecorder.getInstance().i(\"distance\", distance+\"======\");\n// LogRecorder.getInstance().i(\"angle\", angle+\"----11\");\n// LogRecorder.getInstance().i(\"stepPosition\", stepPosition.toString());\n activityHandler.sendMessage(message);\n\n\n }\n\n\n public void onStep1() {\n float angle = (float) OrientationData.getInstance().getAzimuth();\n Message message1 = new Message();\n int degree = (int) Math.toDegrees(angle);//旋转角度\n if (degree < 0) {\n degree += 360;\n }\n\n message1.arg1 =degree;\n activityHandler1.sendMessage(message1);\n\n }\n\n private float pro(List<Float> angs,int phnum)\n {\n float result=0;\n float sum=0;\n\n // LogRecorder.getInstance().i(\"angle\", phnum+\"phnum_______----11\");\n\n for (int i=angs.size()-1;i>(angs.size()-1-phnum);i--){\n\n sum+=angs.get(i);\n\n }\n\n result=sum/phnum;\n\n return result;\n\n }\n\n /**\n * Calculate this step size according to the formula\n * */\n private float getStepSize() {\n float a = (float) Math.pow(WaveRecorder.getInstance().calculateAndReset(), 0.25);\n float c = 0.5f;\n return a * c;\n }\n}"
},
{
"identifier": "StepEventListener",
"path": "app/src/main/java/com/wang/tracker/sensor/StepEventListener.java",
"snippet": "public class StepEventListener implements SensorEventListener {\n private final SensorManager sensorManager;\n private final Sensor stepDetectorSensor, rotationVectorSensor, linearAccelerationSensor, mageSensor,accelerationSensor;\n private StepEventHandler stepEventHandler;\n\n private float[] rotationMatrixFromVector = new float[16];\n private float[] rotationMatrix = new float[16];\n private float[] orientationVals = new float[3];\n\n\n float accValues[] = new float[3];\n //地磁传感器数据\n float magValues[] = new float[3];\n //旋转矩阵,用来保存磁场和加速度的数据\n float r[] = new float[9];\n //模拟方向传感器的数据(原始数据为弧度)\n float values[] = new float[3];\n private Context context;\n\n\n\n\n\n public StepEventListener(SensorManager sensorManager, StepEventHandler stepEventHandler, Context con) {\n this.sensorManager = sensorManager;\n this.stepDetectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);\n this.rotationVectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);\n this.linearAccelerationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);\n this.mageSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);\n this.accelerationSensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);\n this.stepEventHandler = stepEventHandler;\n context=con;\n\n }\n\n public void start() {\n sensorManager.registerListener(this, stepDetectorSensor, SensorManager.SENSOR_DELAY_NORMAL);//步数检测\n sensorManager.registerListener(this, rotationVectorSensor, SensorManager.SENSOR_DELAY_NORMAL);//旋转矢量传感器\n sensorManager.registerListener(this, linearAccelerationSensor, SensorManager.SENSOR_DELAY_NORMAL);//线性加速度-无重力\n sensorManager.registerListener(this, mageSensor, SensorManager.SENSOR_DELAY_NORMAL);//磁场\n sensorManager.registerListener(this, accelerationSensor, SensorManager.SENSOR_DELAY_NORMAL);//加速度传感器\n }\n\n public void stop() {\n sensorManager.unregisterListener(this);\n }\n\n /**\n * Update the corresponding information to the data object for different sensors\n * */\n @Override\n public void onSensorChanged(SensorEvent sensorEvent) {\n switch (sensorEvent.sensor.getType()) {\n case Sensor.TYPE_ROTATION_VECTOR:\n// SensorManager.getRotationMatrixFromVector(rotationMatrixFromVector, sensorEvent.values);\n// SensorManager.remapCoordinateSystem(rotationMatrixFromVector,\n// SensorManager.AXIS_X, SensorManager.AXIS_Z,\n// rotationMatrix);\n// SensorManager.getOrientation(rotationMatrix, orientationVals);\n // OrientationData.getInstance().update(orientationVals);\n break;\n case Sensor.TYPE_LINEAR_ACCELERATION:\n float linearAcceleration = (float) Math.sqrt(\n sensorEvent.values[0] * sensorEvent.values[0]\n + sensorEvent.values[1] * sensorEvent.values[1]\n + sensorEvent.values[2] * sensorEvent.values[2]);\n AccelerationMagnitudeData.getInstance().update(linearAcceleration);\n WaveRecorder.getInstance().update(linearAcceleration);\n //mAcceleValues = sensorEvent.values;\n break;\n case Sensor.TYPE_STEP_DETECTOR:\n stepEventHandler.onStep();\n break;\n case Sensor.TYPE_MAGNETIC_FIELD:\n magValues = sensorEvent.values.clone();\n break;\n case Sensor.TYPE_ACCELEROMETER:\n accValues = sensorEvent.values.clone();\n calculateOrientation();\n break;\n }\n\n\n\n\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n\n\n }\n\n\n public void calculateOrientation(){\n\n SensorManager.getRotationMatrix(r, null, accValues, magValues);\n\n SharedPreferences dataBase =context. getSharedPreferences(\"Sha\", context.MODE_PRIVATE);\n SharedPreferences.Editor edit = dataBase.edit();\n\n /**\n * R:旋转数组\n * values:模拟方向传感器的数据\n */\n\n int a=0;\n int num=20;\n\n String name = dataBase.getString(\"ch1\", \"0\");\n\n num = dataBase.getInt(\"pnum\", 15);\n\n if(name.equals(\"1\"))\n {\n a=1;\n\n }\n\n SensorManager.getOrientation(r, values);\n\n OrientationData.getInstance().update(values,a,num);\n\n stepEventHandler.onStep1();\n\n //将弧度转化为角度后输出\n// float azimuth = (float) Math.toDegrees(values[0]);\n// float pitch = (float) Math.toDegrees(values[1]);\n// float roll = (float) Math.toDegrees(values[2]);\n\n //LogRecorder.getInstance().i(\"angle\", azimuth+\" \"+\"______________\");\n// if(azimuth >= 0 && azimuth <= 90){\n// LogRecorder.getInstance().i(\"angle\", azimuth+\" \"+\"正指向东北方向\");\n// //textViewx.setText(azimuth+\" \"+\"正指向东北方向\");\n// }else{\n// LogRecorder.getInstance().i(\"angle\", azimuth+\"\");\n// //textViewx.setText(azimuth+\"\");\n// }\n// if(pitch <=0 && pitch >= -90){\n// LogRecorder.getInstance().i(\"angle\", pitch+\" \"+\"手机顶部正往上抬起\");\n// //textViewy.setText(pitch+\" \"+\"手机顶部正往上抬起\");\n// }else{\n// LogRecorder.getInstance().i(\"angle\", pitch+\"\");\n// // textViewy.setText(pitch+\"\");\n// }\n// if(roll <=0 && pitch >= -90){\n// LogRecorder.getInstance().i(\"angle\", roll+\" \"+\"手机右侧正往上抬起\");\n// //textViewz.setText(roll+\" \"+\"手机右侧正往上抬起\");\n// }else{\n// LogRecorder.getInstance().i(\"angle\", roll+\"\");\n// // textViewz.setText(roll+\"\");\n// }\n\n\n }\n\n}"
},
{
"identifier": "Permission",
"path": "app/src/main/java/com/wang/tracker/tool/Permission.java",
"snippet": "public class Permission {\n //需要申请权限的数组\n private final String[] permissions = {\n Manifest.permission.ACTIVITY_RECOGNITION,\n Manifest.permission.WRITE_EXTERNAL_STORAGE,\n Manifest.permission.READ_EXTERNAL_STORAGE\n };\n //保存真正需要去申请的权限\n private final List<String> permissionList = new ArrayList<>();\n\n public static int RequestCode = 100;\n\n public void checkPermissions(Activity activity) {\n for (String permission : permissions) {\n// if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {\n// permissionList.add(permission);\n// }\n permissionList.add(permission);\n }\n\n requestPermission(activity);\n\n //有需要去动态申请的权限\n// if (permissionList.size() > 0) {\n// requestPermission(activity);\n// Toast.makeText(activity, \"请授权\", Toast.LENGTH_SHORT).show();\n// }\n// else{\n// Toast.makeText(activity, \"已授权\", Toast.LENGTH_SHORT).show();\n// }\n }\n //去申请的权限\n private void requestPermission(Activity activity) {\n ActivityCompat.requestPermissions(activity,permissionList.toArray(new String[permissionList.size()]),RequestCode);\n }\n\n}"
}
] | import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.wang.tracker.databinding.ActivityFullscreenBinding;
import com.wang.tracker.log.LogRecorder;
import com.wang.tracker.pojo.StepPosition;
import com.wang.tracker.sensor.StepEventHandler;
import com.wang.tracker.sensor.StepEventListener;
import com.wang.tracker.tool.Permission;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 4,503 | package com.wang.tracker;
/**
*
* @Description V2.0
* @Author WangHongyue
* @CreateTime 2023-10-12 15:32
*/
public class MainActivity extends AppCompatActivity {
private static final int UI_ANIMATION_DELAY = 300;
private static final int PERMISSION_REQUEST_CODE =100;
private float x=0,y=0;
private int x623=0;
private final Handler mHideHandler = new Handler();
private TextView text;
private Button cle,abu,save,set;
private Handler positionHandler,positionHandler1;
private int xnum=0;
private int ynum=0;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
if (Build.VERSION.SDK_INT >= 30) {
// mCanvas.getWindowInsetsController().hide(
// WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCanvas.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
};
private View mControlsView;
private CanvasView mCanvas;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = this::hide;
private void clearView() {
tipDialog();
}
/**
* 提示对话框
*/
public void tipDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示:");
builder.setMessage("重置后将恢复初始界面,且轨迹数据将不可保存!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setCancelable(true); //点击对话框以外的区域是否让对话框消失
//设置正面按钮
builder.setPositiveButton("确定重置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.clearPoints(xnum,ynum);
if(positions!=null && positions.size()>0){
positions.clear();
}
dialog.dismiss();
}
});
//设置反面按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create(); //创建AlertDialog对象
//对话框显示的监听事件
dialog.show(); //显示对话框
}
// private void requestPermission() {
// // checkSelfPermission() 检测权限
// String[] PERMISSIONS_STORAGE = {
// Manifest.permission.READ_EXTERNAL_STORAGE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE};
//
// if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE )!= PackageManager.PERMISSION_GRANTED) {
// //TODO 申请存储权限
// ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
// PERMISSION_REQUEST_CODE);
// }
//
// else{
// // Utils.writeTxt(getApplicationContext(),"44444444444",true);
// Toast.makeText(getApplicationContext(),"已授予权限",Toast.LENGTH_SHORT).show();
// }
// }
private ActivityFullscreenBinding binding; | package com.wang.tracker;
/**
*
* @Description V2.0
* @Author WangHongyue
* @CreateTime 2023-10-12 15:32
*/
public class MainActivity extends AppCompatActivity {
private static final int UI_ANIMATION_DELAY = 300;
private static final int PERMISSION_REQUEST_CODE =100;
private float x=0,y=0;
private int x623=0;
private final Handler mHideHandler = new Handler();
private TextView text;
private Button cle,abu,save,set;
private Handler positionHandler,positionHandler1;
private int xnum=0;
private int ynum=0;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
if (Build.VERSION.SDK_INT >= 30) {
// mCanvas.getWindowInsetsController().hide(
// WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCanvas.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
};
private View mControlsView;
private CanvasView mCanvas;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = this::hide;
private void clearView() {
tipDialog();
}
/**
* 提示对话框
*/
public void tipDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示:");
builder.setMessage("重置后将恢复初始界面,且轨迹数据将不可保存!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setCancelable(true); //点击对话框以外的区域是否让对话框消失
//设置正面按钮
builder.setPositiveButton("确定重置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.clearPoints(xnum,ynum);
if(positions!=null && positions.size()>0){
positions.clear();
}
dialog.dismiss();
}
});
//设置反面按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create(); //创建AlertDialog对象
//对话框显示的监听事件
dialog.show(); //显示对话框
}
// private void requestPermission() {
// // checkSelfPermission() 检测权限
// String[] PERMISSIONS_STORAGE = {
// Manifest.permission.READ_EXTERNAL_STORAGE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE};
//
// if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE )!= PackageManager.PERMISSION_GRANTED) {
// //TODO 申请存储权限
// ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
// PERMISSION_REQUEST_CODE);
// }
//
// else{
// // Utils.writeTxt(getApplicationContext(),"44444444444",true);
// Toast.makeText(getApplicationContext(),"已授予权限",Toast.LENGTH_SHORT).show();
// }
// }
private ActivityFullscreenBinding binding; | private StepEventHandler stepEventHandler; | 2 | 2023-10-10 12:49:16+00:00 | 8k |
yc-huang/bsdb | src/main/java/tech/bsdb/read/kv/PartitionedKVReader.java | [
{
"identifier": "AsyncFileReader",
"path": "src/main/java/tech/bsdb/io/AsyncFileReader.java",
"snippet": "public interface AsyncFileReader {\n int QD = 512;\n int DEFAULT_TIMEOUT = 1000; //1 us\n int MAX_TIMEOUT = 10 * 1000 * 1000;//1ms\n\n void start();\n\n /**\n * Caution: the buffer will be reused, so should not be accessed after handler.completed() returned\n *\n * @param fd\n * @param position\n * @param handler\n * @throws InterruptedException\n */\n void read(int fd, long position, CompletionHandler<ByteBuffer, Integer> handler) throws InterruptedException;\n\n void read(int fd, long position, int readLen, CompletionHandler<ByteBuffer, Integer> handler) throws InterruptedException;\n\n void close() throws IOException;\n\n class ReadOperation {\n int fd;\n long reqId;\n long readPosition;\n ByteBuffer readBuffer;\n int offset;\n int limit;\n CompletionHandler<ByteBuffer, Integer> handler;\n int readResponse;\n Object attach;\n int alignedReadSize;\n }\n}"
},
{
"identifier": "NativeFileIO",
"path": "src/main/java/tech/bsdb/io/NativeFileIO.java",
"snippet": "public class NativeFileIO {\n public static final int PAGE_SIZE = 4096;\n public static int openForReadDirect(String file) throws IOException {\n return open(file, Native.O_DIRECT | Native.O_RDONLY | Native.O_NOATIME);\n }\n\n public static int open(String file, int flags) throws IOException {\n int fd = Native.open(file, flags);\n if (fd < 0) {\n throw new IOException(\"Error opening \" + file);\n } else {\n return fd;\n }\n }\n\n public static void close(int fd) {\n Native.close(fd);\n }\n\n public static int getBufferSizeForUnalignedRead(int readLen){\n return alignToPageSize(readLen + PAGE_SIZE);\n }\n\n /**\n * align to OS page size\n *\n * @param size\n * @return aligned size\n */\n public static int alignToPageSize(int size) {\n int r = size / PAGE_SIZE * PAGE_SIZE;\n if (r < size) r += PAGE_SIZE;\n return r;\n }\n\n public static ByteBuffer allocateAlignedBuffer(int size){\n return allocateAlignedBuffer(size, Common.MEMORY_ALIGN);\n //return ByteBuffer.allocateDirect(size + Common.MEMORY_ALIGN*2).alignedSlice(Common.MEMORY_ALIGN);\n }\n\n protected static ByteBuffer allocateAlignedBuffer(int size, int alignTo) {\n long addr = Native.allocateAligned(size, alignTo);\n if (addr > 0) {\n return UnsafeUtil.newDirectByteBuffer(addr, size, addr);\n } else {\n throw new RuntimeException(\"alloc failed\");\n }\n }\n\n public static void freeBuffer(ByteBuffer buffer) {\n //Native.free(((DirectBuffer) buffer).address());\n }\n\n public static long readAlignedTo512(int fd, long position, ByteBuffer dst, int len) throws IOException {\n return readAligned(fd, position, dst, len, -512L);\n }\n\n public static long readAlignedTo4096(int fd, long position, ByteBuffer dst, int len) throws IOException {\n return readAligned(fd, position, dst, len, -4096L);\n }\n\n private static long readAligned(int fd, long position, ByteBuffer dst, int len, long lenAlignMask) throws IOException {\n long alignedPos = position & -4096L; //position align to 4096\n int offset = (int) (position - alignedPos);\n int readLen = len + offset;\n int alignedLen = (int) (readLen & lenAlignMask); //read len align to\n if (alignedLen < readLen) alignedLen += (int) (-lenAlignMask);\n if (dst.remaining() < alignedLen)\n throw new IOException(\"no enough space in buffer to contain \" + alignedLen + \", space remain \" + dst.remaining() + \" \" + dst.position());\n\n long rLen = Native.pread(fd, alignedPos, ((DirectBuffer) dst).address(), alignedLen);\n if (rLen < 0) {\n throw new IOException(\"read return error:\" + rLen);\n } else {\n dst.limit((int) rLen);\n dst.position(offset);\n return rLen;\n }\n }\n}"
},
{
"identifier": "SimpleAsyncFileReader",
"path": "src/main/java/tech/bsdb/io/SimpleAsyncFileReader.java",
"snippet": "public class SimpleAsyncFileReader extends BaseAsyncFileReader {\n\n public SimpleAsyncFileReader(int readLen, int submitThreads, String tag) {\n super(readLen, submitThreads, 0, tag);\n }\n\n @Override\n void submitRequest(int partition, ReadOperation[] reqs, int num) throws IOException {\n for (int i = 0; i < num; i++) {\n ReadOperation op = reqs[i];\n op.readBuffer = getPartitionPooledBuffer(partition)[i];\n op.readBuffer.clear();\n int bytesRead = (int) NativeFileIO.readAlignedTo512(op.fd, op.readPosition, op.readBuffer, op.alignedReadSize);\n callback(op, bytesRead);\n }\n }\n\n @Override\n boolean pollResponseAndCallback(int bucket) {\n return false;\n }\n\n @Override\n void close0() {\n\n }\n\n\n}"
},
{
"identifier": "UringAsyncFileReader",
"path": "src/main/java/tech/bsdb/io/UringAsyncFileReader.java",
"snippet": "public class UringAsyncFileReader extends BaseAsyncFileReader {\n IOUring[] rings;\n long[][][] rss;\n Logger logger = LoggerFactory.getLogger(UringAsyncFileReader.class);\n\n public UringAsyncFileReader(int maxReadSize, int submitThreads, String tag) {\n super(maxReadSize, submitThreads, 0, tag);\n rings = new IOUring[submitThreads];\n rss = new long[submitThreads][][];\n for (int i = 0; i < submitThreads; i++) {\n rings[i] = new IOUring(QD, 0);\n rss[i] = new long[][]{new long[QD], new long[QD]};\n rings[i].registerBuffer(getPartitionPooledBuffer(i));\n }\n }\n\n\n public void registerFile(int[] fds) {\n for (IOUring ring : rings) ring.registerFile(fds);\n }\n\n @Override\n void submitRequest(int partition, ReadOperation[] reqs, int num) {\n for (int i = 0; i < num; i++) {\n ReadOperation op = reqs[i];\n op.readBuffer = getPartitionPooledBuffer(partition)[i];\n op.readBuffer.clear();\n op.reqId = i;\n //this.resultMaps[partition].put(op.reqId, op);\n }\n int cur = 0;\n while (num > cur) {\n int c = submit0(rings[partition], reqs, cur, num);\n cur += c;\n //if(c == 0) pollResponseAndCallback(partition, resultMap);//\n }\n\n long[][] rs = rss[partition];\n\n int resp = 0;\n while (resp < num) {\n //wait results for all submitted requests\n int c = rings[partition].peekCQEntriesNoop(rs);\n if (c > 0) {\n for (int i = 0; i < c; i++) {\n long reqId = rs[0][i];\n int bytesRead = (int) rs[1][i];\n ReadOperation op = reqs[(int) reqId];\n if (op != null) {\n callback(op, bytesRead);\n } else {\n logger.error(\"op should not be null, reqid:{}\", reqId);\n }\n }\n rings[partition].seenCQEntry(c);\n resp += c;\n }\n }\n }\n\n @Override\n boolean pollResponseAndCallback(int partition) {\n /*\n boolean progress = false;\n long[][] rs = rss[partition];\n int c = rings[partition].peekCQEntriesNoop(rs);\n if (c > 0) {\n for (int i = 0; i < c; i++) {\n long reqId = rs[0][i];\n int bytesRead = (int) rs[1][i];\n ReadOperation op = this.resultMaps[partition].remove(reqId);\n if (op != null) {\n callback(op, bytesRead);\n } else {\n //logger.error(\"op should not be null, reqid:{}, resultMap size:{}\", reqId, resultMaps[partition].mappingCount());\n }\n }\n rings[partition].seenCQEntry(c);\n progress = true;\n }\n\n return progress;\n */\n return false;\n }\n\n @Override\n void close0() {\n for (IOUring ring : rings) {\n ring.shutdown();\n }\n }\n\n private int submit0(IOUring ring, ReadOperation[] ops, int from, int to) {\n int freeSqs = ring.availableSQ();\n if (freeSqs <= 0) {\n LockSupport.parkNanos(100);\n return 0;\n } else {\n int available = Math.min(from + freeSqs, to);\n\n for (int i = from; i < available; i++) {\n ReadOperation op = ops[i];\n //ring.prepareRead(op.reqId, op.fd, op.readPosition, op.readBuffer, op.alignedReadSize);\n ring.prepareReadFixed(op.reqId, op.fd, op.readPosition, op.readBuffer, op.alignedReadSize, (int) op.reqId);//reqId is the same as buffer index\n }\n int s = ring.submit();\n return Math.max(s, 0);\n }\n }\n}"
},
{
"identifier": "Common",
"path": "src/main/java/tech/bsdb/util/Common.java",
"snippet": "public class Common {\n public static final String FILE_NAME_KV_DATA = \"kv.db\";\n public static final String FILE_NAME_KEY_HASH = \"hash.db\";\n public static final String FILE_NAME_KV_INDEX = \"index.db\";\n public static final String FILE_NAME_KV_APPROXIMATE_INDEX = \"index_a.db\";\n public static final String FILE_NAME_CONFIG = \"config.properties\";\n public static final String FILE_NAME_SHARED_DICT = \"shared_dict\";\n public static final String FILE_NAME_VALUE_SCHEMA = \"value.schema\";\n\n public static final String CONFIG_KEY_KV_COMPRESS = \"kv.compressed\";\n public static final String CONFIG_KEY_KV_COMPACT = \"kv.compact\";\n public static final String CONFIG_KEY_KV_COMPRESS_BLOCK_SIZE = \"kv.compress.block.size\";\n public static final String CONFIG_KEY_APPROXIMATE_MODE = \"index.approximate\";\n public static final String CONFIG_KEY_CHECKSUM_BITS = \"hash.checksum.bits\";\n public static final String CONFIG_KEY_KV_RECORD_LEN_MAX = \"kv.key.len.max\";\n public static final String CONFIG_KEY_KV_RECORD_LEN_AVG = \"kv.key.len.avg\";\n public static final String CONFIG_KEY_KV_KEY_LEN_MAX = \"kv.key.len.max\";\n public static final String CONFIG_KEY_KV_KEY_LEN_AVG = \"kv.key.len.avg\";\n public static final String CONFIG_KEY_KV_COUNT = \"kv.count\";\n public static final String CONFIG_KEY_KV_VALUE_LEN_MAX = \"kv.value.len.max\";\n public static final String CONFIG_KEY_KV_VALUE_LEN_AVG = \"kv.value.len.avg\";\n public static final String CONFIG_KEY_KV_BLOCK_COMPRESS_LEN_MAX = \"kv.block.compress.max\";\n public static final String CONFIG_KEY_KV_BLOCK_COMPRESS_LEN_AVG = \"kv.block.compress.avg\";\n public static final String CONFIG_KEY_KV_BLOCK_LEN_MAX = \"kv.block.max\";\n public static final String CONFIG_KEY_KV_BLOCK_LEN_AVG = \"kv.block.avg\";\n\n public static final int SLOT_SIZE = 8;\n public static final int MAX_RECORD_SIZE = 32768;//MAX_KEY_SIZE + MAX_VALUE_SIZE + RECORD_HEADER_SIZE; //should be multiply of 512\n public static final int RECORD_HEADER_SIZE = 3;\n public static final int MAX_KEY_SIZE = 255;\n public static final int MAX_VALUE_SIZE = MAX_RECORD_SIZE - MAX_KEY_SIZE - RECORD_HEADER_SIZE;\n\n public static final int DEFAULT_BLOCK_SIZE = 4096; //should be multiply of 4096\n\n public static final int MEMORY_ALIGN = 4096;\n\n public final static boolean REVERSE_ORDER = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;\n\n public final static int CPUS = Runtime.getRuntime().availableProcessors();\n public static final int DEFAULT_COMPRESS_BLOCK_SIZE = 8192;\n\n private static final byte[] DIGITS = {\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,\n -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n };\n public static final int DEFAULT_THREAD_POOL_QUEUE_SIZE = Integer.parseInt(System.getProperty(\"bsdb.queue.base.size\", \"1024\"));\n\n public final static Unsafe unsafe = UnsafeUtil.getUnsafe();\n\n /**\n * check if two byte[] have the same content\n *\n * @param a\n * @param b\n * @return\n */\n public static boolean bytesEquals(byte[] a, byte[] b) {\n if (a != null && b != null && a.length == b.length) {\n for (int i = 0; i < a.length; i++) {\n if (a[i] != b[i]) return false;\n }\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * check if a byte[] and a ByteBuffer have the same content\n *\n * @param a\n * @param b\n * @return\n */\n public static boolean bytesEquals(byte[] a, ByteBuffer b) {\n if (a != null && b != null && a.length == b.limit()) {\n for (int i = 0; i < a.length; i++) {\n if (a[i] != b.get(i)) return false;\n }\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @param buf\n * @param startPos\n * @param endPos\n * @param b\n * @return\n */\n public static long indexOf(MMapBuffer buf, long startPos, long endPos, byte b) {\n long pos = startPos;\n while (pos < endPos) {\n byte r = buf.getByte(pos);\n if (r == b) {\n return pos;\n } else {\n pos++;\n }\n }\n return -1;\n }\n\n private static final char[] HEX_ARRAY = \"0123456789ABCDEF\".toCharArray();\n\n /**\n * convert bytes to it's HEX format, each byte will be converted to 2 chars\n *\n * @param bytes\n * @return hex format of input bytes\n */\n public static char[] bytesToHex(byte[] bytes) {\n char[] hexChars = new char[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = HEX_ARRAY[v >>> 4];\n hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];\n }\n return hexChars;\n }\n\n /**\n * convert HEX format back to bytes, 0 might be added to the first byte if input length is not even\n *\n * @param hex\n * @return bytes of input hex string\n */\n public static byte[] hexToBytes(String hex) {\n return hexToBytes(hex.toCharArray());\n }\n\n public static byte[] hexToBytes(char[] hex) {\n int len = hex.length;\n boolean prefix = false;\n if ((len & 0x2) != 0) {\n len++;\n prefix = true;\n }\n len = len >>> 1;\n byte[] ret = new byte[len];\n\n int startIndex = 0;\n if (prefix) {\n ret[0] = fromHexByte((char) 0, hex[startIndex]);\n } else {\n ret[0] = fromHexByte(hex[startIndex++], hex[startIndex++]);\n }\n\n for (int j = 1; j < len; j++) {\n ret[j] = fromHexByte(hex[startIndex++], hex[startIndex++]);\n }\n return ret;\n }\n\n private static byte fromHexByte(char h, char l) {\n int high = fromHexDigit(h);\n int low = fromHexDigit(l);\n return (byte) ((high << 4) | low);\n }\n\n /**\n * check if a input byte is a valid part of a HEX formatted (0-9,a-f,A-F)\n *\n * @param ch\n * @return\n */\n public static boolean isHexDigit(int ch) {\n return ((ch >>> 8) == 0 && DIGITS[ch] >= 0);\n }\n\n private static int fromHexDigit(int ch) {\n int value;\n if ((ch >>> 8) == 0 && (value = DIGITS[ch]) >= 0) {\n return value;\n }\n throw new NumberFormatException(\"not a hexadecimal digit: \\\"\" + (char) ch + \"\\\" = \" + ch);\n }\n\n\n public static final int MAX_POWER2 = (1 << 30);\n\n /**\n * return the next power of two after @param capacity or\n * capacity if it is already\n */\n public static int toPowerOf2(int capacity) {\n int c = 1;\n if (capacity >= MAX_POWER2) {\n c = MAX_POWER2;\n } else {\n while (c < capacity) c <<= 1;\n }\n\n if (isPowerOf2(c)) {\n return c;\n } else {\n throw new RuntimeException(\"Capacity is not a power of 2.\");\n }\n }\n\n /*\n * define power of 2 slightly strangely to include 1,\n * i.e. capacity 1 is allowed\n */\n private static boolean isPowerOf2(final int p) {\n return (p & (p - 1)) == 0;\n }\n\n\n /**\n * util method for getting cached direct bytebuffer from thread local for reuse\n *\n * @param threadLocal ThreadLocal to contain the cached ByteBuffer\n * @param size the capacity of the ByteBuffer to allocate if not cached, should be consistent\n * @return a cached ByteBuffer\n */\n public static ByteBuffer getBufferFromThreadLocal(ThreadLocal<ByteBuffer> threadLocal, int size, boolean aligned) {\n ByteBuffer buf = threadLocal.get();\n if (buf == null) {\n buf = aligned ? NativeFileIO.allocateAlignedBuffer(size) : ByteBuffer.allocateDirect(size);//ByteBuffer.allocateDirect(size);\n threadLocal.set(buf);\n }\n buf.clear();\n return buf;\n }\n\n public static void copyTo(LBufferAPI mmap, long srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : mmap.toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }\n\n\n /**\n * util method to run tasks parallel and then wait for tasks finished.\n *\n * @param threads thread pool size to run the tasks\n * @param task utility class to submit tasks and return Futures, e.g. (pool, futures) -> {futures.add(pool.submit(() -> {}))}\n */\n\n public static void runParallel(int threads, ParallelTask task, boolean waitForDone) {\n ExecutorService executor = new ThreadPoolExecutor(threads, threads, 1, TimeUnit.SECONDS, new DisruptorBlockingQueueModified<>(1024));\n List<Future> futures = new ArrayList<>();\n task.addTasks(executor, futures);\n if (waitForDone) {\n for (Future future : futures)\n try {\n future.get();\n } catch (Throwable t) {\n t.printStackTrace();\n }\n }\n executor.shutdown();\n }\n\n public interface ParallelTask {\n void addTasks(ExecutorService pool, List<Future> futures);\n }\n\n /**\n * util method to shutdown a ForkJoinPool and blocking until all submitted tasks finished.\n *\n * @param pool\n */\n public static void waitForShutdown(ForkJoinPool pool) {\n pool.shutdown();\n while (!pool.isTerminated()) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n }\n }\n }\n\n public static int getPropertyAsInt(String propKey, int defaultValue) {\n return Integer.parseInt(System.getProperty(propKey, \"\" + defaultValue));\n }\n\n /**\n * return a thread pool with specified threads and default queue size\n *\n * @param num threads in pool\n * @return a new thread pool\n */\n public static ExecutorService fixedThreadPool(int num) {\n return fixedThreadPool(num, DEFAULT_THREAD_POOL_QUEUE_SIZE);\n }\n\n /**\n * return a thread pool with specified threads and queue size\n *\n * @param num threads in pool\n * @param queueLen queue length for buffered tasks\n * @return a new thread pool\n */\n public static ExecutorService fixedThreadPool(int num, int queueLen) {\n return new ThreadPoolExecutor(num, num, 1, TimeUnit.SECONDS, new MPMCBlockingQueue<>(queueLen));\n }\n\n /**\n * get system free memory size\n *\n * @return available memory size in MB\n * @throws IOException\n */\n public static int freeMemory() throws IOException {\n Process p = new ProcessBuilder().command(\"free\", \"-m\").start();\n InputStream out = p.getInputStream();\n BufferedReader reader = new BufferedReader(new InputStreamReader(out));\n reader.readLine();//header line\n String memLine = reader.readLine();\n String[] splits = memLine.split(\" \");\n return Integer.parseInt(splits[splits.length - 1]);\n }\n\n /**\n * calc least-common-multiplier of two inputs\n *\n * @param x\n * @param y\n * @return least-common-multiplier of x,y\n */\n public static int lcm(long x, long y) {\n // will hold gcd\n long g = x;\n long yc = y;\n\n // get the gcd first\n while (yc != 0) {\n long t = g;\n g = yc;\n yc = t % yc;\n }\n\n return (int) (x * y / g);\n }\n\n public static BufferedReader getReader(File input, Charset charset) throws IOException {\n Path inPath = input.toPath();\n InputStream is = Files.newInputStream(inPath, StandardOpenOption.READ);\n String extension = com.google.common.io.Files.getFileExtension(input.getName());\n if (\"gz\".equals(extension)) {\n is = new GZIPInputStream(is);\n } else if (\"zstd\".equals(extension)) {\n is = new ZstdInputStream(is);\n }\n return new BufferedReader(new InputStreamReader(is, charset));\n }\n\n public static boolean isUringEnabled(){\n return Boolean.getBoolean(\"bsdb.uring\") && Native.Uring.available;\n }\n}"
}
] | import tech.bsdb.io.AsyncFileReader;
import tech.bsdb.io.NativeFileIO;
import tech.bsdb.io.SimpleAsyncFileReader;
import tech.bsdb.io.UringAsyncFileReader;
import tech.bsdb.util.Common;
import com.google.common.io.Files;
import org.apache.commons.configuration2.Configuration;
import xerial.larray.mmap.MMapBuffer;
import xerial.larray.mmap.MMapMode;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler; | 6,730 | package tech.bsdb.read.kv;
public abstract class PartitionedKVReader extends BaseKVReader {
protected MMapBuffer[] mmaps;
protected final int[] fds;
protected ThreadLocal<ByteBuffer> threadLocalPooledBuffer = new ThreadLocal<>();
protected AsyncFileReader asyncReader;
protected final int maxRecordSize;
protected final boolean useDirectIO;
protected int partitions;
public PartitionedKVReader(File kvFile, Configuration config, boolean async, boolean useDirectIO, boolean initReader) throws IOException {
super(config);
this.useDirectIO = useDirectIO;
//maxRecordSize = NativeFileIO.alignToPageSize(config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE); | package tech.bsdb.read.kv;
public abstract class PartitionedKVReader extends BaseKVReader {
protected MMapBuffer[] mmaps;
protected final int[] fds;
protected ThreadLocal<ByteBuffer> threadLocalPooledBuffer = new ThreadLocal<>();
protected AsyncFileReader asyncReader;
protected final int maxRecordSize;
protected final boolean useDirectIO;
protected int partitions;
public PartitionedKVReader(File kvFile, Configuration config, boolean async, boolean useDirectIO, boolean initReader) throws IOException {
super(config);
this.useDirectIO = useDirectIO;
//maxRecordSize = NativeFileIO.alignToPageSize(config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE); | maxRecordSize = config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE; | 4 | 2023-10-07 03:32:27+00:00 | 8k |
reinershir/Shir-Boot | src/main/java/io/github/reinershir/boot/controller/DevelopmentController.java | [
{
"identifier": "Result",
"path": "src/main/java/io/github/reinershir/boot/common/Result.java",
"snippet": "@Schema(description = \"Response DTO\")\n@JsonInclude(value = JsonInclude.Include.ALWAYS)//Even if the returned object is null, it will still be returned when this annotation is added.\npublic class Result<T> implements Serializable{\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -472604879542896258L;\n\n\t@Schema(description = \"Response Message\", nullable = false, example = \"success!\")\n\tprivate String message;\n\t@Schema(description = \"The return result code, by default 00000 indicates a successful request.\", required = true, example = \"00000\")\n\tprivate String code;\n\t@Schema(description = \"Return Value\", nullable = true)\n\tprivate T data = null;\n\t\n\tpublic Result(T value) {\n\t\tthis.data=value;\n\t\tinitSuccess();\n\t}\n\t\n\tpublic Result(String message,T value) {\n\t\tthis.data=value;\n\t\tinitSuccess();\n\t\tthis.message=message;\n\t}\n\t\n\tpublic Result() {\n\t\tinitSuccess();\n\t}\n\t\n\tprivate void initSuccess() {\n\t\tthis.message = IMessager.getInstance().getMessage(\"message.success\");\n\t\tthis.code = ShirBootContracts.RESP_CODE_SUCCESS;\n\t}\n\t\n\tpublic static <T> Result<T> ok() {\n\t\treturn new Result<T>();\n\t}\n\t\n\tpublic static <T> Result<T> ok(T value) {\n\t\treturn new Result<T>(value);\n\t}\n\tpublic static <T> Result<T> ok(String message) {\n\t\treturn new Result<>(message,ShirBootContracts.RESP_CODE_SUCCESS,true);\n\t}\n\t\n\tpublic static <T> Result<T> ok(String message,T value) {\n\t\treturn new Result<T>(message,value);\n\t}\n\t\n\tpublic static <T> Result<T> failed() {\n\t\treturn new Result<T>(IMessager.getInstance().getMessage(\"message.failed\"),ShirBootContracts.RESP_CODE_FAILE,false);\n\t}\n\t\n\tpublic static <T> Result<T> failed(String message) {\n\t\treturn new Result<T>(message,ShirBootContracts.RESP_CODE_FAILE,false);\n\t}\n\t\n\tpublic static <T> Result<T> failed(String message,String code) {\n\t\treturn new Result<T>(message,code,false);\n\t}\n\t\n\tpublic Result(String message, String code,boolean isSuccess) {\n\t\tsuper();\n\t\tthis.message = message;\n\t\tthis.code = code;\n\t}\n\tpublic String getMessage() {\n\t\treturn message;\n\t}\n\tpublic void setMessage(String message) {\n\t\tthis.message = message;\n\t}\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\tpublic void setCode(String code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic T getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(T data) {\n\t\tthis.data = data;\n\t}\n\n\t\n\n}"
},
{
"identifier": "EasyAutoModule",
"path": "src/main/java/io/github/reinershir/boot/core/easygenerator/generator/EasyAutoModule.java",
"snippet": "public enum EasyAutoModule {\n\tCONTROLLER_CLASS(\"controller\"),\n\tCRITERIA_CLASS(\"criteria\"),\n\tSERVICE_INTERFACE(\"service\"),\n\tSERVICE_IMPLEMENTS(\"serviceImpl\"),\n\tPAGE(\"page\"),\n\tMODEL(\"model\"),\n\tMYBATIS_MAPPER_INTERFACE(\"dao\"),\n\tMYBATIS_MAPPER_XML(\"mapper\");\n\t\n\tString value;\n\tprivate EasyAutoModule(String value) {\n\t\tthis.value=value;\n\t}\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\t\n\t\n}"
},
{
"identifier": "MicroSMSCodeGenerator",
"path": "src/main/java/io/github/reinershir/boot/core/easygenerator/generator/MicroSMSCodeGenerator.java",
"snippet": "@Component\npublic class MicroSMSCodeGenerator {\n\n\tprivate final String TEMPLATE_DIR = \"/templates/sm\";\n\n\tprivate String javaModuleFolder = null;\n\n\t//mapper存放前置路径\n\tprivate String resourcesFolder = null;\n\t\n\tprivate String baseControllerImport = null;\n\n\tString basePath = System.getProperty(\"user.dir\") + \"/src/main/java/\";\n\t\n\tDatabaseInfo databaseInfo;\n\t\n\tDruidDataSource dataSource;\n\t\n\t@Autowired\n\tpublic MicroSMSCodeGenerator(DruidDataSource dataSource) {\n\t\tthis.dataSource = dataSource;\n\t}\n\t\n\tpublic MicroSMSCodeGenerator(DatabaseInfo databaseInfo) {\n\t\tthis.databaseInfo=databaseInfo;\n\t}\n\t\n\tprivate Connection getConnectionByDatebaseInfo(DatabaseInfo databaseInfo) throws ClassNotFoundException, SQLException {\n\t\t// 驱动程序名\n\t\tString driver = databaseInfo.getDriver();\n\t\t// URL指向要访问的数据库名mydata\n\t\tString url = databaseInfo.getUrl();\n\t\t// MySQL配置时的用户名\n\t\tString user = databaseInfo.getName();\n\t\t// MySQL配置时的密码\n\t\tString password = databaseInfo.getPassword();\n\t\t// 加载驱动程序\n\t\tClass.forName(driver);\n\t\t// 1.getConnection()方法,连接MySQL数据库!!\n\t\tConnection connection = DriverManager.getConnection(url, user, password);\n\t\tif (!connection.isClosed()) {\n\t\t\tSystem.out.println(\"Succeeded connecting to the Database!\");\n\t\t\treturn connection;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprivate Connection getConnection() throws SQLException, ClassNotFoundException {\n\t\tif(this.dataSource!=null) {\n\t\t\treturn this.dataSource.getConnection();\n\t\t}else if(this.databaseInfo!=null) {\n\t\t\treturn getConnectionByDatebaseInfo(this.databaseInfo);\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic List<FieldInfo> getTableFields(String tableName) throws SQLException, ClassNotFoundException{\n\t\tString primaryKeyColumnName = null;\n\t\tList<FieldInfo> fieldInfoList = new ArrayList<>();\n\t\tConnection connection = getConnection();\n\t\tStatement statement = connection.createStatement();\n\t\tDatabaseMetaData metaData = connection.getMetaData();\n\t\t//ResultSet tableRet = metaData.getTables(null, \"%\", tableName, new String[] { \"TABLE\" });\n\t\tString catalog = connection.getCatalog();\n\t\tResultSet resultSet = metaData.getColumns(catalog, \"%\", tableName, \"%\");\n\t\tResultSet primaryKeyResultSet = metaData.getPrimaryKeys(catalog, null, tableName);\n\t\twhile (primaryKeyResultSet.next()) {\n\t\t\tprimaryKeyColumnName = primaryKeyResultSet.getString(\"COLUMN_NAME\");\n\t\t}\n\t\twhile (resultSet.next()) {\n\t\t\tString columnName = resultSet.getString(\"COLUMN_NAME\");\n\t\t\tInteger columnLength = resultSet.getInt(\"COLUMN_SIZE\");\n\t\t\t//String columnType = colRet.getString(\"TYPE_NAME\");\n\t\t\tString comment = null;\n\t\t\tString defaultValue = null;\n\t\t\tboolean isNull = true;\n\t\t\t//获取字段注释 TODO 根据不同数据库执行不同的获取字段SQL\n\t\t\tResultSet rs = statement.executeQuery(\"show full columns from \" + tableName);\n\t\t\twhile (rs.next()) {\n\t\t\t\tif (columnName.equals(rs.getString(\"Field\"))) {\n\t\t\t\t\tcomment = rs.getString(\"Comment\");\n\t\t\t\t\tString canBeNull = rs.getString(\"Null\");\n\t\t\t\t\tisNull = !\"NO\".equalsIgnoreCase(canBeNull);\n\t\t\t\t\tdefaultValue = rs.getString(\"Default\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//数据库字段类型\n\t\t\tint dt = resultSet.getInt(\"DATA_TYPE\");\n\t\t\tString javaType = \"String\";\n\t\t\tswitch (dt) {\n\t\t\tcase Types.BIGINT:\n\t\t\t\tjavaType = \"Long\";\n\t\t\t\tbreak;\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\t\tjavaType = \"Integer\";\n\t\t\t\tbreak;\n\t\t\tcase Types.FLOAT:\n\t\t\tcase Types.REAL:\n\t\t\t\tjavaType = \"Float\";\n\t\t\t\tbreak;\n\t\t\tcase Types.DOUBLE:\n\t\t\t\tjavaType = \"Double\";\n\t\t\t\tbreak;\n\t\t\tcase Types.DATE:\n\t\t\tcase Types.TIMESTAMP:\n\t\t\tcase Types.TIMESTAMP_WITH_TIMEZONE:\n\t\t\t\tjavaType = \"Date\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tFieldInfo f = new FieldInfo(FieldUtils.camelName(columnName), javaType,columnLength);\n\t\t\tf.setComment(comment);\n\t\t\tf.setColumnName(columnName);\n\t\t\tf.setIsNull(isNull);\n\t\t\tf.setDefaultValue(defaultValue);\n\t\t\tif (columnName.equals(primaryKeyColumnName)) {\n\t\t\t\tSystem.out.println(\"primary Key is \"+primaryKeyColumnName);\n\t\t\t\tf.setIsPrimaryKey(true);\n\t\t\t}\n\t\t\tfieldInfoList.add(f);\n\t\t}\n\t\tresultSet.close();\n\t\tprimaryKeyResultSet.close();\n\t\tcloseConnection(connection);\n\t\treturn fieldInfoList;\n\t}\n\t\n\tprivate void closeConnection(Connection connection) {\n\t\ttry {\n\t\t\tconnection.close();\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}finally {\n\t\t\ttry {\n\t\t\t\tif (connection != null)\n\t\t\t\t\tconnection.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic String generateCodeToZip(String modelPackage, String commonPath,\n\t\t\tEasyAutoModule[] modules,GenerateInfo... genetateInfo) throws Exception{\n\t\tString path = System.getProperty(\"user.dir\") + \"/codes/\"+new Date().getTime();\n\t\tString generatePath = path+\"/\";\n\t\tFile f = new File(generatePath);\n\t\tif(!f.exists()) {\n\t\t\tf.mkdirs();\n\t\t}\n\t\tif(generateModel(generatePath, modelPackage, commonPath, modules, genetateInfo)) {\n\t\t\tString zipPath = path+\".zip\";\n\t\t\tDailyFileUtil.doCompress(f, new File(zipPath));\n\t\t\treturn zipPath;\n\t\t}\n\t\treturn null;\n\t}\n\n\n\tpublic boolean generateModel(@Nullable String path,String modelPackage, String commonPath,\n\t\t\tEasyAutoModule[] modules,GenerateInfo... genetateInfo) throws ClassNotFoundException {\n\t\tbaseControllerImport = commonPath+\".controller\";\n\t\tString generatePath = StringUtils.hasText(path)?path:basePath;\n\t\tjavaModuleFolder = generatePath + commonPath.replaceAll(\"\\\\.\", \"/\");// replace\n\t\tresourcesFolder = generatePath + commonPath.replaceAll(\"\\\\.\", \"/\") + \"/mapper\";\n\t\tConnection connection = null;\n\t\ttry {\n\t\t\tconnection = getConnection();\n\t\t} catch (ClassNotFoundException | SQLException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t} \n\t\tfor (GenerateInfo g : genetateInfo) {\n\t\t\tString tableName = g.getTableName();\n\t\t\t// 连接数据库获取字段表名=================================================\n\t\t\tList<FieldInfo> fieldInfoList;\n\t\t\ttry {\n\t\t\t\tfieldInfoList = getTableFields(tableName);\n\t\t\t\tif(!CollectionUtils.isEmpty(g.getFieldInfos())) {\n\t\t\t\t\t//和参数数组组装\n\t\t\t\t\tint begin = 0;\n\t\t\t\t\tfor (int i = 0; i < fieldInfoList.size(); i++) {\n\t\t\t\t\t\tString fieldName = fieldInfoList.get(i).getName();\n\t\t\t\t\t\tfor (int j = begin; j < g.getFieldInfos().size(); j++) {\n\t\t\t\t\t\t\tString columnName = g.getFieldInfos().get(j).getName();\n\t\t\t\t\t\t\tif(fieldName.equals(columnName)) {\n\t\t\t\t\t\t\t\tfieldInfoList.get(i).setOperation(g.getFieldInfos().get(j).getOperation());\n\t\t\t\t\t\t\t\tbegin = ++j;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tg.setFieldInfos(fieldInfoList);\n\t\t\t} catch (SQLException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tcloseConnection(connection);\n\t\tSystem.out.println(\"Start generate...\");\n\t\ttry {\n\t\t\tgenerateByTemplate(commonPath,modelPackage,generatePath,modules,genetateInfo);\n\t\t\tSystem.out.println(\"Code generation successful! Please refresh your project.\");\n\t\t\treturn true;\n\t\t} catch (TemplateException | IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * 生成所有\n\t * \n\t * @param allClass\n\t * @param modules\n\t * @throws TemplateException\n\t * @throws IOException\n\t */\n\tprivate void generateByTemplate(String commonPath, String modulePackage,String generatePath, EasyAutoModule[] modules,GenerateInfo... genetateInfo) throws TemplateException, IOException {\n\t\tString mds = \"#\";\n\t\tif (modules == null) {\n\t\t\tmds = \"#controller#criteria#dao#mapper#page#service#serviceImpl#\";\n\t\t} else {\n\t\t\tfor (int i = 0; i < modules.length; i++) {\n\t\t\t\tmds += modules[i].value + \"#\";\n\t\t\t}\n\t\t}\n\t\tgeneratorFile(commonPath,modulePackage,generatePath, mds,genetateInfo);\n\t}\n\n\t/**\n\t * 生成文件\n\t * \n\t * @param allClass\n\t * @param modules\n\t * @throws TemplateException\n\t * @throws IOException\n\t */\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tprivate void generatorFile(String commonPath, String modulePackage,String generatePath,\n\t\t\tString modules,GenerateInfo... genetateInfo) throws TemplateException, IOException {\n\t\tfor (GenerateInfo g : genetateInfo) {\n\t\t\t/* Create a data-model */\n\t\t\tMap root = new HashMap();\n\t\t\t// mapper中resultType 包路径\n\t\t\tString pkgName = commonPath;\n\t\t\t// 模块\n\t\t\tString module = modulePackage;\n\t\t\tif (module.contains(\".\")) {\n\t\t\t\tmodule = module.substring(module.lastIndexOf(\".\") + 1);\n\t\t\t}\n\t\t\tString modelName = g.getModelName();\n\t\t\tString table = g.getTableName();\n\t\t\tString className = g.getModelName();\n\n\t\t\t// 条件属性数据列表\n\t\t\tSet<String> propertys = new LinkedHashSet<String>();\n\t\t\t// 需要额外导入的包列表\n\t\t\tSet<String> imports = new LinkedHashSet<String>();\n\t\t\t//freemarker用变量\n\t\t\troot.put(\"table\",g.getTableName());\n\t\t\troot.put(\"modelDescription\",g.getModelDescription());\n\t\t\t// 表格列显示信息\n\t\t\troot.put(\"fieldInfos\",g.getFieldInfos());\n\t\t\troot.put(\"commonPath\", commonPath);\n\t\t\troot.put(\"pkgName\", pkgName);\n\t\t\troot.put(\"Imports\", imports);\n\t\t\troot.put(\"Propertys\", propertys);\n\n\t\t\troot.put(\"Module\", module);\n\t\t\troot.put(\"Imports\", imports);\n\t\t\troot.put(\"ClassName\", g.getModelName());\n\t\t\troot.put(\"baseControllerImport\", baseControllerImport);\n\t\t\troot.put(\"modelPackage\", modulePackage);\n\t\t\t\n\t\t\t//root.put(\"idType\", idClass.getSimpleName()); //ID类型\n\n\t\t\t// 配置\n\t\t\tConfiguration cfg = new Configuration(Configuration.VERSION_2_3_32);\n\t\t\tcfg.setSharedVariable(\"messages\", new InternationalizationDirectiveModel());\n\t\t\tcfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);\n\t\t\tcfg.setDefaultEncoding(\"UTF-8\");\n\t\t\t// cfg.setDirectoryForTemplateLoading(new File(folder));\n\t\t\tcfg.setClassForTemplateLoading(MicroSMSCodeGenerator.class, TEMPLATE_DIR);\n\n\t\t\tTemplate template = null;\n\t\t\tString fileName = null;\n\t\t\tString criteriaFolder = null;\n\t\t\tFile dir = null;\n\t\t\tFileWriter out = null;\n\n\t\t\t\n\t\t\tif(modules.contains(\"model\")) {\n\t\t\t\tEntityInfo entityInfo = new EntityInfo(commonPath,modelName, g.getFieldInfos());\n\t\t\t\tMap<String,Object> map = new HashMap<>();\n\t\t\t\tmap.put(\"entityInfo\", entityInfo);\n\t\t\t\tmap.put(\"commonPath\", commonPath);\n\t\t\t\tmap.put(\"modelPackage\", modulePackage);\n\t\t\t\tmap.put(\"ClassName\",modelName);\n\t\t\t\tmap.put(\"tableName\",table);\n\t\t\t\tmap.put(\"generateUtil\", new QueryGenerator());\n\t\t\t\tSystem.out.println(\"Generate Model...\");\n\t\t\t\t// 生成model\n\t\t\t\t// cfg.setDirectoryForTemplateLoading(new File(folder));\n\t\t\t\ttemplate = cfg.getTemplate(\"model.tpl\");\n\t\t\t\tfileName = modelName + \".java\";\n\t\t\t\tcriteriaFolder = javaModuleFolder + \"/model/\";\n\t\t\t\tSystem.out.println(\"model path:\"+criteriaFolder);\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(map, out);\n\t\t\t\ttemplate.setAutoFlush(true);\n\t\t\t}\n\n\t\t\tif (modules.contains(\"dao\")) {\n\t\t\t\ttemplate = cfg.getTemplate(\"dao.tpl\");\n\t\t\t\tfileName = className + \"Mapper.java\";\n\t\t\t\tString daoFolder = javaModuleFolder + \"/mapper/\";\n\t\t\t\tdir = new File(daoFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(daoFolder + fileName);\n\t\t\t\ttemplate.process(root, out);\n\t\t\t\tout.close();\n\t\t\t}\n\n\t\t\tif (modules.contains(\"mapper\")) {\n\t\t\t\ttemplate = cfg.getTemplate(\"mapper.tpl\");\n\t\t\t\tfileName = className + \"Mapper.xml\";\n\t\t\t\tcriteriaFolder = resourcesFolder + \"/\";// + \"/\" + module + \"/\";\n\t\t\t\tSystem.out.println(\"mapper path :\" + criteriaFolder);\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(root, out);\n\t\t\t\tout.close();\n\t\t\t}\n\n\t\t\tif (modules.contains(\"service\")) { \n\t\t\t\ttemplate = cfg.getTemplate(\"service.tpl\");\n\t\t\t\tfileName = className + \"Service.java\"; \n\t\t\t\tcriteriaFolder = javaModuleFolder +\n\t\t\t\t\"/service/\"; dir = new File(criteriaFolder); \n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs(); \n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(root, out); out.close(); \n\t\t\t}\n\n\t\t\tif (modules.contains(\"serviceImpl\")) {\n\t\t\t\ttemplate = cfg.getTemplate(\"serviceImpl.tpl\");\n\t\t\t\tfileName = className + \"ServiceImpl.java\";\n\t\t\t\tcriteriaFolder = javaModuleFolder + \"/service/impl/\";\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(root, out);\n\t\t\t\tout.close();\n\t\t\t}\n\n\t\t\tif (modules.contains(\"controller\")) {\n\t\t\t\ttemplate = cfg.getTemplate(\"controller.tpl\");\n\t\t\t\tfileName = className + \"Controller.java\";\n\t\t\t\tcriteriaFolder = javaModuleFolder + \"/controller/\";\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(root, out);\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\t\n\t\t\tif (modules.contains(\"page\")) {\n\t\t\t\ttemplate = cfg.getTemplate(\"page.tpl\");\n\t\t\t\tfileName = className + \".vue\";\n\t\t\t\tcriteriaFolder = generatePath + \"/vue/\";\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tout = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate.process(root, out);\n\t\t\t\tout.close();\n\t\t\t\t//生成api.js\n\t\t\t\tcriteriaFolder = generatePath+\"/vue/api/\";\n\t\t\t\tdir = new File(criteriaFolder);\n\t\t\t\tif (!dir.exists()) {\n\t\t\t\t\tdir.mkdirs();\n\t\t\t\t}\n\t\t\t\tfileName = className + \".js\";\n\t\t\t\tFileWriter jsWriter = new FileWriter(criteriaFolder + fileName);\n\t\t\t\ttemplate = cfg.getTemplate(\"api_js.tpl\");\n\t\t\t\ttemplate.process(root, jsWriter);\n\t\t\t\tjsWriter.close();\n\t\t\t}\n\t\t}\n\t\t\t\n\t}\n\n}"
},
{
"identifier": "FieldInfo",
"path": "src/main/java/io/github/reinershir/boot/core/easygenerator/model/FieldInfo.java",
"snippet": "public class FieldInfo {\n\n\tprivate String name;\n\tprivate String javaType;\n\tprivate String comment;\n\t//对应的数据库字段名称\n\tprivate String columnName;\n\tprivate boolean isPrimaryKey = false;\n\tprivate String defaultValue;\n\t/**\n\t * 该字段的查询条件\n\t */\n\tprivate String operation;\n\t/**\n\t * 字段长度\n\t */\n\tprivate Integer columnLength;\n\t/**\n\t * 是否允许空值\n\t */\n\tprivate boolean isNull = true;\n\t\n\tpublic FieldInfo() {}\n\t\n\tpublic FieldInfo(String name,String javaType, Integer columnLength) {\n\t\tsuper();\n\t\tthis.name = name;\n\t\tthis.javaType = javaType;\n\t\tthis.columnLength = columnLength;\n\t}\n\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 getJavaType() {\n\t\treturn javaType;\n\t}\n\tpublic void setJavaType(String javaType) {\n\t\tthis.javaType = javaType;\n\t}\n\tpublic String getComment() {\n\t\treturn comment;\n\t}\n\tpublic void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\tpublic String getColumnName() {\n\t\treturn columnName;\n\t}\n\tpublic void setColumnName(String columnName) {\n\t\tthis.columnName = columnName;\n\t}\n\tpublic boolean getIsPrimaryKey() {\n\t\treturn isPrimaryKey;\n\t}\n\tpublic void setIsPrimaryKey(boolean isPrimaryKey) {\n\t\tthis.isPrimaryKey = isPrimaryKey;\n\t}\n\tpublic String getDefaultValue() {\n\t\treturn defaultValue;\n\t}\n\tpublic void setDefaultValue(String defaultValue) {\n\t\tthis.defaultValue = defaultValue;\n\t}\n\tpublic boolean getIsNull() {\n\t\treturn isNull;\n\t}\n\tpublic void setIsNull(boolean isNull) {\n\t\tthis.isNull = isNull;\n\t}\n\tpublic Integer getColumnLength() {\n\t\treturn columnLength;\n\t}\n\tpublic void setColumnLength(Integer columnLength) {\n\t\tthis.columnLength = columnLength;\n\t}\n\n\tpublic String getOperation() {\n\t\treturn operation;\n\t}\n\n\tpublic void setOperation(String operation) {\n\t\tthis.operation = operation;\n\t}\n\t\n\t\n}"
},
{
"identifier": "GenerateInfo",
"path": "src/main/java/io/github/reinershir/boot/core/easygenerator/model/GenerateInfo.java",
"snippet": "public class GenerateInfo {\n\n\tprivate String tableName;\n\tprivate String modelName;\n\t/**\n\t * 实体类说明,用于生成代码时的注释\n\t */\n\tprivate String modelDescription;\n\t/**\n\t * 根据数据库查询到的字段信息\n\t */\n\tprivate List<FieldInfo> fieldInfos;\n\t\n\tpublic GenerateInfo(String tableName, String modelName, String modelDescription) {\n\t\tsuper();\n\t\tthis.tableName = tableName;\n\t\tthis.modelName = modelName;\n\t\tthis.modelDescription = modelDescription;\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 getModelName() {\n\t\treturn modelName;\n\t}\n\tpublic void setModelName(String modelName) {\n\t\tthis.modelName = modelName;\n\t}\n\tpublic List<FieldInfo> getFieldInfos() {\n\t\treturn fieldInfos;\n\t}\n\tpublic void setFieldInfos(List<FieldInfo> fieldInfos) {\n\t\tthis.fieldInfos = fieldInfos;\n\t}\n\tpublic String getModelDescription() {\n\t\treturn modelDescription;\n\t}\n\tpublic void setModelDescription(String modelDescription) {\n\t\tthis.modelDescription = modelDescription;\n\t}\n\t\n\t\n\t\n}"
},
{
"identifier": "IMessager",
"path": "src/main/java/io/github/reinershir/boot/core/international/IMessager.java",
"snippet": "@Slf4j\npublic class IMessager {\n\n\tprivate Properties properties;\n\tprivate static IMessager instance;\n\t\n\tpublic IMessager() throws IOException {\n\t\tString defaultPath = \"i18n/message.properties\";\n\t\tString path = \"i18n/message_\"+LocaleContextHolder.getLocale().getLanguage().toLowerCase()+\"_\"+LocaleContextHolder.getLocale().getCountry()+\".properties\";\n\t\t\n\t\tResource resource = new ClassPathResource(path);\n\t try {\n\t\t\tthis.properties = PropertiesLoaderUtils.loadProperties(resource);\n\t\t} catch (FileNotFoundException e) {\n\t\t\tthis.properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(defaultPath));\n\t\t\tlog.warn(\"Unable to retrieve internationalization configuration path :{}, will attempt to use default configuration path.\",path);\n\t \tif(properties==null) {\n\t \t\tthrow new BaseException(\"Can not find internationalization properties\");\n\t \t}\n\t\t}\n\t}\n\t\n\tpublic static synchronized IMessager getInstance() {\n\t\t\tif(IMessager.instance==null) {\n\t\t\t\ttry {\n\t\t\t\t\tIMessager.instance = new IMessager();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\treturn IMessager.instance;\n\t\t\n\t}\n\t\n\tpublic static String getMessageByCode(String code) {\n\t\treturn IMessager.getInstance().getMessage(code);\n\t}\n\t\n\tpublic String getMessage(String code) {\n\t\treturn this.properties.getProperty(code);\n\t}\n}"
},
{
"identifier": "CodeGenerateDTO",
"path": "src/main/java/io/github/reinershir/boot/dto/req/CodeGenerateDTO.java",
"snippet": "@Data\n@Schema(description = \"Code generate DTO\")\npublic class CodeGenerateDTO {\n\n\t@NotBlank(message = \"package name can not be null\")\n\t@Schema(description=\"package path name\")\n\tprivate String packageName;\n\t\n\t@NotBlank(message = \"model name can not be null\")\n\tprivate String modelName;\n\t\n\t@NotBlank(message = \"table name can not be null\")\n\t@Schema(description=\"table name\")\n\tprivate String tableName;\n\t\n\t@Schema(description=\"fields\")\n\tprivate List<ColumnInfo> fieldInfos;\n\t\n\t@NotBlank(message = \"model description can not be null\")\n\t@Schema(description=\"model description\")\n\tprivate String modelDescription;\n}"
},
{
"identifier": "BusinessException",
"path": "src/main/java/io/github/reinershir/boot/exception/BusinessException.java",
"snippet": "public class BusinessException extends BaseException{\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 7193838327170006378L;\n\tpublic BusinessException(String message,Object ...formatParam){\n\t\tsuper(message,formatParam);\n\t}\n\tpublic BusinessException(String message,String code,Object ...formatParam){\n\t\tsuper(message,code,formatParam);\n\t}\n}"
}
] | import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.reinershir.auth.annotation.OptionType;
import io.github.reinershir.auth.annotation.Permission;
import io.github.reinershir.auth.annotation.PermissionMapping;
import io.github.reinershir.boot.common.Result;
import io.github.reinershir.boot.core.easygenerator.generator.EasyAutoModule;
import io.github.reinershir.boot.core.easygenerator.generator.MicroSMSCodeGenerator;
import io.github.reinershir.boot.core.easygenerator.model.FieldInfo;
import io.github.reinershir.boot.core.easygenerator.model.GenerateInfo;
import io.github.reinershir.boot.core.international.IMessager;
import io.github.reinershir.boot.dto.req.CodeGenerateDTO;
import io.github.reinershir.boot.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse; | 6,624 | package io.github.reinershir.boot.controller;
@RequestMapping("development")
@RestController
@Tag(description = "Development management",name = "Development management")
@PermissionMapping(value="DEVELOPMENT")
public class DevelopmentController {
@Autowired
MicroSMSCodeGenerator codeGenerator;
@Permission(name = "Get Table columns",value = OptionType.LIST)
@Operation(summary = "Get Table columns",description = "Get Table columns")
@Parameter(name = "tableName",required = false,description = "Parent menu id")
@GetMapping("/codeGenerate/{tableName}/columns")
public Result<List<FieldInfo>> getColumns(@PathVariable(value="tableName",required = true) String tableName){
try {
return Result.ok(codeGenerator.getTableFields(tableName));
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return Result.failed(IMessager.getMessageByCode("message.error"));
}
}
@Permission(name = "Code generate",value = OptionType.LIST)
@Operation(summary = "Code generate",description = "Generate front-end and back-end codes")
@PostMapping("/codeGenerate/codes")
public void generate(@RequestBody @Validated CodeGenerateDTO dto,HttpServletResponse response){ | package io.github.reinershir.boot.controller;
@RequestMapping("development")
@RestController
@Tag(description = "Development management",name = "Development management")
@PermissionMapping(value="DEVELOPMENT")
public class DevelopmentController {
@Autowired
MicroSMSCodeGenerator codeGenerator;
@Permission(name = "Get Table columns",value = OptionType.LIST)
@Operation(summary = "Get Table columns",description = "Get Table columns")
@Parameter(name = "tableName",required = false,description = "Parent menu id")
@GetMapping("/codeGenerate/{tableName}/columns")
public Result<List<FieldInfo>> getColumns(@PathVariable(value="tableName",required = true) String tableName){
try {
return Result.ok(codeGenerator.getTableFields(tableName));
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return Result.failed(IMessager.getMessageByCode("message.error"));
}
}
@Permission(name = "Code generate",value = OptionType.LIST)
@Operation(summary = "Code generate",description = "Generate front-end and back-end codes")
@PostMapping("/codeGenerate/codes")
public void generate(@RequestBody @Validated CodeGenerateDTO dto,HttpServletResponse response){ | GenerateInfo generateInfo = new GenerateInfo(dto.getTableName(),dto.getModelName(),dto.getModelDescription()); | 4 | 2023-10-10 13:06:54+00:00 | 8k |
wise-old-man/wiseoldman-runelite-plugin | src/main/java/net/wiseoldman/panel/SkillingPanel.java | [
{
"identifier": "Format",
"path": "src/main/java/net/wiseoldman/util/Format.java",
"snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n DecimalFormat df = new DecimalFormat();\n df.setGroupingUsed(false);\n df.setRoundingMode(RoundingMode.FLOOR);\n df.setMaximumFractionDigits(2);\n\n // < 10 million\n if (num < 10_000_000 && num > -10_000_000)\n {\n df.setMaximumFractionDigits(0);\n return df.format(num / 1000.0) + \"k\";\n }\n\n // < 1 billion\n if (num < 1_000_000_000 && num > -1_000_000_000)\n {\n return df.format( num / 1_000_000.0) + \"m\";\n }\n\n return df.format(num / 1_000_000_000.0) + \"b\";\n }\n\n public static String formatNumber(double num)\n {\n if ((num < 10000 && num > -10000))\n {\n return String.format(\"%.0f\", num);\n }\n\n DecimalFormat df = new DecimalFormat();\n df.setRoundingMode(RoundingMode.FLOOR);\n df.setMaximumFractionDigits(2);\n\n return df.format(num / 1000.0) + \"k\";\n }\n\n public static String formatDate(String date, boolean relative)\n {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd MMM yyyy, HH:mm\");\n ZoneId localZone = ZoneId.systemDefault();\n ZonedDateTime updatedAt = Instant.parse(date).atZone(localZone);\n\n if (relative)\n {\n String lastUpdated = \"\";\n ZonedDateTime now = Instant.now().atZone(localZone);\n long difference = Duration.between(updatedAt, now).toHours();\n\n if (difference == 0)\n {\n return \"less than 1 hour ago\";\n }\n\n long days = difference / 24;\n long hours = difference % 24;\n\n String dayUnit = days > 1 ? \" days, \" : \" day, \";\n String hourUnit = hours > 1 ? \" hours ago\" : \" hour ago\";\n\n lastUpdated += days > 0 ? days + dayUnit : \"\";\n lastUpdated += hours > 0 ? hours + hourUnit : \"\";\n\n return lastUpdated;\n }\n else\n {\n return formatter.format(updatedAt);\n }\n }\n}"
},
{
"identifier": "WomUtilsConfig",
"path": "src/main/java/net/wiseoldman/WomUtilsConfig.java",
"snippet": "@ConfigGroup(WomUtilsPlugin.CONFIG_GROUP)\npublic interface WomUtilsConfig extends Config\n{\n\t@ConfigSection(\n\t\tname = \"Group\",\n\t\tdescription = \"The group configurations\",\n\t\tposition = 1\n\t)\n\tString groupConfig = \"groupConfig\";\n\n\t@ConfigSection(\n\t\tname = \"Lookup\",\n\t\tdescription = \"Lookup menu option configurations\",\n\t\tposition = 2\n\t)\n\tString lookupConfig = \"lookupConfig\";\n\n\t@ConfigSection(\n\t\tname = \"Competitions\",\n\t\tdescription = \"Competition configurations\",\n\t\tposition = 3\n\t)\n\tString competitionConfig = \"competitionConfig\";\n\n\t@ConfigSection(\n\t\tname = \"Event codeword\",\n\t\tdescription = \"Event codeword configurations\",\n\t\tposition = 4\n\t)\n\tString eventCodeword = \"eventCodeword\";\n\n\t@ConfigItem(\n\t\tkeyName = \"playerLookupOption\",\n\t\tname = \"Player option\",\n\t\tdescription = \"Add WOM Lookup option to players\",\n\t\tposition = 0,\n\t\tsection = lookupConfig\n\t)\n\tdefault boolean playerLookupOption() { return true; }\n\n\t@ConfigItem(\n\t\tkeyName = \"menuLookupOption\",\n\t\tname = \"Menu option\",\n\t\tdescription = \"Add WOM Lookup option to menus\",\n\t\tposition = 1,\n\t\tsection = lookupConfig\n\t)\n\tdefault boolean menuLookupOption() { return true; }\n\n\t@ConfigItem(\n\t\tkeyName = \"virtualLevels\",\n\t\tname = \"Virtual levels\",\n\t\tdescription = \"Show virtual levels in the side bar on lookup\",\n\t\tposition = 2,\n\t\tsection = lookupConfig\n\t)\n\tdefault boolean virtualLevels() { return false; }\n\n\t@ConfigItem(\n\t\tkeyName = \"relativeTime\",\n\t\tname = \"Relative time\",\n\t\tdescription = \"Display last updated time relative to current date and time\",\n\t\tposition = 3,\n\t\tsection = lookupConfig\n\t)\n\tdefault boolean relativeTime() { return false; }\n\n\t@ConfigItem(\n\t\tkeyName = \"showIcons\",\n\t\tname = \"Show icons\",\n\t\tdescription = \"Show icons in friend list and clan chat for people who are in the WOM group\",\n\t\tposition = 0,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean showicons()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName= \"showFlags\",\n\t\tname = \"Show flags\",\n\t\tdescription = \"Show flags instead of the group icon where possible for your group members, requires icons to be enabled.\",\n\t\tposition = 1,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean showFlags()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"importGroup\",\n\t\tname = \"Import Group option\",\n\t\tdescription = \"Add Import WOM Group menu option to the clan chat tab\",\n\t\tposition = 2,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean importGroup()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"browseGroup\",\n\t\tname = \"Browse Group option\",\n\t\tdescription = \"Add Browse WOM Group menu option to the clan chat tab\",\n\t\tposition = 3,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean browseGroup()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"addRemoveMember\",\n\t\tname = \"Add/Remove Member option\",\n\t\tdescription = \"Add options to add & remove players from group, to clan chat and friend list\",\n\t\tposition = 4,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean addRemoveMember()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"syncClanButton\",\n\t\tname = \"Sync Clan button\",\n\t\tdescription = \"Add a sync clan button to the clan members list in settings if a group is configured\",\n\t\tposition = 5,\n\t\tsection = groupConfig\n\t)\n\tdefault boolean syncClanButton()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"alwaysIncludedOnSync\",\n\t\tname = \"Always Included\",\n\t\tdescription = \"Players that will always be included in the group regardless of clan sync method, comma separated names\",\n\t\tposition = 6,\n\t\tsection = groupConfig\n\t)\n\tdefault String alwaysIncludedOnSync()\n\t{\n\t\treturn \"\";\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"groupId\",\n\t\tname = \"Group Id\",\n\t\tdescription = \"The group id in WOM\",\n\t\tposition = 7,\n\t\tsection = groupConfig\n\t)\n\tdefault int groupId()\n\t{\n\t\treturn 0;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"verificationCode\",\n\t\tname = \"Verification code\",\n\t\tdescription = \"Verification code for the WOM group\",\n\t\tsecret = true,\n\t\tposition = 8,\n\t\tsection = groupConfig\n\t)\n\tdefault String verificationCode()\n\t{\n\t\treturn \"\";\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"competitionLoginMessage\",\n\t\tname = \"Login info\",\n\t\tdescription = \"Show ongoing competition info when logging in\",\n\t\tposition = 1,\n\t\tsection = competitionConfig\n\t)\n\tdefault boolean competitionLoginMessage()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"timerOngoing\",\n\t\tname = \"Timer Ongoing\",\n\t\tdescription = \"Displays timers for ongoing competitions\",\n\t\tposition = 2,\n\t\tsection = competitionConfig\n\t)\n\tdefault boolean timerOngoing()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"timerUpcoming\",\n\t\tname = \"Timer Upcoming\",\n\t\tdescription = \"Display timers for upcoming competitions\",\n\t\tposition = 3,\n\t\tsection = competitionConfig\n\t)\n\tdefault boolean timerUpcoming()\n\t{\n\t\treturn false;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"upcomingMaxDays\",\n\t\tname = \"Upcoming up to\",\n\t\tdescription = \"Don't show info for competitions later than this many days in the future\",\n\t\tposition = 4,\n\t\tsection = competitionConfig\n\t)\n\t@Range(\n\t\tmax = 365\n\t)\n\t@Units(\" days\")\n\tdefault int upcomingMaxDays()\n\t{\n\t\treturn 7;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"sendCompetitionNotification\",\n\t\tname = \"Competition Notifications\",\n\t\tdescription = \"Sends notifications at start and end times for competitions\",\n\t\tposition = 5,\n\t\tsection = competitionConfig\n\t)\n\tdefault boolean sendCompetitionNotification()\n\t{\n\t\treturn false;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"displayCodeword\",\n\t\tname = \"Display codeword\",\n\t\tdescription = \"Displays an event codeword overlay\",\n\t\tposition = 13,\n\t\tsection = eventCodeword\n\t)\n\tdefault boolean displayCodeword()\n\t{\n\t\treturn false;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"configuredCodeword\",\n\t\tname = \"Codeword\",\n\t\tdescription = \"Event codeword\",\n\t\tposition = 14,\n\t\tsection = eventCodeword\n\t)\n\tdefault String configuredCodeword()\n\t{\n\t\treturn \"WOMCodeword\";\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"showTimestamp\",\n\t\tname = \"Show timestamp\",\n\t\tdescription = \"Attach a timestamp to the codeword\",\n\t\tposition = 15,\n\t\tsection = eventCodeword\n\t)\n\tdefault boolean showTimestamp()\n\t{\n\t\treturn true;\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"codewordColor\",\n\t\tname = \"Codeword color\",\n\t\tdescription = \"Overlay codeword color\",\n\t\tposition = 16,\n\t\tsection = eventCodeword\n\t)\n\tdefault Color codewordColor()\n\t{\n\t\treturn new Color(0x00FF6A);\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"timestampColor\",\n\t\tname = \"Timestamp color\",\n\t\tdescription = \"Overlay timestamp color\",\n\t\tposition = 16,\n\t\tsection = eventCodeword\n\t)\n\tdefault Color timestampColor()\n\t{\n\t\treturn new Color(0xFFFFFF);\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"hiddenCompetitionIds\",\n\t\tname = \"\",\n\t\tdescription = \"\",\n\t\thidden = true\n\t)\n\tdefault String hiddenCompetitionIds()\n\t{\n\t\treturn \"[]\";\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"hiddenCompetitionIds\",\n\t\tname = \"\",\n\t\tdescription = \"\",\n\t\thidden = true\n\t)\n\tvoid hiddenCompetitionIds(String value);\n\n\t@ConfigItem(\n\t\tkeyName = \"ignoredRanks\",\n\t\tname = \"\",\n\t\tdescription = \"\",\n\t\thidden = true\n\t)\n\tdefault String ignoredRanks()\n\t{\n\t\treturn \"[]\";\n\t}\n\n\t@ConfigItem(\n\t\tkeyName = \"ignoredRanks\",\n\t\tname = \"\",\n\t\tdescription = \"\",\n\t\thidden = true\n\t)\n\tvoid ignoredRanks(String value);\n}"
},
{
"identifier": "PlayerInfo",
"path": "src/main/java/net/wiseoldman/beans/PlayerInfo.java",
"snippet": "@Value\npublic class PlayerInfo\n{\n int id;\n String username;\n String displayName;\n PlayerType type;\n PlayerBuild build;\n String country;\n boolean flagged;\n long exp;\n double ehp;\n double ehb;\n double ttm;\n double tt200m;\n String registeredAt;\n String updatedAt;\n String lastChangedAt;\n String lastImportedAt;\n int combatLevel;\n Snapshot latestSnapshot;\n}"
},
{
"identifier": "Skill",
"path": "src/main/java/net/wiseoldman/beans/Skill.java",
"snippet": "@Value\npublic class Skill\n{\n\tString metric;\n\tlong experience;\n\tint rank;\n\tint level;\n\tdouble ehp;\n}"
},
{
"identifier": "Snapshot",
"path": "src/main/java/net/wiseoldman/beans/Snapshot.java",
"snippet": "@Value\npublic class Snapshot\n{\n\tint id;\n\tint playerId;\n\tString createdAt;\n\tString importedAt;\n\tSnapshotData data;\n}"
}
] | import com.google.common.collect.ImmutableList;
import net.wiseoldman.util.Format;
import net.wiseoldman.WomUtilsConfig;
import net.wiseoldman.beans.PlayerInfo;
import net.wiseoldman.beans.Skill;
import net.wiseoldman.beans.Snapshot;
import net.runelite.api.Experience;
import net.runelite.client.ui.ColorScheme;
import net.runelite.client.util.QuantityFormatter;
import net.runelite.client.hiscore.HiscoreSkill;
import net.runelite.client.hiscore.HiscoreSkillType;
import javax.inject.Inject;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static net.runelite.client.hiscore.HiscoreSkill.*; | 4,143 | package net.wiseoldman.panel;
class SkillingPanel extends JPanel
{
/**
* Real skills, ordered in the way they should be displayed in the panel.
*/
private static final List<HiscoreSkill> SKILLS = ImmutableList.of(
ATTACK, DEFENCE, STRENGTH,
HITPOINTS, RANGED, PRAYER,
MAGIC, COOKING, WOODCUTTING,
FLETCHING, FISHING, FIREMAKING,
CRAFTING, SMITHING, MINING,
HERBLORE, AGILITY, THIEVING,
SLAYER, FARMING, RUNECRAFT,
HUNTER, CONSTRUCTION
);
static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)};
TableRow overallRow;
List<RowPair> tableRows = new ArrayList<>();
WomUtilsConfig config;
@Inject
private SkillingPanel(WomUtilsConfig config)
{
this.config = config;
setLayout(new GridLayout(0, 1));
StatsTableHeader tableHeader = new StatsTableHeader("skilling");
// Handle overall separately because it's special
overallRow = new TableRow(
OVERALL.name(), OVERALL.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
overallRow.setBackground(ROW_COLORS[1]);
add(tableHeader);
add(overallRow);
for (int i = 0; i < SKILLS.size(); i++)
{
HiscoreSkill skill = SKILLS.get(i);
TableRow row = new TableRow(
skill.name(), skill.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
row.setBackground(ROW_COLORS[i%2]);
tableRows.add(new RowPair(skill, row));
add(row);
}
}
public void update(PlayerInfo info)
{
if (info == null)
{
return;
}
Snapshot latestSnapshot = info.getLatestSnapshot();
for (RowPair rp : tableRows)
{
HiscoreSkill skill = rp.getSkill();
TableRow row = rp.getRow();
row.update(latestSnapshot.getData().getSkills().getSkill(skill), config.virtualLevels());
}
updateTotalLevel(latestSnapshot);
}
private void updateTotalLevel(Snapshot snapshot)
{
int totalLevel = 0;
Skill overall = snapshot.getData().getSkills().getSkill(OVERALL);
long overallExperience = overall.getExperience();
int overallRank = overall.getRank();
for (HiscoreSkill skill : SKILLS)
{
int experience = (int) snapshot.getData().getSkills().getSkill(skill).getExperience();
int level = experience >= 0 ? Experience.getLevelForXp(experience) : 0;
totalLevel += !config.virtualLevels() && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level;
}
JLabel expLabel = overallRow.labels.get("experience");
JLabel levelLabel = overallRow.labels.get("level");
JLabel rankLabel = overallRow.labels.get("rank");
JLabel ehpLabel = overallRow.labels.get("ehp");
| package net.wiseoldman.panel;
class SkillingPanel extends JPanel
{
/**
* Real skills, ordered in the way they should be displayed in the panel.
*/
private static final List<HiscoreSkill> SKILLS = ImmutableList.of(
ATTACK, DEFENCE, STRENGTH,
HITPOINTS, RANGED, PRAYER,
MAGIC, COOKING, WOODCUTTING,
FLETCHING, FISHING, FIREMAKING,
CRAFTING, SMITHING, MINING,
HERBLORE, AGILITY, THIEVING,
SLAYER, FARMING, RUNECRAFT,
HUNTER, CONSTRUCTION
);
static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)};
TableRow overallRow;
List<RowPair> tableRows = new ArrayList<>();
WomUtilsConfig config;
@Inject
private SkillingPanel(WomUtilsConfig config)
{
this.config = config;
setLayout(new GridLayout(0, 1));
StatsTableHeader tableHeader = new StatsTableHeader("skilling");
// Handle overall separately because it's special
overallRow = new TableRow(
OVERALL.name(), OVERALL.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
overallRow.setBackground(ROW_COLORS[1]);
add(tableHeader);
add(overallRow);
for (int i = 0; i < SKILLS.size(); i++)
{
HiscoreSkill skill = SKILLS.get(i);
TableRow row = new TableRow(
skill.name(), skill.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
row.setBackground(ROW_COLORS[i%2]);
tableRows.add(new RowPair(skill, row));
add(row);
}
}
public void update(PlayerInfo info)
{
if (info == null)
{
return;
}
Snapshot latestSnapshot = info.getLatestSnapshot();
for (RowPair rp : tableRows)
{
HiscoreSkill skill = rp.getSkill();
TableRow row = rp.getRow();
row.update(latestSnapshot.getData().getSkills().getSkill(skill), config.virtualLevels());
}
updateTotalLevel(latestSnapshot);
}
private void updateTotalLevel(Snapshot snapshot)
{
int totalLevel = 0;
Skill overall = snapshot.getData().getSkills().getSkill(OVERALL);
long overallExperience = overall.getExperience();
int overallRank = overall.getRank();
for (HiscoreSkill skill : SKILLS)
{
int experience = (int) snapshot.getData().getSkills().getSkill(skill).getExperience();
int level = experience >= 0 ? Experience.getLevelForXp(experience) : 0;
totalLevel += !config.virtualLevels() && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level;
}
JLabel expLabel = overallRow.labels.get("experience");
JLabel levelLabel = overallRow.labels.get("level");
JLabel rankLabel = overallRow.labels.get("rank");
JLabel ehpLabel = overallRow.labels.get("ehp");
| expLabel.setText(overallExperience >= 0 ? Format.formatNumber(overallExperience) : "--"); | 0 | 2023-10-09 14:23:06+00:00 | 8k |
PeytonPlayz595/c0.0.23a_01 | src/main/java/com/mojang/minecraft/player/Inventory.java | [
{
"identifier": "User",
"path": "src/main/java/com/mojang/minecraft/User.java",
"snippet": "public final class User {\n\tpublic static List creativeTiles;\n\tpublic String name;\n\tpublic String sessionId;\n\tpublic String mpPass;\n\n\tpublic User(String var1, String var2) {\n\t\tthis.name = var1;\n\t\tthis.sessionId = var2;\n\t}\n\n\tstatic {\n\t\t(creativeTiles = new ArrayList()).add(Tile.rock);\n\t\tcreativeTiles.add(Tile.wood);\n\t\tcreativeTiles.add(Tile.dirt);\n\t\tcreativeTiles.add(Tile.stoneBrick);\n\t\tcreativeTiles.add(Tile.log);\n\t\tcreativeTiles.add(Tile.leaf);\n\t\tcreativeTiles.add(Tile.bush);\n\t\tcreativeTiles.add(Tile.plantYellow);\n\t\tcreativeTiles.add(Tile.plantRed);\n\t\tcreativeTiles.add(Tile.mushroomBrown);\n\t\tcreativeTiles.add(Tile.mushroomRed);\n\t\tcreativeTiles.add(Tile.sand);\n\t\tcreativeTiles.add(Tile.gravel);\n\t\tcreativeTiles.add(Tile.glass);\n\t\tcreativeTiles.add(Tile.sponge);\n\t\tcreativeTiles.add(Tile.blockGold);\n\t\tcreativeTiles.add(Tile.clothRed);\n\t\tcreativeTiles.add(Tile.clothOrange);\n\t\tcreativeTiles.add(Tile.clothYellow);\n\t\tcreativeTiles.add(Tile.clothChartreuse);\n\t\tcreativeTiles.add(Tile.clothGreen);\n\t\tcreativeTiles.add(Tile.clothSpringGreen);\n\t\tcreativeTiles.add(Tile.clothCyan);\n\t\tcreativeTiles.add(Tile.clothCapri);\n\t\tcreativeTiles.add(Tile.clothUltramarine);\n\t\tcreativeTiles.add(Tile.clothViolet);\n\t\tcreativeTiles.add(Tile.clothPurple);\n\t\tcreativeTiles.add(Tile.clothMagenta);\n\t\tcreativeTiles.add(Tile.clothRose);\n\t\tcreativeTiles.add(Tile.clothDarkGray);\n\t\tcreativeTiles.add(Tile.clothGray);\n\t\tcreativeTiles.add(Tile.clothWhite);\n\t}\n}"
},
{
"identifier": "Tile",
"path": "src/main/java/com/mojang/minecraft/level/tile/Tile.java",
"snippet": "public class Tile {\n\tprotected static Random random = new Random();\n\tpublic static final Tile[] tiles = new Tile[256];\n\tpublic static final boolean[] shouldTick = new boolean[256];\n\tprivate static int[] tickSpeed = new int[256];\n\tpublic static final Tile rock = (new Tile(1, 1)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile grass = (new GrassTile(2)).setSoundAndGravity(Tile.SoundType.grass, 0.9F, 1.0F);\n\tpublic static final Tile dirt = (new DirtTile(3, 2)).setSoundAndGravity(Tile.SoundType.grass, 0.8F, 1.0F);\n\tpublic static final Tile wood = (new Tile(4, 16)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile stoneBrick = (new Tile(5, 4)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F);\n\tpublic static final Tile bush = (new Bush(6, 15)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F);\n\tpublic static final Tile unbreakable = (new Tile(7, 17)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile water = (new LiquidTile(8, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F);\n\tpublic static final Tile calmWater = (new CalmLiquidTile(9, Liquid.water)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F);\n\tpublic static final Tile lava = (new LiquidTile(10, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F);\n\tpublic static final Tile calmLava = (new CalmLiquidTile(11, Liquid.lava)).setSoundAndGravity(Tile.SoundType.none, 1.0F, 1.0F);\n\tpublic static final Tile sand = (new FallingTile(12, 18)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F);\n\tpublic static final Tile gravel = (new FallingTile(13, 19)).setSoundAndGravity(Tile.SoundType.gravel, 0.8F, 1.0F);\n\tpublic static final Tile oreGold = (new Tile(14, 32)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile oreIron = (new Tile(15, 33)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile oreCoal = (new Tile(16, 34)).setSoundAndGravity(Tile.SoundType.stone, 1.0F, 1.0F);\n\tpublic static final Tile log = (new LogTile(17)).setSoundAndGravity(Tile.SoundType.wood, 1.0F, 1.0F);\n\tpublic static final Tile leaf = (new LeafTile(18, 22, true)).setSoundAndGravity(Tile.SoundType.grass, 1.0F, 0.4F);\n\tpublic static final Tile sponge = (new SpongeTile(19)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 0.9F);\n\tpublic static final Tile glass = (new GlassTile(20, 49, false)).setSoundAndGravity(Tile.SoundType.metal, 1.0F, 1.0F);\n\tpublic static final Tile clothRed = (new Tile(21, 64)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothOrange = (new Tile(22, 65)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothYellow = (new Tile(23, 66)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothChartreuse = (new Tile(24, 67)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothGreen = (new Tile(25, 68)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothSpringGreen = (new Tile(26, 69)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothCyan = (new Tile(27, 70)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothCapri = (new Tile(28, 71)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothUltramarine = (new Tile(29, 72)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothViolet = (new Tile(30, 73)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothPurple = (new Tile(31, 74)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothMagenta = (new Tile(32, 75)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothRose = (new Tile(33, 76)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothDarkGray = (new Tile(34, 77)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothGray = (new Tile(35, 78)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile clothWhite = (new Tile(36, 79)).setSoundAndGravity(Tile.SoundType.cloth, 1.0F, 1.0F);\n\tpublic static final Tile plantYellow = (new Bush(37, 13)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F);\n\tpublic static final Tile plantRed = (new Bush(38, 12)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F);\n\tpublic static final Tile mushroomBrown = (new Bush(39, 29)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F);\n\tpublic static final Tile mushroomRed = (new Bush(40, 28)).setSoundAndGravity(Tile.SoundType.none, 0.7F, 1.0F);\n\tpublic static final Tile blockGold = (new Tile(41, 40)).setSoundAndGravity(Tile.SoundType.metal, 0.7F, 1.0F);\n\tpublic int tex;\n\tpublic final int id;\n\tpublic Tile.SoundType soundType;\n\tprivate float xx0;\n\tprivate float yy0;\n\tprivate float zz0;\n\tprivate float xx1;\n\tprivate float yy1;\n\tprivate float zz1;\n\tpublic float particleGravity;\n\n\tprotected Tile(int var1) {\n\t\ttiles[var1] = this;\n\t\tthis.id = var1;\n\t\tthis.setShape(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);\n\t}\n\n\tprotected final Tile setSoundAndGravity(Tile.SoundType var1, float var2, float var3) {\n\t\tthis.particleGravity = var3;\n\t\tthis.soundType = var1;\n\t\treturn this;\n\t}\n\n\tprotected final void setTicking(boolean var1) {\n\t\tshouldTick[this.id] = var1;\n\t}\n\n\tprotected final void setShape(float var1, float var2, float var3, float var4, float var5, float var6) {\n\t\tthis.xx0 = var1;\n\t\tthis.yy0 = var2;\n\t\tthis.zz0 = var3;\n\t\tthis.xx1 = var4;\n\t\tthis.yy1 = var5;\n\t\tthis.zz1 = var6;\n\t}\n\n\tprotected Tile(int var1, int var2) {\n\t\tthis(var1);\n\t\tthis.tex = var2;\n\t}\n\n\tpublic final void setTickSpeed(int var1) {\n\t\ttickSpeed[this.id] = 16;\n\t}\n\n\tpublic boolean render(Tesselator var1, Level var2, int var3, int var4, int var5, int var6) {\n\t\tboolean var7 = false;\n\t\tfloat var8 = 0.5F;\n\t\tfloat var9 = 0.8F;\n\t\tfloat var10 = 0.6F;\n\t\tfloat var11;\n\t\tif(this.shouldRenderFace(var2, var4, var5 - 1, var6, var3, 0)) {\n\t\t\tvar11 = this.getBrightness(var2, var4, var5 - 1, var6);\n\t\t\tvar1.color(var8 * var11, var8 * var11, var8 * var11);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 0);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\tif(this.shouldRenderFace(var2, var4, var5 + 1, var6, var3, 1)) {\n\t\t\tvar11 = this.getBrightness(var2, var4, var5 + 1, var6);\n\t\t\tvar1.color(var11 * 1.0F, var11 * 1.0F, var11 * 1.0F);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 1);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\tif(this.shouldRenderFace(var2, var4, var5, var6 - 1, var3, 2)) {\n\t\t\tvar11 = this.getBrightness(var2, var4, var5, var6 - 1);\n\t\t\tvar1.color(var9 * var11, var9 * var11, var9 * var11);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 2);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\tif(this.shouldRenderFace(var2, var4, var5, var6 + 1, var3, 3)) {\n\t\t\tvar11 = this.getBrightness(var2, var4, var5, var6 + 1);\n\t\t\tvar1.color(var9 * var11, var9 * var11, var9 * var11);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 3);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\tif(this.shouldRenderFace(var2, var4 - 1, var5, var6, var3, 4)) {\n\t\t\tvar11 = this.getBrightness(var2, var4 - 1, var5, var6);\n\t\t\tvar1.color(var10 * var11, var10 * var11, var10 * var11);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 4);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\tif(this.shouldRenderFace(var2, var4 + 1, var5, var6, var3, 5)) {\n\t\t\tvar11 = this.getBrightness(var2, var4 + 1, var5, var6);\n\t\t\tvar1.color(var10 * var11, var10 * var11, var10 * var11);\n\t\t\tthis.renderFace(var1, var4, var5, var6, 5);\n\t\t\tvar7 = true;\n\t\t}\n\n\t\treturn var7;\n\t}\n\n\tprotected float getBrightness(Level var1, int var2, int var3, int var4) {\n\t\treturn var1.getBrightness(var2, var3, var4);\n\t}\n\n\tprotected boolean shouldRenderFace(Level var1, int var2, int var3, int var4, int var5, int var6) {\n\t\treturn var5 == 1 ? false : !var1.isSolidTile(var2, var3, var4);\n\t}\n\n\tprotected int getTexture(int var1) {\n\t\treturn this.tex;\n\t}\n\n\tpublic void renderFace(Tesselator var1, int var2, int var3, int var4, int var5) {\n\t\tint var6 = this.getTexture(var5);\n\t\tint var7 = var6 % 16 << 4;\n\t\tvar6 = var6 / 16 << 4;\n\t\tfloat var8 = (float)var7 / 256.0F;\n\t\tfloat var17 = ((float)var7 + 15.99F) / 256.0F;\n\t\tfloat var9 = (float)var6 / 256.0F;\n\t\tfloat var16 = ((float)var6 + 15.99F) / 256.0F;\n\t\tfloat var10 = (float)var2 + this.xx0;\n\t\tfloat var14 = (float)var2 + this.xx1;\n\t\tfloat var11 = (float)var3 + this.yy0;\n\t\tfloat var15 = (float)var3 + this.yy1;\n\t\tfloat var12 = (float)var4 + this.zz0;\n\t\tfloat var13 = (float)var4 + this.zz1;\n\t\tif(var5 == 0) {\n\t\t\tvar1.vertexUV(var10, var11, var13, var8, var16);\n\t\t\tvar1.vertexUV(var10, var11, var12, var8, var9);\n\t\t\tvar1.vertexUV(var14, var11, var12, var17, var9);\n\t\t\tvar1.vertexUV(var14, var11, var13, var17, var16);\n\t\t} else if(var5 == 1) {\n\t\t\tvar1.vertexUV(var14, var15, var13, var17, var16);\n\t\t\tvar1.vertexUV(var14, var15, var12, var17, var9);\n\t\t\tvar1.vertexUV(var10, var15, var12, var8, var9);\n\t\t\tvar1.vertexUV(var10, var15, var13, var8, var16);\n\t\t} else if(var5 == 2) {\n\t\t\tvar1.vertexUV(var10, var15, var12, var17, var9);\n\t\t\tvar1.vertexUV(var14, var15, var12, var8, var9);\n\t\t\tvar1.vertexUV(var14, var11, var12, var8, var16);\n\t\t\tvar1.vertexUV(var10, var11, var12, var17, var16);\n\t\t} else if(var5 == 3) {\n\t\t\tvar1.vertexUV(var10, var15, var13, var8, var9);\n\t\t\tvar1.vertexUV(var10, var11, var13, var8, var16);\n\t\t\tvar1.vertexUV(var14, var11, var13, var17, var16);\n\t\t\tvar1.vertexUV(var14, var15, var13, var17, var9);\n\t\t} else if(var5 == 4) {\n\t\t\tvar1.vertexUV(var10, var15, var13, var17, var9);\n\t\t\tvar1.vertexUV(var10, var15, var12, var8, var9);\n\t\t\tvar1.vertexUV(var10, var11, var12, var8, var16);\n\t\t\tvar1.vertexUV(var10, var11, var13, var17, var16);\n\t\t} else if(var5 == 5) {\n\t\t\tvar1.vertexUV(var14, var11, var13, var8, var16);\n\t\t\tvar1.vertexUV(var14, var11, var12, var17, var16);\n\t\t\tvar1.vertexUV(var14, var15, var12, var17, var9);\n\t\t\tvar1.vertexUV(var14, var15, var13, var8, var9);\n\t\t}\n\t}\n\n\tpublic final void renderBackFace(Tesselator var1, int var2, int var3, int var4, int var5) {\n\t\tint var6 = this.getTexture(var5);\n\t\tfloat var7 = (float)(var6 % 16) / 16.0F;\n\t\tfloat var8 = var7 + 0.999F / 16.0F;\n\t\tfloat var16 = (float)(var6 / 16) / 16.0F;\n\t\tfloat var9 = var16 + 0.999F / 16.0F;\n\t\tfloat var10 = (float)var2 + this.xx0;\n\t\tfloat var14 = (float)var2 + this.xx1;\n\t\tfloat var11 = (float)var3 + this.yy0;\n\t\tfloat var15 = (float)var3 + this.yy1;\n\t\tfloat var12 = (float)var4 + this.zz0;\n\t\tfloat var13 = (float)var4 + this.zz1;\n\t\tif(var5 == 0) {\n\t\t\tvar1.vertexUV(var14, var11, var13, var8, var9);\n\t\t\tvar1.vertexUV(var14, var11, var12, var8, var16);\n\t\t\tvar1.vertexUV(var10, var11, var12, var7, var16);\n\t\t\tvar1.vertexUV(var10, var11, var13, var7, var9);\n\t\t}\n\n\t\tif(var5 == 1) {\n\t\t\tvar1.vertexUV(var10, var15, var13, var7, var9);\n\t\t\tvar1.vertexUV(var10, var15, var12, var7, var16);\n\t\t\tvar1.vertexUV(var14, var15, var12, var8, var16);\n\t\t\tvar1.vertexUV(var14, var15, var13, var8, var9);\n\t\t}\n\n\t\tif(var5 == 2) {\n\t\t\tvar1.vertexUV(var10, var11, var12, var8, var9);\n\t\t\tvar1.vertexUV(var14, var11, var12, var7, var9);\n\t\t\tvar1.vertexUV(var14, var15, var12, var7, var16);\n\t\t\tvar1.vertexUV(var10, var15, var12, var8, var16);\n\t\t}\n\n\t\tif(var5 == 3) {\n\t\t\tvar1.vertexUV(var14, var15, var13, var8, var16);\n\t\t\tvar1.vertexUV(var14, var11, var13, var8, var9);\n\t\t\tvar1.vertexUV(var10, var11, var13, var7, var9);\n\t\t\tvar1.vertexUV(var10, var15, var13, var7, var16);\n\t\t}\n\n\t\tif(var5 == 4) {\n\t\t\tvar1.vertexUV(var10, var11, var13, var8, var9);\n\t\t\tvar1.vertexUV(var10, var11, var12, var7, var9);\n\t\t\tvar1.vertexUV(var10, var15, var12, var7, var16);\n\t\t\tvar1.vertexUV(var10, var15, var13, var8, var16);\n\t\t}\n\n\t\tif(var5 == 5) {\n\t\t\tvar1.vertexUV(var14, var15, var13, var7, var16);\n\t\t\tvar1.vertexUV(var14, var15, var12, var8, var16);\n\t\t\tvar1.vertexUV(var14, var11, var12, var8, var9);\n\t\t\tvar1.vertexUV(var14, var11, var13, var7, var9);\n\t\t}\n\n\t}\n\n\tpublic static void renderFaceNoTexture(Entity var0, Tesselator var1, int var2, int var3, int var4, int var5) {\n\t\tfloat var6 = (float)var2;\n\t\tfloat var7 = (float)var2 + 1.0F;\n\t\tfloat var8 = (float)var3;\n\t\tfloat var9 = (float)var3 + 1.0F;\n\t\tfloat var10 = (float)var4;\n\t\tfloat var11 = (float)var4 + 1.0F;\n\t\tif(var5 == 0 && (float)var3 > var0.y) {\n\t\t\tvar1.vertex(var6, var8, var11);\n\t\t\tvar1.vertex(var6, var8, var10);\n\t\t\tvar1.vertex(var7, var8, var10);\n\t\t\tvar1.vertex(var7, var8, var11);\n\t\t}\n\n\t\tif(var5 == 1 && (float)var3 < var0.y) {\n\t\t\tvar1.vertex(var7, var9, var11);\n\t\t\tvar1.vertex(var7, var9, var10);\n\t\t\tvar1.vertex(var6, var9, var10);\n\t\t\tvar1.vertex(var6, var9, var11);\n\t\t}\n\n\t\tif(var5 == 2 && (float)var4 > var0.z) {\n\t\t\tvar1.vertex(var6, var9, var10);\n\t\t\tvar1.vertex(var7, var9, var10);\n\t\t\tvar1.vertex(var7, var8, var10);\n\t\t\tvar1.vertex(var6, var8, var10);\n\t\t}\n\n\t\tif(var5 == 3 && (float)var4 < var0.z) {\n\t\t\tvar1.vertex(var6, var9, var11);\n\t\t\tvar1.vertex(var6, var8, var11);\n\t\t\tvar1.vertex(var7, var8, var11);\n\t\t\tvar1.vertex(var7, var9, var11);\n\t\t}\n\n\t\tif(var5 == 4 && (float)var2 > var0.x) {\n\t\t\tvar1.vertex(var6, var9, var11);\n\t\t\tvar1.vertex(var6, var9, var10);\n\t\t\tvar1.vertex(var6, var8, var10);\n\t\t\tvar1.vertex(var6, var8, var11);\n\t\t}\n\n\t\tif(var5 == 5 && (float)var2 < var0.x) {\n\t\t\tvar1.vertex(var7, var8, var11);\n\t\t\tvar1.vertex(var7, var8, var10);\n\t\t\tvar1.vertex(var7, var9, var10);\n\t\t\tvar1.vertex(var7, var9, var11);\n\t\t}\n\n\t}\n\n\tpublic AABB getTileAABB(int var1, int var2, int var3) {\n\t\treturn new AABB((float)var1, (float)var2, (float)var3, (float)(var1 + 1), (float)(var2 + 1), (float)(var3 + 1));\n\t}\n\n\tpublic boolean blocksLight() {\n\t\treturn true;\n\t}\n\n\tpublic boolean isSolid() {\n\t\treturn true;\n\t}\n\n\tpublic void tick(Level var1, int var2, int var3, int var4, Random var5) {\n\t}\n\n\tpublic final void destroy(Level var1, int var2, int var3, int var4, ParticleEngine var5) {\n\t\tfor(int var6 = 0; var6 < 4; ++var6) {\n\t\t\tfor(int var7 = 0; var7 < 4; ++var7) {\n\t\t\t\tfor(int var8 = 0; var8 < 4; ++var8) {\n\t\t\t\t\tfloat var9 = (float)var2 + ((float)var6 + 0.5F) / (float)4;\n\t\t\t\t\tfloat var10 = (float)var3 + ((float)var7 + 0.5F) / (float)4;\n\t\t\t\t\tfloat var11 = (float)var4 + ((float)var8 + 0.5F) / (float)4;\n\t\t\t\t\tParticle var12 = new Particle(var1, var9, var10, var11, var9 - (float)var2 - 0.5F, var10 - (float)var3 - 0.5F, var11 - (float)var4 - 0.5F, this);\n\t\t\t\t\tvar5.particles.add(var12);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic Liquid getLiquidType() {\n\t\treturn Liquid.none;\n\t}\n\n\tpublic void neighborChanged(Level var1, int var2, int var3, int var4, int var5) {\n\t}\n\n\tpublic void onBlockAdded(Level var1, int var2, int var3, int var4) {\n\t}\n\n\tpublic int getTickDelay() {\n\t\treturn 0;\n\t}\n\n\tpublic void onTileAdded(Level var1, int var2, int var3, int var4) {\n\t}\n\n\tpublic void onTileRemoved(Level var1, int var2, int var3, int var4) {\n\t}\n\n\tpublic static enum SoundType {\n\t\tnone(\"-\", 0.0F, 0.0F),\n\t\tgrass(\"grass\", 0.6F, 1.0F),\n\t\tcloth(\"grass\", 0.7F, 1.2F),\n\t\tgravel(\"gravel\", 1.0F, 1.0F),\n\t\tstone(\"stone\", 1.0F, 1.0F),\n\t\tmetal(\"stone\", 1.0F, 2.0F),\n\t\twood(\"wood\", 1.0F, 1.0F);\n\n\t\tpublic final String name;\n\t\tprivate final float volume;\n\t\tprivate final float pitch;\n\n\t\tprivate SoundType(String var3, float var4, float var5) {\n\t\t\tthis.name = var3;\n\t\t\tthis.volume = var4;\n\t\t\tthis.pitch = var5;\n\t\t}\n\n\t\tpublic final float getVolume() {\n\t\t\treturn this.volume / (Tile.random.nextFloat() * 0.4F + 1.0F) * 0.5F;\n\t\t}\n\n\t\tpublic final float getPitch() {\n\t\t\treturn this.pitch / (Tile.random.nextFloat() * 0.2F + 0.9F);\n\t\t}\n\t}\n}"
}
] | import com.mojang.minecraft.User;
import com.mojang.minecraft.level.tile.Tile; | 6,727 | package com.mojang.minecraft.player;
public final class Inventory {
public int[] slots = new int[9];
public int selectedSlot = 0;
public Inventory() {
for(int var1 = 0; var1 < 9; ++var1) { | package com.mojang.minecraft.player;
public final class Inventory {
public int[] slots = new int[9];
public int selectedSlot = 0;
public Inventory() {
for(int var1 = 0; var1 < 9; ++var1) { | this.slots[var1] = ((Tile)User.creativeTiles.get(var1)).id; | 1 | 2023-10-10 17:10:45+00:00 | 8k |
vaylor27/config | common/src/main/java/net/vakror/jamesconfig/config/config/performance/DefaultConfigPerformanceAnalyzer.java | [
{
"identifier": "Config",
"path": "common/src/main/java/net/vakror/jamesconfig/config/config/Config.java",
"snippet": "public abstract class Config {\n public abstract void generateDefaultConfig();\n\n @NotNull\n public abstract File getConfigDir();\n\n public abstract String getSubPath();\n\n public abstract ResourceLocation getName();\n\n @Override\n public String toString() {\n return this.getName().toString();\n }\n\n public abstract void readConfig(boolean overrideCurrent);\n\n public IConfigPerformanceAnalyzer getConfigAnalyzer() {\n return DefaultConfigPerformanceAnalyzer.INSTANCE;\n }\n\n public final void analyzeConfigPerformance() {\n Path path = Platform.getGameFolder().resolve(\"config performance\");\n File directory = path.toFile();\n if (!directory.exists() && !directory.mkdirs()) {\n throw new IllegalStateException(\"Cannot create config analysis directory!\");\n }\n File thisConfigFile = path.resolve(this.getName().toString()).toFile();\n try {\n if (thisConfigFile.exists()) {\n thisConfigFile.delete();\n }\n thisConfigFile.createNewFile();\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n try (FileWriter writer = new FileWriter(thisConfigFile)) {\n writer.append(getConfigAnalyzer().getPerformanceAnalysis(this));\n writer.flush();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public abstract boolean shouldReadConfig();\n\n public abstract void writeConfig();\n\n public abstract List<JsonObject> serialize();\n\n /**\n *\n * @return whether to clear this config before it is synced. Recommended for all non-clientside configs\n */\n public abstract boolean shouldClearBeforeSync();\n\n /**\n * will not do anything if config is clientside\n * @return whether to sync\n */\n public boolean shouldSync() {\n return true;\n }\n\n public abstract void add(ConfigObject object);\n\n public abstract List<ConfigObject> getAll();\n\n public abstract List<ConfigObject> parse(JsonObject jsonObject);\n\n public abstract void clear();\n}"
},
{
"identifier": "MultiObjectRegistryConfigImpl",
"path": "common/src/main/java/net/vakror/jamesconfig/config/config/registry/multi_object/MultiObjectRegistryConfigImpl.java",
"snippet": "public abstract class MultiObjectRegistryConfigImpl extends Config {\n\n public final List<ConfigObject> objects = new ArrayList<>();\n\n @Override\n public final void generateDefaultConfig() {\n this.resetToDefault();\n this.writeConfig();\n }\n\n @Override\n @NotNull\n public final File getConfigDir() {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath()).toFile();\n return configDir;\n }\n\n @NotNull\n public final File getConfigFile(String fileName) {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath() + \"/\" + fileName + \".json\").toFile();\n return configDir;\n }\n\n @Override\n public abstract String getSubPath();\n\n @Override\n public abstract ResourceLocation getName();\n\n @Override\n public String toString() {\n return this.getName().toString();\n }\n\n public Stopwatch loadTime;\n public Map<String, Stopwatch> parseTime = new HashMap<>();\n\n @Override\n public final void readConfig(boolean overrideCurrent) {\n Stopwatch stopwatch1 = Stopwatch.createStarted();\n if (shouldReadConfig()) {\n if (!overrideCurrent) {\n JamesConfigMod.LOGGER.info(\"Reading configs: \" + this.getName());\n File[] configFiles = this.getConfigDir().listFiles(File::isFile);\n if (configFiles != null && configFiles.length != 0) {\n for (File file : configFiles) {\n try (FileReader reader = new FileReader(file)) {\n Stopwatch stopwatch = Stopwatch.createStarted();\n JamesConfigMod.LOGGER.info(\"Reading config object {} for config {}\", this, file.getName());\n JsonObject jsonObject = (JsonObject) new JsonParser().parse(reader); /*we are doing this the deprecated way for 1.17.1 compat*/\n currentFile = file;\n List<ConfigObject> configObjects = parse(jsonObject);\n if (configObjects != null) {\n for (ConfigObject object : configObjects) {\n if (object != null) {\n add(object);\n }\n }\n }\n stopwatch.stop();\n parseTime.put(file.getName(), stopwatch);\n JamesConfigMod.LOGGER.info(\"Finished reading config object {}\", file.getName());\n } catch (IOException e) {\n System.out.println(e.getClass());\n e.printStackTrace();\n JamesConfigMod.LOGGER.warn(\"Error with object {} in config {}, generating new\", file.getName(), this);\n this.generateDefaultConfig();\n }\n }\n currentFile = null;\n } else {\n this.generateDefaultConfig();\n JamesConfigMod.LOGGER.warn(\"Config \" + this.getName() + \"not found, generating new\");\n }\n JamesConfigMod.LOGGER.info(\"Finished reading config\");\n } else {\n this.generateDefaultConfig();\n JamesConfigMod.LOGGER.info(\"Successfully Overwrote config {}\", this);\n }\n if (!this.isValid()) {\n JamesConfigMod.LOGGER.error(\"Config {} was found to be invalid, discarding all values\", this.getName());\n this.clear();\n }\n }\n stopwatch1.stop();\n loadTime = stopwatch1;\n }\n\n public abstract boolean isValueAcceptable(ConfigObject value);\n\n public abstract boolean shouldDiscardConfigOnUnacceptableValue();\n\n public abstract void invalidate();\n\n public abstract boolean isValid();\n\n private File currentFile = null;\n\n @Override\n public final List<ConfigObject> parse(JsonObject jsonObject) {\n if (!jsonObject.has(\"type\") || !jsonObject.get(\"type\").isJsonPrimitive() || !jsonObject.getAsJsonPrimitive(\"type\").isString()) {\n JamesConfigMod.LOGGER.error(\"Config object {} either does not contain a type field, or the type field is not a string\", currentFile.getName());\n } else {\n ConfigObject object = ConfigObject.deserializeUnknown(jsonObject, this.toString());\n if (object != null) {\n if (shouldAddObject(object)) {\n if (this.isValueAcceptable(object)) {\n return List.of(object);\n } else {\n if (shouldDiscardConfigOnUnacceptableValue()) {\n JamesConfigMod.LOGGER.error(\"Discarding config because value {} is unacceptable\", object.getName());\n this.invalidate();\n } else {\n JamesConfigMod.LOGGER.error(\"Discarding unacceptable value {} in config {}\", object.getName(), getName());\n this.discardValue(object);\n }\n }\n }\n }\n }\n return null;\n }\n\n @Override\n public List<ConfigObject> getAll() {\n return objects;\n }\n\n public abstract void discardValue(ConfigObject object);\n\n public abstract boolean shouldAddObject(ConfigObject object);\n\n protected abstract void resetToDefault();\n\n @Override\n public final void writeConfig() {\n JamesConfigMod.LOGGER.info(\"Writing config {}\", this);\n File cfgDir = this.getConfigDir();\n if (!cfgDir.exists()) {\n if (!cfgDir.mkdirs()) {\n JamesConfigMod.LOGGER.error(\"Failed to create config directory {}\", cfgDir.getPath());\n return;\n }\n JamesConfigMod.LOGGER.info(\"Finished creating config directory {}\", cfgDir.getPath());\n }\n for (ConfigObject object: getAll()) {\n JamesConfigMod.LOGGER.info(\"Attempting to write config object {} for config {}\", object.getName(), this);\n try(\n FileWriter writer = new FileWriter(getConfigFile(object.getName().replaceAll(\" \", \"_\").replaceAll(\"[^A-Za-z0-9_]\", \"\").toLowerCase()));\n JsonWriter jsonWriter = new JsonWriter(writer)) {\n jsonWriter.setIndent(\" \");\n jsonWriter.setSerializeNulls(true);\n jsonWriter.setLenient(true);\n if (!(object.serialize() instanceof JsonObject)) {\n JamesConfigMod.LOGGER.error(\"Config object {} in config {} does not have a json object at root, skipping write\", object.getName(), this);\n } else {\n Streams.write(object.serialize(), jsonWriter);\n writer.flush();\n }\n JamesConfigMod.LOGGER.info(\"Successfully wrote config object {} for config {}\", object.getName(), this);\n } catch (IOException e) {\n JamesConfigMod.LOGGER.error(\"Failed to write config object {} for config {}\", object.getName(), this);\n e.printStackTrace();\n }\n }\n JamesConfigMod.LOGGER.info(\"Finished writing config\");\n }\n\n @Override\n public final List<JsonObject> serialize() {\n JamesConfigMod.LOGGER.info(\"Writing config {} to network\", this);\n List<JsonObject> jsonObject = new ArrayList<>();\n for (ConfigObject object : getAll()) {\n JamesConfigMod.LOGGER.info(\"Writing config object {} in config {} to network\", object.getName(), this);\n if (!(object.serialize() instanceof JsonObject)) {\n JamesConfigMod.LOGGER.error(\"Config object {} in config {} does not have a json object at root, skipping write\", object.getName(), this);\n } else {\n jsonObject.add((JsonObject) object.serialize());\n JamesConfigMod.LOGGER.info(\"Finished writing config object {} in config {} to network\", object.getName(), this);\n }\n }\n JamesConfigMod.LOGGER.info(\"Finished writing config {} to network\", this);\n return jsonObject;\n }\n}"
},
{
"identifier": "SingleObjectRegistryConfigImpl",
"path": "common/src/main/java/net/vakror/jamesconfig/config/config/registry/single_object/SingleObjectRegistryConfigImpl.java",
"snippet": "public abstract class SingleObjectRegistryConfigImpl<P extends ConfigObject> extends Config {\n\n public final List<P> objects = new ArrayList<>();\n\n @Override\n public void generateDefaultConfig() {\n this.clear();\n this.resetToDefault();\n this.writeConfig();\n }\n\n @Override\n @NotNull\n public File getConfigDir() {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath()).toFile();\n return configDir;\n }\n\n @NotNull\n public File getConfigFile(String fileName) {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath() + \"/\" + fileName + \".json\").toFile();\n return configDir;\n }\n\n @Override\n public abstract String getSubPath();\n\n @Override\n public abstract ResourceLocation getName();\n\n @Override\n public String toString() {\n return this.getName().toString();\n }\n\n @Override\n public void readConfig(boolean overrideCurrent) {\n readConfig(false, true);\n }\n\n public abstract boolean isValueAcceptable(P value);\n\n public abstract boolean shouldDiscardConfigOnUnacceptableValue();\n\n public abstract void invalidate();\n\n public abstract boolean isValid();\n\n public Stopwatch loadTime;\n public Map<String, Stopwatch> parseTime = new HashMap<>();\n\n public void readConfig(boolean overrideCurrent, boolean shouldCallAgain) {\n Stopwatch stopwatch1 = Stopwatch.createStarted();\n if (shouldReadConfig()) {\n if (!overrideCurrent) {\n JamesConfigMod.LOGGER.info(\"Reading configs: \" + this.getName());\n File[] configFiles = this.getConfigDir().listFiles(File::isFile);\n if (configFiles != null && configFiles.length != 0) {\n for (File file : configFiles) {\n try (FileReader reader = new FileReader(file)) {\n Stopwatch stopwatch = Stopwatch.createStarted();\n JamesConfigMod.LOGGER.info(\"Reading config object {} for config {}\", this, file.getName());\n JsonObject jsonObject = (JsonObject) new JsonParser().parse(reader);\n List<P> configObjects = parse(jsonObject).stream().map((object -> (P) object)).toList();\n for (ConfigObject object : configObjects) {\n if (object != null) {\n add(object);\n }\n }\n stopwatch.stop();\n parseTime.put(file.getName(), stopwatch);\n JamesConfigMod.LOGGER.info(\"Finished reading config object {}\", file.getName());\n } catch (Exception e) {\n System.out.println(e.getClass());\n e.printStackTrace();\n JamesConfigMod.LOGGER.warn(\"Error with object {} in config {}, generating new\", file.getName(), this);\n this.generateDefaultConfig();\n if (shouldCallAgain) {\n this.objects.clear();\n readConfig(false, false);\n }\n }\n }\n } else {\n this.generateDefaultConfig();\n if (shouldCallAgain) {\n this.objects.clear();\n readConfig(false, false);\n }\n JamesConfigMod.LOGGER.warn(\"Config \" + this.getName() + \"not found, generating new\");\n }\n JamesConfigMod.LOGGER.info(\"Finished reading config\");\n } else {\n this.generateDefaultConfig();\n if (shouldCallAgain) {\n this.objects.clear();\n readConfig(false, false);\n }\n JamesConfigMod.LOGGER.info(\"Successfully Overwrote config {}\", this);\n }\n if (!this.isValid()) {\n JamesConfigMod.LOGGER.error(\"Config {} was found to be invalid, discarding all values\", this.getName());\n this.clear();\n }\n }\n stopwatch1.stop();\n loadTime = stopwatch1;\n }\n\n public abstract P decode(JsonObject object);\n\n @Override\n public List<ConfigObject> parse(JsonObject jsonObject) {\n P object = null;\n try {\n object = decode(jsonObject);\n } catch (Exception e) {\n JamesConfigMod.LOGGER.error(\"Error Parsing Config {}\", this.getName().toString());\n e.printStackTrace();\n }\n if (object != null) {\n if (shouldAddObject(object)) {\n if (this.isValueAcceptable(object)) {\n return List.of(object);\n } else {\n if (shouldDiscardConfigOnUnacceptableValue()) {\n JamesConfigMod.LOGGER.error(\"Discarding config because value {} is unacceptable\", object.getName());\n this.invalidate();\n } else {\n JamesConfigMod.LOGGER.error(\"Discarding unacceptable value {} in config {}\", object.getName(), getName());\n this.discardValue(object);\n }\n }\n }\n }\n return null;\n }\n\n @Override\n public List<ConfigObject> getAll() {\n return objects.stream().map((object) -> (ConfigObject) object).toList();\n }\n\n public abstract void discardValue(P object);\n\n public abstract boolean shouldAddObject(P object);\n\n protected abstract void resetToDefault();\n\n @Override\n public void writeConfig() {\n JamesConfigMod.LOGGER.info(\"Writing config {}\", this);\n File cfgDir = this.getConfigDir();\n if (!cfgDir.exists()) {\n if (!cfgDir.mkdirs()) {\n JamesConfigMod.LOGGER.error(\"Failed to create config directory {}\", cfgDir.getPath());\n return;\n }\n JamesConfigMod.LOGGER.info(\"Finished creating config directory {}\", cfgDir.getPath());\n }\n for (ConfigObject object : getAll()) {\n JamesConfigMod.LOGGER.info(\"Attempting to write config object {} for config {}\", object.getName(), this);\n try (\n FileWriter writer = new FileWriter(getConfigFile(object.getName().replaceAll(\" \", \"_\").replaceAll(\"[^A-Za-z0-9_]\", \"\").toLowerCase()));\n JsonWriter jsonWriter = new JsonWriter(writer)) {\n jsonWriter.setIndent(\" \");\n jsonWriter.setSerializeNulls(true);\n jsonWriter.setLenient(true);\n JsonElement element = object.serialize();\n if (!(element instanceof JsonObject)) {\n JamesConfigMod.LOGGER.error(\"Config object {} in config {} does not have a json object at root, skipping write\", object.getName(), this);\n } else {\n Streams.write(element, jsonWriter);\n writer.flush();\n }\n JamesConfigMod.LOGGER.info(\"Successfully wrote config object {} for config {}\", object.getName(), this);\n } catch (IOException e) {\n JamesConfigMod.LOGGER.error(\"Failed to write config object {} for config {}\", object.getName(), this);\n e.printStackTrace();\n }\n }\n JamesConfigMod.LOGGER.info(\"Finished writing config\");\n }\n\n @Override\n public List<JsonObject> serialize() {\n JamesConfigMod.LOGGER.info(\"Writing config {} to network\", this);\n List<JsonObject> jsonObject = new ArrayList<>();\n for (ConfigObject object : getAll()) {\n try {\n JamesConfigMod.LOGGER.info(\"Writing config object {} in config {} to network\", object.getName(), this);\n JsonElement element = object.serialize();\n if (!(element instanceof JsonObject)) {\n JamesConfigMod.LOGGER.error(\"Config object {} in config {} does not have a json object at root, skipping write\", object.getName(), this);\n } else {\n jsonObject.add((JsonObject) element);\n JamesConfigMod.LOGGER.info(\"Finished writing config object {} in config {} to network\", object.getName(), this);\n }\n } catch (Exception e) {\n JamesConfigMod.LOGGER.error(\"Failed to write config object {} in config {} to network\", object.getName(), this);\n e.printStackTrace();\n }\n }\n JamesConfigMod.LOGGER.info(\"Finished writing config {} to network\", this);\n return jsonObject;\n }\n}"
},
{
"identifier": "SettingConfigImpl",
"path": "common/src/main/java/net/vakror/jamesconfig/config/config/setting/SettingConfigImpl.java",
"snippet": "public abstract class SettingConfigImpl extends Config {\n\n public Map<String, ConfigObject> requiredSettingsMap = new HashMap<>();\n\n @Override\n public void generateDefaultConfig() {\n this.clear();\n setRequiredSettingsMap();\n this.requiredSettingsMap.forEach(this::setValue);\n this.writeConfig();\n }\n\n @Override\n @NotNull\n public File getConfigDir() {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath()).toFile();\n return configDir;\n }\n\n\n public final void setRequiredSettingsMap() {\n if (requiredSettingsMap.isEmpty()) {\n for (ConfigObject defaultValue : getRequiredSettings()) {\n requiredSettingsMap.put(defaultValue.getName(), defaultValue);\n }\n }\n }\n\n @NotNull\n public File getConfigFile() {\n File configDir;\n configDir = Platform.getConfigFolder().resolve(getSubPath() + \"/\" + getFileName() + \".json\").toFile();\n return configDir;\n }\n\n @Override\n public abstract String getSubPath();\n\n @Override\n public abstract ResourceLocation getName();\n\n @Override\n public String toString() {\n return this.getName().toString();\n }\n\n /**\n * contents of config object will be used as defaults\n */\n public abstract List<ConfigObject> getRequiredSettings();\n\n public abstract String getFileName();\n\n public Stopwatch loadTime;\n public Map<String, Stopwatch> parseTime = new HashMap<>();\n\n @Override\n public void readConfig(boolean overrideCurrent) {\n if (shouldReadConfig()) {\n if (!overrideCurrent) {\n JamesConfigMod.LOGGER.info(\"Reading config {}\", this);\n try {\n File file = getConfigFile();\n if (file.exists()) {\n try (FileReader reader = new FileReader(file)) {\n JsonObject jsonObject = (JsonObject) new JsonParser().parse(reader);\n Stopwatch stopwatch = Stopwatch.createStarted();\n List<ConfigObject> configObjects = parse(jsonObject);\n stopwatch.stop();\n loadTime = stopwatch;\n JamesConfigMod.LOGGER.info(\"Setting values in config {} to parsed value\", this);\n for (ConfigObject object : configObjects) {\n JamesConfigMod.LOGGER.info(\"Setting value {} to parsed value in setting config {}\", object.getName(), this);\n setValue(object.getName(), object);\n JamesConfigMod.LOGGER.info(\"Finished setting value {} to parsed value\", object.getName());\n }\n JamesConfigMod.LOGGER.info(\"Finished setting values in config {} to parsed value\", this);\n } catch (IOException e) {\n System.out.println(e.getClass());\n e.printStackTrace();\n JamesConfigMod.LOGGER.warn(\"Error with config {}, generating new\", this);\n this.generateDefaultConfig();\n }\n } else {\n this.generateDefaultConfig();\n JamesConfigMod.LOGGER.warn(\"Config \" + this.getName() + \"not found, generating new\");\n }\n } catch (JsonIOException | JsonSyntaxException e) {\n throw new IllegalStateException(e);\n }\n JamesConfigMod.LOGGER.info(\"Finished reading config\");\n } else {\n this.generateDefaultConfig();\n JamesConfigMod.LOGGER.info(\"Successfully Overwrote config {}\", this);\n }\n }\n }\n\n @Override\n public List<ConfigObject> parse(JsonObject jsonObject) {\n setRequiredSettingsMap();\n JamesConfigMod.LOGGER.info(\"Parsing config {}\", this);\n List<ConfigObject> list = new ArrayList<>();\n for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {\n String key = entry.getKey();\n Stopwatch stopwatch = Stopwatch.createStarted();\n if (!requiredSettingsMap.containsKey(key)) {\n JamesConfigMod.LOGGER.error(\"Key {} present in config {}, even though it was not requested\", key, getFileName());\n } else {\n ConfigObject object = requiredSettingsMap.get(key);\n try {\n ConfigObject object1 = object.deserialize(key, entry.getValue(), requiredSettingsMap.get(key), getName().toString());\n object1.setName(key);\n list.add(object1);\n } catch (Exception e) {\n JamesConfigMod.LOGGER.error(\"Error reading config object {}, skipping. Make sure it is the right type.\", key);\n e.printStackTrace();\n }\n }\n stopwatch.stop();\n parseTime.put(key, stopwatch);\n }\n JamesConfigMod.LOGGER.info(\"Finished parsing config\");\n return list;\n }\n\n public abstract void setValue(String name, ConfigObject value);\n\n @Override\n public void writeConfig() {\n JamesConfigMod.LOGGER.info(\"Writing config {}\", this);\n File cfgDir = this.getConfigDir();\n if (!cfgDir.exists() && !cfgDir.mkdirs()) {\n return;\n }\n try (\n FileWriter writer = new FileWriter(getConfigFile());\n JsonWriter jsonWriter = new JsonWriter(writer)) {\n\n\n JsonObject object = new JsonObject();\n for (ConfigObject configObject : getAll()) {\n object.add(configObject.getName(), configObject.serialize());\n }\n\n jsonWriter.setIndent(\" \");\n jsonWriter.setSerializeNulls(true);\n jsonWriter.setLenient(true);\n Streams.write(object, jsonWriter);\n writer.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n JamesConfigMod.LOGGER.info(\"Finished writing config\");\n }\n\n public List<JsonObject> serialize() {\n JsonObject object = new JsonObject();\n for (ConfigObject configObject : getAll()) {\n object.add(configObject.getName(), configObject.serialize());\n }\n return List.of(object);\n }\n}"
}
] | import com.google.common.base.Stopwatch;
import net.vakror.jamesconfig.config.config.Config;
import net.vakror.jamesconfig.config.config.registry.multi_object.MultiObjectRegistryConfigImpl;
import net.vakror.jamesconfig.config.config.registry.single_object.SingleObjectRegistryConfigImpl;
import net.vakror.jamesconfig.config.config.setting.SettingConfigImpl;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit; | 5,564 | package net.vakror.jamesconfig.config.config.performance;
public class DefaultConfigPerformanceAnalyzer implements IConfigPerformanceAnalyzer {
DecimalFormat format = new DecimalFormat("0.##");
public static final DefaultConfigPerformanceAnalyzer INSTANCE = new DefaultConfigPerformanceAnalyzer();
@Override
public String getPerformanceAnalysis(Config config) {
if (config instanceof MultiObjectRegistryConfigImpl multiObjectRegistryConfig) {
return getMultiObjectRegistryConfigAnalysis(multiObjectRegistryConfig); | package net.vakror.jamesconfig.config.config.performance;
public class DefaultConfigPerformanceAnalyzer implements IConfigPerformanceAnalyzer {
DecimalFormat format = new DecimalFormat("0.##");
public static final DefaultConfigPerformanceAnalyzer INSTANCE = new DefaultConfigPerformanceAnalyzer();
@Override
public String getPerformanceAnalysis(Config config) {
if (config instanceof MultiObjectRegistryConfigImpl multiObjectRegistryConfig) {
return getMultiObjectRegistryConfigAnalysis(multiObjectRegistryConfig); | } else if (config instanceof SingleObjectRegistryConfigImpl<?> singleObjectRegistryConfig) { | 2 | 2023-10-07 23:04:49+00:00 | 8k |
uku3lig/ukuwayplus | src/main/java/net/uku3lig/ukuway/UkuwayPlus.java | [
{
"identifier": "UkuwayConfig",
"path": "src/main/java/net/uku3lig/ukuway/config/UkuwayConfig.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UkuwayConfig implements IConfig<UkuwayConfig> {\n private boolean hideCosmetics = false;\n private boolean discordRPC = true;\n private boolean inventoryRarities = true;\n private boolean autoSell = false;\n private boolean ambientSounds = true;\n private boolean activitySongs = true;\n\n @Override\n public UkuwayConfig defaultConfig() {\n return new UkuwayConfig();\n }\n\n public static UkuwayConfig get() {\n return UkuwayPlus.getManager().getConfig();\n }\n}"
},
{
"identifier": "Jukebox",
"path": "src/main/java/net/uku3lig/ukuway/jukebox/Jukebox.java",
"snippet": "public class Jukebox implements ClientPlayerTickable {\n private long ticksElapsed = -1;\n private int partPointer = -1;\n @Getter\n private JukeboxTrack currentTrack = null;\n private JukeboxTrack.Part currentPart = null;\n\n public void play(JukeboxTrack track) {\n this.stop();\n this.currentTrack = track;\n this.currentPart = track.getParts().get(0);\n\n this.playCurrentPart();\n }\n\n private void loop() {\n this.ticksElapsed = 0;\n this.partPointer++;\n\n this.currentPart = currentTrack.getParts().get(partPointer % currentTrack.getParts().size());\n\n this.playCurrentPart();\n }\n\n public void stop() {\n MinecraftClient.getInstance().getSoundManager().stopAll();\n this.currentTrack = null;\n this.currentPart = null;\n this.ticksElapsed = 0;\n this.partPointer = 0;\n }\n\n private void playCurrentPart() {\n try {\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.playSound(SoundEvent.of(this.currentPart.id()), SoundCategory.RECORDS, 1, 1);\n }\n } catch (Exception e) {\n UkuwayPlus.getLogger().error(\"An issue occurred when looping music with the Jukebox.\", e);\n }\n }\n\n @Override\n public void tick() {\n if (UkuwayPlus.isConnected() && this.currentTrack != null && this.currentPart != null) {\n if (this.ticksElapsed >= this.currentPart.length()) loop();\n else this.ticksElapsed++;\n }\n }\n}"
},
{
"identifier": "FriendListManager",
"path": "src/main/java/net/uku3lig/ukuway/ui/FriendListManager.java",
"snippet": "public class FriendListManager {\n @Getter\n private static final Set<String> friends = new HashSet<>();\n\n private static GenericContainerScreenHandler oldHandler = null;\n private static long ticksElapsed = 0;\n\n @Getter\n private static boolean init = false;\n\n public static void tick() {\n if (MinecraftClient.getInstance().currentScreen instanceof GenericContainerScreen containerScreen) {\n checkFriends(containerScreen);\n } else if (ticksElapsed >= 50 && !init && MinecraftClient.getInstance().player != null) {\n init = true;\n MinecraftClient.getInstance().player.networkHandler.sendChatCommand(\"friend\");\n }\n\n ticksElapsed++;\n }\n\n private static void checkFriends(GenericContainerScreen containerScreen) {\n long count = containerScreen.getScreenHandler().getStacks().stream().map(ItemStack::getItem).filter(Items.PLAYER_HEAD::equals).count();\n if (count == friends.size() || count <= 1) {\n return; // friend list didn't change, no need to check\n }\n\n init = true;\n\n GenericContainerScreenHandler handler = containerScreen.getScreenHandler();\n if (oldHandler != null && oldHandler == handler) return;\n oldHandler = handler;\n\n Optional<Slot> nextPageSlot = handler.slots.stream().filter(slot -> slot.getStack().isOf(Items.PAPER)\n && slot.getStack().getNbt() != null && slot.getStack().getNbt().asString().contains(\"→\"))\n .findFirst();\n\n CompletableFuture.runAsync(() -> {\n for (ItemStack itemStack : handler.getStacks()) {\n NbtCompound nbt = itemStack.getNbt();\n if (nbt == null || !itemStack.isOf(Items.PLAYER_HEAD) || nbt.toString().contains(\"Left click to Accept\")) {\n continue;\n }\n\n NbtCompound skullOwner = nbt.getCompound(\"SkullOwner\");\n String name = skullOwner.getString(\"Name\").toLowerCase(Locale.ROOT);\n if (!name.isBlank()) friends.add(name);\n }\n });\n\n nextPageSlot.ifPresentOrElse(slot -> containerScreen.onMouseClick(slot, 0, 0, SlotActionType.PICKUP),\n () -> MinecraftClient.getInstance().setScreen(null));\n }\n\n private FriendListManager() {\n }\n}"
},
{
"identifier": "Shop",
"path": "src/main/java/net/uku3lig/ukuway/ui/Shop.java",
"snippet": "public class Shop {\n @Setter @NotNull\n private ShopType oldShopType = ShopType.UNKNOWN;\n\n public void tick() {\n if (MinecraftClient.getInstance().currentScreen == null || !(MinecraftClient.getInstance().currentScreen instanceof GenericContainerScreen containerScreen)) {\n oldShopType = ShopType.UNKNOWN;\n return;\n }\n\n if (getShopType(containerScreen) == ShopType.UNKNOWN) {\n oldShopType = ShopType.UNKNOWN;\n return;\n }\n\n ShopType shopType = getShopType(containerScreen);\n boolean fill = GLFW.glfwGetKey(GLFW.glfwGetCurrentContext(), KeyBindingHelper.getBoundKeyOf(KeyboardManager.autoSell).getCode()) == GLFW.GLFW_PRESS;\n\n if ((shopType == ShopType.FRUIT || shopType == ShopType.FISH) && ((UkuwayConfig.get().isAutoSell() && shopType != oldShopType) || fill)) {\n List<Slot> emptyChestSlots = new ArrayList<>();\n List<Slot> playerItemSlots = new ArrayList<>();\n GenericContainerScreenHandler handler = containerScreen.getScreenHandler();\n\n for (Slot slot : handler.slots) {\n if (slot.inventory instanceof PlayerInventory) {\n HideawayItem item = HideawayItem.fromStack(slot.getStack());\n if (item != null && item.type() == ItemType.ITEM && !item.notSave() && !slot.getStack().isOf(Items.FISHING_ROD)) {\n playerItemSlots.add(slot);\n }\n } else if (slot.getStack().isEmpty()) {\n emptyChestSlots.add(slot);\n }\n }\n\n for (Slot playerSlot : playerItemSlots) {\n if (emptyChestSlots.isEmpty()) break;\n\n Slot emptySlot = emptyChestSlots.get(0);\n containerScreen.onMouseClick(playerSlot, emptySlot.id, 0, SlotActionType.QUICK_MOVE);\n\n if (!emptySlot.getStack().isEmpty()) {\n emptyChestSlots.remove(0);\n }\n }\n }\n\n oldShopType = shopType;\n }\n\n @NotNull\n private ShopType getShopType(GenericContainerScreen containerScreen) {\n GenericContainerScreenHandler handler = containerScreen.getScreenHandler();\n String screenName = containerScreen.getTitle().getString();\n if (screenName.contains(\"\\uE00C\") || screenName.contains(\"\\uE010\")) {\n FriendListManager.tick(); // qhar????????\n return ShopType.UNKNOWN;\n }\n\n\n for (ItemStack itemStack : handler.getStacks()) {\n if (itemStack.getNbt() == null) continue;\n String nbtData = itemStack.getNbt().asString();\n\n if (nbtData.contains(\"buy\")) {\n if (nbtData.contains(\"The Marmoset Monkey Brothers\")) return ShopType.FRUIT;\n if (nbtData.contains(\"Bill Beaks\")) return ShopType.FISH;\n } else if (nbtData.contains(\"same rarity\")) {\n return ShopType.TRADER;\n }\n }\n\n return ShopType.UNKNOWN;\n }\n\n public enum ShopType {\n FRUIT,\n FISH,\n TRADER,\n UNKNOWN\n }\n}"
},
{
"identifier": "Wardrobe",
"path": "src/main/java/net/uku3lig/ukuway/ui/Wardrobe.java",
"snippet": "public class Wardrobe {\n public static final Vec3d LOCATION = new Vec3d(66.5f, 5f, -130.5f);\n\n @Getter\n private static final Set<UUID> wardrobePlayers = new HashSet<>();\n\n\n public static void tick() {\n ClientPlayerEntity clientPlayer = MinecraftClient.getInstance().player;\n if (clientPlayer == null) return;\n\n if (!clientPlayer.isSpectator() && !clientPlayer.getPos().isInRange(LOCATION, 5)) {\n wardrobePlayers.clear();\n return;\n }\n\n int boxWidth = 3 * 2;\n Box boundingBox = Box.of(clientPlayer.getPos(), boxWidth, boxWidth, boxWidth);\n List<PlayerEntity> playerList = clientPlayer.clientWorld.getPlayers(TargetPredicate.createNonAttackable(), clientPlayer, boundingBox);\n\n wardrobePlayers.clear();\n for (PlayerEntity player : playerList) {\n if (player == clientPlayer) continue;\n wardrobePlayers.add(player.getUuid());\n }\n }\n\n private Wardrobe() {\n }\n}"
},
{
"identifier": "DiscordManager",
"path": "src/main/java/net/uku3lig/ukuway/util/DiscordManager.java",
"snippet": "@Slf4j\npublic class DiscordManager {\n @Getter\n private static boolean active = false;\n private static IPCClient client;\n private static Instant start;\n\n public static void start() {\n if (!active && UkuwayConfig.get().isDiscordRPC()) {\n log.info(\"Starting Discord RPC client...\");\n client = new IPCClient(1158161117915398214L);\n client.setListener(new ModIPCListener());\n\n try {\n client.connect();\n active = true;\n start = Instant.now();\n update();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } catch (Exception e) {\n log.warn(\"An error happened while trying to connect to Discord\", e);\n }\n }\n }\n\n public static void update() {\n if (active && UkuwayConfig.get().isDiscordRPC()) {\n RichPresence.Builder builder = new RichPresence.Builder();\n\n builder.setState(\"in the teawieverse\")\n .setDetails(UkuwayPlus.isConnected() ? \"playing hideaway\" : \"clicking buttons\")\n .setStartTimestamp(start.getEpochSecond())\n .setLargeImage(UkuwayPlus.isConnected() ? \"hideaway\" : \"ukuway\",\n UkuwayPlus.findVersion().map(v -> \"ukuway+ \" + v).orElse(\"this person broke minecraft\"))\n .setSmallImage(\"https://mc-heads.net/avatar/\" + MinecraftClient.getInstance().getSession().getUuid(), \"made with spite & anger\");\n\n client.sendRichPresence(builder.build());\n } else {\n start();\n }\n }\n\n public static void stop() {\n if (active) {\n client.close();\n active = false;\n }\n }\n\n public static void setStatus(boolean enabled) {\n if (enabled) start();\n else stop();\n }\n\n private static class ModIPCListener implements IPCListener {\n\n @Override\n public void onPacketSent(IPCClient client, Packet packet) {\n // unneeded\n }\n\n @Override\n public void onPacketReceived(IPCClient client, Packet packet) {\n // unneeded\n }\n\n @Override\n public void onActivityJoin(IPCClient client, String secret) {\n // unneeded\n }\n\n @Override\n public void onActivitySpectate(IPCClient client, String secret) {\n // unneeded\n }\n\n @Override\n public void onActivityJoinRequest(IPCClient client, String secret, User user) {\n // unneeded\n }\n\n @Override\n public void onReady(IPCClient client) {\n UkuwayPlus.getLogger().info(\"Discord RPC client connected!\");\n }\n\n @Override\n public void onClose(IPCClient client, JsonObject json) {\n UkuwayPlus.getLogger().info(\"Discord RPC client closed!\");\n }\n\n @Override\n public void onDisconnect(IPCClient client, Throwable t) {\n // unneeded\n }\n }\n\n private DiscordManager() {\n }\n}"
},
{
"identifier": "KeyboardManager",
"path": "src/main/java/net/uku3lig/ukuway/util/KeyboardManager.java",
"snippet": "public class KeyboardManager {\n public static final KeyBinding autoSell = new KeyBinding(\"key.hp.autoSell\", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_S, \"categories.hp\");\n\n private static final List<KeyBindingWrapper> binds = List.of(\n create(\"key.hp.jukebox\", GLFW.GLFW_KEY_J, () -> MinecraftClient.getInstance().setScreen(new JukeboxScreen(null))),\n new KeyBindingWrapper(autoSell, () -> {\n if (!UkuwayConfig.get().isAutoSell() && MinecraftClient.getInstance().currentScreen != null) {\n UkuwayPlus.getShop().tick();\n }\n }),\n create(\"key.hp.luggage\", GLFW.GLFW_KEY_B, () -> clickSlot(1, MinecraftClient.getInstance())),\n create(\"key.hp.wardrobe\", GLFW.GLFW_KEY_G, () -> clickSlot(2, MinecraftClient.getInstance())),\n create(\"key.hp.profile\", GLFW.GLFW_KEY_Z, () -> clickSlot(3, MinecraftClient.getInstance())),\n create(\"key.hp.friends\", GLFW.GLFW_KEY_U, () -> clickSlot(4, MinecraftClient.getInstance())),\n create(\"key.hp.journal\", GLFW.GLFW_KEY_Y, () -> clickSlot(43, MinecraftClient.getInstance())),\n create(\"key.hp.palm_plate\", GLFW.GLFW_KEY_V, () -> clickSlot(44, MinecraftClient.getInstance())),\n create(\"key.hp.mail\", GLFW.GLFW_KEY_C, () -> {\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.networkHandler.sendChatCommand(\"mail\");\n }\n })\n );\n\n public static void register() {\n for (KeyBindingWrapper bind : binds) {\n KeyBindingHelper.registerKeyBinding(bind.keyBinding);\n }\n\n ClientTickEvents.END_CLIENT_TICK.register(client -> {\n for (KeyBindingWrapper bind : binds) {\n while (bind.keyBinding.wasPressed()) {\n bind.action.run();\n }\n }\n });\n }\n \n private static void clickSlot(Integer slotNumber, MinecraftClient client) {\n if (client.interactionManager != null && client.player != null) {\n ScreenHandler screenHandler = client.player.currentScreenHandler;\n client.interactionManager.clickSlot(screenHandler.syncId, slotNumber, 0, SlotActionType.PICKUP, client.player);\n }\n }\n\n public record KeyBindingWrapper(KeyBinding keyBinding, Runnable action) {\n }\n\n private static KeyBindingWrapper create(String translationKey, int code, Runnable action) {\n return new KeyBindingWrapper(new KeyBinding(translationKey, InputUtil.Type.KEYSYM, code, \"categories.hp\"), action);\n }\n\n private KeyboardManager() {\n }\n}"
}
] | import lombok.Getter;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ingame.GenericContainerScreen;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.uku3lig.ukulib.config.ConfigManager;
import net.uku3lig.ukuway.config.UkuwayConfig;
import net.uku3lig.ukuway.jukebox.Jukebox;
import net.uku3lig.ukuway.ui.FriendListManager;
import net.uku3lig.ukuway.ui.Shop;
import net.uku3lig.ukuway.ui.Wardrobe;
import net.uku3lig.ukuway.util.DiscordManager;
import net.uku3lig.ukuway.util.KeyboardManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import java.util.function.Consumer; | 4,004 | package net.uku3lig.ukuway;
@Environment(EnvType.CLIENT)
public class UkuwayPlus implements ClientModInitializer {
@Getter
private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.class, "ukuway-plus");
@Getter
private static final Logger logger = LoggerFactory.getLogger(UkuwayPlus.class);
@Getter
public static final Jukebox jukebox = new Jukebox();
@Getter | package net.uku3lig.ukuway;
@Environment(EnvType.CLIENT)
public class UkuwayPlus implements ClientModInitializer {
@Getter
private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.class, "ukuway-plus");
@Getter
private static final Logger logger = LoggerFactory.getLogger(UkuwayPlus.class);
@Getter
public static final Jukebox jukebox = new Jukebox();
@Getter | public static final Shop shop = new Shop(); | 3 | 2023-10-07 00:02:04+00:00 | 8k |
YumiProject/yumi-gradle-licenser | src/main/java/dev/yumi/gradle/licenser/impl/LicenseHeader.java | [
{
"identifier": "YumiLicenserGradlePlugin",
"path": "src/main/java/dev/yumi/gradle/licenser/YumiLicenserGradlePlugin.java",
"snippet": "public class YumiLicenserGradlePlugin implements Plugin<Project> {\n\tpublic static final String LICENSE_TASK_SUFFIX = \"License\";\n\tpublic static final String CHECK_TASK_PREFIX = \"check\";\n\tpublic static final String APPLY_TASK_PREFIX = \"apply\";\n\n\tprivate static final String DEBUG_MODE_PROPERTY = \"yumi.gradle.licenser.debug\";\n\t/**\n\t * Represents whether the debug mode is enabled or not using the {@value #DEBUG_MODE_PROPERTY} system property.\n\t */\n\tpublic static final boolean DEBUG_MODE = Boolean.getBoolean(DEBUG_MODE_PROPERTY);\n\n\t@Override\n\tpublic void apply(Project project) {\n\t\tvar ext = project.getExtensions().create(\"license\", YumiLicenserGradleExtension.class, project);\n\n\t\t// Register tasks.\n\t\tproject.getPlugins().withType(JavaBasePlugin.class).configureEach(plugin -> {\n\t\t\tvar sourceSets = project.getExtensions().getByType(SourceSetContainer.class);\n\n\t\t\tsourceSets.matching(sourceSet -> !ext.isSourceSetExcluded(sourceSet))\n\t\t\t\t\t.all(sourceSet -> {\n\t\t\t\t\t\tproject.getTasks().register(getTaskName(\"check\", sourceSet), CheckLicenseTask.class, sourceSet, ext)\n\t\t\t\t\t\t\t\t.configure(task -> task.onlyIf(t -> !ext.isSourceSetExcluded(sourceSet)));\n\t\t\t\t\t\tproject.getTasks().register(getTaskName(\"apply\", sourceSet), ApplyLicenseTask.class, sourceSet, ext)\n\t\t\t\t\t\t\t\t.configure(task -> task.onlyIf(t -> !ext.isSourceSetExcluded(sourceSet)));\n\t\t\t\t\t});\n\t\t});\n\n\t\tvar globalCheck = this.registerGroupedTask(project, CHECK_TASK_PREFIX, task -> {\n\t\t\ttask.dependsOn(project.getTasks().withType(CheckLicenseTask.class));\n\n\t\t\ttask.setDescription(\"Checks whether source files in every source sets contain a valid license header.\");\n\t\t\ttask.setGroup(\"verification\");\n\t\t});\n\t\tthis.registerGroupedTask(project, APPLY_TASK_PREFIX, task -> {\n\t\t\ttask.dependsOn(project.getTasks().withType(ApplyLicenseTask.class));\n\n\t\t\ttask.setDescription(\"Applies the correct license headers to source files in every source sets.\");\n\t\t\ttask.setGroup(\"generation\");\n\t\t});\n\n\t\tproject.getPlugins().withType(LifecycleBasePlugin.class).configureEach(plugin -> {\n\t\t\tproject.getTasks().named(LifecycleBasePlugin.CHECK_TASK_NAME).configure(task -> {\n\t\t\t\ttask.dependsOn(globalCheck);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * {@return the task name of a given action for a given source set}\n\t *\n\t * @param action the task action\n\t * @param sourceSet the source set the task is applied to\n\t */\n\tpublic static String getTaskName(String action, SourceSet sourceSet) {\n\t\tif (sourceSet.getName().equals(\"main\")) {\n\t\t\treturn action + LICENSE_TASK_SUFFIX + \"Main\";\n\t\t} else {\n\t\t\treturn sourceSet.getTaskName(action + LICENSE_TASK_SUFFIX, null);\n\t\t}\n\t}\n\n\tprivate TaskProvider<Task> registerGroupedTask(Project project, String action, Action<Task> consumer) {\n\t\tvar task = project.getTasks().register(action + LICENSE_TASK_SUFFIX + 's');\n\t\ttask.configure(consumer);\n\t\treturn task;\n\t}\n}"
},
{
"identifier": "HeaderRule",
"path": "src/main/java/dev/yumi/gradle/licenser/api/rule/HeaderRule.java",
"snippet": "public class HeaderRule {\n\tprivate final String name;\n\tprivate final List<HeaderLine> lines;\n\tprivate final Map<String, VariableType<?>> variables;\n\tprivate final LicenseYearSelectionMode yearSelectionMode;\n\n\tpublic HeaderRule(\n\t\t\t@NotNull String name,\n\t\t\t@NotNull List<HeaderLine> lines,\n\t\t\t@NotNull Map<String, VariableType<?>> variables,\n\t\t\t@NotNull LicenseYearSelectionMode yearSelectionMode\n\t) {\n\t\tthis.name = name;\n\t\tthis.lines = lines;\n\t\tthis.variables = variables;\n\t\tthis.yearSelectionMode = yearSelectionMode;\n\t}\n\n\t/**\n\t * {@return the name of this header rule}\n\t */\n\t@Contract(pure = true)\n\tpublic @NotNull String getName() {\n\t\treturn this.name;\n\t}\n\n\t/**\n\t * {@return a view of the lines of this header}\n\t */\n\t@Contract(pure = true)\n\tpublic @UnmodifiableView @NotNull List<HeaderLine> getLines() {\n\t\treturn Collections.unmodifiableList(this.lines);\n\t}\n\n\t/**\n\t * {@return the year selection mode}\n\t */\n\t@Contract(pure = true)\n\tpublic @NotNull LicenseYearSelectionMode getYearSelectionMode() {\n\t\treturn this.yearSelectionMode;\n\t}\n\n\t/**\n\t * Parses the given header according to the current rules, may throw an exception if the header is not valid.\n\t *\n\t * @param header the header to check\n\t * @return parsed data, contain the successfully parsed variables, and the error if parsing failed\n\t */\n\tpublic @NotNull ParsedData parseHeader(@NotNull List<String> header) {\n\t\tvar variableValues = new HashMap<String, Object>();\n\t\tvar presentOptionalLines = new HashSet<Integer>();\n\t\tint headerLineIndex = 0, ruleLineIndex = 0;\n\n\t\tfor (; headerLineIndex < header.size(); headerLineIndex++) {\n\t\t\tString headerLine = header.get(headerLineIndex);\n\n\t\t\tif (ruleLineIndex >= this.lines.size()) {\n\t\t\t\treturn new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, \"There is unexpected extra header lines.\"));\n\t\t\t}\n\n\t\t\tHeaderLine ruleLine = this.lines.get(ruleLineIndex);\n\t\t\tString error;\n\t\t\twhile ((error = this.parseLine(headerLine, ruleLine, variableValues)) != null) {\n\t\t\t\tif (ruleLine.optional()) { // If the line is optional, attempts to check the next line.\n\t\t\t\t\truleLine = this.lines.get(++ruleLineIndex);\n\t\t\t\t} else {\n\t\t\t\t\treturn new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, error));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (ruleLine.optional()) {\n\t\t\t\tpresentOptionalLines.add(ruleLineIndex);\n\t\t\t}\n\n\t\t\truleLineIndex++;\n\t\t}\n\n\t\treturn new ParsedData(variableValues, presentOptionalLines, null);\n\t}\n\n\tprivate @Nullable String parseLine(\n\t\t\t@NotNull String headerLine,\n\t\t\t@NotNull HeaderLine currentLine,\n\t\t\t@NotNull Map<String, Object> variablesMap\n\t) {\n\t\tint currentIndex = 0;\n\n\t\tfor (var token : currentLine.tokens()) {\n\t\t\tif (token instanceof TextToken textToken) {\n\t\t\t\tString text = textToken.content();\n\t\t\t\tint theoreticalEnd = currentIndex + text.length();\n\n\t\t\t\tif (theoreticalEnd > headerLine.length()) {\n\t\t\t\t\treturn \"Header is cut short, stopped at \"\n\t\t\t\t\t\t\t+ headerLine.length()\n\t\t\t\t\t\t\t+ \" instead of \"\n\t\t\t\t\t\t\t+ theoreticalEnd\n\t\t\t\t\t\t\t+ \".\";\n\t\t\t\t}\n\n\t\t\t\tString toCheck = headerLine.substring(currentIndex, theoreticalEnd);\n\n\t\t\t\tif (!text.equals(toCheck)) {\n\t\t\t\t\treturn \"Text differs at \" + currentIndex + \", got \\\"\" + toCheck + \"\\\", expected \\\"\" + text + \"\\\".\";\n\t\t\t\t}\n\n\t\t\t\tcurrentIndex = currentIndex + text.length();\n\t\t\t} else if (token instanceof VarToken varToken) {\n\t\t\t\tvar type = this.variables.get(varToken.variable());\n\t\t\t\tvar result = type.parseVar(headerLine, currentIndex);\n\n\t\t\t\tif (result.isEmpty()) {\n\t\t\t\t\treturn \"Failed to parse variable \\\"\" + varToken.variable() + \"\\\" at \" + currentIndex + \".\";\n\t\t\t\t}\n\n\t\t\t\tvar old = variablesMap.put(varToken.variable(), result.get().data());\n\t\t\t\tif (old != null && !old.equals(result.get().data())) {\n\t\t\t\t\treturn \"Diverging variable values for \\\"\" + varToken.variable() + \"\\\".\";\n\t\t\t\t}\n\n\t\t\t\tcurrentIndex = result.get().end();\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Applies this header rule to the provided parsed data to create a valid up-to-date header comment.\n\t *\n\t * @param data the data parsed by attempting to read the header comment\n\t * @param context the context of the file to update\n\t * @return the updated header comment\n\t */\n\t@SuppressWarnings({\"rawtypes\", \"unchecked\"})\n\tpublic @NotNull List<String> apply(@NotNull ParsedData data, @NotNull HeaderFileContext context) {\n\t\tvar result = new ArrayList<String>();\n\n\t\tfor (int i = 0; i < this.lines.size(); i++) {\n\t\t\tvar line = this.lines.get(i);\n\n\t\t\tif (!line.optional() || data.presentOptionalLines.contains(i)) {\n\t\t\t\tvar builder = new StringBuilder();\n\n\t\t\t\tfor (var token : line.tokens()) {\n\t\t\t\t\tif (token instanceof TextToken textToken) {\n\t\t\t\t\t\tbuilder.append(textToken.content());\n\t\t\t\t\t} else if (token instanceof VarToken varToken) {\n\t\t\t\t\t\tvar type = (VariableType) this.variables.get(varToken.variable());\n\t\t\t\t\t\tvar previous = data.variables.get(varToken.variable());\n\n\t\t\t\t\t\tvar newValue = type.getUpToDate(context, previous);\n\n\t\t\t\t\t\tbuilder.append(type.getAsString(newValue));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresult.add(builder.toString());\n\t\t\t}\n\t\t}\n\n\t\tUtils.trimLines(result, String::isEmpty);\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) return true;\n\t\tif (o == null || this.getClass() != o.getClass()) return false;\n\t\tHeaderRule that = (HeaderRule) o;\n\t\treturn Objects.equals(this.lines, that.lines);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(this.lines);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"HeaderRule{\" +\n\t\t\t\t\"lines=\" + this.lines +\n\t\t\t\t'}';\n\t}\n\n\t/**\n\t * Parses the header rule from the given header rule text.\n\t *\n\t * @param name the name of the header rule to parse\n\t * @param raw the raw header rule text\n\t * @return the parsed header rule\n\t * @throws HeaderParseException if parsing the header rule fails\n\t */\n\tpublic static @NotNull HeaderRule parse(@NotNull String name, @NotNull List<String> raw) throws HeaderParseException {\n\t\tList<HeaderLine> parsed = new ArrayList<>();\n\t\tvar variables = new HashMap<String, VariableType<?>>();\n\t\tvar yearSelectionMode = LicenseYearSelectionMode.PROJECT;\n\n\t\tboolean optionalMode = false;\n\t\tfor (int i = 0; i < raw.size(); i++) {\n\t\t\tString line = raw.get(i);\n\n\t\t\tif (line.startsWith(\"#\")) {\n\t\t\t\t// Instruction for special behavior.\n\t\t\t\tString[] instruction = line.substring(1).trim().split(\"\\\\s+\");\n\n\t\t\t\tif (instruction.length == 0) {\n\t\t\t\t\tthrow new HeaderParseException(i, \"No valid instructions could be found.\");\n\t\t\t\t}\n\n\t\t\t\tswitch (instruction[0]) {\n\t\t\t\t\tcase \"optional\":\n\t\t\t\t\t\toptionalMode = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"end\":\n\t\t\t\t\t\toptionalMode = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"type\":\n\t\t\t\t\t\tif (instruction.length != 3) {\n\t\t\t\t\t\t\tthrow new HeaderParseException(i, \"Invalid type instruction. Expected variable name and type.\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString variableName = instruction[1];\n\t\t\t\t\t\tString variableTypeRaw = instruction[2];\n\n\t\t\t\t\t\tvar variableType = VariableType.TYPES.get(variableTypeRaw);\n\n\t\t\t\t\t\tif (variableType == null) {\n\t\t\t\t\t\t\tthrow new HeaderParseException(\n\t\t\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\t\t\t\"Invalid variable type \\\"\" + variableTypeRaw + \"\\\" for variable \\\"\" + variableName + \"\\\".\"\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvariables.put(variableName, variableType);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"year_selection\":\n\t\t\t\t\t\tif (instruction.length != 2) {\n\t\t\t\t\t\t\tthrow new HeaderParseException(i, \"Invalid year selection instruction. Expected selection mode (project or file).\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tString modeName = instruction[1];\n\t\t\t\t\t\tvar mode = LicenseYearSelectionMode.byName(modeName.toUpperCase());\n\n\t\t\t\t\t\tif (mode == null) {\n\t\t\t\t\t\t\tthrow new HeaderParseException(\n\t\t\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t\t\t\t\"Invalid year selection mode \\\"\" + modeName + \"\\\".\"\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tyearSelectionMode = mode;\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new HeaderParseException(i, \"Unknown instruction: \\\"\" + instruction[0] + \"\\\".\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tparsed.add(parseLine(line, optionalMode));\n\t\t\t}\n\t\t}\n\n\t\t// Trim lines.\n\t\tUtils.trimLines(parsed, HeaderLine::isEmpty);\n\n\t\tvariables.putAll(VariableType.DEFAULT_VARIABLES);\n\t\tSet<String> undeclaredVariables = new HashSet<>();\n\n\t\tfor (var line : parsed) {\n\t\t\tfor (var token : line.tokens()) {\n\t\t\t\tif (token instanceof VarToken varToken) {\n\t\t\t\t\tif (!variables.containsKey(varToken.variable())) {\n\t\t\t\t\t\tundeclaredVariables.add(varToken.variable());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!undeclaredVariables.isEmpty()) {\n\t\t\tthrow new HeaderParseException(\n\t\t\t\t\t0,\n\t\t\t\t\t\"Undeclared variables found: \" + String.join(\", \", undeclaredVariables) + \".\"\n\t\t\t);\n\t\t}\n\n\t\treturn new HeaderRule(name, parsed, variables, yearSelectionMode);\n\t}\n\n\n\t/**\n\t * Parses out the tokens of a line of the license header.\n\t *\n\t * @param line the line to parse\n\t * @param optional {@code true} if the line is optional, or {@code false} otherwise\n\t * @return the parsed line\n\t */\n\tprivate static @NotNull HeaderLine parseLine(@NotNull String line, boolean optional) {\n\t\tList<RuleToken> tokens = new ArrayList<>();\n\n\t\tint lastLandmark = 0;\n\t\tboolean backslash = false;\n\n\t\tfor (int i = 0; i < line.length(); i++) {\n\t\t\tchar c = line.charAt(i);\n\n\t\t\tif (c == '$' && !backslash && Utils.matchCharAt(line, i + 1, '{')) {\n\t\t\t\tString variable = readVar(line, i + 2);\n\n\t\t\t\tif (variable != null) {\n\t\t\t\t\tif (lastLandmark != i) {\n\t\t\t\t\t\ttokens.add(new TextToken(line.substring(lastLandmark, i)));\n\t\t\t\t\t}\n\n\t\t\t\t\ttokens.add(new VarToken(variable));\n\t\t\t\t\ti += variable.length() + 2;\n\t\t\t\t\tlastLandmark = i + 1;\n\t\t\t\t}\n\t\t\t} else if (c == '\\\\') {\n\t\t\t\tbackslash = !backslash;\n\t\t\t} else {\n\t\t\t\tbackslash = false;\n\t\t\t}\n\t\t}\n\n\t\tif (lastLandmark < line.length()) {\n\t\t\ttokens.add(new TextToken(line.substring(lastLandmark)));\n\t\t}\n\n\t\treturn new HeaderLine(tokens, optional);\n\t}\n\n\t/**\n\t * Attempts to read the variable at the given index in the line.\n\t *\n\t * @param line the line to read the variable from\n\t * @param start the index where the variable name starts\n\t * @return the variable name, or {@code null} if no variable could be parsed\n\t */\n\tprivate static @Nullable String readVar(@NotNull String line, int start) {\n\t\tint end = start;\n\n\t\tfor (int i = start; i < line.length(); i++) {\n\t\t\tchar c = line.charAt(i);\n\n\t\t\tif (c == '_' || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {\n\t\t\t\tcontinue;\n\t\t\t} else if (c == '}') {\n\t\t\t\t// END.\n\t\t\t\tend = i;\n\t\t\t\tbreak;\n\t\t\t} else return null;\n\t\t}\n\n\t\tif (end != start) {\n\t\t\treturn line.substring(start, end);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Represents the data parsed by reading a header comment using a given header rule.\n\t *\n\t * @param variables the parsed variable values\n\t * @param presentOptionalLines the indices of the optional lines that were present\n\t * @param error an error if the parsing failed, or {@code null} otherwise\n\t */\n\tpublic record ParsedData(\n\t\t\tMap<String, ?> variables,\n\t\t\tSet<Integer> presentOptionalLines,\n\t\t\t@Nullable HeaderParseException error\n\t) {}\n}"
}
] | import dev.yumi.gradle.licenser.YumiLicenserGradlePlugin;
import dev.yumi.gradle.licenser.api.rule.HeaderFileContext;
import dev.yumi.gradle.licenser.api.rule.HeaderRule;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map; | 4,549 | /*
* Copyright 2023 Yumi Project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package dev.yumi.gradle.licenser.impl;
/**
* Represents the valid license headers for this project.
*
* @author LambdAurora
* @version 1.0.0
* @since 1.0.0
*/
public final class LicenseHeader {
private final List<HeaderRule> rules;
public LicenseHeader(HeaderRule... rules) {
this(new ArrayList<>(List.of(rules)));
}
public LicenseHeader(List<HeaderRule> rules) {
this.rules = rules;
}
/**
* {@return {@code true} if this license header is valid and can be used for validation, otherwise {@code false}}
*/
public boolean isValid() {
return !this.rules.isEmpty();
}
/**
* Adds a header rule.
*
* @param rule the rule to add
*/
public void addRule(HeaderRule rule) {
this.rules.add(rule);
}
/**
* Validates the given file.
*
* @param header the existing header
* @return a list of validation errors if there's any
*/
public @NotNull List<ValidationError> validate(@NotNull List<String> header) {
var errors = new ArrayList<ValidationError>();
for (var rule : this.rules) {
var result = rule.parseHeader(header);
if (result.error() != null) {
errors.add(new ValidationError(rule.getName(), result.error()));
} else {
return List.of();
}
}
return errors;
}
/**
* Formats the given file to contain the correct license header.
*
* @param project the project the file is in
* @param logger the logger
* @param path the path of the file
* @param readComment the read header comment if successful, or {@code null} otherwise
* @return {@code true} if files changed, otherwise {@code false}
*/
public @Nullable List<String> format(Project project, Logger logger, Path path, @Nullable List<String> readComment) {
List<String> newHeader = null;
if (readComment == null) { | /*
* Copyright 2023 Yumi Project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package dev.yumi.gradle.licenser.impl;
/**
* Represents the valid license headers for this project.
*
* @author LambdAurora
* @version 1.0.0
* @since 1.0.0
*/
public final class LicenseHeader {
private final List<HeaderRule> rules;
public LicenseHeader(HeaderRule... rules) {
this(new ArrayList<>(List.of(rules)));
}
public LicenseHeader(List<HeaderRule> rules) {
this.rules = rules;
}
/**
* {@return {@code true} if this license header is valid and can be used for validation, otherwise {@code false}}
*/
public boolean isValid() {
return !this.rules.isEmpty();
}
/**
* Adds a header rule.
*
* @param rule the rule to add
*/
public void addRule(HeaderRule rule) {
this.rules.add(rule);
}
/**
* Validates the given file.
*
* @param header the existing header
* @return a list of validation errors if there's any
*/
public @NotNull List<ValidationError> validate(@NotNull List<String> header) {
var errors = new ArrayList<ValidationError>();
for (var rule : this.rules) {
var result = rule.parseHeader(header);
if (result.error() != null) {
errors.add(new ValidationError(rule.getName(), result.error()));
} else {
return List.of();
}
}
return errors;
}
/**
* Formats the given file to contain the correct license header.
*
* @param project the project the file is in
* @param logger the logger
* @param path the path of the file
* @param readComment the read header comment if successful, or {@code null} otherwise
* @return {@code true} if files changed, otherwise {@code false}
*/
public @Nullable List<String> format(Project project, Logger logger, Path path, @Nullable List<String> readComment) {
List<String> newHeader = null;
if (readComment == null) { | if (YumiLicenserGradlePlugin.DEBUG_MODE) { | 0 | 2023-10-08 20:51:43+00:00 | 8k |
5152Alotobots/2024_Crescendo_Preseason | src/main/java/frc/robot/chargedup/commands/auto/basic/Auto_leftredescape_Cmd.java | [
{
"identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj",
"path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java",
"snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj. */\n private SubSys_DriveTrain subSys_DriveTrain;\n\n private String pathPlannerTrajName;\n private boolean setPose;\n private boolean setYaw;\n private Alliance setAlliance;\n private PathConstraints constraints;\n\n private PathPlannerTrajectory ppTraj;\n\n private final PIDController xDistancePID;\n private final PIDController yDistancePID;\n private final PIDController rotationPID;\n\n private Timer timer;\n\n /**\n * Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj Follow PathPlanner Trajectory\n *\n * @param subSys_DriveTrain SubSys_DriveTrain Drive Train subsystem\n * @param pathPlannerTraj String Name of PathPlannerTraj\n */\n public Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj(\n SubSys_DriveTrain subSys_DriveTrain,\n String pathPlannerTrajName,\n boolean setPose,\n boolean setYaw,\n Alliance setAlliance) {\n\n this.subSys_DriveTrain = subSys_DriveTrain;\n this.pathPlannerTrajName = pathPlannerTrajName;\n this.setPose = setPose;\n this.setYaw = setYaw;\n this.setAlliance = setAlliance;\n\n // Use addRequirements() here to declare subsystem dependencies.\n addRequirements(subSys_DriveTrain);\n\n // Load Path\n this.constraints = PathPlanner.getConstraintsFromPath(this.pathPlannerTrajName);\n this.ppTraj = PathPlanner.loadPath(this.pathPlannerTrajName, this.constraints);\n // new PathConstraints(2.7, 3.0));\n\n this.ppTraj = PathPlannerTrajectory.transformTrajectoryForAlliance(this.ppTraj, setAlliance);\n this.xDistancePID =\n new PIDController(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Pgain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Igain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Dgain);\n this.xDistancePID.setTolerance(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.PositionTolerance,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.VelocityTolerance);\n\n this.yDistancePID =\n new PIDController(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Pgain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Igain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.Dgain);\n this.yDistancePID.setTolerance(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.PositionTolerance,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveTrajectoryPID.VelocityTolerance);\n\n this.rotationPID =\n new PIDController(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.RotationTrajectoryPID.Pgain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.RotationTrajectoryPID.Igain,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.RotationTrajectoryPID.Dgain);\n this.rotationPID.enableContinuousInput(-180, 180);\n this.rotationPID.setTolerance(\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.RotationTrajectoryPID.PositionTolerance,\n SubSys_DriveTrain_Constants.DriveTrainTrajSettings.RotationTrajectoryPID.VelocityTolerance);\n\n this.timer = new Timer();\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {\n // Check if the Odometry should be reset\n if (setYaw) {\n this.subSys_DriveTrain.setYaw(ppTraj.getInitialHolonomicPose().getRotation().getDegrees());\n }\n if (setPose) {\n this.subSys_DriveTrain.setPose(ppTraj.getInitialHolonomicPose());\n }\n\n this.xDistancePID.reset();\n this.xDistancePID.setSetpoint(ppTraj.getInitialHolonomicPose().getX());\n\n this.yDistancePID.reset();\n this.yDistancePID.setSetpoint(ppTraj.getInitialHolonomicPose().getY());\n\n this.rotationPID.reset();\n this.rotationPID.setSetpoint(ppTraj.getInitialHolonomicPose().getRotation().getDegrees());\n\n timer.reset();\n timer.start();\n }\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n double currentTime = this.timer.get();\n PathPlannerState desiredState = (PathPlannerState) ppTraj.sample(currentTime);\n\n Pose2d currentPose = subSys_DriveTrain.getPose();\n\n double xCmd = this.xDistancePID.calculate(currentPose.getX(), desiredState.poseMeters.getX());\n SmartDashboard.putNumber(\"xPID_xCmd\", xCmd);\n\n double yCmd = this.yDistancePID.calculate(currentPose.getY(), desiredState.poseMeters.getY());\n SmartDashboard.putNumber(\"yPID_yCmd\", yCmd);\n\n double rotCmd =\n this.rotationPID.calculate(\n this.subSys_DriveTrain.getHeading().getDegrees(),\n desiredState.holonomicRotation.getDegrees());\n SmartDashboard.putNumber(\"rotPID_rotCmd\", rotCmd);\n\n this.subSys_DriveTrain.Drive(\n xCmd * SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveSpeedMultiplier,\n yCmd * SubSys_DriveTrain_Constants.DriveTrainTrajSettings.DriveSpeedMultiplier,\n rotCmd,\n true,\n false,\n false);\n\n SmartDashboard.putBoolean(\"x dist at set\", this.xDistancePID.atSetpoint());\n SmartDashboard.putBoolean(\"y dist at set\", this.yDistancePID.atSetpoint());\n SmartDashboard.putBoolean(\"rot dist at set\", this.rotationPID.atSetpoint());\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n this.subSys_DriveTrain.Drive(0.0, 0.0, 0.0, false, false, false);\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n PathPlannerState endState = ppTraj.getEndState();\n PathPlannerState currentState = (PathPlannerState) ppTraj.sample(this.timer.get());\n if (endState == currentState) {\n return true;\n }\n return false;\n }\n}"
},
{
"identifier": "SubSys_DriveTrain",
"path": "src/main/java/frc/robot/library/drivetrains/SubSys_DriveTrain.java",
"snippet": "public class SubSys_DriveTrain extends SubsystemBase {\n /** Creates a new Drive SubSystem. */\n\n // Drive Types - Select only 1\n\n // Tank\n // private final TankDriveSubSys m_Drive =\n // new TankDriveSubSys;\n\n // Mecanum\n // private final MecanumDriveSubSys m_Drive =\n // new MecanumDriveSubSys;\n\n // Swerve\n private SubSys_SwerveDrive driveTrain;\n\n // Drive Commands\n private double driveXDirCmd = 0;\n private double driveYDirCmd = 0;\n private double driveZRotCmd = 0;\n private boolean driveFieldOriented = true;\n private boolean driveRotateLeftPtCmd = false;\n private boolean driveRotateRightPtCmd = false;\n\n // GyroScope\n private SubSys_PigeonGyro gyroSubSys;\n\n /**\n * SubSys_DriveTrain Constructor\n *\n * @param gyroSubSys SubSys_PigeonGyro\n */\n public SubSys_DriveTrain(SubSys_PigeonGyro gyroSubSys) {\n this.gyroSubSys = gyroSubSys;\n this.driveTrain = new SubSys_SwerveDrive(this.gyroSubSys);\n }\n\n @Override\n public void periodic() {\n // This method will be called once per scheduler run\n\n // Send Drive Commands\n driveTrain.drive(\n new Translation2d(driveXDirCmd, driveYDirCmd),\n driveZRotCmd,\n driveFieldOriented,\n true,\n driveRotateLeftPtCmd,\n driveRotateRightPtCmd);\n\n // Put pose and Heading to smart dashboard\n SmartDashboard.putNumber(\"Pose X\", getPose().getX());\n SmartDashboard.putNumber(\"Pose Y\", getPose().getY());\n SmartDashboard.putNumber(\"Heading (Degrees)\", getHeading().getDegrees());\n\n // Put Drive Commands to smart dashboard\n SmartDashboard.putNumber(\"driveXDirCmd\", driveXDirCmd);\n SmartDashboard.putNumber(\"driveYDirCmd\", driveYDirCmd);\n SmartDashboard.putNumber(\"driveZRotCmd\", driveZRotCmd);\n }\n\n /***********************************************************************************/\n /* ***** Public DriveTrain Methods ***** */\n /***********************************************************************************/\n\n // ***** DriveTrain Info *****\n\n /**\n * getMaxDriveSubSysSpd Returns Max Drive SubSystem Speed\n *\n * @return double DriveTrain Maximum Speed (m/s)\n */\n public double getMaxDriveSubSysSpd() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxSpd;\n }\n\n public double getMaxDriveTurboSubSysSpd() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboSpd;\n }\n\n public double getMaxDriveSubSysTurboPctOutput() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboPctOutput;\n }\n\n public double getMaxDriveSubSysTurboAccel() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboAccel;\n }\n\n /**\n * getMaxDriveSubSysRotSpd Returns Max Drive Subsystem Rotation\n *\n * @return double DriveTrain Maximum Speed (rads/s)\n */\n public double getMaxDriveSubSysRotSpd() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxRotSpeed;\n }\n\n public double getMaxDriveSubSysTurboRotSpd() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboRotSpeed;\n }\n\n public double getMaxDriveSubSysTurboRotPctOutput() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboRotPctOutput;\n }\n\n public double getMaxDriveSubSysTurboRotAccel() {\n return SubSys_DriveTrain_Constants.DriveTrainMaxTurboRotAccel;\n }\n\n // ***** Drive Methods *****\n\n /**\n * Drive Method to drive the robot using setpoint.\n *\n * @param xSpdCmd Speed Cmd of the robot in the x direction (forward) m/s.\n * @param ySpdCmd Speed Cmd of the robot in the y direction (sideways) m/s.\n * @param rotSpdCmd Rotational speed Cmd of the robot. rad/s\n * @param fieldRelative Whether the provided x and y speeds are relative to the field.\n * @param rotateLeftPt boolean Rotate around Left Pt\n * @param rotateRightPt boolean Rotate around Right Pt\n */\n @SuppressWarnings(\"ParameterName\")\n public void Drive(\n double xSpdCmd,\n double ySpdCmd,\n double rotSpdCmd,\n boolean fieldRelative,\n boolean rotateLeftPtCmd,\n boolean rotateRightPtCmd) {\n\n // Limit Cmds to Chassis Limits\n driveXDirCmd =\n Math.min(\n Math.max(xSpdCmd, -Robot.MaxSpeeds.DriveTrain.DriveTrainMaxSpd),\n Robot.MaxSpeeds.DriveTrain.DriveTrainMaxSpd);\n driveYDirCmd =\n Math.min(\n Math.max(ySpdCmd, -Robot.MaxSpeeds.DriveTrain.DriveTrainMaxSpd),\n Robot.MaxSpeeds.DriveTrain.DriveTrainMaxSpd);\n driveZRotCmd =\n Math.min(\n Math.max(rotSpdCmd, -Robot.MaxSpeeds.DriveTrain.DriveTrainMaxRotSpeed),\n Robot.MaxSpeeds.DriveTrain.DriveTrainMaxRotSpeed);\n driveFieldOriented = fieldRelative;\n driveRotateLeftPtCmd = rotateLeftPtCmd;\n driveRotateRightPtCmd = rotateRightPtCmd;\n }\n\n // ***** Odometry *****\n\n /**\n * getHeading Get Swerve Drive Heading in Rotation2d\n *\n * @return Rotation2d Heading of the drive train\n */\n public Rotation2d getHeading() {\n return this.driveTrain.getHeading();\n }\n\n /**\n * setGyroYaw set Gyro Yaw Value\n *\n * @param degrees\n */\n public void setYaw(double degrees) {\n this.driveTrain.setYaw(degrees);\n }\n\n /** setGyroYawToZero set Gyro Yaw Value to Zero */\n public void setYawToZero() {\n this.driveTrain.setYawToZero();\n }\n\n /**\n * getPose Get the X and Y position of the drivetrain from the DriveTrain\n *\n * @return Pose2d X and Y position of the drivetrain\n */\n public Pose2d getPose() {\n return this.driveTrain.getPose();\n }\n\n /**\n * setPose Set Pose of the drivetrain\n *\n * @param pose Pose2d X and Y position of the drivetrain\n */\n public void setPose(Pose2d pose) {\n this.driveTrain.setPose(pose);\n }\n\n /**\n * setPoseToOrigin Set Pose of the drivetrain to 0,0\n *\n * @param pose Pose2d X and Y position of the drivetrain\n */\n public void setPoseToOrigin() {\n this.driveTrain.setPose(new Pose2d());\n }\n\n /** setPoseDriveMtrsToZero Set Pose and Drive Motors to Zero */\n public void setPoseDriveMtrsToZero() {\n this.driveTrain.setPoseDriveMtrsToZero();\n }\n}"
},
{
"identifier": "SubSys_PigeonGyro",
"path": "src/main/java/frc/robot/library/gyroscopes/pigeon2/SubSys_PigeonGyro.java",
"snippet": "public class SubSys_PigeonGyro extends SubsystemBase {\n /** Creates a new NavXGyro. */\n private Pigeon2 pigeon2Gyro;\n\n private double gyroOffsetDegrees;\n\n public SubSys_PigeonGyro() {\n this.pigeon2Gyro = new Pigeon2(Constants.CAN_IDs.Pigeon2_ID);\n this.gyroOffsetDegrees = 0.0;\n // m_Pigeon2Gyro.setYaw(0);\n }\n\n @Override\n public void periodic() {\n // This method will be called once per scheduler run\n\n // Display\n SmartDashboard.putNumber(\"Pigeon_getRawYaw\", getRawYaw());\n SmartDashboard.putNumber(\"Pigeon_getYaw\", getYaw());\n SmartDashboard.putNumber(\"Pigeon_getYawRotation2d\", getYawRotation2d().getDegrees());\n // SmartDashboard.putNumber(\"GyroCompass\", m_Pigeon2Gyro.getCompassHeading());\n }\n\n public double getRawGyroPitch() {\n return this.pigeon2Gyro.getPitch();\n }\n\n public double getRawGyroRoll() {\n return this.pigeon2Gyro.getRoll();\n }\n\n /**\n * Return Raw Gyro Angle\n *\n * @return Raw Angle double raw Gyro Angle\n */\n public double getRawYaw() {\n return this.pigeon2Gyro.getYaw();\n }\n\n public double getYaw() {\n return getRawYaw() - this.gyroOffsetDegrees;\n }\n\n /**\n * Return Gyro Angle in Degrees\n *\n * @return Gyro Angle double Degrees\n */\n public double getYawAngle() {\n return Math.IEEEremainder(getYaw(), 360)\n * (SubSys_NavXGyro_Constants.GyroReversed ? -1.0 : 1.0);\n }\n\n /**\n * Return Gyro Angle in Rotation2d\n *\n * @return Gyro Angle Rotation2d\n */\n public Rotation2d getYawRotation2d() {\n return Rotation2d.fromDegrees(getYawAngle());\n }\n\n /** Zero Gyro */\n public void zeroYaw() {\n this.gyroOffsetDegrees = getRawYaw();\n }\n\n /** Set Gyro */\n public void setYaw(double yawDegrees) {\n this.gyroOffsetDegrees = getRawYaw() - yawDegrees;\n }\n}"
}
] | import edu.wpi.first.wpilibj.DriverStation.Alliance;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj;
import frc.robot.library.drivetrains.SubSys_DriveTrain;
import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro; | 4,392 | // 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.chargedup.commands.auto.basic;
/**
* *Link For PathPlanner
* *https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_6
*/
public class Auto_leftredescape_Cmd extends SequentialCommandGroup {
private final SubSys_DriveTrain m_DriveTrain; | // 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.chargedup.commands.auto.basic;
/**
* *Link For PathPlanner
* *https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_6
*/
public class Auto_leftredescape_Cmd extends SequentialCommandGroup {
private final SubSys_DriveTrain m_DriveTrain; | private final SubSys_PigeonGyro m_pigeonGyro; | 2 | 2023-10-09 00:27:11+00:00 | 8k |
nexus3a/monitor-remote-agent | src/main/java/com/monitor/parser/onec/OneCTJ.java | [
{
"identifier": "Token",
"path": "src/main/java/com/monitor/parser/Token.java",
"snippet": "public class Token implements java.io.Serializable {\r\n\r\n /**\r\n * The version identifier for this Serializable class. Increment only if the <i>serialized</i> form of the class\r\n * changes.\r\n */\r\n private static final long serialVersionUID = 1L;\r\n\r\n /**\r\n * An integer that describes the kind of this token. This numbering system is determined by JavaCCParser, and a\r\n * table of these numbers is stored in the file ...Constants.java.\r\n */\r\n public int kind;\r\n public long bytesRead;\r\n\r\n /**\r\n * The line number of the first character of this Token.\r\n */\r\n public int beginLine;\r\n /**\r\n * The column number of the first character of this Token.\r\n */\r\n public int beginColumn;\r\n /**\r\n * The line number of the last character of this Token.\r\n */\r\n public int endLine;\r\n /**\r\n * The column number of the last character of this Token.\r\n */\r\n public int endColumn;\r\n\r\n /**\r\n * The string image of the token.\r\n */\r\n public String image;\r\n\r\n /**\r\n * A reference to the next regular (non-special) token from the input stream. If this is the last token from the\r\n * input stream, or if the token manager has not read tokens beyond this one, this field is set to null. This is\r\n * true only if this token is also a regular token. Otherwise, see below for a description of the contents of this\r\n * field.\r\n */\r\n public Token next;\r\n\r\n /**\r\n * This field is used to access special tokens that occur prior to this token, but after the immediately preceding\r\n * regular (non-special) token. If there are no such special tokens, this field is set to null. When there are more\r\n * than one such special token, this field refers to the last of these special tokens, which in turn refers to the\r\n * next previous special token through its specialToken field, and so on until the first special token (whose\r\n * specialToken field is null). The next fields of special tokens refer to other special tokens that immediately\r\n * follow it (without an intervening regular token). If there is no such token, this field is null.\r\n */\r\n public Token specialToken;\r\n\r\n /**\r\n * An optional attribute value of the Token. Tokens which are not used as syntactic sugar will often contain\r\n * meaningful values that will be used later on by the compiler or interpreter. This attribute value is often\r\n * different from the image. Any subclass of Token that actually wants to return a non-null value can override this\r\n * method as appropriate.\r\n */\r\n public Object getValue() {\r\n return null;\r\n }\r\n\r\n /**\r\n * No-argument constructor\r\n */\r\n public Token() {\r\n }\r\n\r\n /**\r\n * Constructs a new token for the specified Image.\r\n */\r\n public Token(int kind) {\r\n this(kind, null);\r\n }\r\n\r\n /**\r\n * Constructs a new token for the specified Image and Kind.\r\n */\r\n public Token(int kind, String image) {\r\n this.kind = kind;\r\n this.image = image;\r\n }\r\n\r\n /**\r\n * Returns the image.\r\n */\r\n public String toString() {\r\n return image;\r\n }\r\n\r\n /**\r\n * Returns a new Token object, by default. However, if you want, you can create and return subclass objects based on\r\n * the value of ofKind. Simply add the cases to the switch for all those special cases. For example, if you have a\r\n * subclass of Token called IDToken that you want to create if ofKind is ID, simply add something like :\r\n *\r\n * case MyParserConstants.ID : return new IDToken(ofKind, image);\r\n *\r\n * to the following switch statement. Then you can cast matchedToken variable to the appropriate type and use sit in\r\n * your lexical actions.\r\n */\r\n public static Token newToken(int ofKind, String image) {\r\n switch (ofKind) {\r\n default:\r\n return new Token(ofKind, image);\r\n }\r\n }\r\n\r\n public static Token newToken(int ofKind) {\r\n return newToken(ofKind, null);\r\n }\r\n\r\n}\r"
},
{
"identifier": "ParseException",
"path": "src/main/java/com/monitor/parser/ParseException.java",
"snippet": "public class ParseException extends Exception {\r\n\r\n /**\r\n * The version identifier for this Serializable class.\r\n * Increment only if the <i>serialized</i> form of the\r\n * class changes.\r\n */\r\n private static final long serialVersionUID = 1L;\r\n\r\n /**\r\n * The end of line string for this machine.\r\n */\r\n protected static String EOL = System.getProperty(\"line.separator\", \"\\n\");\r\n\r\n /**\r\n * This constructor is used by the method \"generateParseException\"\r\n * in the generated parser. Calling this constructor generates\r\n * a new object of this type with the fields \"currentToken\",\r\n * \"expectedTokenSequences\", and \"tokenImage\" set.\r\n */\r\n public ParseException(Token currentTokenVal,\r\n int[][] expectedTokenSequencesVal,\r\n String[] tokenImageVal\r\n )\r\n {\r\n super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));\r\n currentToken = currentTokenVal;\r\n expectedTokenSequences = expectedTokenSequencesVal;\r\n tokenImage = tokenImageVal;\r\n }\r\n\r\n /**\r\n * The following constructors are for use by you for whatever\r\n * purpose you can think of. Constructing the exception in this\r\n * manner makes the exception behave in the normal way - i.e., as\r\n * documented in the class \"Throwable\". The fields \"errorToken\",\r\n * \"expectedTokenSequences\", and \"tokenImage\" do not contain\r\n * relevant information. The JavaCC generated code does not use\r\n * these constructors.\r\n */\r\n\r\n public ParseException() {\r\n super();\r\n }\r\n\r\n /** Constructor with message. */\r\n public ParseException(String message) {\r\n super(message);\r\n }\r\n\r\n\r\n /**\r\n * This is the last token that has been consumed successfully. If\r\n * this object has been created due to a parse error, the token\r\n * followng this token will (therefore) be the first error token.\r\n */\r\n public Token currentToken;\r\n\r\n /**\r\n * Each entry in this array is an array of integers. Each array\r\n * of integers represents a sequence of tokens (by their ordinal\r\n * values) that is expected at this point of the parse.\r\n */\r\n public int[][] expectedTokenSequences;\r\n\r\n /**\r\n * This is a reference to the \"tokenImage\" array of the generated\r\n * parser within which the parse error occurred. This array is\r\n * defined in the generated ...Constants interface.\r\n */\r\n public String[] tokenImage;\r\n\r\n /**\r\n * It uses \"currentToken\" and \"expectedTokenSequences\" to generate a parse\r\n * error message and returns it. If this object has been created\r\n * due to a parse error, and you do not catch it (it gets thrown\r\n * from the parser) the correct error message\r\n * gets displayed.\r\n */\r\n private static String initialise(Token currentToken,\r\n int[][] expectedTokenSequences,\r\n String[] tokenImage) {\r\n\r\n StringBuffer expected = new StringBuffer();\r\n int maxSize = 0;\r\n for (int i = 0; i < expectedTokenSequences.length; i++) {\r\n if (maxSize < expectedTokenSequences[i].length) {\r\n maxSize = expectedTokenSequences[i].length;\r\n }\r\n for (int j = 0; j < expectedTokenSequences[i].length; j++) {\r\n expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');\r\n }\r\n if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {\r\n expected.append(\"...\");\r\n }\r\n expected.append(EOL).append(\" \");\r\n }\r\n String retval = \"Encountered \\\"\";\r\n Token tok = currentToken.next;\r\n for (int i = 0; i < maxSize; i++) {\r\n if (i != 0) retval += \" \";\r\n if (tok.kind == 0) {\r\n retval += tokenImage[0];\r\n break;\r\n }\r\n retval += \" \" + tokenImage[tok.kind];\r\n retval += \" \\\"\";\r\n retval += add_escapes(tok.image);\r\n retval += \" \\\"\";\r\n tok = tok.next;\r\n }\r\n retval += \"\\\" at line \" + currentToken.next.beginLine + \", column \" + currentToken.next.beginColumn;\r\n retval += \".\" + EOL;\r\n \r\n \r\n if (expectedTokenSequences.length == 0) {\r\n // Nothing to add here\r\n } else {\r\n\t if (expectedTokenSequences.length == 1) {\r\n\t retval += \"Was expecting:\" + EOL + \" \";\r\n\t } else {\r\n\t retval += \"Was expecting one of:\" + EOL + \" \";\r\n\t }\r\n\t retval += expected.toString();\r\n }\r\n \r\n return retval;\r\n }\r\n\r\n\r\n /**\r\n * Used to convert raw characters to their escaped version\r\n * when these raw version cannot be used as part of an ASCII\r\n * string literal.\r\n */\r\n static String add_escapes(String str) {\r\n StringBuffer retval = new StringBuffer();\r\n char ch;\r\n for (int i = 0; i < str.length(); i++) {\r\n switch (str.charAt(i))\r\n {\r\n case '\\b':\r\n retval.append(\"\\\\b\");\r\n continue;\r\n case '\\t':\r\n retval.append(\"\\\\t\");\r\n continue;\r\n case '\\n':\r\n retval.append(\"\\\\n\");\r\n continue;\r\n case '\\f':\r\n retval.append(\"\\\\f\");\r\n continue;\r\n case '\\r':\r\n retval.append(\"\\\\r\");\r\n continue;\r\n case '\\\"':\r\n retval.append(\"\\\\\\\"\");\r\n continue;\r\n case '\\'':\r\n retval.append(\"\\\\\\'\");\r\n continue;\r\n case '\\\\':\r\n retval.append(\"\\\\\\\\\");\r\n continue;\r\n default:\r\n if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\r\n String s = \"0000\" + Integer.toString(ch, 16);\r\n retval.append(\"\\\\u\" + s.substring(s.length() - 4, s.length()));\r\n } else {\r\n retval.append(ch);\r\n }\r\n continue;\r\n }\r\n }\r\n return retval.toString();\r\n }\r\n\r\n}\r"
},
{
"identifier": "ParserParameters",
"path": "src/main/java/com/monitor/parser/ParserParameters.java",
"snippet": "public class ParserParameters {\r\n \r\n private Set<String> excludeData;\r\n private int maxTokenLength;\r\n private String parserErrorLog;\r\n private int delay;\r\n\r\n public ParserParameters() {\r\n excludeData = new HashSet<>();\r\n maxTokenLength = 1024 * 32;\r\n parserErrorLog = \"logs/parser-errors\";\r\n delay = 0;\r\n }\r\n\r\n public Set<String> getExcludeData() {\r\n return excludeData;\r\n }\r\n\r\n public void setExcludeData(Set<String> excludeData) {\r\n this.excludeData = excludeData;\r\n }\r\n\r\n public int getMaxTokenLength() {\r\n return maxTokenLength;\r\n }\r\n\r\n public void setMaxTokenLength(int maxTokenLength) {\r\n this.maxTokenLength = maxTokenLength;\r\n }\r\n\r\n public String getParserErrorLog() {\r\n return parserErrorLog;\r\n }\r\n\r\n public void setParserErrorLog(String parserErrorLog) {\r\n this.parserErrorLog = parserErrorLog;\r\n }\r\n\r\n public int getDelay() {\r\n return delay;\r\n }\r\n\r\n public void setDelay(int delay) {\r\n this.delay = delay;\r\n }\r\n \r\n}\r"
}
] | import com.monitor.parser.Token;
import com.monitor.parser.ParseException;
import com.monitor.parser.ParserParameters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 4,138 | package com.monitor.parser.onec;
/*
* Copyright 2021 Aleksei Andreev
*
* 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.
*
*/
public class OneCTJ implements OneCTJConstants {
private final static long MICROSECONDS_TO_1970 = 62135596800000L * 1000L;
private final static byte[] ZEROES = "0000000".getBytes();
private final static byte CHR0 = '0';
private final static String SQL_PARAMETERS_PROP_MARKER = "\np_0:";
private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private final static TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT+0");
private final static String SQL_PARAMETERS_PROP_NAME = "Sql.p_N";
private final static String DATE_TIME_PROP_NAME = "dateTime";
private final static String START_DATE_TIME_PROP_NAME = "startDateTime";
private final static String ONLY_TIME_PROP_NAME = "onlyTime";
private final static String CONTEXT_LAST_LINE_PROP_NAME = "ContextLastLine";
private final static String TIMESTAMP_PROP_NAME = "timestamp";
private final static String LOCKS_PROP_NAME = "Locks";
private final static String LOCK_SPACE_NAME_PROP_NAME = "space";
private final static String LOCK_SPACE_TYPE_PROP_NAME = "type";
private final static String LOCK_SPACE_RECORDS_PROP_NAME = "records";
private final static String LOCK_SPACE_RECORDS_COUNT_PROP_NAME = "recordsCount";
private final static String LOCK_GRANULARITY_PROP_NAME = "granularity";
private static final Pattern UNPRINTABLE_PATTERN = Pattern.compile("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]");
static {
DATE_FORMAT.setTimeZone(TIME_ZONE);
}
private final OneCTJRecord logRecord0 = new OneCTJRecord();
private final OneCTJRecord logRecord1 = new OneCTJRecord();
private OneCTJRecord logRecord = logRecord1;
private OneCTJRecord readyLogRecord = logRecord0;
private long bytesRead;
private long readyBytesRead;
private final byte[] ms6 = new byte[6];
private String propertyName;
private String propertyValue;
protected long recordsCount = 0L;
private long perfomance = 0L;
private boolean v82format;
private String event;
private String year;
private String month;
private String day;
private String hours;
private String minutes;
private String seconds;
private String microseconds;
private String yyyyMMddhh;
private long microsecondsBase;
private long microsecondsValue;
private String sqlParametersPropValue;
private String lastLineParameterValue;
private ArrayList<HashMap<String, Object>> lockSpaces; // список наборов свойств пространств блокировки
private HashMap<String, Object> lockSpaceProps; // набор свойств текущего пространства блокировок
private ArrayList<HashMap<String, String>> lockRecords; // список записей блокировок (их свойств) для текущего пространства
private int lockRecordsCount; // количество записей блокировок (их свойств) для текущего пространства
private HashMap<String, String> lockRecordProps; // набор свойств текущей записи блокировки
private boolean includeLockRecords; // нужно ли собирать данные полей блокировки
public static void main(String args[]) throws Throwable {
/*
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\20092816.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21112514.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21120914.EXCP.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.SDBL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.TDEADLOCK.log"), "UTF-8");
// System.out.println("perfomance: " + parser.getPerfomance());
// System.out.println("records: " + parser.getRecordsCount());
*/
System.out.println("test = " + DATE_FORMAT.format(new Date((63827362557274001L - MICROSECONDS_TO_1970 - 999983) / 1000L)));
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\L70\\00000001.log"),
"UTF-8", | package com.monitor.parser.onec;
/*
* Copyright 2021 Aleksei Andreev
*
* 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.
*
*/
public class OneCTJ implements OneCTJConstants {
private final static long MICROSECONDS_TO_1970 = 62135596800000L * 1000L;
private final static byte[] ZEROES = "0000000".getBytes();
private final static byte CHR0 = '0';
private final static String SQL_PARAMETERS_PROP_MARKER = "\np_0:";
private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private final static TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT+0");
private final static String SQL_PARAMETERS_PROP_NAME = "Sql.p_N";
private final static String DATE_TIME_PROP_NAME = "dateTime";
private final static String START_DATE_TIME_PROP_NAME = "startDateTime";
private final static String ONLY_TIME_PROP_NAME = "onlyTime";
private final static String CONTEXT_LAST_LINE_PROP_NAME = "ContextLastLine";
private final static String TIMESTAMP_PROP_NAME = "timestamp";
private final static String LOCKS_PROP_NAME = "Locks";
private final static String LOCK_SPACE_NAME_PROP_NAME = "space";
private final static String LOCK_SPACE_TYPE_PROP_NAME = "type";
private final static String LOCK_SPACE_RECORDS_PROP_NAME = "records";
private final static String LOCK_SPACE_RECORDS_COUNT_PROP_NAME = "recordsCount";
private final static String LOCK_GRANULARITY_PROP_NAME = "granularity";
private static final Pattern UNPRINTABLE_PATTERN = Pattern.compile("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]");
static {
DATE_FORMAT.setTimeZone(TIME_ZONE);
}
private final OneCTJRecord logRecord0 = new OneCTJRecord();
private final OneCTJRecord logRecord1 = new OneCTJRecord();
private OneCTJRecord logRecord = logRecord1;
private OneCTJRecord readyLogRecord = logRecord0;
private long bytesRead;
private long readyBytesRead;
private final byte[] ms6 = new byte[6];
private String propertyName;
private String propertyValue;
protected long recordsCount = 0L;
private long perfomance = 0L;
private boolean v82format;
private String event;
private String year;
private String month;
private String day;
private String hours;
private String minutes;
private String seconds;
private String microseconds;
private String yyyyMMddhh;
private long microsecondsBase;
private long microsecondsValue;
private String sqlParametersPropValue;
private String lastLineParameterValue;
private ArrayList<HashMap<String, Object>> lockSpaces; // список наборов свойств пространств блокировки
private HashMap<String, Object> lockSpaceProps; // набор свойств текущего пространства блокировок
private ArrayList<HashMap<String, String>> lockRecords; // список записей блокировок (их свойств) для текущего пространства
private int lockRecordsCount; // количество записей блокировок (их свойств) для текущего пространства
private HashMap<String, String> lockRecordProps; // набор свойств текущей записи блокировки
private boolean includeLockRecords; // нужно ли собирать данные полей блокировки
public static void main(String args[]) throws Throwable {
/*
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\20092816.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21112514.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21120914.EXCP.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.SDBL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.TDEADLOCK.log"), "UTF-8");
// System.out.println("perfomance: " + parser.getPerfomance());
// System.out.println("records: " + parser.getRecordsCount());
*/
System.out.println("test = " + DATE_FORMAT.format(new Date((63827362557274001L - MICROSECONDS_TO_1970 - 999983) / 1000L)));
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\L70\\00000001.log"),
"UTF-8", | new ParserParameters()); | 2 | 2023-10-11 20:25:12+00:00 | 8k |
mhaupt/basicode | src/main/java/de/haupz/basicode/ast/ExpressionNode.java | [
{
"identifier": "InterpreterState",
"path": "src/main/java/de/haupz/basicode/interpreter/InterpreterState.java",
"snippet": "public class InterpreterState {\n\n /**\n * The root node of the program whose state this instance represents.\n */\n private final ProgramNode program;\n\n /**\n * The running program's output channel.\n */\n private final BasicOutput out;\n\n /**\n * The running program's input channel.\n */\n private final BasicInput in;\n\n /**\n * The interpreter configuration. This is controllable using command line flags.\n */\n private final Configuration configuration;\n\n /**\n * Variables used in the program. Note that variables and arrays don't share a namespace, hence the {@link #arrays}\n * field contains the latter.\n */\n private final Map<String, Object> vars = new HashMap<>();\n\n /**\n * Arrays used in the program. Note that variables and arrays don't share a namespace, hence the {@link #vars}\n * field contains the former.\n */\n private final Map<String, BasicArray> arrays = new HashMap<>();\n\n /**\n * The call stack, for {@code GOSUB}/{@code RETURN} handling.\n */\n private final Stack<Integer> callStack = new Stack<>();\n\n /**\n * A triple to keep track of running {@code FOR} loops.\n *\n * @param startIndex the index, into the {@link #program}'s statements list, of the {@code FOR} statement that is\n * the head of the loop.\n * @param end the end value of the loop iterator.\n * @param step the step by which to increase/decrease the loop iterator.\n */\n public record For(int startIndex, Number end, Number step) {}\n\n /**\n * Map the names of running loops' iterator variables to their {@linkplain For loop records}.\n */\n private final Map<String, For> runningForLoops = new HashMap<>();\n\n /**\n * The index, into the {@link #program}'s statements list, of the next statement to execute.\n */\n private int statementIndex = 0;\n\n /**\n * If {@code true}, notifies the interpreter that it should terminate execution.\n */\n private boolean end = false;\n\n /**\n * If {@code true}, notifies the interpreter that it needs to execute a jump.\n */\n private boolean lineJump = false;\n\n /**\n * If {@code true}, notifies the interpreter that it needs to execute a return.\n */\n private boolean ret = false;\n\n /**\n * If {@code true}, notifies the interpreter that it needs to execute a loop backedge.\n */\n private boolean backedge = false;\n\n /**\n * If {@code true}, notifies the interpreter that it needs to skip the remainder of statements on the current line\n * of code.\n */\n private boolean skipLine = false;\n\n /**\n * The target line of a jump the interpreter needs to execute. Used when {@link #lineJump} is {@code trye}.\n */\n private int lineJumpTarget;\n\n /**\n * The target of a loop backedge jump the interpreter needs to execute. Used when {@link #backedge} is {@code true}.\n */\n private int backedgeTarget;\n\n /**\n * The pointer into the program's {@code DATA} collection. It always contains the index the next {@code READ}\n * statement would read from.\n */\n private int dataPtr = 0;\n\n /**\n * The currently open file output, or {@code null} if none is open.\n */\n private PrintStream currentOutFile;\n\n /**\n * The currently open file input, or {@code null} if none is open.\n */\n private BufferedReader currentInFile;\n\n /**\n * The \"printer\".\n */\n private PrintStream printer;\n\n /**\n * Create an interpreter state, and initialise BASICODE standard variables.\n *\n * @param program the program whose run this interpreter state represents.\n * @param in the input channel for the program.\n * @param out the output channel for the program.\n * @param configuration the interpreter configuration used for the execution of the program.\n */\n public InterpreterState(ProgramNode program, BasicInput in, BasicOutput out, Configuration configuration) {\n this.program = program;\n this.in = in;\n this.out = out;\n this.configuration = configuration;\n initialiseStandardVariables();\n }\n\n /**\n * <p>Initialise BASICODE standard variables.</p>\n *\n * <p>The following variables are initialised:<ul>\n * <li>{@code CC}: a numerical array containing two numbers representing the default foreground ({@code CC(0)})\n * and background ({@code CC(1)}) colours. The foreground colour is initialised to yellow; the background\n * colour, to blue.</li>\n * <li>{@code CN}: a number controlling whether, in graphics mode, text will be drawn using the foreground\n * colour. It is initialised to 0, implying that the foreground colour will be used.</li>\n * </ul></p>\n */\n private void initialiseStandardVariables() {\n // colours\n BasicArray1D cc = new BasicArray1D(ArrayType.NUMBER, 2);\n cc.setAt(0, -1, 6.0); // foreground: yellow\n cc.setAt(1, -1, 1.0); // background: blue\n setArray(\"CC\", cc);\n // drawing text defaults to using the foreground colour\n setVar(\"CN\", 0.0);\n }\n\n /**\n * @return the {@link #program}'s input channel.\n */\n public BasicInput getInput() {\n return in;\n }\n\n /**\n * @return the {@link #program}'s output channel.\n */\n public BasicOutput getOutput() {\n return out;\n }\n\n /**\n * @return the interpreter configuration.\n */\n public Configuration getConfiguration() {\n return configuration;\n }\n\n /**\n * Set a variable. If the variable does not exist, it will be created; if it exists, its previous value will be\n * overwritten.\n *\n * @param id the variable's name.\n * @param value the variable's new value.\n */\n public void setVar(String id, Object value) {\n vars.put(id, value);\n }\n\n /**\n * Retrieve a variable, if it exists.\n *\n * @param id the variable's name.\n * @return the variable's value wrapped in an {@link Optional}, if it exists; otherwise, {@code empty}.\n */\n public Optional<Object> getVar(String id) {\n return Optional.ofNullable(vars.get(id));\n }\n\n /**\n * Set an array. This is <em>not</em> setting a value at some index in an array, but rather binding an array to a\n * variable name.\n *\n * @param id the array variable's name.\n * @param value the array.\n */\n public void setArray(String id, BasicArray value) {\n arrays.put(id, value);\n }\n\n /**\n * Retrieve an array, if it exists.\n *\n * @param id the array's variable name.\n * @return the array, wrapped in an {@link Optional}, if it exists; otherwise, {@code empty}.\n */\n public Optional<BasicArray> getArray(String id) {\n return Optional.ofNullable(arrays.get(id));\n }\n\n /**\n * Remove a single variable. Do nothing if it doesn't exist.\n *\n * @param id the variable's name.\n */\n public void removeVar(String id) {\n vars.remove(id);\n }\n\n /**\n * Remove all variables.\n */\n public void clearVars() {\n vars.clear();\n }\n\n /**\n * Note that program execution should terminate upon the next possible occasion.\n */\n public void terminate() {\n end = true;\n }\n\n /**\n * @return {@code true} if the interpreter has been notified to terminate.\n */\n public boolean shouldEnd() {\n return end;\n }\n\n /**\n * @return {@code true} if the next operation the interpreter should execute is a jump to a specific line.\n */\n public boolean isLineJumpNext() {\n return lineJump;\n }\n\n /**\n * Note that a jump should be executed. The target of the jump should be set using {@link #setLineJumpTarget(int)}.\n */\n public void requestLineJump() {\n lineJump = true;\n }\n\n /**\n * Note that a jump has been completed, and execution can proceed normally.\n */\n public void lineJumpDone() {\n lineJump = false;\n }\n\n /**\n * @return the target line number of a jump. This value is valid only while {@link #requestLineJump()} is\n * {@code true}.\n */\n public int getLineJumpTarget() {\n return lineJumpTarget;\n }\n\n /**\n * Note that a return from a {@code GOSUB} should be executed.\n */\n public void requestReturn() {\n ret = true;\n }\n\n /**\n * Note that a return from a {@code GOSUB} has been completed.\n */\n public void returnDone() {\n ret = false;\n }\n\n /**\n * @return {@code true} if the next operation the interpreter should execute is a return from a {@code GOSUB}.\n */\n public boolean isReturnNext() {\n return ret;\n }\n\n /**\n * Set the target line number (as given in the BASIC source code) of a jump.\n *\n * @param target the line number.\n */\n public void setLineJumpTarget(int target) {\n lineJumpTarget = target;\n }\n\n /**\n * @return the index of the next statement to be executed in the {@link #program}'s statement list.\n */\n public int getStatementIndex() {\n return statementIndex;\n }\n\n /**\n * Increment the {@link #program}'s statement index.\n */\n public void incStatementIndex() {\n ++statementIndex;\n }\n\n /**\n * Set the index of the next statement to be executed in the {@link #program}'s statement list.\n *\n * @param nextStmt the index of the next statement to be executed.\n */\n public void setNextStatement(int nextStmt) {\n statementIndex = nextStmt;\n }\n\n /**\n * Push a \"return address\" on the call stack. This is the next statement after a {@code GOSUB} statement, for\n * instance.\n */\n public void pushReturnIndex() {\n callStack.push(statementIndex + 1);\n }\n\n /**\n * @return the statement index from the top of the call stack.\n */\n public int getReturnIndex() {\n return callStack.pop();\n }\n\n /**\n * Clear the entire call stack.\n */\n public void clearCallStack() {\n callStack.removeAllElements();\n }\n\n /**\n * @return the interpreter's call stack.\n */\n public Stack<Integer> getCallStack() {\n return callStack;\n }\n\n /**\n * Check whether a loop using a given iterator variable is currently running.\n *\n * @param id the name of the iterator variable.\n * @return {@code true} if the variable name is an iterator variable in a running {@code FOR} loop.\n */\n public boolean isRunningLoop(String id) {\n return runningForLoops.containsKey(id);\n }\n\n /**\n * Note the start of a {@code FOR} loop by memorising its iterator variable, end value, and step width in a\n * {@link For} record.\n *\n * @param id the name of the iterator variable used in the loop.\n * @param end the end value of the loop's iterator variable.\n * @param step the step width by which the iterator variable is to be incremented/decremented after each iteration.\n */\n public void startLoop(String id, Number end, Number step) {\n runningForLoops.put(id, new For(statementIndex, end, step));\n }\n\n /**\n * Note that the loop with the given iterator variable has ended.\n *\n * @param id the name of the iterator variable.\n */\n public void stopLoop(String id) {\n runningForLoops.remove(id);\n }\n\n /**\n * Retrieve the {@link For} record for a running loop with the given iterator variable.\n *\n * @param id the iterator variable for which the loop information is to be retrieved.\n * @return the corresponding {@link For} record, or {@code null}, if there is no running loop with the given\n * iterator variable.\n */\n public For getLoop(String id) {\n return runningForLoops.get(id);\n }\n\n /**\n * Note that the interpreter should next execute a loop backedge jump.\n */\n public void requestBackedge() {\n backedge = true;\n }\n\n /**\n * Note that a backedge jump has just been completed.\n */\n public void backedgeDone() {\n backedge = false;\n }\n\n /**\n * @return {@code true} if the next operation to be performed by the interpreter should be a loop backedge jump.\n */\n public boolean isBackedgeNext() {\n return backedge;\n }\n\n /**\n * Note the statement index of a loop head ({@code FOR} statement), to be targeted by a loop backedge jump.\n *\n * @param b the statement index of the {@code FOR} statement to jump to.\n */\n public void setBackedgeTarget(int b) {\n backedgeTarget = b;\n }\n\n /**\n * @return the current backedge target (a statement index referencing a {@code FOR} statement).\n */\n public int getBackedgeTarget() {\n return backedgeTarget;\n }\n\n /**\n * Note that the interpreter should skip the execution of the remainder of the current line. This is relevant for\n * {@code IF} statements, for example, if the condition does not hold but the {@code THEN} branch consists of\n * multiple statements separated by colons.\n */\n public void requestSkipLine() {\n skipLine = true;\n }\n\n /**\n * @return {@code trye} if the next operation the interpreter should perform is to skip the remainder of the current\n * line of code.\n */\n public boolean isSkipLine() {\n return skipLine;\n }\n\n /**\n * Note that the interpreter has finished skipping the remainder of the current line of code.\n */\n public void skipLineDone() {\n skipLine = false;\n }\n\n /**\n * Reset the {@code DATA} pointer to 0, so that the next {@code READ} statement will read from the first\n * {@code DATA} element again.\n */\n public void resetDataPtr() {\n dataPtr = 0;\n }\n\n /**\n * @return the next {@code DATA} element to be read, and increment the {@link #dataPtr}.\n */\n public Object readNextDataItem() {\n List<Object> dataList = program.getDataList();\n if (dataPtr >= dataList.size()) {\n throw new IllegalStateException(String.format(\"read index %d exceeds size %d\", dataPtr, dataList.size()));\n }\n return dataList.get(dataPtr++);\n }\n\n /**\n * @return the current output file.\n */\n public PrintStream getCurrentOutFile() {\n return currentOutFile;\n }\n\n /**\n * Set the current output file.\n * @param currentOutFile the output file.\n */\n public void setCurrentOutFile(PrintStream currentOutFile) {\n this.currentOutFile = currentOutFile;\n }\n\n /**\n * @return the current input file.\n */\n public BufferedReader getCurrentInFile() {\n return currentInFile;\n }\n\n /**\n * Set the current input file.\n *\n * @param currentInFile the current input file.\n */\n public void setCurrentInFile(BufferedReader currentInFile) {\n this.currentInFile = currentInFile;\n }\n\n /**\n * @return the printer.\n */\n public PrintStream getPrinter() {\n return printer;\n }\n\n /**\n * Set the printer.\n *\n * @param printer the printer.\n */\n public void setPrinter(PrintStream printer) {\n this.printer = printer;\n }\n\n /**\n * Close all open files maintained by the interpreter state. This is about the {@link #currentInFile},\n * {@link #currentOutFile}, and {@link #printer}.\n */\n public void closeFiles() {\n if (null != currentInFile) {\n try {\n currentInFile.close();\n } catch (IOException e) {\n // ignore\n }\n }\n if (null != currentOutFile) {\n currentOutFile.flush();\n currentOutFile.close();\n }\n if (null != printer) {\n printer.flush();\n printer.close();\n }\n }\n\n}"
},
{
"identifier": "Token",
"path": "src/main/java/de/haupz/basicode/parser/Token.java",
"snippet": "public class Token implements java.io.Serializable {\n\n /**\n * The version identifier for this Serializable class.\n * Increment only if the <i>serialized</i> form of the\n * class changes.\n */\n private static final long serialVersionUID = 1L;\n\n /**\n * An integer that describes the kind of this token. This numbering\n * system is determined by JavaCCParser, and a table of these numbers is\n * stored in the file ...Constants.java.\n */\n public int kind;\n\n /** The line number of the first character of this Token. */\n public int beginLine;\n /** The column number of the first character of this Token. */\n public int beginColumn;\n /** The line number of the last character of this Token. */\n public int endLine;\n /** The column number of the last character of this Token. */\n public int endColumn;\n\n /**\n * The string image of the token.\n */\n public String image;\n\n /**\n * A reference to the next regular (non-special) token from the input\n * stream. If this is the last token from the input stream, or if the\n * token manager has not read tokens beyond this one, this field is\n * set to null. This is true only if this token is also a regular\n * token. Otherwise, see below for a description of the contents of\n * this field.\n */\n public Token next;\n\n /**\n * This field is used to access special tokens that occur prior to this\n * token, but after the immediately preceding regular (non-special) token.\n * If there are no such special tokens, this field is set to null.\n * When there are more than one such special token, this field refers\n * to the last of these special tokens, which in turn refers to the next\n * previous special token through its specialToken field, and so on\n * until the first special token (whose specialToken field is null).\n * The next fields of special tokens refer to other special tokens that\n * immediately follow it (without an intervening regular token). If there\n * is no such token, this field is null.\n */\n public Token specialToken;\n\n /**\n * An optional attribute value of the Token.\n * Tokens which are not used as syntactic sugar will often contain\n * meaningful values that will be used later on by the compiler or\n * interpreter. This attribute value is often different from the image.\n * Any subclass of Token that actually wants to return a non-null value can\n * override this method as appropriate.\n */\n public Object getValue() {\n return null;\n }\n\n /**\n * No-argument constructor\n */\n public Token() {}\n\n /**\n * Constructs a new token for the specified Image.\n */\n public Token(int kind)\n {\n this(kind, null);\n }\n\n /**\n * Constructs a new token for the specified Image and Kind.\n */\n public Token(int kind, String image)\n {\n this.kind = kind;\n this.image = image;\n }\n\n /**\n * Returns the image.\n */\n @Override\n public String toString()\n {\n return image;\n }\n\n /**\n * Returns a new Token object, by default. However, if you want, you\n * can create and return subclass objects based on the value of ofKind.\n * Simply add the cases to the switch for all those special cases.\n * For example, if you have a subclass of Token called IDToken that\n * you want to create if ofKind is ID, simply add something like :\n *\n * case MyParserConstants.ID : return new IDToken(ofKind, image);\n *\n * to the following switch statement. Then you can cast matchedToken\n * variable to the appropriate type and use sit in your lexical actions.\n */\n public static Token newToken(int ofKind, String image)\n {\n switch(ofKind)\n {\n default : return new Token(ofKind, image);\n }\n }\n\n public static Token newToken(int ofKind)\n {\n return newToken(ofKind, null);\n }\n\n}"
}
] | import de.haupz.basicode.interpreter.InterpreterState;
import de.haupz.basicode.parser.Token;
import java.util.List; | 5,382 | package de.haupz.basicode.ast;
/**
* The super class of all AST nodes representing BASICODE expressions. It overrides
* {@link BasicNode#run(InterpreterState)} to throw an exception, as this method will not be used in the entire
* hierarchy.
*/
public abstract class ExpressionNode extends BasicNode {
@Override | package de.haupz.basicode.ast;
/**
* The super class of all AST nodes representing BASICODE expressions. It overrides
* {@link BasicNode#run(InterpreterState)} to throw an exception, as this method will not be used in the entire
* hierarchy.
*/
public abstract class ExpressionNode extends BasicNode {
@Override | public final void run(InterpreterState state) { | 0 | 2023-10-14 12:20:59+00:00 | 8k |
Thenuka22/BakerySalesnOrdering_System | BakeryPosSystem/src/bakerypossystem/Model/Menu.java | [
{
"identifier": "Bottom",
"path": "BakeryPosSystem/src/bakerypossystem/Model/Bottom.java",
"snippet": "public class Bottom extends javax.swing.JPanel {\n\n public void setAlpha(float alpha) {\n this.alpha = alpha;\n }\n\n private float alpha;\n\n public Bottom() {\n initComponents();\n setOpaque(false);\n setBackground(new Color(9, 34, 21));\n }\n\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n jLabel1 = new javax.swing.JLabel();\n\n setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));\n\n jLabel1.setFont(new java.awt.Font(\"sansserif\", 1, 14)); // NOI18N\n jLabel1.setForeground(new java.awt.Color(237, 237, 237));\n jLabel1.setText(\"Exit\");\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)\n .addContainerGap())\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addGap(14, 14, 14)\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addGap(17, 17, 17))\n );\n }// </editor-fold>//GEN-END:initComponents\n\n @Override\n public void paint(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));\n g2.setColor(getBackground());\n g2.fillRoundRect(5, 5, getWidth() - 10, getHeight() - 10, 20, 20);\n super.paint(grphcs);\n }\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel jLabel1;\n // End of variables declaration//GEN-END:variables\n}"
},
{
"identifier": "Header",
"path": "BakeryPosSystem/src/bakerypossystem/Model/Header.java",
"snippet": "public class Header extends javax.swing.JPanel {\n\n public void setAlpha(float alpha) {\n this.alpha = alpha;\n }\n\n private float alpha;\n\n public Header() {\n initComponents();\n setOpaque(false);\n }\n\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n jLabel1 = new javax.swing.JLabel();\n\n jLabel1.setFont(new java.awt.Font(\"sansserif\", 1, 18)); // NOI18N\n jLabel1.setForeground(new java.awt.Color(255, 255, 255));\n jLabel1.setText(\"Bakery Shop\");\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()\n .addGap(14, 14, 14)\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addContainerGap())\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addComponent(jLabel1)\n .addContainerGap(12, Short.MAX_VALUE))\n );\n }// </editor-fold>//GEN-END:initComponents\n\n @Override\n public void paint(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));\n super.paint(grphcs);\n }\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel jLabel1;\n // End of variables declaration//GEN-END:variables\n}"
},
{
"identifier": "EventMenuSelected",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/EventMenuSelected.java",
"snippet": "public interface EventMenuSelected {\n\n public void selected(int index);\n}"
},
{
"identifier": "MenuController",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/MenuController.java",
"snippet": "public class MenuController {\n\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public Icon getIcon() {\n return icon;\n }\n\n public void setIcon(Icon icon) {\n this.icon = icon;\n }\n\n public MenuController(String menuName, Icon icon) {\n this.menuName = menuName;\n this.icon = icon;\n }\n\n public MenuController() {\n }\n\n private String menuName;\n private Icon icon;\n}"
},
{
"identifier": "MenuController",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/MenuController.java",
"snippet": "public class MenuController {\n\n public String getMenuName() {\n return menuName;\n }\n\n public void setMenuName(String menuName) {\n this.menuName = menuName;\n }\n\n public Icon getIcon() {\n return icon;\n }\n\n public void setIcon(Icon icon) {\n this.icon = icon;\n }\n\n public MenuController(String menuName, Icon icon) {\n this.menuName = menuName;\n this.icon = icon;\n }\n\n public MenuController() {\n }\n\n private String menuName;\n private Icon icon;\n}"
},
{
"identifier": "ButtonCustom",
"path": "BakeryPosSystem/src/CustomComponents/ButtonCustom.java",
"snippet": "public class ButtonCustom extends JButton {\n\n public ButtonCustom() {\n setContentAreaFilled(false);\n setCursor(new Cursor(Cursor.HAND_CURSOR));\n setBackground(new Color(65, 152, 216));\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(getBackground());\n g2.fillRoundRect(10, 10, getWidth() - 20, getHeight() - 20, 20, 20);\n super.paintComponent(grphcs);\n }\n}"
},
{
"identifier": "ButtonCustom",
"path": "BakeryPosSystem/src/CustomComponents/ButtonCustom.java",
"snippet": "public class ButtonCustom extends JButton {\n\n public ButtonCustom() {\n setContentAreaFilled(false);\n setCursor(new Cursor(Cursor.HAND_CURSOR));\n setBackground(new Color(65, 152, 216));\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(getBackground());\n g2.fillRoundRect(10, 10, getWidth() - 20, getHeight() - 20, 20, 20);\n super.paintComponent(grphcs);\n }\n}"
},
{
"identifier": "EventMenuSelected",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/EventMenuSelected.java",
"snippet": "public interface EventMenuSelected {\n\n public void selected(int index);\n}"
},
{
"identifier": "MenuItem",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/MenuItem.java",
"snippet": "public class MenuItem extends javax.swing.JPanel {\n\n public int getIndex() {\n return index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n public boolean isSelected() {\n return selected;\n }\n\n public void setSelected(boolean selected) {\n this.selected = selected;\n repaint();\n }\n\n private final List<EventMenuSelected> events = new ArrayList<>();\n private int index;\n private boolean selected;\n private boolean mouseOver;\n\n public MenuItem(Icon icon, String name, int index) {\n initComponents();\n setOpaque(false);\n this.index = index;\n lbIcon.setIcon(icon);\n lbName.setText(name);\n addMouseListener(new MouseAdapter() {\n @Override\n public void mouseEntered(MouseEvent me) {\n mouseOver = true;\n }\n\n @Override\n public void mouseExited(MouseEvent me) {\n mouseOver = false;\n }\n\n @Override\n public void mouseReleased(MouseEvent me) {\n if (SwingUtilities.isLeftMouseButton(me)) {\n if (mouseOver) {\n setSelected(true);\n repaint();\n runEvent();\n }\n }\n }\n });\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n if (selected) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(new Color(1, 122, 167));\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));\n g2.fillRect(0, 0, getWidth(), getHeight());\n g2.setComposite(AlphaComposite.SrcOver);\n g2.setColor(new Color(245, 245, 245));\n g2.fillRect(0, 0, 2, getHeight());\n }\n super.paintComponent(grphcs);\n }\n\n private void runEvent() {\n for (EventMenuSelected event : events) {\n event.selected(index);\n }\n }\n\n public void addEvent(EventMenuSelected event) {\n events.add(event);\n }\n\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n lbIcon = new javax.swing.JLabel();\n lbName = new javax.swing.JLabel();\n\n lbIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);\n\n lbName.setFont(new java.awt.Font(\"sansserif\", 1, 14)); // NOI18N\n lbName.setForeground(new java.awt.Color(250, 250, 250));\n lbName.setText(\"Menu Name\");\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addGap(10, 10, 10)\n .addComponent(lbIcon, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(10, 10, 10)\n .addComponent(lbName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addGap(10, 10, 10))\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)\n .addComponent(lbIcon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(lbName, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n }// </editor-fold>//GEN-END:initComponents\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel lbIcon;\n private javax.swing.JLabel lbName;\n // End of variables declaration//GEN-END:variables\n}"
},
{
"identifier": "MenuItem",
"path": "BakeryPosSystem/src/bakerypossystem/Controller/MenuItem.java",
"snippet": "public class MenuItem extends javax.swing.JPanel {\n\n public int getIndex() {\n return index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n public boolean isSelected() {\n return selected;\n }\n\n public void setSelected(boolean selected) {\n this.selected = selected;\n repaint();\n }\n\n private final List<EventMenuSelected> events = new ArrayList<>();\n private int index;\n private boolean selected;\n private boolean mouseOver;\n\n public MenuItem(Icon icon, String name, int index) {\n initComponents();\n setOpaque(false);\n this.index = index;\n lbIcon.setIcon(icon);\n lbName.setText(name);\n addMouseListener(new MouseAdapter() {\n @Override\n public void mouseEntered(MouseEvent me) {\n mouseOver = true;\n }\n\n @Override\n public void mouseExited(MouseEvent me) {\n mouseOver = false;\n }\n\n @Override\n public void mouseReleased(MouseEvent me) {\n if (SwingUtilities.isLeftMouseButton(me)) {\n if (mouseOver) {\n setSelected(true);\n repaint();\n runEvent();\n }\n }\n }\n });\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n if (selected) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(new Color(1, 122, 167));\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));\n g2.fillRect(0, 0, getWidth(), getHeight());\n g2.setComposite(AlphaComposite.SrcOver);\n g2.setColor(new Color(245, 245, 245));\n g2.fillRect(0, 0, 2, getHeight());\n }\n super.paintComponent(grphcs);\n }\n\n private void runEvent() {\n for (EventMenuSelected event : events) {\n event.selected(index);\n }\n }\n\n public void addEvent(EventMenuSelected event) {\n events.add(event);\n }\n\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n lbIcon = new javax.swing.JLabel();\n lbName = new javax.swing.JLabel();\n\n lbIcon.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);\n\n lbName.setFont(new java.awt.Font(\"sansserif\", 1, 14)); // NOI18N\n lbName.setForeground(new java.awt.Color(250, 250, 250));\n lbName.setText(\"Menu Name\");\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addGap(10, 10, 10)\n .addComponent(lbIcon, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)\n .addGap(10, 10, 10)\n .addComponent(lbName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addGap(10, 10, 10))\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGroup(layout.createSequentialGroup()\n .addContainerGap()\n .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)\n .addComponent(lbIcon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n .addComponent(lbName, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))\n .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n );\n }// </editor-fold>//GEN-END:initComponents\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel lbIcon;\n private javax.swing.JLabel lbName;\n // End of variables declaration//GEN-END:variables\n}"
}
] | import bakerypossystem.Model.Bottom;
import bakerypossystem.Model.Header;
import bakerypossystem.Controller.EventMenuSelected;
import bakerypossystem.Controller.MenuController;
import bakerypossystem.Controller.MenuController;
import CustomComponents.ButtonCustom;
import CustomComponents.ButtonCustom;
import bakerypossystem.Controller.EventMenuSelected;
import bakerypossystem.Controller.MenuItem;
import bakerypossystem.Controller.MenuItem;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout; | 4,286 | package bakerypossystem.Model;
public class Menu extends javax.swing.JPanel {
public void setEvent(EventMenuSelected event) {
this.event = event;
}
private MigLayout layout;
private JPanel panelMenu;
private JButton cmdMenu;
private JButton cmdLogOut;
private Header header;
private Bottom bottom;
private EventMenuSelected event;
public Menu() {
initComponents();
setOpaque(false);
init();
}
private void init() {
setLayout(new MigLayout("wrap, fillx, insets 0", "[fill]", "5[]0[]push[60]0"));
panelMenu = new JPanel();
header = new Header();
bottom = new Bottom();
createButtonMenu();
createButtonLogout();
panelMenu.setOpaque(false);
layout = new MigLayout("fillx, wrap", "0[fill]0", "0[]3[]0");
panelMenu.setLayout(layout);
add(cmdMenu, "pos 1al 0al 100% 50");
add(cmdLogOut, "pos 1al 1al 100% 100, height 60!");
add(header);
add(panelMenu);
add(bottom);
}
public void addMenu(MenuController menu) {
MenuItem item = new MenuItem(menu.getIcon(), menu.getMenuName(), panelMenu.getComponentCount());
item.addEvent(new EventMenuSelected() {
@Override
public void selected(int index) {
clearMenu(index);
}
});
item.addEvent(event);
panelMenu.add(item);
}
private void createButtonMenu() {
cmdMenu = new JButton();
cmdMenu.setContentAreaFilled(false);
cmdMenu.setCursor(new Cursor(Cursor.HAND_CURSOR));
cmdMenu.setIcon(new ImageIcon(getClass().getResource("/icon/menu.png")));
cmdMenu.setBorder(new EmptyBorder(5, 12, 5, 12));
}
private void createButtonLogout() { | package bakerypossystem.Model;
public class Menu extends javax.swing.JPanel {
public void setEvent(EventMenuSelected event) {
this.event = event;
}
private MigLayout layout;
private JPanel panelMenu;
private JButton cmdMenu;
private JButton cmdLogOut;
private Header header;
private Bottom bottom;
private EventMenuSelected event;
public Menu() {
initComponents();
setOpaque(false);
init();
}
private void init() {
setLayout(new MigLayout("wrap, fillx, insets 0", "[fill]", "5[]0[]push[60]0"));
panelMenu = new JPanel();
header = new Header();
bottom = new Bottom();
createButtonMenu();
createButtonLogout();
panelMenu.setOpaque(false);
layout = new MigLayout("fillx, wrap", "0[fill]0", "0[]3[]0");
panelMenu.setLayout(layout);
add(cmdMenu, "pos 1al 0al 100% 50");
add(cmdLogOut, "pos 1al 1al 100% 100, height 60!");
add(header);
add(panelMenu);
add(bottom);
}
public void addMenu(MenuController menu) {
MenuItem item = new MenuItem(menu.getIcon(), menu.getMenuName(), panelMenu.getComponentCount());
item.addEvent(new EventMenuSelected() {
@Override
public void selected(int index) {
clearMenu(index);
}
});
item.addEvent(event);
panelMenu.add(item);
}
private void createButtonMenu() {
cmdMenu = new JButton();
cmdMenu.setContentAreaFilled(false);
cmdMenu.setCursor(new Cursor(Cursor.HAND_CURSOR));
cmdMenu.setIcon(new ImageIcon(getClass().getResource("/icon/menu.png")));
cmdMenu.setBorder(new EmptyBorder(5, 12, 5, 12));
}
private void createButtonLogout() { | cmdLogOut = new ButtonCustom(); | 6 | 2023-10-11 16:55:32+00:00 | 8k |
giteecode/bookmanage2-public | nhXJH-admin/src/main/java/com/nhXJH/web/domain/BaseDeptAuthority.java | [
{
"identifier": "SysDept",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysDept.java",
"snippet": "public class SysDept extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 部门ID */\n private Long deptId;\n\n /** 父部门ID */\n private Long parentId;\n\n /** 祖级列表 */\n private String ancestors;\n\n /** 部门名称 */\n private String deptName;\n\n /** 显示顺序 */\n private String orderNum;\n\n /** 负责人 */\n private String leader;\n\n /** 联系电话 */\n private String phone;\n\n /** 邮箱 */\n private String email;\n\n /** 部门状态:0正常,1停用 */\n @Excel(name = \"状态\",readConverterExp=\"1=失效,0=有效\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 父部门名称 */\n private String parentName;\n \n /** 子部门 */\n private List<SysDept> children = new ArrayList<SysDept>();\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getParentId() {\n return parentId;\n }\n\n public void setParentId(Long parentId) {\n this.parentId = parentId;\n }\n\n public String getAncestors() {\n return ancestors;\n }\n\n public void setAncestors(String ancestors) {\n this.ancestors = ancestors;\n }\n\n @NotBlank(message = \"部门名称不能为空\")\n @Size(min = 0, max = 30, message = \"部门名称长度不能超过30个字符\")\n public String getDeptName() {\n return deptName;\n }\n\n public void setDeptName(String deptName) {\n this.deptName = deptName;\n }\n\n @NotBlank(message = \"显示顺序不能为空\")\n public String getOrderNum() {\n return orderNum;\n }\n\n public void setOrderNum(String orderNum) {\n this.orderNum = orderNum;\n }\n\n public String getLeader() {\n return leader;\n }\n\n public void setLeader(String leader) {\n this.leader = leader;\n }\n\n @Size(min = 0, max = 11, message = \"联系电话长度不能超过11个字符\")\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\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 getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public String getParentName() {\n return parentName;\n }\n\n public void setParentName(String parentName) {\n this.parentName = parentName;\n }\n\n public List<SysDept> getChildren() {\n return children;\n }\n\n public void setChildren(List<SysDept> children) {\n this.children = children;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"deptId\", getDeptId())\n .append(\"parentId\", getParentId())\n .append(\"ancestors\", getAncestors())\n .append(\"deptName\", getDeptName())\n .append(\"orderNum\", getOrderNum())\n .append(\"leader\", getLeader())\n .append(\"phone\", getPhone())\n .append(\"email\", getEmail())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .toString();\n }\n}"
},
{
"identifier": "SysUser",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysUser.java",
"snippet": "public class SysUser extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /** 用户账号 */\n @Excel(name = \"登录名称\")\n private String userName;\n\n /** 用户昵称 */\n @Excel(name = \"用户名称\")\n private String nickName;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 手机号码 */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /** 用户性别 */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 用户头像 */\n private String avatar;\n\n /** 密码 */\n private String password;\n\n /** 盐加密 */\n private String salt;\n\n /** 帐号状态(0正常 1停用) */\n @Excel(name = \"帐号状态(0=正常,1=停用)\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 最后登录IP */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /** 最后登录时间 */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /** 部门对象 */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private SysDept dept;\n\n /** 角色对象 */\n private List<SysRole> roles;\n\n /** 角色组 */\n private Long[] roleIds;\n\n /** 岗位组 */\n private Long[] postIds;\n\n /** 角色ID */\n private Long roleId;\n\n public SysUser() {\n\n }\n\n public SysUser(Long userId) {\n this.userId = userId;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public boolean isAdmin() {\n return isAdmin(this.userId);\n }\n\n public static boolean isAdmin(Long userId) {\n return userId != null && 1L == userId;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getNickName() {\n return nickName;\n }\n\n public void setNickName(String nickName) {\n this.nickName = nickName;\n }\n\n @Xss(message = \"用户账号不能包含脚本字符\")\n @NotBlank(message = \"用户账号不能为空\")\n @Size(min = 0, max = 30, message = \"用户账号长度不能超过30个字符\")\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber() {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber) {\n this.phonenumber = phonenumber;\n }\n\n public String getSex() {\n return sex;\n }\n\n public void setSex(String sex) {\n this.sex = sex;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n @JsonProperty\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getSalt() {\n return salt;\n }\n\n public void setSalt(String salt) {\n this.salt = salt;\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 getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp() {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp) {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate() {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate) {\n this.loginDate = loginDate;\n }\n\n public SysDept getDept() {\n return dept;\n }\n\n public void setDept(SysDept dept) {\n this.dept = dept;\n }\n\n public List<SysRole> getRoles() {\n return roles;\n }\n\n public void setRoles(List<SysRole> roles) {\n this.roles = roles;\n }\n\n public Long[] getRoleIds() {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds) {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds() {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds) {\n this.postIds = postIds;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"userName\", getUserName())\n .append(\"nickName\", getNickName())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .toString();\n }\n}"
},
{
"identifier": "BaseEntity",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/BaseEntity.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\npublic class BaseEntity implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /** 搜索值 */\n private String searchValue;\n\n /** 创建者 */\n private String createBy;\n\n /** 创建时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date createTime;\n\n /** 更新者 */\n private String updateBy;\n\n /** 更新时间 */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date updateTime;\n\n /** 备注 */\n private String remark;\n\n /** 是否被删除 */\n private String isDel;\n /** 状态,默认1 */\n\n /** 创建人 */\n private Long createPersonal;\n\n /** 更新人 */\n private Long updatePersonal;\n\n\n /** 请求参数 */\n private Map<String, Object> params;\n\n public Map<String, Object> getParams() {\n if (params == null) {\n params = new HashMap<>();\n }\n return params;\n }\n\n public Long getSnowID(){\n try {\n Thread.sleep(1);\n SnowFlakeUtil snowFlakeUtil = new SnowFlakeUtil();\n return snowFlakeUtil.snowflakeId();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n return getSnowID();\n }\n}"
}
] | import com.nhXJH.common.annotation.Excels;
import com.nhXJH.common.core.domain.entity.SysDept;
import com.nhXJH.common.core.domain.entity.SysUser;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.nhXJH.common.annotation.Excel;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.nhXJH.common.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.nhXJH.common.core.domain.BaseEntity; | 3,927 | package com.nhXJH.web.domain;
/**
* 用户可访问部门信息对象 base_dept_authority
*
* @author xjh
* @date 2022-02-27
*/
@TableName("base_dept_authority")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseDeptAuthority extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
@ApiModelProperty("id")
private Long id;
/** 部门id */
// @Excel(name = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@Excels({
@Excel(name = "可访问部门",targetAttr = "deptName",type = Excel.Type.EXPORT)
})
private SysDept dept;
/** 用户id */
// @Excel(name = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@Excels({
@Excel(name = "用户名",targetAttr = "userName",type = Excel.Type.EXPORT)
}) | package com.nhXJH.web.domain;
/**
* 用户可访问部门信息对象 base_dept_authority
*
* @author xjh
* @date 2022-02-27
*/
@TableName("base_dept_authority")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseDeptAuthority extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
@ApiModelProperty("id")
private Long id;
/** 部门id */
// @Excel(name = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@Excels({
@Excel(name = "可访问部门",targetAttr = "deptName",type = Excel.Type.EXPORT)
})
private SysDept dept;
/** 用户id */
// @Excel(name = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@Excels({
@Excel(name = "用户名",targetAttr = "userName",type = Excel.Type.EXPORT)
}) | private SysUser sysUser; | 1 | 2023-10-13 07:19:20+00:00 | 8k |
M-D-Team/ait-fabric-1.20.1 | src/main/java/mdteam/ait/core/item/ArtronCollectorItem.java | [
{
"identifier": "ConsoleBlockEntity",
"path": "src/main/java/mdteam/ait/core/blockentities/ConsoleBlockEntity.java",
"snippet": "public class ConsoleBlockEntity extends BlockEntity implements BlockEntityTicker<ConsoleBlockEntity> {\n public final AnimationState ANIM_FLIGHT = new AnimationState();\n public int animationTimer = 0;\n public final List<ConsoleControlEntity> controlEntities = new ArrayList<>();\n private boolean needsControls = true;\n private boolean needsSync = true;\n private UUID tardisId;\n private Identifier type;\n private Identifier variant;\n private boolean wasPowered = false;\n private boolean needsReloading = true; // this is to ensure we get properly synced when reloaded yup ( does not work for multipalery : (\n\n public static final Identifier SYNC_TYPE = new Identifier(AITMod.MOD_ID, \"sync_console_type\");\n public static final Identifier SYNC_VARIANT = new Identifier(AITMod.MOD_ID, \"sync_console_variant\");\n public static final Identifier ASK = new Identifier(AITMod.MOD_ID, \"client_ask_console\");\n\n public ConsoleBlockEntity(BlockPos pos, BlockState state) {\n super(AITBlockEntityTypes.CONSOLE_BLOCK_ENTITY_TYPE, pos, state);\n Tardis found = TardisUtil.findTardisByPosition(pos);\n if (found != null)\n this.setTardis(found);\n }\n\n @Override\n public void writeNbt(NbtCompound nbt) {\n if (this.getTardis() == null) {\n AITMod.LOGGER.error(\"this.getTardis() is null! Is \" + this + \" invalid? BlockPos: \" + \"(\" + this.getPos().toShortString() + \")\");\n }\n\n if (type != null)\n nbt.putString(\"type\", type.toString());\n if (variant != null)\n nbt.putString(\"variant\", variant.toString());\n\n super.writeNbt(nbt);\n if (this.tardisId != null)\n nbt.putString(\"tardis\", this.tardisId.toString());\n }\n\n @Override\n public void readNbt(NbtCompound nbt) {\n super.readNbt(nbt);\n if (nbt.contains(\"tardis\")) {\n this.setTardis(UUID.fromString(nbt.getString(\"tardis\")));\n }\n\n if (nbt.contains(\"type\"))\n setType(Identifier.tryParse(nbt.getString(\"type\")));\n if (nbt.contains(\"variant\")) {\n setVariant(Identifier.tryParse(nbt.getString(\"variant\")));\n }\n\n spawnControls();\n markNeedsSyncing();\n markDirty();\n }\n\n @Override\n public NbtCompound toInitialChunkDataNbt() {\n NbtCompound nbt = super.toInitialChunkDataNbt();\n if (nbt.contains(\"type\"))\n setType(ConsoleRegistry.REGISTRY.get(Identifier.tryParse(nbt.getString(\"type\"))));\n if (nbt.contains(\"variant\")) {\n setVariant(Identifier.tryParse(nbt.getString(\"variant\")));\n }\n\n if (type != null)\n nbt.putString(\"type\", type.toString());\n if (variant != null)\n nbt.putString(\"variant\", variant.toString());\n markNeedsControl();\n markNeedsSyncing();\n markDirty();\n return nbt;\n }\n\n @Nullable\n @Override\n public Packet<ClientPlayPacketListener> toUpdatePacket() {\n return BlockEntityUpdateS2CPacket.create(this);\n }\n\n public Tardis getTardis() {\n if (this.tardisId == null) {\n AITMod.LOGGER.warn(\"Console at \" + this.getPos() + \" is finding TARDIS!\");\n this.findTardis();\n }\n\n if (isClient()) {\n return ClientTardisManager.getInstance().getLookup().get(this.tardisId);\n }\n\n return ServerTardisManager.getInstance().getTardis(this.tardisId);\n }\n\n private void findTardis() {\n this.setTardis(TardisUtil.findTardisByInterior(pos));\n markDirty();\n }\n\n public void ask() {\n if (!getWorld().isClient()) return;\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeBlockPos(this.getPos());\n ClientPlayNetworking.send(ASK, buf);\n }\n\n public void sync() {\n if (isClient()) return;\n\n // ServerTardisManager.getInstance().sendToSubscribers(this.getTardis());\n // getTardis().markDirty();\n syncType();\n syncVariant();\n /*getWorld().updateListeners(getPos(), getWorld().getBlockState(getPos()), getWorld().getBlockState(getPos()), Block.NOTIFY_ALL);*/\n needsSync = false;\n }\n\n private void syncType() {\n if (!hasWorld() || world.isClient()) return;\n\n PacketByteBuf buf = PacketByteBufs.create();\n\n buf.writeString(getConsoleSchema().id().toString());\n buf.writeBlockPos(getPos());\n\n for (PlayerEntity player : world.getPlayers()) {\n ServerPlayNetworking.send((ServerPlayerEntity) player, SYNC_TYPE, buf); // safe cast as we know its server\n }\n }\n\n private void syncVariant() {\n if (!hasWorld() || world.isClient()) return;\n\n PacketByteBuf buf = PacketByteBufs.create();\n\n buf.writeString(getVariant().id().toString());\n buf.writeBlockPos(getPos());\n\n for (PlayerEntity player : world.getPlayers()) {\n ServerPlayNetworking.send((ServerPlayerEntity) player, SYNC_VARIANT, buf); // safe cast as we know its server\n }\n }\n\n public void setTardis(Tardis tardis) {\n if (tardis == null) {\n AITMod.LOGGER.error(\"Tardis was null in ConsoleBlockEntity at \" + this.getPos());\n return;\n }\n\n this.tardisId = tardis.getUuid();\n // force re-link a desktop if it's not null\n this.linkDesktop();\n }\n\n public void setTardis(UUID uuid) {\n this.tardisId = uuid;\n\n this.linkDesktop();\n }\n\n public void linkDesktop() {\n if (this.getTardis() == null)\n return;\n if (this.getTardis() != null)\n this.setDesktop(this.getDesktop());\n }\n\n public TardisDesktop getDesktop() {\n return this.getTardis().getDesktop();\n }\n\n public ConsoleSchema getConsoleSchema() {\n if (type == null) setType(ConsoleRegistry.HARTNELL);\n\n return ConsoleRegistry.REGISTRY.get(type);\n }\n\n public void setType(Identifier var) {\n type = var;\n\n syncType();\n markDirty();\n }\n public void setType(ConsoleSchema schema) {\n setType(schema.id());\n }\n\n\n public ConsoleVariantSchema getVariant() {\n if (variant == null) {\n // oh no : (\n // lets just pick any\n setVariant(ConsoleVariantRegistry.withParent(getConsoleSchema()).stream().findAny().get());\n }\n\n return ConsoleVariantRegistry.REGISTRY.get(variant);\n }\n public void setVariant(Identifier var) {\n variant = var;\n\n if (!(getVariant().parent().id().equals(type))) {\n AITMod.LOGGER.warn(\"Variant was set and it doesnt match this consoles type!\");\n AITMod.LOGGER.warn(variant + \" | \" + type);\n\n if (hasWorld() && getWorld().isClient()) ask();\n }\n\n syncVariant();\n markDirty();\n }\n public void setVariant(ConsoleVariantSchema schema) {\n setVariant(schema.id());\n }\n\n /**\n * Sets the new {@link ConsoleSchema} and refreshes the console entities\n */\n private void changeConsole(ConsoleSchema var) {\n changeConsole(var, ConsoleVariantRegistry.withParent(var).stream().findAny().get());\n }\n\n private void changeConsole(ConsoleSchema var, ConsoleVariantSchema variant) {\n setType(var);\n setVariant(variant);\n\n if (!world.isClient() && world == TardisUtil.getTardisDimension())\n redoControls();\n }\n\n private void redoControls() {\n killControls();\n markNeedsControl();\n }\n\n public static ConsoleSchema nextConsole(ConsoleSchema current) {\n List<ConsoleSchema> list = ConsoleRegistry.REGISTRY.stream().toList();\n\n int idx = list.indexOf(current);\n if (idx < 0 || idx+1 == list.size()) return list.get(0);\n return list.get(idx + 1);\n }\n public static ConsoleVariantSchema nextVariant(ConsoleVariantSchema current) {\n List<ConsoleVariantSchema> list = ConsoleVariantRegistry.withParent(current.parent());\n\n int idx = list.indexOf(current);\n if (idx < 0 || idx+1 == list.size()) return list.get(0);\n return list.get(idx + 1);\n }\n\n public void useOn(World world, boolean sneaking, PlayerEntity player) {\n if (player == null)\n return;\n\n// if (world != TardisUtil.getTardisDimension())\n// return;\n\n /* if (player.getMainHandStack().getItem() == Items.STICK) changeConsole(nextConsole(getConsoleSchema()));\n if (player.getMainHandStack().getItem() == Items.BONE) setVariant(nextVariant(getVariant()));\n if (player.getMainHandStack().getItem() == Items.SHEARS) {\n world.breakBlock(pos, true);\n for (ConsoleControlEntity entity : controlEntities) {\n entity.discard();\n }\n world.spawnEntity(new ItemEntity(world, pos.getX() + 0.5f, pos.getY(), pos.getZ() + 0.5f, new ItemStack(AITBlocks.CONSOLE)));\n this.getDesktop().setConsolePos(null);\n markRemoved();\n }*/\n }\n\n @Override\n public void markRemoved() {\n this.killControls();\n super.markRemoved();\n }\n\n public void setDesktop(TardisDesktop desktop) {\n if (isClient()) return;\n\n desktop.setConsolePos(new AbsoluteBlockPos.Directed(\n this.pos, TardisUtil.getTardisDimension(), this.getCachedState().get(HorizontalDirectionalBlock.FACING))\n );\n }\n\n public boolean wasPowered() {\n if(this.getTardis() == null) return false;\n return this.wasPowered ^ this.getTardis().hasPower();\n }\n\n public void checkAnimations() {\n // DO NOT RUN THIS ON SERVER!!\n\n animationTimer++;\n\n ANIM_FLIGHT.startIfNotRunning(animationTimer);\n }\n\n\n public void onBroken() {\n this.killControls();\n }\n\n public void killControls() {\n controlEntities.forEach(Entity::discard);\n controlEntities.clear();\n sync();\n }\n\n public void spawnControls() {\n BlockPos current = getPos();\n\n if (!(getWorld() instanceof ServerWorld server))\n return;\n if (getWorld().getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD)\n return;\n\n killControls();\n ConsoleSchema consoleType = getConsoleSchema();\n ControlTypes[] controls = consoleType.getControlTypes();\n Arrays.stream(controls).toList().forEach(control -> {\n\n ConsoleControlEntity controlEntity = new ConsoleControlEntity(AITEntityTypes.CONTROL_ENTITY_TYPE, getWorld());\n\n Vector3f position = current.toCenterPos().toVector3f().add(control.getOffset().x(), control.getOffset().y(), control.getOffset().z());\n controlEntity.setPosition(position.x(), position.y(), position.z());\n controlEntity.setYaw(0.0f);\n controlEntity.setPitch(0.0f);\n\n controlEntity.setControlData(consoleType, control, this.getPos());\n\n server.spawnEntity(controlEntity);\n this.controlEntities.add(controlEntity);\n });\n\n this.needsControls = false;\n //System.out.println(\"SpawnControls(): I'm getting run :) somewhere..\");\n }\n\n public void markNeedsControl() {\n this.needsControls = true;\n }\n public void markNeedsSyncing() {\n this.needsSync = true;\n }\n\n @Override\n public void tick(World world, BlockPos pos, BlockState state, ConsoleBlockEntity blockEntity) {\n if (this.needsControls) {\n spawnControls();\n }\n if (needsSync)\n sync();\n if (needsReloading) {\n markNeedsSyncing();\n needsReloading = false;\n }\n\n /*List<ConsoleControlEntity> entitiesNeedingControl = new ArrayList<>();\n Box entityBox = new Box(pos.north(2).east(2).up(2), pos.south(2).west(2).down(2));\n List<ConsoleControlEntity> entities = TardisUtil.getTardisDimension().getEntitiesByClass(ConsoleControlEntity.class, entityBox, (e) -> true);\n\n for (ConsoleControlEntity entity : controlEntities) {\n if (entities.isEmpty()) {\n entitiesNeedingControl.add(entity);\n }\n }\n\n controlEntities.removeAll(entitiesNeedingControl);\n\n if (!entitiesNeedingControl.isEmpty()) {\n markNeedsControl();\n }*/\n\n if (world.getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) {\n this.markRemoved();\n }\n\n // idk\n if (world.isClient()) {\n this.checkAnimations();\n }\n }\n\n}"
},
{
"identifier": "ExteriorBlockEntity",
"path": "src/main/java/mdteam/ait/core/blockentities/ExteriorBlockEntity.java",
"snippet": "public class ExteriorBlockEntity extends BlockEntity implements BlockEntityTicker<ExteriorBlockEntity> { // fixme copy tardishandler and refactor to use uuids instead, this is incredibly inefficient and the main cause of lag.\n private UUID tardisId;\n public int animationTimer = 0;\n public final AnimationState DOOR_STATE = new AnimationState();\n private ExteriorAnimation animation;\n\n public ExteriorBlockEntity(BlockPos pos, BlockState state) {\n super(AITBlockEntityTypes.EXTERIOR_BLOCK_ENTITY_TYPE, pos, state);\n }\n\n public void useOn(ServerWorld world, boolean sneaking, PlayerEntity player) {\n if (player == null)\n return;\n if (this.getTardis().isGrowth())\n return;\n\n if (player.getMainHandStack().getItem() instanceof KeyItem && !getTardis().isSiegeMode() && !getTardis().getHandlers().getInteriorChanger().isGenerating()) {\n ItemStack key = player.getMainHandStack();\n NbtCompound tag = key.getOrCreateNbt();\n if (!tag.contains(\"tardis\")) {\n return;\n }\n if (Objects.equals(this.getTardis().getUuid().toString(), tag.getString(\"tardis\"))) {\n DoorHandler.toggleLock(this.getTardis(), (ServerPlayerEntity) player);\n } else {\n world.playSound(null, pos, SoundEvents.BLOCK_NOTE_BLOCK_BIT.value(), SoundCategory.BLOCKS, 1F, 0.2F);\n player.sendMessage(Text.literal(\"TARDIS does not identify with key\"), true);\n }\n return;\n }\n\n if (sneaking && getTardis().isSiegeMode() && !getTardis().isSiegeBeingHeld()) {\n SiegeTardisItem.pickupTardis(getTardis(), (ServerPlayerEntity) player);\n return;\n }\n\n DoorHandler.useDoor(this.getTardis(), (ServerWorld) this.getWorld(), this.getPos(), (ServerPlayerEntity) player);\n // fixme maybe this is required idk the doorhandler already marks the tardis dirty || tardis().markDirty();\n if (sneaking)\n return;\n }\n\n @Nullable\n @Override\n public Packet<ClientPlayPacketListener> toUpdatePacket() {\n return BlockEntityUpdateS2CPacket.create(this);\n }\n\n @Override\n public void writeNbt(NbtCompound nbt) {\n if (this.getTardis() == null) {\n AITMod.LOGGER.error(\"this.tardis() is null! Is \" + this + \" invalid? BlockPos: \" + \"(\" + this.getPos().toShortString() + \")\");\n }\n super.writeNbt(nbt);\n if (tardisId != null)\n nbt.putString(\"tardis\", this.tardisId.toString());\n nbt.putFloat(\"alpha\", this.getAlpha());\n }\n\n @Override\n public void readNbt(NbtCompound nbt) {\n super.readNbt(nbt);\n if (nbt.contains(\"tardis\")) {\n this.tardisId = UUID.fromString(nbt.getString(\"tardis\"));\n }\n if (this.getAnimation() != null)\n this.getAnimation().setAlpha(nbt.getFloat(\"alpha\"));\n if(this.getTardis() != null)\n this.getTardis().markDirty();\n }\n\n public void onEntityCollision(Entity entity) {\n if (this.getTardis() != null && this.getTardis().getDoor().isOpen()) {\n if (!this.getTardis().getLockedTardis())\n if (!DependencyChecker.hasPortals() || !getTardis().getExterior().getType().hasPortals())\n TardisUtil.teleportInside(this.getTardis(), entity);\n }\n }\n\n public Tardis getTardis() {\n if (this.tardisId == null) {\n //AITMod.LOGGER.warn(\"Exterior at \" + this.getPos() + \" is finding TARDIS!\");\n this.findTardisFromPosition();\n }\n\n if (isClient()) {\n return ClientTardisManager.getInstance().getLookup().get(this.tardisId);\n }\n\n return ServerTardisManager.getInstance().getTardis(this.tardisId);\n }\n\n public void setTardis(Tardis tardis) {\n this.tardisId = tardis.getUuid();\n }\n\n private void findTardisFromPosition() { // should only be used if tardisId is null so we can hopefully refind the tardis\n Tardis found = findTardisByPosition(this.getPos());\n\n if (found == null) return;\n\n this.tardisId = found.getUuid();\n }\n\n @Override\n public void tick(World world, BlockPos pos, BlockState blockState, ExteriorBlockEntity blockEntity) {\n if (this.animation != null)\n this.getAnimation().tick();\n\n if(world.isClient()) {\n this.checkAnimations();\n }\n\n if (this.getTardis() == null) return;\n\n // Should be when tardis is set to landed / position is changed instead. fixme\n if (!world.isClient() && (blockState.getBlock() instanceof ExteriorBlock)) {\n // For checking falling\n ((ExteriorBlock) blockState.getBlock()).tryFall(blockState, (ServerWorld) world, pos);\n }\n\n if (!world.isClient() && this.getTardis() != null && !PropertiesHandler.getBool(this.getTardis().getHandlers().getProperties(), PropertiesHandler.PREVIOUSLY_LOCKED) && this.getTardis().getTravel().getState() == MAT && this.getAlpha() >= 0.9f) {\n for (ServerPlayerEntity entity : world.getEntitiesByClass(ServerPlayerEntity.class, new Box(this.getPos()).expand(0, 1, 0), EntityPredicates.EXCEPT_SPECTATOR)) {\n TardisUtil.teleportInside(this.getTardis(), entity); // fixme i dont like how this works you can just run into peoples tardises while theyre landing\n }\n }\n\n // ensures we dont exist during flight\n if (!world.isClient() && this.getTardis().getTravel().getState() == FLIGHT) {\n world.removeBlock(this.getPos(), false);\n }\n }\n\n // es caca\n public void verifyAnimation() {\n if (this.animation != null || this.getTardis() == null || this.getTardis().getExterior() == null)\n return;\n\n this.animation = this.getTardis().getExterior().getVariant().animation(this);\n AITMod.LOGGER.warn(\"Created new ANIMATION for \" + this);\n this.animation.setupAnimation(this.getTardis().getTravel().getState());\n\n if (this.getWorld() != null) {\n if (!this.getWorld().isClient()) {\n this.animation.tellClientsToSetup(this.getTardis().getTravel().getState());\n }\n }\n }\n\n public void checkAnimations() {\n // DO NOT RUN THIS ON SERVER!!\n if(getTardis() == null) return;\n animationTimer++;\n// if (!DOOR_STATE.isRunning()) {\n// DOOR_STATE.startIfNotRunning(animationTimer);\n// }\n if(getTardis().getHandlers().getDoor().getAnimationExteriorState() == null) return;;\n if (getTardis().getHandlers().getDoor().getAnimationExteriorState() == null || !(getTardis().getHandlers().getDoor().getAnimationExteriorState().equals(getTardis().getDoor().getDoorState()))) {\n DOOR_STATE.start(animationTimer);\n getTardis().getHandlers().getDoor().tempExteriorState = getTardis().getDoor().getDoorState();\n }\n }\n\n public ExteriorAnimation getAnimation() {\n this.verifyAnimation();\n\n return this.animation;\n }\n\n public ExteriorSchema getExteriorType() {\n if(this.getTardis() == null) return ExteriorRegistry.REGISTRY.get(CapsuleExterior.REFERENCE);\n return this.getTardis().getExterior().getType();\n }\n\n public float getAlpha() {\n if (this.getAnimation() == null) {\n return 1f;\n }\n\n return this.getAnimation().getAlpha();\n }\n\n public void onBroken() {\n if(this.getTardis() != null)\n this.getTardis().getTravel().setState(TardisTravel.State.FLIGHT);\n }\n}"
},
{
"identifier": "RiftChunk",
"path": "src/main/java/mdteam/ait/core/interfaces/RiftChunk.java",
"snippet": "public interface RiftChunk {\n Integer getArtronLevels();\n void setArtronLevels(int artron);\n\n Boolean isRiftChunk();\n}"
},
{
"identifier": "DeltaTimeManager",
"path": "src/main/java/mdteam/ait/core/managers/DeltaTimeManager.java",
"snippet": "public class DeltaTimeManager {\n\n private static final HashMap<String, Long> nextUpdateTimeMap = new HashMap<>();\n\n /**\n *\n * @param string ID of the delta delay\n * @param timeDelay delay in ms\n */\n public static void createDelay(String string, Long timeDelay) {\n long nextUpdateTime = System.currentTimeMillis() + timeDelay;\n if (!nextUpdateTimeMap.containsKey(string)) {\n nextUpdateTimeMap.put(string, nextUpdateTime);\n } else {\n nextUpdateTimeMap.replace(string, nextUpdateTime);\n }\n }\n\n public static boolean isStillWaitingOnDelay(String string) {\n if (!nextUpdateTimeMap.containsKey(string)) return false;\n return nextUpdateTimeMap.get(string) > System.currentTimeMillis();\n }\n}"
}
] | import mdteam.ait.core.blockentities.ConsoleBlockEntity;
import mdteam.ait.core.blockentities.ExteriorBlockEntity;
import mdteam.ait.core.interfaces.RiftChunk;
import mdteam.ait.core.managers.DeltaTimeManager;
import net.minecraft.block.Block;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Formatting;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID; | 5,959 | package mdteam.ait.core.item;
public class ArtronCollectorItem extends Item {
public static final String AU_LEVEL = "au_level";
public static final String UUID_KEY = "uuid";
public static final Integer COLLECTOR_MAX_FUEL = 1500;
public ArtronCollectorItem(Settings settings) {
super(settings);
}
@Override
public ItemStack getDefaultStack() {
ItemStack stack = new ItemStack(this);
NbtCompound nbt = stack.getOrCreateNbt();
nbt.putDouble(AU_LEVEL, 0);
return super.getDefaultStack();
}
@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
if(world.isClient()) return;
if (!(entity instanceof ServerPlayerEntity) || !selected) return;
| package mdteam.ait.core.item;
public class ArtronCollectorItem extends Item {
public static final String AU_LEVEL = "au_level";
public static final String UUID_KEY = "uuid";
public static final Integer COLLECTOR_MAX_FUEL = 1500;
public ArtronCollectorItem(Settings settings) {
super(settings);
}
@Override
public ItemStack getDefaultStack() {
ItemStack stack = new ItemStack(this);
NbtCompound nbt = stack.getOrCreateNbt();
nbt.putDouble(AU_LEVEL, 0);
return super.getDefaultStack();
}
@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
if(world.isClient()) return;
if (!(entity instanceof ServerPlayerEntity) || !selected) return;
| RiftChunk riftChunk = (RiftChunk) world.getChunk(entity.getBlockPos()); | 2 | 2023-10-08 00:38:53+00:00 | 8k |
jianjian3219/044_bookmanage2-public | nhXJH-admin/src/main/java/com/nhXJH/web/domain/vo/BookShelfVO.java | [
{
"identifier": "SysDept",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysDept.java",
"snippet": "public class SysDept extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 部门ID */\n private Long deptId;\n\n /** 父部门ID */\n private Long parentId;\n\n /** 祖级列表 */\n private String ancestors;\n\n /** 部门名称 */\n private String deptName;\n\n /** 显示顺序 */\n private String orderNum;\n\n /** 负责人 */\n private String leader;\n\n /** 联系电话 */\n private String phone;\n\n /** 邮箱 */\n private String email;\n\n /** 部门状态:0正常,1停用 */\n @Excel(name = \"状态\",readConverterExp=\"1=失效,0=有效\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 父部门名称 */\n private String parentName;\n \n /** 子部门 */\n private List<SysDept> children = new ArrayList<SysDept>();\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n public Long getParentId() {\n return parentId;\n }\n\n public void setParentId(Long parentId) {\n this.parentId = parentId;\n }\n\n public String getAncestors() {\n return ancestors;\n }\n\n public void setAncestors(String ancestors) {\n this.ancestors = ancestors;\n }\n\n @NotBlank(message = \"部门名称不能为空\")\n @Size(min = 0, max = 30, message = \"部门名称长度不能超过30个字符\")\n public String getDeptName() {\n return deptName;\n }\n\n public void setDeptName(String deptName) {\n this.deptName = deptName;\n }\n\n @NotBlank(message = \"显示顺序不能为空\")\n public String getOrderNum() {\n return orderNum;\n }\n\n public void setOrderNum(String orderNum) {\n this.orderNum = orderNum;\n }\n\n public String getLeader() {\n return leader;\n }\n\n public void setLeader(String leader) {\n this.leader = leader;\n }\n\n @Size(min = 0, max = 11, message = \"联系电话长度不能超过11个字符\")\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\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 getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public String getParentName() {\n return parentName;\n }\n\n public void setParentName(String parentName) {\n this.parentName = parentName;\n }\n\n public List<SysDept> getChildren() {\n return children;\n }\n\n public void setChildren(List<SysDept> children) {\n this.children = children;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"deptId\", getDeptId())\n .append(\"parentId\", getParentId())\n .append(\"ancestors\", getAncestors())\n .append(\"deptName\", getDeptName())\n .append(\"orderNum\", getOrderNum())\n .append(\"leader\", getLeader())\n .append(\"phone\", getPhone())\n .append(\"email\", getEmail())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .toString();\n }\n}"
},
{
"identifier": "SysUser",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysUser.java",
"snippet": "public class SysUser extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /** 用户账号 */\n @Excel(name = \"登录名称\")\n private String userName;\n\n /** 用户昵称 */\n @Excel(name = \"用户名称\")\n private String nickName;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 手机号码 */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /** 用户性别 */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 用户头像 */\n private String avatar;\n\n /** 密码 */\n private String password;\n\n /** 盐加密 */\n private String salt;\n\n /** 帐号状态(0正常 1停用) */\n @Excel(name = \"帐号状态(0=正常,1=停用)\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 最后登录IP */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /** 最后登录时间 */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /** 部门对象 */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private SysDept dept;\n\n /** 角色对象 */\n private List<SysRole> roles;\n\n /** 角色组 */\n private Long[] roleIds;\n\n /** 岗位组 */\n private Long[] postIds;\n\n /** 角色ID */\n private Long roleId;\n\n public SysUser() {\n\n }\n\n public SysUser(Long userId) {\n this.userId = userId;\n }\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public boolean isAdmin() {\n return isAdmin(this.userId);\n }\n\n public static boolean isAdmin(Long userId) {\n return userId != null && 1L == userId;\n }\n\n public Long getDeptId() {\n return deptId;\n }\n\n public void setDeptId(Long deptId) {\n this.deptId = deptId;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getNickName() {\n return nickName;\n }\n\n public void setNickName(String nickName) {\n this.nickName = nickName;\n }\n\n @Xss(message = \"用户账号不能包含脚本字符\")\n @NotBlank(message = \"用户账号不能为空\")\n @Size(min = 0, max = 30, message = \"用户账号长度不能超过30个字符\")\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber() {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber) {\n this.phonenumber = phonenumber;\n }\n\n public String getSex() {\n return sex;\n }\n\n public void setSex(String sex) {\n this.sex = sex;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n @JsonProperty\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getSalt() {\n return salt;\n }\n\n public void setSalt(String salt) {\n this.salt = salt;\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 getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp() {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp) {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate() {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate) {\n this.loginDate = loginDate;\n }\n\n public SysDept getDept() {\n return dept;\n }\n\n public void setDept(SysDept dept) {\n this.dept = dept;\n }\n\n public List<SysRole> getRoles() {\n return roles;\n }\n\n public void setRoles(List<SysRole> roles) {\n this.roles = roles;\n }\n\n public Long[] getRoleIds() {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds) {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds() {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds) {\n this.postIds = postIds;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"userName\", getUserName())\n .append(\"nickName\", getNickName())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .toString();\n }\n}"
},
{
"identifier": "BaseBookClassCn",
"path": "nhXJH-system/src/main/java/com/nhXJH/system/domain/po/BaseBookClassCn.java",
"snippet": "@TableName(\"base_book_class_cn\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BaseBookClassCn extends BaseEntity implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /** 图书类别编号ID */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n @Id\n// @GeneratedValue(strategy = GenerationType.IDENTITY, generator = \"UserIdentityGenerator\")\n// @GenericGenerator(name = \"UserIdentityGenerator\", strategy = \"com.demo.UserIdentityGenerator\")\n private Long id;\n\n /** 图书类别编号 */\n @Excel(name = \"类别编号\")\n private String code;\n\n /** 图书类别名称 */\n @Excel(name = \"类别名称\")\n private String name;\n\n /** 父级类别ID */\n @Excel(name = \"父级类别\")\n private Long parentId;\n\n /** 图书类别级别 */\n @Excel(name = \"图书类别级别\")\n @TableField(\"class\")\n private Integer clasz;\n\n /** 图书类别别名 */\n @Excel(name = \"图书类别别名\")\n private String aliName;\n\n /** 状态是否禁用(默认1,禁用0) */\n @Excel(name = \"状态\",readConverterExp=\"0=失效,1=有效\")\n private String status;\n\n /** 创建人id */\n @Excel(name = \"创建人id\")\n private Long createPersonal;\n /**\n * 状态\n */\n @Excel(name = \"创建时间\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date createTime;\n\n\n /** 更新人id */\n @Excel(name = \"更新人id\")\n private Long updatePersonal;\n /**\n * 状态\n */\n\n @Excel(name = \"更新时间\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private Date updateTime;\n\n\n /** 子类别 */\n private List<BaseBookClassCn> children = new ArrayList<BaseBookClassCn>();\n public List<BaseBookClassCn> getChildren() {\n return children;\n }\n public void setChildren(List<BaseBookClassCn> children) {\n this.children = children;\n }\n// /** 删除时间 */\n// @JsonFormat(pattern = \"yyyy-MM-dd\")\n// @Excel(name = \"删除时间\", width = 30, dateFormat = \"yyyy-MM-dd\")\n// private Date delTime;\n//\n// /** 删除人ID */\n// @Excel(name = \"删除人ID\")\n// private String delPersonal;\n\n\n// @Override\n// public String toString() {\n// return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n// .append(\"id\", getId())\n// .append(\"code\", getCode())\n// .append(\"name\", getName())\n// .append(\"clasz\", getClasz())\n// .append(\"aliName\", getAliName())\n// .append(\"status\", getStatus())\n// .append(\"createTime\", getCreateTime())\n// .append(\"createPersonal\", getCreatePersonal())\n// .append(\"updateTime\", getUpdateTime())\n// .append(\"updatePersonal\", getUpdatePersonal())\n// .append(\"delTime\", getDelTime())\n// .append(\"delPersonal\", getDelPersonal())\n// .toString();\n// }\n}"
},
{
"identifier": "StockBookshelf",
"path": "nhXJH-admin/src/main/java/com/nhXJH/web/domain/StockBookshelf.java",
"snippet": "@TableName(\"library_stock_bookshelf\")\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class StockBookshelf extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 书架id */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n @ApiModelProperty(\"ID\")\n private Long id;\n\n /** 书架编码 */\n @Excel(name = \"书架编码\")\n @ApiModelProperty(\"书架编码\")\n private String code;\n\n /** 书架名称 */\n @Excel(name = \"书架名称\")\n @ApiModelProperty(\"书架名称\")\n private String name;\n\n /** 书架标题 */\n @Excel(name = \"书架标题\")\n @ApiModelProperty(\"书架标题\")\n private String title;\n\n /** 书架存书类别ID */\n @Excel(name = \"书架存书类别\")\n @ApiModelProperty(\"书架存书类别ID\")\n private Long bookType;\n\n @Excels({\n @Excel(name = \"存书类别编码\", targetAttr = \"code\", type = Excel.Type.EXPORT),\n @Excel(name = \"存书类别\", targetAttr = \"name\", type = Excel.Type.EXPORT)\n })\n private BaseBookClassCn classCn;\n\n /** 备注 */\n @Excel(name = \"备注\")\n @ApiModelProperty(\"备注\")\n private String mark;\n\n /** 状态,默认1,表示存在,失效使用0表示 */\n @Excel(name = \"状态\",readConverterExp=\"0=失效,1=有效\")\n @ApiModelProperty(\"状态,默认1,表示存在,失效使用0表示\")\n private String status;\n\n /** 部门ID */\n @Excel(name = \"部门\")\n @ApiModelProperty(\"部门ID\")\n private Long dept;\n\n /** 创建人ID */\n @Excel(name = \"创建人\")\n @ApiModelProperty(\"创建人ID\")\n private Long createPersonal;\n\n /** 更新人ID */\n @Excel(name = \"更新人\")\n @ApiModelProperty(\"更新人ID\")\n private Long updatePersonal;\n\n// public StockBookshelf getStockShelf(){\n// StockBookshelf bookshelf = new StockBookshelf();\n// bookshelf.setId (this.getId());// id;\n// bookshelf.setCode (this.getCode());// code;\n// bookshelf.setName (this.getName());// name;\n// bookshelf.setTitle (this.getTitle());// title;\n// bookshelf.setBookType (this.getBookType());// bookType;\n// bookshelf.setMark (this.getMark());// mark;\n// bookshelf.setStatus (this.getStatus());// status;\n// bookshelf.setDept (this.getDept());// dept;\n// bookshelf.setCreatePersonal (this.getCreatePersonal());// createPersonal;\n// bookshelf.setUpdatePersonal (this.getUpdatePersonal());// updatePersonal;\n// bookshelf.setCreateTime (this.getCreateTime());// createPersonal;\n// bookshelf.setUpdateTime (this.getUpdateTime());// updatePersonal;\n// return bookshelf;\n// }\n}"
}
] | import com.nhXJH.common.core.domain.entity.SysDept;
import com.nhXJH.common.core.domain.entity.SysUser;
import com.nhXJH.system.domain.po.BaseBookClassCn;
import com.nhXJH.web.domain.StockBookshelf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; | 4,937 | package com.nhXJH.web.domain.vo;
/**
* Created by IntelliJ IDEA.
* User: xjh
* Date: 2022/2/22
* Time: 10:07
* 图书书架返回结果实体
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookShelfVO extends StockBookshelf {
SysUser createUser;
SysUser updateUser;
SysDept sysDept; | package com.nhXJH.web.domain.vo;
/**
* Created by IntelliJ IDEA.
* User: xjh
* Date: 2022/2/22
* Time: 10:07
* 图书书架返回结果实体
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookShelfVO extends StockBookshelf {
SysUser createUser;
SysUser updateUser;
SysDept sysDept; | BaseBookClassCn bookClassCn; | 2 | 2023-10-14 04:57:42+00:00 | 8k |
aleksandarsusnjar/paniql | core/src/main/java/net/susnjar/paniql/models/InterfaceModel.java | [
{
"identifier": "Environment",
"path": "core/src/main/java/net/susnjar/paniql/Environment.java",
"snippet": "public class Environment {\n private static final String SCHEMA_SEPARATOR = System.lineSeparator() + System.lineSeparator();\n\n private final TypeDefinitionRegistry typeRegistry;\n\n private final HashMap<String, OutputTypeModel> outputTypes = new HashMap<>();\n\n private final ObjectTypeModel queryType;\n private final ObjectTypeModel mutationType;\n private final ObjectTypeModel subscriptionType;\n\n public Environment(final File... schemaFiles) throws IOException {\n this(Arrays.asList(schemaFiles).stream().map(File::toPath).collect(Collectors.toList()));\n }\n\n public Environment(final Path... schemaPaths) throws IOException {\n this(Arrays.asList(schemaPaths));\n }\n\n public Environment(final Collection<Path> schemaPaths) throws IOException {\n this(parsePathSchemas(schemaPaths));\n }\n\n public Environment(final String... schemas) {\n this(parseTextSchemas(Arrays.asList(schemas)));\n }\n\n public Environment(final TypeDefinitionRegistry typeRegistry) {\n this.typeRegistry = typeRegistry;\n\n ScalarModel.registerStandardTypes(this);\n registerCustomTypes();\n\n processTypeExtensions();\n initializeDirectRelations();\n establishIndirectRelations();\n\n discoverFields();\n relateFields();\n applyTypeCardinalityDefaults();\n applyFieldCardinalityDefaults();\n applyTypePricingDefaults();\n applyFieldPricingDefaults();\n processJoins();\n\n this.queryType = getOutputType(\"Query\");\n this.mutationType = getOutputType(\"Mutation\");\n this.subscriptionType = getOutputType(\"Subscription\");\n }\n\n public Request request(final String graphQLRequest) {\n Parser parser = new Parser();\n final Document document = parser.parseDocument(graphQLRequest);\n return request(document);\n }\n\n public Request request(final Document document) {\n return new Request(document, this);\n }\n\n public Invoice invoice(final String document) {\n return request(document).invoice();\n }\n\n public Invoice invoice(final Document document) {\n return request(document).invoice();\n }\n\n private void registerCustomTypes() {\n for (final TypeDefinition typeDef: typeRegistry.getTypes(TypeDefinition.class)) {\n OutputTypeModel typeModel = null;\n if (typeDef instanceof InterfaceTypeDefinition) {\n final InterfaceTypeDefinition actual = (InterfaceTypeDefinition)typeDef;\n typeModel = new InterfaceModel(this, actual);\n } else if (typeDef instanceof SDLExtensionDefinition) {\n // we'll handle this separately and expect to find the type to extend first.\n continue;\n } else if (typeDef instanceof EnumTypeDefinition) {\n final EnumTypeDefinition actual = (EnumTypeDefinition)typeDef;\n typeModel = new EnumTypeModel(this, actual);\n } else if (typeDef instanceof ScalarTypeDefinition) {\n final ScalarTypeDefinition actual = (ScalarTypeDefinition)typeDef;\n typeModel = new ScalarModel(this, actual);\n } else if (typeDef instanceof UnionTypeDefinition) {\n final UnionTypeDefinition actual = (UnionTypeDefinition)typeDef;\n typeModel = new UnionModel(this, actual);\n } else if (typeDef instanceof ObjectTypeDefinition) {\n final ObjectTypeDefinition actual = (ObjectTypeDefinition)typeDef;\n typeModel = new ObjectTypeModel(this, actual);\n }\n\n if (typeModel != null) {\n registerType(typeModel);\n }\n }\n }\n\n public void registerType(final OutputTypeModel typeModel) {\n outputTypes.put(typeModel.getSimpleName(), typeModel);\n }\n\n private void processTypeExtensions() {\n for (final TypeDefinition t: typeRegistry.getTypes(TypeDefinition.class)) {\n if (t instanceof EnumTypeExtensionDefinition) {\n final EnumTypeExtensionDefinition extension = (EnumTypeExtensionDefinition)t;\n final EnumTypeModel extendedType = (EnumTypeModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof ScalarTypeExtensionDefinition) {\n final ScalarTypeExtensionDefinition extension = (ScalarTypeExtensionDefinition)t;\n final ScalarModel extendedType = (ScalarModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof UnionTypeExtensionDefinition) {\n final UnionTypeExtensionDefinition extension = (UnionTypeExtensionDefinition)t;\n final UnionModel extendedType = (UnionModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof ObjectTypeExtensionDefinition) {\n final ObjectTypeExtensionDefinition extension = (ObjectTypeExtensionDefinition)t;\n final ObjectTypeModel extendedType = (ObjectTypeModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof InterfaceTypeExtensionDefinition) {\n final InterfaceTypeExtensionDefinition extension = (InterfaceTypeExtensionDefinition)t;\n final InterfaceModel extendedType = (InterfaceModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n }\n }\n }\n\n private void initializeDirectRelations() {\n outputTypes.forEach((name, type) -> type.processDirectRelations());\n }\n\n private void establishIndirectRelations() {\n outputTypes.forEach((name, type) -> type.processIndirectRelations());\n }\n\n private void discoverFields() {\n outputTypes.forEach((name, type) -> type.discoverFields());\n }\n\n private void relateFields() {\n outputTypes.forEach((name, type) -> type.relateFields());\n }\n\n private void applyTypeCardinalityDefaults() {\n outputTypes.forEach((name, type) -> type.applyTypeCardinalityDefaults());\n }\n\n private void applyFieldCardinalityDefaults() {\n outputTypes.forEach((name, type) -> type.applyFieldCardinalityDefaults());\n }\n\n private void applyTypePricingDefaults() {\n outputTypes.forEach((name, type) -> type.applyTypePricingDefaults());\n }\n\n private void applyFieldPricingDefaults() {\n outputTypes.forEach((name, type) -> type.applyFieldPricingDefaults());\n }\n\n private void processJoins() {\n outputTypes.forEach((name, type) -> type.processJoins());\n }\n\n public ObjectTypeModel getQueryType() {\n return queryType;\n }\n\n public ObjectTypeModel getMutationType() {\n return mutationType;\n }\n\n public ObjectTypeModel getSubscriptionType() {\n return subscriptionType;\n }\n\n public <T extends OutputTypeModel<?, ?>> T getOutputType(String name) {\n return (T)this.outputTypes.get(name);\n }\n\n public static String getPaniqlSchema() {\n try {\n final String packagePath = Environment.class.getPackageName().replaceAll(\"\\\\.\", \"/\");\n final String resourcePath = packagePath + \"/PaniqlSchema.graphqls\";\n try (\n final InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);\n final Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);\n final BufferedReader bufferedReader = new BufferedReader(reader);\n ) {\n return bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));\n }\n } catch (IOException x) {\n throw new RuntimeException(\"Unexpected I/O error while reading Paniql schema.\");\n }\n }\n\n private static TypeDefinitionRegistry parseTextSchemas(final Collection<String> schemas) {\n final String paniqlSchema = getPaniqlSchema();\n int schemaSize = paniqlSchema.length();\n for (final String schema: schemas) {\n schemaSize += SCHEMA_SEPARATOR.length() + schema.length();\n }\n final StringBuilder schemaBuilder = new StringBuilder(schemaSize);\n schemaBuilder.append(paniqlSchema);\n for (final String schema: schemas) {\n schemaBuilder.append(SCHEMA_SEPARATOR);\n schemaBuilder.append(schema);\n }\n SchemaParser parser = new SchemaParser();\n return parser.parse(schemaBuilder.toString());\n }\n\n private static TypeDefinitionRegistry parsePathSchemas(Collection<Path> schemaPaths) throws IOException {\n final String paniqlSchema = getPaniqlSchema();\n final StringBuilder schemaBuilder = new StringBuilder(65536);\n schemaBuilder.append(paniqlSchema);\n for (final Path path: schemaPaths) {\n schemaBuilder.append(SCHEMA_SEPARATOR);\n schemaBuilder.append(Files.readString(path));\n }\n SchemaParser parser = new SchemaParser();\n return parser.parse(schemaBuilder.toString());\n }\n\n}"
},
{
"identifier": "Bounds",
"path": "core/src/main/java/net/susnjar/paniql/pricing/Bounds.java",
"snippet": "public class Bounds {\n public static final Bounds ALWAYS_0 = new Bounds(0.0d, 0.0d, 0.0d, 0.0d);\n public static final Bounds LOW_AVERAGE = new Bounds(0.0d, 0.1, 0.5d, 1.0d);\n public static final Bounds LINEAR_0_TO_1 = new Bounds(0.0d, 0.5, 0.95d, 1.0d);\n public static final Bounds HIGH_AVERAGE = new Bounds(0.0d, 0.9, 0.99d, 1.0d);\n public static final Bounds ALWAYS_1 = new Bounds(1.0d, 1.0d, 1.0d, 1.0d);\n\n private final double minimum;\n private final double average;\n private final double percentile95;\n private final double maximum;\n\n public Bounds(\n final double minimum,\n final double average,\n final double percentile95,\n final double maximum\n ) {\n if (average < minimum) throw new IllegalArgumentException(\"Average must not be less than the minimum.\");\n if (percentile95 < average) throw new IllegalArgumentException(\"95% percentile must not be less than the average.\");\n if (maximum < percentile95) throw new IllegalArgumentException(\"Maximum must not be less than the 95% percentile.\");\n\n this.minimum = minimum;\n this.average = average;\n this.percentile95 = percentile95;\n this.maximum = maximum;\n }\n\n public double getMinimum() {\n return minimum;\n }\n\n public double getAverage() {\n return average;\n }\n\n public double getPercentile95() {\n return percentile95;\n }\n\n public double getMaximum() {\n return maximum;\n }\n\n public boolean isAlwaysZero() {\n return this.equals(ALWAYS_0);\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 Bounds that = (Bounds) o;\n return Double.compare(that.minimum, minimum) == 0\n && Double.compare(that.average, average) == 0\n && Double.compare(that.percentile95, percentile95) == 0\n && Double.compare(that.maximum, maximum) == 0;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(minimum, average, percentile95, maximum);\n }\n\n /**\n * Returns a type with values that are sums of the\n * corresponding values of this and the specified other tuple.\n */\n public Bounds plus(final Bounds other) {\n return new Bounds(\n this.minimum + other.getMinimum(),\n this.average + other.getAverage(),\n this.percentile95 + other.getPercentile95(),\n this.maximum + other.getMaximum()\n );\n }\n\n /**\n * Returns a type with values that are products of the\n * corresponding values of this and the specified common factor.\n * \n * @see #times(double, double, double, double)\n * @see #times(Bounds)\n */\n public Bounds times(final double commonFactor) {\n return times(commonFactor, commonFactor, commonFactor, commonFactor);\n }\n\n /**\n * Returns a type with values that are products of the\n * corresponding values of this and the specified factor.\n * \n * @see #times(double) \n * @see #times(Bounds)\n */\n public Bounds times(\n final double minimumFactor,\n final double averageFactor,\n final double percentile95Factor,\n final double maximumFactor\n ) {\n return new Bounds(\n this.minimum * minimumFactor,\n this.average * averageFactor,\n this.percentile95 * percentile95Factor,\n this.maximum * maximumFactor\n );\n }\n\n /**\n * Returns a type with values that are products of the\n * corresponding values of this and the specified other tuple.\n */\n public Bounds times(Bounds other) {\n return times(\n other.getMinimum(),\n other.getAverage(),\n other.getPercentile95(),\n other.getMaximum()\n );\n }\n\n public Bounds floorDiv(final double maxQuantityPerFlatFee) {\n return new Bounds(\n Math.floor(this.minimum / maxQuantityPerFlatFee),\n Math.floor(this.average / maxQuantityPerFlatFee),\n Math.floor(this.percentile95 / maxQuantityPerFlatFee),\n Math.floor(this.maximum / maxQuantityPerFlatFee)\n );\n }\n\n public Bounds ceilDiv(final double maxQuantityPerFlatFee, final double min) {\n return new Bounds(\n Math.max(Math.ceil(this.minimum / maxQuantityPerFlatFee), min),\n Math.max(Math.ceil(this.average / maxQuantityPerFlatFee), min),\n Math.max(Math.ceil(this.percentile95 / maxQuantityPerFlatFee), min),\n Math.max(Math.ceil(this.maximum / maxQuantityPerFlatFee), min)\n );\n }\n\n public static Bounds min(final Bounds a, final Bounds b) {\n double max = Math.min(a.getMaximum(), b.getMaximum());\n double p95 = Math.min(Math.min(a.getPercentile95(), b.getPercentile95()), max);\n double avg = Math.min(Math.min(a.getAverage(), b.getAverage()), p95);\n double min = Math.min(Math.min(a.getMinimum(), b.getMinimum()), avg);\n return new Bounds(min, avg, p95, max);\n }\n\n public static Bounds max(final Bounds a, final Bounds b) {\n double min = Math.max(a.getMinimum(), b.getMinimum());\n double avg = Math.max(Math.max(a.getAverage(), b.getAverage()), min);\n double p95 = Math.max(Math.max(a.getPercentile95(), b.getPercentile95()), avg);\n double max = Math.max(Math.max(a.getMaximum(), b.getMaximum()), p95);\n return new Bounds(min, avg, p95, max);\n }\n}"
},
{
"identifier": "BoundsCollector",
"path": "core/src/main/java/net/susnjar/paniql/pricing/BoundsCollector.java",
"snippet": "public class BoundsCollector implements Collector<Bounds, BoundsCollector, Bounds> {\n private double minimum = 0.0d;\n private double average = 0.0d;\n private double percentile95 = 0.0d;\n private double maximum = 0.0d;\n\n public void add(final Bounds other) {\n this.minimum += other.getMinimum();\n this.average += other.getAverage();\n this.percentile95 += other.getPercentile95();\n this.maximum += other.getMaximum();\n }\n\n public void add(final Bounds other, final double commonFactor) {\n this.minimum += other.getMinimum() * commonFactor;\n this.average += other.getAverage() * commonFactor;\n this.percentile95 += other.getPercentile95() * commonFactor;\n this.maximum += other.getMaximum() * commonFactor;\n }\n\n public void add(final Bounds other, final double minFactor, final double avgFactor, final double p95factor, final double maxFactor) {\n this.minimum += other.getMinimum() * minFactor;\n this.average += other.getAverage() * avgFactor;\n this.percentile95 += other.getPercentile95() * p95factor;\n this.maximum += other.getMaximum() * maxFactor;\n }\n\n public void add(final Bounds other, final Bounds factor) {\n add(other, factor.getMinimum(), factor.getAverage(), factor.getPercentile95(), factor.getMaximum());\n }\n\n public void add(final Bounds other, final double commonFactor, final Bounds factor) {\n add(other, commonFactor * factor.getMinimum(), commonFactor * factor.getAverage(), commonFactor * factor.getPercentile95(), commonFactor * factor.getMaximum());\n }\n\n public Bounds getCurrent() {\n return new Bounds(minimum, average, percentile95, maximum);\n }\n\n @Override\n public Supplier<BoundsCollector> supplier() {\n return () -> new BoundsCollector();\n }\n\n @Override\n public BiConsumer<BoundsCollector, Bounds> accumulator() {\n return (a, t) -> a.add(t);\n }\n\n @Override\n public BinaryOperator<BoundsCollector> combiner() {\n return (a, b) -> { a.add(b.getCurrent()); return a; };\n }\n\n @Override\n public Function<BoundsCollector, Bounds> finisher() {\n return (a) -> a.getCurrent();\n }\n\n @Override\n public Set<Characteristics> characteristics() {\n return Collections.emptySet();\n }\n}"
}
] | import graphql.language.InterfaceTypeDefinition;
import graphql.language.InterfaceTypeExtensionDefinition;
import graphql.language.Type;
import graphql.language.TypeName;
import net.susnjar.paniql.Environment;
import net.susnjar.paniql.pricing.Bounds;
import net.susnjar.paniql.pricing.BoundsCollector; | 4,167 | package net.susnjar.paniql.models;
public class InterfaceModel extends FieldContainerModel<InterfaceTypeDefinition, InterfaceTypeExtensionDefinition> {
public InterfaceModel(Environment environment, InterfaceTypeDefinition definition) {
super(environment, definition);
}
@Override | package net.susnjar.paniql.models;
public class InterfaceModel extends FieldContainerModel<InterfaceTypeDefinition, InterfaceTypeExtensionDefinition> {
public InterfaceModel(Environment environment, InterfaceTypeDefinition definition) {
super(environment, definition);
}
@Override | protected Bounds getDefaultCardinality() { | 1 | 2023-10-10 01:58:56+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.