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
leluque/java2uml
src/main/java/br/com/luque/java2uml/plantuml/writer/classdiagram/PlantUMLClassWriter.java
[ { "identifier": "Clazz", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/Clazz.java", "snippet": "public abstract class Clazz extends BaseItem {\n private final Class<?> javaClass;\n private final boolean abstract_;\n private boolean interface_;\n\n public Clazz(Class<?> javaClass, ClazzPool clazzPool) {\n super(Objects.requireNonNull(javaClass).getSimpleName(), clazzPool);\n this.javaClass = javaClass;\n this.abstract_ = Modifier.isAbstract(javaClass.getModifiers());\n this.interface_ = javaClass.isInterface();\n }\n\n public Class<?> getJavaClass() {\n return javaClass;\n }\n\n public boolean isAbstract() {\n return abstract_;\n }\n\n public boolean isInterface() {\n return interface_;\n }\n\n public void setInterface(boolean interface_) {\n this.interface_ = interface_;\n }\n\n public void extractClassInfo() {\n }\n}" }, { "identifier": "Method", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/Method.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Method extends BaseItem {\n private java.lang.reflect.Method method;\n private java.lang.reflect.Constructor<?> constructor;\n private Visibilities visibility;\n private Parameter[] parameters;\n private Clazz returnType;\n private boolean static_;\n private boolean abstract_;\n\n public Method(java.lang.reflect.Method method, ClazzPool clazzPool) {\n super(method.getName(), clazzPool);\n setMethod(method);\n extractMethodInfo();\n }\n\n public Method(java.lang.reflect.Constructor<?> constructor, ClazzPool clazzPool) {\n super(constructor.getDeclaringClass().getSimpleName(), clazzPool);\n setConstructor(constructor);\n extractConstructorInfo();\n }\n\n public void setMethod(java.lang.reflect.Method method) {\n this.method = Objects.requireNonNull(method);\n }\n\n public void setConstructor(java.lang.reflect.Constructor<?> constructor) {\n this.constructor = Objects.requireNonNull(constructor);\n }\n\n public Visibilities getVisibility() {\n return visibility;\n }\n\n public void setVisibility(Visibilities visibility) {\n this.visibility = Objects.requireNonNull(visibility);\n }\n\n public Parameter[] getParameters() {\n return parameters;\n }\n\n public void setParameters(Parameter[] parameters) {\n this.parameters = parameters;\n }\n\n public Clazz getReturnType() {\n return returnType;\n }\n\n public void setReturnType(Clazz returnType) {\n this.returnType = Objects.requireNonNull(returnType);\n }\n\n public boolean isConstructor() {\n return returnType == null;\n }\n\n public boolean isStatic() {\n return static_;\n }\n\n public boolean isAbstract() {\n return abstract_;\n }\n\n public boolean hasDependency() {\n return getDependencies().length > 0;\n }\n\n public Clazz[] getDependencies() {\n List<Clazz> dependencies = new ArrayList<>();\n if (returnType != null && getClazzPool().getRules().includes(returnType.getJavaClass())) {\n dependencies.add(returnType);\n }\n Stream.of(parameters).filter(p -> getClazzPool().getRules().includes(p.getType().getJavaClass())).forEach(p -> dependencies.add(p.getType()));\n return dependencies.toArray(Clazz[]::new);\n }\n\n private void extractMethodInfo() {\n this.visibility = Visibilities.fromModifiers(method.getModifiers());\n this.parameters = Stream.of(method.getParameters()).map(p -> new Parameter(p.getName(), getClazzPool().getFor(p.getType()), getClazzPool())).toArray(Parameter[]::new);\n this.returnType = getClazzPool().getFor(method.getReturnType());\n this.static_ = java.lang.reflect.Modifier.isStatic(method.getModifiers());\n this.abstract_ = java.lang.reflect.Modifier.isAbstract(method.getModifiers());\n }\n\n private void extractConstructorInfo() {\n this.visibility = Visibilities.fromModifiers(constructor.getModifiers());\n this.parameters = Stream.of(constructor.getParameters()).map(p -> new Parameter(p.getName(), getClazzPool().getFor(p.getType()), getClazzPool())).toArray(Parameter[]::new);\n }\n}" }, { "identifier": "ScopedClazz", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/ScopedClazz.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class ScopedClazz extends Clazz {\n private Clazz superclass;\n private Clazz[] interfaces;\n private Field[] fields;\n private Method[] methods;\n\n public ScopedClazz(Class<?> javaClass, ClazzPool clazzPool) {\n super(javaClass, clazzPool);\n }\n\n public void extractClassInfo() {\n extractSuperclass();\n extractInterfaces();\n fields = Stream.of(getJavaClass().getDeclaredFields()).map(f -> Field.from(this, f, getClazzPool())).toArray(Field[]::new);\n methods = Stream.concat(Stream.of(getJavaClass().getDeclaredMethods()).map(m -> new Method(m, getClazzPool())),\n Stream.of(getJavaClass().getDeclaredConstructors()).map(m -> new Method(m, getClazzPool()))).toArray(Method[]::new);\n }\n\n public void extractSuperclass() {\n if (null != getJavaClass().getSuperclass() && getClazzPool().getRules().includes(getJavaClass().getSuperclass())) {\n superclass = getClazzPool().getFor(getJavaClass().getSuperclass());\n }\n }\n\n public int countSuperclasses() {\n return hasSuperclass() ? 1 : 0;\n }\n\n public boolean hasSuperclass() {\n return superclass != null;\n }\n\n public Clazz getSuperclass() {\n return superclass;\n }\n\n\n public int countInterfaces() {\n return interfaces.length;\n }\n\n public void extractInterfaces() {\n interfaces = Stream.of(getJavaClass().getInterfaces()).filter(i -> getClazzPool().getRules().includes(i)).map(i -> getClazzPool().getFor(i)).toArray(Clazz[]::new);\n }\n\n public boolean hasInterfaces() {\n return getInterfaces() != null && getInterfaces().length > 0;\n }\n\n public Clazz[] getInterfaces() {\n return interfaces;\n }\n\n public int countFields() {\n return fields.length;\n }\n\n public int countMethods() {\n return methods.length;\n }\n\n public int countConstructors() {\n return Stream.of(methods).filter(Method::isConstructor).toArray().length;\n }\n\n public int countNonConstructorMethods() {\n return Stream.of(methods).filter(m -> !m.isConstructor()).toArray().length;\n }\n\n public int countRelationshipFields() {\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).toArray().length;\n }\n\n public int countNonRelationshipFields() {\n return Stream.of(fields).filter(f -> !(f instanceof RelationshipField)).toArray().length;\n }\n\n public RelationshipField[] getRelationshipFields() {\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).toArray(RelationshipField[]::new);\n }\n\n public Optional<RelationshipField> getRelationshipField(String fieldName) {\n if (null == fields) {\n return Optional.empty();\n }\n return Stream.of(fields).filter(f -> f instanceof RelationshipField).map(RelationshipField.class::cast).filter(f -> f.getName().equals(fieldName)).findFirst();\n }\n\n public Field[] getNonRelationshipFields() {\n return Stream.of(fields).filter(f -> !(f instanceof RelationshipField)).toArray(Field[]::new);\n }\n\n public Method[] getConstructors() {\n return Stream.of(methods).filter(Method::isConstructor).toArray(Method[]::new);\n }\n\n public Method[] getNonConstructorMethods() {\n return Stream.of(methods).filter(m -> !m.isConstructor()).toArray(Method[]::new);\n }\n\n public boolean hasConstructors() {\n return getNonConstructorMethods().length > 0;\n }\n\n public Clazz[] getDependencies() {\n return Stream.of(methods).flatMap(method -> Stream.of(method.getDependencies())).toArray(Clazz[]::new);\n }\n\n public boolean hasAssociationOfAnyTypeWith(Clazz other) {\n return Stream.of(getRelationshipFields()).anyMatch(f -> f.getOtherSide().equals(other));\n }\n\n}" }, { "identifier": "UnscopedClazz", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/UnscopedClazz.java", "snippet": "public class UnscopedClazz extends Clazz {\n public UnscopedClazz(Class<?> javaClass, ClazzPool clazzPool) {\n super(javaClass, clazzPool);\n }\n}" }, { "identifier": "ClassWriter", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/writer/ClassWriter.java", "snippet": "public interface ClassWriter {\n String getString(Clazz clazz);\n}" } ]
import br.com.luque.java2uml.core.classdiagram.reflection.model.Clazz; import br.com.luque.java2uml.core.classdiagram.reflection.model.Method; import br.com.luque.java2uml.core.classdiagram.reflection.model.ScopedClazz; import br.com.luque.java2uml.core.classdiagram.reflection.model.UnscopedClazz; import br.com.luque.java2uml.core.classdiagram.writer.ClassWriter; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream;
2,425
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLClassWriter implements ClassWriter { private final PlantUMLFieldWriter fieldWriter; private final PlantUMLConstructorWriter constructorWriter; private final PlantUMLMethodWriter methodWriter; private boolean generateAccessors = false; public PlantUMLClassWriter(PlantUMLFieldWriter fieldWriter, PlantUMLConstructorWriter constructorWriter, PlantUMLMethodWriter methodWriter) { this.fieldWriter = Objects.requireNonNull(fieldWriter); this.constructorWriter = Objects.requireNonNull(constructorWriter); this.methodWriter = Objects.requireNonNull(methodWriter); } public PlantUMLClassWriter generateAccessors(boolean generateAccessors) { this.generateAccessors = generateAccessors; return this; } @Override public String getString(Clazz clazz) { if (clazz instanceof UnscopedClazz) { return ""; } StringBuilder result = new StringBuilder(); result.append(getClassDefinition(clazz)); result.append(" {\n");
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLClassWriter implements ClassWriter { private final PlantUMLFieldWriter fieldWriter; private final PlantUMLConstructorWriter constructorWriter; private final PlantUMLMethodWriter methodWriter; private boolean generateAccessors = false; public PlantUMLClassWriter(PlantUMLFieldWriter fieldWriter, PlantUMLConstructorWriter constructorWriter, PlantUMLMethodWriter methodWriter) { this.fieldWriter = Objects.requireNonNull(fieldWriter); this.constructorWriter = Objects.requireNonNull(constructorWriter); this.methodWriter = Objects.requireNonNull(methodWriter); } public PlantUMLClassWriter generateAccessors(boolean generateAccessors) { this.generateAccessors = generateAccessors; return this; } @Override public String getString(Clazz clazz) { if (clazz instanceof UnscopedClazz) { return ""; } StringBuilder result = new StringBuilder(); result.append(getClassDefinition(clazz)); result.append(" {\n");
if (clazz instanceof ScopedClazz scopedClazz) {
2
2023-11-10 16:49:58+00:00
4k
javpower/JavaVision
src/main/java/com/github/javpower/javavision/util/Yolo8Util.java
[ { "identifier": "Yolov8sOnnxRuntimeDetect", "path": "src/main/java/com/github/javpower/javavision/detect/Yolov8sOnnxRuntimeDetect.java", "snippet": "public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator {\n\n public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException {\n super(modelPath, labels,confThreshold,nmsThreshold);\n }\n // 实现加载图像的逻辑\n @Override\n protected Mat loadImage(String imagePath) {\n return Imgcodecs.imread(imagePath);\n }\n // 实现图像预处理的逻辑\n @Override\n protected void preprocessImage(Mat image) {\n Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB);\n // 更改 image 尺寸及其他预处理逻辑\n }\n // 实现推理的逻辑\n @Override\n protected float[][] runInference(Mat image) throws OrtException {\n Letterbox letterbox = new Letterbox();\n int rows = letterbox.getHeight();\n int cols = letterbox.getWidth();\n int channels = image.channels();\n float[] pixels = new float[channels * rows * cols];\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n double[] pixel = image.get(j, i);\n for (int k = 0; k < channels; k++) {\n pixels[rows * cols * k + j * cols + i] = (float) pixel[k] / 255.0f;\n }\n }\n }\n // 创建OnnxTensor对象\n long[] shape = { 1L, (long)channels, (long)rows, (long)cols };\n OnnxTensor tensor = OnnxTensor.createTensor(environment, FloatBuffer.wrap(pixels), shape);\n Map<String, OnnxTensor> inputs = new HashMap<>();\n inputs.put(session.getInputNames().iterator().next(), tensor);\n\n OrtSession.Result output = session.run(inputs);\n float[][] outputData = ((float[][][]) output.get(0).getValue())[0];\n\n return transposeMatrix(outputData);\n }\n // 实现输出后处理的逻辑\n @Override\n protected Map<Integer, List<float[]>> postprocessOutput(float[][] outputData) {\n Map<Integer, List<float[]>> class2Bbox = new HashMap<>();\n\n for (float[] bbox : outputData) {\n float[] conditionalProbabilities = Arrays.copyOfRange(bbox, 4, bbox.length);\n int label = argmax(conditionalProbabilities);\n float conf = conditionalProbabilities[label];\n if (conf < confThreshold) continue;\n bbox[4] = conf;\n xywh2xyxy(bbox);\n if (bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) continue;\n class2Bbox.putIfAbsent(label, new ArrayList<>());\n class2Bbox.get(label).add(bbox);\n }\n\n return class2Bbox;\n }\n private static void xywh2xyxy(float[] bbox) {\n float x = bbox[0];\n float y = bbox[1];\n float w = bbox[2];\n float h = bbox[3];\n\n bbox[0] = x - w * 0.5f;\n bbox[1] = y - h * 0.5f;\n bbox[2] = x + w * 0.5f;\n bbox[3] = y + h * 0.5f;\n }\n private static int argmax(float[] a) {\n float re = -Float.MAX_VALUE;\n int arg = -1;\n for (int i = 0; i < a.length; i++) {\n if (a[i] >= re) {\n re = a[i];\n arg = i;\n }\n }\n return arg;\n }\n public static Yolov8sOnnxRuntimeDetect criteria() throws OrtException, IOException {\n // 这里需要引入JAR包的拷贝逻辑,您可以根据自己的需要将其处理为合适的方式\n JarFileUtils.copyFileFromJar(\"/onnx/models/yolov8s.onnx\", PathConstants.ONNX,null,false,true);\n String modelPath = PathConstants.TEMP_DIR+PathConstants.ONNX+\"/yolov8s.onnx\";\n float confThreshold = 0.35f;\n float nmsThreshold = 0.55f;\n String[] labels = {\n \"person\", \"bicycle\", \"car\", \"motorcycle\", \"airplane\", \"bus\", \"train\",\n \"truck\", \"boat\", \"traffic light\", \"fire hydrant\", \"stop sign\", \"parking meter\",\n \"bench\", \"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\",\n \"zebra\", \"giraffe\", \"backpack\", \"umbrella\", \"handbag\", \"tie\", \"suitcase\",\n \"frisbee\", \"skis\", \"snowboard\", \"sports ball\", \"kite\", \"baseball bat\",\n \"baseball glove\", \"skateboard\", \"surfboard\", \"tennis racket\", \"bottle\",\n \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\", \"apple\",\n \"sandwich\", \"orange\", \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\",\n \"cake\", \"chair\", \"couch\", \"potted plant\", \"bed\", \"dining table\", \"toilet\",\n \"tv\", \"laptop\", \"mouse\", \"remote\", \"keyboard\", \"cell phone\", \"microwave\",\n \"oven\", \"toaster\", \"sink\", \"refrigerator\", \"book\", \"clock\", \"vase\", \"scissors\",\n \"teddy bear\", \"hair drier\", \"toothbrush\"\n };\n return new Yolov8sOnnxRuntimeDetect(modelPath, confThreshold, nmsThreshold, labels);\n }\n}" }, { "identifier": "Detection", "path": "src/main/java/com/github/javpower/javavision/entity/Detection.java", "snippet": "public class Detection{\n\n public String label;\n\n private Integer clsId;\n\n public float[] bbox;\n\n public float confidence;\n\n\n public Detection(String label,Integer clsId, float[] bbox, float confidence){\n this.clsId = clsId;\n this.label = label;\n this.bbox = bbox;\n this.confidence = confidence;\n }\n\n public Detection(){\n\n }\n\n public Integer getClsId() {\n return clsId;\n }\n\n public void setClsId(Integer clsId) {\n this.clsId = clsId;\n }\n\n public String getLabel() {\n return label;\n }\n\n public void setLabel(String label) {\n this.label = label;\n }\n\n public float[] getBbox() {\n return bbox;\n }\n\n public void setBbox(float[] bbox) {\n }\n\n\n @Override\n public String toString() {\n return \" label=\"+label +\n \" \\t clsId=\"+clsId +\n \" \\t x0=\"+bbox[0] +\n \" \\t y0=\"+bbox[1] +\n \" \\t x1=\"+bbox[2] +\n \" \\t y1=\"+bbox[3] +\n \" \\t score=\"+confidence;\n }\n}" } ]
import ai.onnxruntime.OrtException; import cn.hutool.json.JSONUtil; import com.github.javpower.javavision.detect.Yolov8sOnnxRuntimeDetect; import com.github.javpower.javavision.entity.Detection; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.List;
1,926
package com.github.javpower.javavision.util; /** * Yolov8 * 物体检测 * * @author gc.x */ @Slf4j public class Yolo8Util {
package com.github.javpower.javavision.util; /** * Yolov8 * 物体检测 * * @author gc.x */ @Slf4j public class Yolo8Util {
public static List<Detection> runOcr(String imagePath) throws OrtException, IOException {
1
2023-11-10 01:57:37+00:00
4k
tientham/rn-video
android/src/main/java/com/rnvideo/RnVideoPackage.java
[ { "identifier": "BlurGifViewManager", "path": "android/src/main/java/com/rnvideo/video/BlurGifViewManager.java", "snippet": "public class BlurGifViewManager extends ViewGroupManager<BlurGifView> {\n private static final String REACT_PACKAGE = \"RnVideo-3sbg\";\n private final String SET_SOURCE = \"source\";\n\n private ThemedReactContext reactContext;\n\n public BlurGifViewManager() {\n }\n\n @Override\n public String getName() {\n return REACT_PACKAGE;\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n protected BlurGifView createViewInstance(ThemedReactContext reactContext) {\n this.reactContext = reactContext;\n return new BlurGifView(reactContext);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_SOURCE)\n public void setSource(final BlurGifView playerView, @Nullable String source) {\n if (source == null) {\n return;\n }\n playerView.setSource(source);\n }\n}" }, { "identifier": "GifViewManager", "path": "android/src/main/java/com/rnvideo/video/GifViewManager.java", "snippet": "public class GifViewManager extends ViewGroupManager<GifView> {\n private static final String REACT_PACKAGE = \"RnVideo-3sg\";\n private final String SET_SOURCE = \"source\";\n\n private ThemedReactContext reactContext;\n\n public GifViewManager() {\n }\n\n @Override\n public String getName() {\n return REACT_PACKAGE;\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n protected GifView createViewInstance(ThemedReactContext reactContext) {\n this.reactContext = reactContext;\n return new GifView(reactContext);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_SOURCE)\n public void setSource(final GifView playerView, @Nullable String source) {\n if (source == null) {\n return;\n }\n playerView.setSource(source);\n }\n}" }, { "identifier": "RnVideoConfig", "path": "android/src/main/java/com/rnvideo/video/RnVideoConfig.java", "snippet": "public interface RnVideoConfig {\n\n LoadErrorHandlingPolicy buildLoadErrorHandlingPolicy(int minLoadRetryCount);\n\n void setDisableDisconnectError(boolean disableDisconnectError);\n boolean getDisableDisconnectError();\n\n DefaultBandwidthMeter getBandwidthMeter();\n \n}" }, { "identifier": "RnVideoConfigImpl", "path": "android/src/main/java/com/rnvideo/video/RnVideoConfigImpl.java", "snippet": "public class RnVideoConfigImpl implements RnVideoConfig {\n\n private final DefaultBandwidthMeter bandwidthMeter;\n private boolean disableDisconnectError = false;\n\n public @OptIn(markerClass = UnstableApi.class) RnVideoConfigImpl(Context context) {\n this.bandwidthMeter = new DefaultBandwidthMeter.Builder(context).build();\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n public LoadErrorHandlingPolicy buildLoadErrorHandlingPolicy(int minLoadRetryCount) {\n if (this.disableDisconnectError) {\n // Use custom error handling policy to prevent throwing an error when losing network connection\n return new ReactExoplayerLoadErrorHandlingPolicy(minLoadRetryCount);\n }\n return new DefaultLoadErrorHandlingPolicy(minLoadRetryCount);\n }\n\n @Override\n public void setDisableDisconnectError(boolean disableDisconnectError) {\n this.disableDisconnectError = disableDisconnectError;\n }\n\n @Override\n public boolean getDisableDisconnectError() {\n return this.disableDisconnectError;\n }\n\n @Override\n public DefaultBandwidthMeter getBandwidthMeter() {\n return bandwidthMeter;\n }\n}" }, { "identifier": "ThreeSecPlayerViewManager", "path": "android/src/main/java/com/rnvideo/video/ThreeSecPlayerViewManager.java", "snippet": "public class ThreeSecPlayerViewManager extends ViewGroupManager<ThreeSecPlayerView> {\n private static final String REACT_PACKAGE = \"RnVideo-3sp\";\n private final String SET_SOURCE = \"source\";\n private final String SET_PLAY = \"play\";\n private final String SET_REPLAY = \"replay\";\n private final String SET_VOLUME = \"volume\";\n\n private ThemedReactContext reactContext;\n\n public ThreeSecPlayerViewManager() {\n }\n\n @Override\n public String getName() {\n return REACT_PACKAGE;\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n protected ThreeSecPlayerView createViewInstance(ThemedReactContext reactContext) {\n this.reactContext = reactContext;\n return new ThreeSecPlayerView(reactContext);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_SOURCE)\n public void setSource(final ThreeSecPlayerView playerView, @Nullable String source) {\n if (source == null) {\n return;\n }\n playerView.setSource(source);\n }\n}" }, { "identifier": "ThreeSecVideoViewManager", "path": "android/src/main/java/com/rnvideo/video/ThreeSecVideoViewManager.java", "snippet": "public class ThreeSecVideoViewManager extends SimpleViewManager<ThreeSecVideoView> {\n private static final String REACT_PACKAGE = \"RnVideo-3sv\";\n private final String SET_SOURCE = \"source\";\n private final String SET_PLAY = \"play\";\n private final String SET_REPLAY = \"replay\";\n private final String SET_VOLUME = \"volume\";\n\n private ThemedReactContext reactContext;\n\n private RnVideoConfig config;\n\n public ThreeSecVideoViewManager(RnVideoConfig config) {\n this.config = config;\n }\n\n @Override\n public String getName() {\n return REACT_PACKAGE;\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n protected ThreeSecVideoView createViewInstance(ThemedReactContext reactContext) {\n this.reactContext = reactContext;\n return new ThreeSecVideoView(reactContext, config);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_SOURCE)\n public void setSource(final ThreeSecVideoView playerView, @Nullable String source) {\n if (source == null) {\n return;\n }\n playerView.setSource(source);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_PLAY, defaultBoolean = true)\n public void setPlay(final ThreeSecVideoView playerView, boolean shouldPlay) {\n Log.d(REACT_PACKAGE, \"setPlay: \" + String.valueOf(shouldPlay));\n playerView.setPlay(shouldPlay);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_REPLAY, defaultBoolean = true)\n public void setReplay(final ThreeSecVideoView playerView, boolean replay) {\n Log.d(REACT_PACKAGE, \"set replay: \" + String.valueOf(replay));\n playerView.setReplay(replay);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_VOLUME, defaultFloat = 0f)\n public void setVolume(final ThreeSecVideoView playerView, float volume) {\n Log.d(REACT_PACKAGE, \"set volume: \" + String.valueOf(volume));\n playerView.setMediaVolume(volume);\n }\n}" }, { "identifier": "VideoViewManager", "path": "android/src/main/java/com/rnvideo/video/VideoViewManager.java", "snippet": "public class VideoViewManager extends SimpleViewManager<VideoView> {\n private static final String REACT_PACKAGE = \"RnVideo\";\n private final String SET_SOURCE = \"source\";\n private final String SET_PLAY = \"play\";\n private final String SET_REPLAY = \"replay\";\n private final String SET_VOLUME = \"volume\";\n\n private ThemedReactContext reactContext;\n\n private RnVideoConfig config;\n\n public VideoViewManager(RnVideoConfig config) {\n this.config = config;\n }\n\n @Override\n public String getName() {\n return REACT_PACKAGE;\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @Override\n protected VideoView createViewInstance(ThemedReactContext reactContext) {\n this.reactContext = reactContext;\n return new VideoView(reactContext, config);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_SOURCE)\n public void setSource(final VideoView playerView, @Nullable String source) {\n if (source == null) {\n return;\n }\n playerView.setSource(source);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_PLAY, defaultBoolean = true)\n public void setPlay(final VideoView playerView, boolean shouldPlay) {\n Log.d(VideoViewManager.REACT_PACKAGE, \"setPlay: \" + String.valueOf(shouldPlay));\n playerView.setPlay(shouldPlay);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_REPLAY, defaultBoolean = true)\n public void setReplay(final VideoView playerView, boolean replay) {\n Log.d(VideoViewManager.REACT_PACKAGE, \"set replay: \" + String.valueOf(replay));\n playerView.setReplay(replay);\n }\n\n @SuppressLint(\"UnsafeOptInUsageError\")\n @ReactProp(name = SET_VOLUME, defaultFloat = 0f)\n public void setVolume(final VideoView playerView, float volume) {\n Log.d(VideoViewManager.REACT_PACKAGE, \"set volume: \" + String.valueOf(volume));\n playerView.setMediaVolume(volume);\n }\n}" } ]
import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.rnvideo.video.BlurGifViewManager; import com.rnvideo.video.GifViewManager; import com.rnvideo.video.RnVideoConfig; import com.rnvideo.video.RnVideoConfigImpl; import com.rnvideo.video.ThreeSecPlayerViewManager; import com.rnvideo.video.ThreeSecVideoViewManager; import com.rnvideo.video.VideoViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List;
2,555
package com.rnvideo; public class RnVideoPackage implements ReactPackage { private RnVideoConfig config; public RnVideoPackage() { } public RnVideoPackage(RnVideoConfig config) { this.config = config; } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { if (config == null) { config = new RnVideoConfigImpl(reactContext); } return Arrays.<ViewManager>asList( new VideoViewManager(config), new ThreeSecVideoViewManager(config), new ThreeSecPlayerViewManager(),
package com.rnvideo; public class RnVideoPackage implements ReactPackage { private RnVideoConfig config; public RnVideoPackage() { } public RnVideoPackage(RnVideoConfig config) { this.config = config; } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { if (config == null) { config = new RnVideoConfigImpl(reactContext); } return Arrays.<ViewManager>asList( new VideoViewManager(config), new ThreeSecVideoViewManager(config), new ThreeSecPlayerViewManager(),
new GifViewManager(),
1
2023-11-11 16:54:59+00:00
4k
feiniaojin/graceful-response-boot2
src/main/java/com/feiniaojin/gracefulresponse/advice/GlobalExceptionAdvice.java
[ { "identifier": "ExceptionAliasRegister", "path": "src/main/java/com/feiniaojin/gracefulresponse/ExceptionAliasRegister.java", "snippet": "public class ExceptionAliasRegister {\n\n private final Logger logger = LoggerFactory.getLogger(ExceptionAliasRegister.class);\n\n private ConcurrentHashMap<Class<? extends Throwable>, ExceptionAliasFor> aliasForMap = new ConcurrentHashMap<>();\n\n /**\n * 注册\n *\n * @param throwableClass\n * @return\n */\n public ExceptionAliasRegister doRegisterExceptionAlias(Class<? extends Throwable> throwableClass) {\n\n ExceptionAliasFor exceptionAliasFor = throwableClass.getAnnotation(ExceptionAliasFor.class);\n if (exceptionAliasFor == null) {\n logger.error(\"注册了未加ExceptionAliasFor的异常,throwableClass={}\", throwableClass);\n throw new RuntimeException();\n }\n\n Class<? extends Throwable>[] classes = exceptionAliasFor.aliasFor();\n for (Class<? extends Throwable> c : classes) {\n aliasForMap.put(c, exceptionAliasFor);\n }\n\n return this;\n }\n\n /**\n * 获取\n *\n * @param tClazz\n * @return\n */\n public ExceptionAliasFor getExceptionAliasFor(Class<? extends Throwable> tClazz) {\n return aliasForMap.get(tClazz);\n }\n}" }, { "identifier": "GracefulResponseException", "path": "src/main/java/com/feiniaojin/gracefulresponse/GracefulResponseException.java", "snippet": "public class GracefulResponseException extends RuntimeException {\n\n /**\n * 响应码\n */\n private String code;\n /**\n * 提示信息\n */\n private String msg;\n\n public GracefulResponseException() {\n }\n\n public GracefulResponseException(String msg) {\n super(msg);\n this.msg = msg;\n }\n\n public GracefulResponseException(String code, String msg) {\n super(msg);\n this.code = code;\n this.msg = msg;\n }\n\n public GracefulResponseException(String msg, Throwable cause) {\n super(msg, cause);\n this.msg = msg;\n }\n\n public GracefulResponseException(String code, String msg, Throwable cause) {\n super(msg, cause);\n this.code = code;\n this.msg = msg;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getMsg() {\n return msg;\n }\n}" }, { "identifier": "GracefulResponseProperties", "path": "src/main/java/com/feiniaojin/gracefulresponse/GracefulResponseProperties.java", "snippet": "@ConfigurationProperties(prefix = \"graceful-response\")\npublic class GracefulResponseProperties {\n\n /**\n * 在全局异常处理器中打印异常,默认不打印\n */\n private boolean printExceptionInGlobalAdvice = false;\n\n /**\n * 默认的Response实现类名称,配置了responseClassFullName,则responseStyle不生效\n */\n private String responseClassFullName;\n\n /**\n * responseStyle的风格,responseClassFullName为空时才会生效\n * responseStyle==null或者responseStyle==0,Response风格为 DefaultResponseImplStyle0\n * responseStyle=1,Response风格为 DefaultResponseImplStyle1\n */\n private Integer responseStyle;\n\n /**\n * 默认的成功返回码\n */\n private String defaultSuccessCode = DefaultConstants.DEFAULT_SUCCESS_CODE;\n\n /**\n * 默认的成功提示\n */\n private String defaultSuccessMsg = DefaultConstants.DEFAULT_SUCCESS_MSG;\n\n /**\n * 默认的失败码\n */\n private String defaultErrorCode = DefaultConstants.DEFAULT_ERROR_CODE;\n\n /**\n * 默认的失败提示\n */\n private String defaultErrorMsg = DefaultConstants.DEFAULT_ERROR_MSG;\n\n /**\n * Validate异常码,不提供的话默认DefaultConstants.DEFAULT_ERROR_CODE\n */\n private String defaultValidateErrorCode;\n\n /**\n * 例外包路径\n */\n private List<String> excludePackages;\n\n /**\n * 不使用@ExceptionMapper和@ExceptionAliasFor修饰的原生异常\n * 是否使用异常信息Throwable类的detailMessage进行返回\n * originExceptionUsingDetailMessage=false,则msg=defaultErrorMsg\n */\n private Boolean originExceptionUsingDetailMessage = false;\n\n public boolean isPrintExceptionInGlobalAdvice() {\n return printExceptionInGlobalAdvice;\n }\n\n public void setPrintExceptionInGlobalAdvice(boolean printExceptionInGlobalAdvice) {\n this.printExceptionInGlobalAdvice = printExceptionInGlobalAdvice;\n }\n\n public String getDefaultSuccessCode() {\n return defaultSuccessCode;\n }\n\n public void setDefaultSuccessCode(String defaultSuccessCode) {\n this.defaultSuccessCode = defaultSuccessCode;\n }\n\n public String getDefaultSuccessMsg() {\n return defaultSuccessMsg;\n }\n\n public void setDefaultSuccessMsg(String defaultSuccessMsg) {\n this.defaultSuccessMsg = defaultSuccessMsg;\n }\n\n public String getDefaultErrorCode() {\n return defaultErrorCode;\n }\n\n public void setDefaultErrorCode(String defaultErrorCode) {\n this.defaultErrorCode = defaultErrorCode;\n }\n\n public String getDefaultErrorMsg() {\n return defaultErrorMsg;\n }\n\n public void setDefaultErrorMsg(String defaultErrorMsg) {\n this.defaultErrorMsg = defaultErrorMsg;\n }\n\n public String getResponseClassFullName() {\n return responseClassFullName;\n }\n\n public void setResponseClassFullName(String responseClassFullName) {\n this.responseClassFullName = responseClassFullName;\n }\n\n public Integer getResponseStyle() {\n return responseStyle;\n }\n\n public void setResponseStyle(Integer responseStyle) {\n this.responseStyle = responseStyle;\n }\n\n public String getDefaultValidateErrorCode() {\n return defaultValidateErrorCode;\n }\n\n public void setDefaultValidateErrorCode(String defaultValidateErrorCode) {\n this.defaultValidateErrorCode = defaultValidateErrorCode;\n }\n\n public List<String> getExcludePackages() {\n return excludePackages;\n }\n\n public void setExcludePackages(List<String> excludePackages) {\n this.excludePackages = excludePackages;\n }\n\n public Boolean getOriginExceptionUsingDetailMessage() {\n return originExceptionUsingDetailMessage;\n }\n\n public void setOriginExceptionUsingDetailMessage(Boolean originExceptionUsingDetailMessage) {\n this.originExceptionUsingDetailMessage = originExceptionUsingDetailMessage;\n }\n}" }, { "identifier": "ResponseFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/api/ResponseFactory.java", "snippet": "public interface ResponseFactory {\n\n\n /**\n * 创建新的空响应.\n *\n * @return\n */\n Response newEmptyInstance();\n\n /**\n * 创建新的空响应.\n *\n * @param statusLine 响应行信息.\n * @return\n */\n Response newInstance(ResponseStatus statusLine);\n\n /**\n * 创建新的响应.\n *\n * @return\n */\n Response newSuccessInstance();\n\n /**\n * 从数据中创建成功响应.\n *\n * @param data 响应数据.\n * @return\n */\n Response newSuccessInstance(Object data);\n\n /**\n * 创建新的失败响应.\n *\n * @return\n */\n Response newFailInstance();\n\n}" }, { "identifier": "ResponseStatusFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/api/ResponseStatusFactory.java", "snippet": "public interface ResponseStatusFactory {\n /**\n * 获得响应成功的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultSuccess();\n\n /**\n * 获得失败的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultError();\n\n\n /**\n * 从code和msg创建ResponseStatus\n * @param code\n * @param msg\n * @return\n */\n ResponseStatus newInstance(String code,String msg);\n\n}" }, { "identifier": "Response", "path": "src/main/java/com/feiniaojin/gracefulresponse/data/Response.java", "snippet": "public interface Response {\n\n /**\n * 设置响应行\n *\n * @param statusLine\n */\n void setStatus(ResponseStatus statusLine);\n\n /**\n * 获取响应行\n *\n * @return\n */\n ResponseStatus getStatus();\n\n /**\n * 设置响应数据.\n *\n * @param payload 设置的响应数据.\n */\n void setPayload(Object payload);\n\n /**\n * 获得响应数据.\n *\n * @return\n */\n Object getPayload();\n}" }, { "identifier": "ResponseStatus", "path": "src/main/java/com/feiniaojin/gracefulresponse/data/ResponseStatus.java", "snippet": "public interface ResponseStatus {\n /**\n * 设置响应码.\n *\n * @param code 设置的响应码.\n */\n void setCode(String code);\n\n /**\n * 获得响应码.\n *\n * @return\n */\n String getCode();\n\n /**\n * 设置响应提示信息.\n *\n * @param msg 设置响应提示信息.\n */\n void setMsg(String msg);\n\n /**\n * 获得响应信息.\n *\n * @return\n */\n String getMsg();\n}" } ]
import com.feiniaojin.gracefulresponse.ExceptionAliasRegister; import com.feiniaojin.gracefulresponse.GracefulResponseException; import com.feiniaojin.gracefulresponse.GracefulResponseProperties; import com.feiniaojin.gracefulresponse.api.ExceptionAliasFor; import com.feiniaojin.gracefulresponse.api.ExceptionMapper; import com.feiniaojin.gracefulresponse.api.ResponseFactory; import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory; import com.feiniaojin.gracefulresponse.data.Response; import com.feiniaojin.gracefulresponse.data.ResponseStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.Order; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource;
2,773
package com.feiniaojin.gracefulresponse.advice; /** * 全局异常处理. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @ControllerAdvice @Order(200) public class GlobalExceptionAdvice implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class); @Resource private ResponseStatusFactory responseStatusFactory; @Resource private ResponseFactory responseFactory; private ExceptionAliasRegister exceptionAliasRegister; @Resource private GracefulResponseProperties gracefulResponseProperties; @Resource private GracefulResponseProperties properties; /** * 异常处理逻辑. * * @param throwable 业务逻辑抛出的异常 * @return 统一返回包装后的结果 */ @ExceptionHandler({Throwable.class}) @ResponseBody public Response exceptionHandler(Throwable throwable) { if (gracefulResponseProperties.isPrintExceptionInGlobalAdvice()) { logger.error("Graceful Response:GlobalExceptionAdvice捕获到异常,message=[{}]", throwable.getMessage(), throwable); }
package com.feiniaojin.gracefulresponse.advice; /** * 全局异常处理. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @ControllerAdvice @Order(200) public class GlobalExceptionAdvice implements ApplicationContextAware { private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class); @Resource private ResponseStatusFactory responseStatusFactory; @Resource private ResponseFactory responseFactory; private ExceptionAliasRegister exceptionAliasRegister; @Resource private GracefulResponseProperties gracefulResponseProperties; @Resource private GracefulResponseProperties properties; /** * 异常处理逻辑. * * @param throwable 业务逻辑抛出的异常 * @return 统一返回包装后的结果 */ @ExceptionHandler({Throwable.class}) @ResponseBody public Response exceptionHandler(Throwable throwable) { if (gracefulResponseProperties.isPrintExceptionInGlobalAdvice()) { logger.error("Graceful Response:GlobalExceptionAdvice捕获到异常,message=[{}]", throwable.getMessage(), throwable); }
ResponseStatus statusLine;
6
2023-11-15 10:54:19+00:00
4k
innogames/flink-real-time-crm
src/main/java/com/innogames/analytics/rtcrm/sink/TriggerCampaignSink.java
[ { "identifier": "Campaign", "path": "src/main/java/com/innogames/analytics/rtcrm/entity/Campaign.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Campaign {\n\n\tprivate int campaignId;\n\tprivate boolean enabled;\n\tprivate String game;\n\tprivate String eventName;\n\tprivate String startDate;\n\tprivate String endDate;\n\tprivate String filter;\n\n\t@JsonIgnore\n\tprivate transient JSObject filterFunction;\n\n\tpublic Campaign() {\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic void setEnabled(final boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\n\tpublic int getCampaignId() {\n\t\treturn campaignId;\n\t}\n\n\tpublic void setCampaignId(final int campaignId) {\n\t\tthis.campaignId = campaignId;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tpublic void setStartDate(final String startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\tpublic String getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tpublic void setEndDate(final String endDate) {\n\t\tthis.endDate = endDate;\n\t}\n\n\tpublic String getFilter() {\n\t\treturn filter;\n\t}\n\n\tpublic void setFilter(final String filter) {\n\t\tthis.filter = filter;\n\t}\n\n\tpublic JSObject getFilterFunction() throws ScriptException {\n\t\tif (filterFunction == null) {\n\t\t\tfilterFunction = (JSObject) NashornEngine.getInstance().eval(getFilter());\n\t\t}\n\n\t\treturn filterFunction;\n\t}\n\n}" }, { "identifier": "TrackingEvent", "path": "src/main/java/com/innogames/analytics/rtcrm/entity/TrackingEvent.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class TrackingEvent {\n\n\tprivate String schemaVersion;\n\tprivate String eventId;\n\tprivate String systemType;\n\tprivate String systemName;\n\tprivate String game;\n\tprivate String market;\n\tprivate Integer playerId;\n\tprivate String eventType;\n\tprivate String eventName;\n\tprivate String eventScope;\n\tprivate String createdAt;\n\tprivate String receivedAt;\n\tprivate String hostname;\n\n\tprivate Map<String, Object> context;\n\n\tprivate Map<String, Object> data;\n\n\tpublic TrackingEvent() {\n\t}\n\n\tpublic String getSchemaVersion() {\n\t\treturn schemaVersion;\n\t}\n\n\tpublic void setSchemaVersion(final String schemaVersion) {\n\t\tthis.schemaVersion = schemaVersion;\n\t}\n\n\tpublic String getEventId() {\n\t\treturn eventId;\n\t}\n\n\tpublic void setEventId(final String eventId) {\n\t\tthis.eventId = eventId;\n\t}\n\n\tpublic String getSystemType() {\n\t\treturn systemType;\n\t}\n\n\tpublic void setSystemType(final String systemType) {\n\t\tthis.systemType = systemType;\n\t}\n\n\tpublic String getSystemName() {\n\t\treturn systemName;\n\t}\n\n\tpublic void setSystemName(final String systemName) {\n\t\tthis.systemName = systemName;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getMarket() {\n\t\treturn market;\n\t}\n\n\tpublic void setMarket(final String market) {\n\t\tthis.market = market;\n\t}\n\n\tpublic Integer getPlayerId() {\n\t\treturn playerId;\n\t}\n\n\tpublic void setPlayerId(final Integer playerId) {\n\t\tthis.playerId = playerId;\n\t}\n\n\tpublic String getEventType() {\n\t\treturn eventType;\n\t}\n\n\tpublic void setEventType(final String eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getEventScope() {\n\t\treturn eventScope;\n\t}\n\n\tpublic void setEventScope(final String eventScope) {\n\t\tthis.eventScope = eventScope;\n\t}\n\n\tpublic String getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(final String createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic String getReceivedAt() {\n\t\treturn receivedAt;\n\t}\n\n\tpublic void setReceivedAt(final String receivedAt) {\n\t\tthis.receivedAt = receivedAt;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic void setHostname(final String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\tpublic Map<String, Object> getContext() {\n\t\treturn context;\n\t}\n\n\tpublic void setContext(final Map<String, Object> context) {\n\t\tthis.context = context;\n\t}\n\n\tpublic Map<String, Object> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(final Map<String, Object> data) {\n\t\tthis.data = data;\n\t}\n\n}" }, { "identifier": "Trigger", "path": "src/main/java/com/innogames/analytics/rtcrm/entity/Trigger.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Trigger {\n\n\tprivate Campaign campaign;\n\tprivate TrackingEvent event;\n\n\tpublic Trigger() {\n\t}\n\n\tpublic Trigger(final Campaign campaign, final TrackingEvent event) {\n\t\tthis.campaign = campaign;\n\t\tthis.event = event;\n\t}\n\n\tpublic Campaign getCampaign() {\n\t\treturn campaign;\n\t}\n\n\tpublic void setCampaign(final Campaign campaign) {\n\t\tthis.campaign = campaign;\n\t}\n\n\tpublic TrackingEvent getEvent() {\n\t\treturn event;\n\t}\n\n\tpublic void setEvent(final TrackingEvent event) {\n\t\tthis.event = event;\n\t}\n\n}" }, { "identifier": "StringProducer", "path": "src/main/java/com/innogames/analytics/rtcrm/kafka/StringProducer.java", "snippet": "public class StringProducer {\n\n\tprivate final Properties properties;\n\tprivate Producer<String, String> producer;\n\n\tpublic StringProducer(final Properties properties) {\n\t\tthis.properties = new Properties();\n\n\t\t// default settings\n\t\tthis.properties.put(\"bootstrap.servers\", \"localhost:9092\");\n\t\tthis.properties.put(\"acks\", \"all\");\n\t\tthis.properties.put(\"buffer.memory\", 33554432);\n\t\tthis.properties.put(\"compression.type\", \"snappy\");\n\t\tthis.properties.put(\"retries\", 3);\n\t\tthis.properties.put(\"batch.size\", 16384);\n\t\tthis.properties.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\t\tthis.properties.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\n\t\t// custom settings\n\t\tif (properties != null) {\n\t\t\tthis.properties.putAll(properties);\n\t\t}\n\t}\n\n\tpublic void start() {\n\t\tthis.producer = new KafkaProducer<>(this.properties);\n\t}\n\n\tpublic void stop() {\n\t\tthis.flush();\n\t\tthis.producer.close();\n\t}\n\n\tpublic void flush() {\n\t\tthis.producer.flush();\n\t}\n\n\tpublic Future<RecordMetadata> send(ProducerRecord<String, String> record) {\n\t\treturn this.producer.send(record);\n\t}\n\n\tpublic Future<RecordMetadata> send(String topic, String message) {\n\t\treturn this.send(new ProducerRecord<>(topic, message));\n\t}\n\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrm.entity.Campaign; import com.innogames.analytics.rtcrm.entity.TrackingEvent; import com.innogames.analytics.rtcrm.entity.Trigger; import com.innogames.analytics.rtcrm.kafka.StringProducer; import java.util.Properties; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
2,087
package com.innogames.analytics.rtcrm.sink; public class TriggerCampaignSink extends RichSinkFunction<Tuple2<TrackingEvent, Campaign>> { private static final ObjectMapper objectMapper = new ObjectMapper();
package com.innogames.analytics.rtcrm.sink; public class TriggerCampaignSink extends RichSinkFunction<Tuple2<TrackingEvent, Campaign>> { private static final ObjectMapper objectMapper = new ObjectMapper();
private transient StringProducer stringProducer;
3
2023-11-12 17:52:45+00:00
4k
BlyznytsiaOrg/bring
core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/AnnotationBringBeanRegistry.java
[ { "identifier": "BeanDefinitionRegistry", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/BeanDefinitionRegistry.java", "snippet": "public interface BeanDefinitionRegistry {\n\n /**\n * Registers a bean definition in the registry.\n *\n * @param beanDefinition The definition of the bean to be registered.\n */\n void registerBeanDefinition(BeanDefinition beanDefinition);\n \n}" }, { "identifier": "BeanRegistry", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/BeanRegistry.java", "snippet": "public interface BeanRegistry {\n\n /**\n * Registers a bean with its associated BeanDefinition in the registry.\n *\n * @param beanName The name of the bean to be registered.\n * @param beanDefinition The definition of the bean being registered.\n */\n void registerBean(String beanName, BeanDefinition beanDefinition);\n \n}" }, { "identifier": "ClassPathScannerFactory", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/scaner/ClassPathScannerFactory.java", "snippet": "@Slf4j\npublic class ClassPathScannerFactory {\n\n private final List<ClassPathScanner> classPathScanners;\n private final List<AnnotationResolver> annotationResolvers;\n\n // List of annotations indicating beans created by the scanning process.\n @Getter\n private final List<Class<? extends Annotation>> createdBeanAnnotations;\n\n /**\n * Constructs the ClassPathScannerFactory with reflections for initializing scanners and resolvers.\n *\n * @param reflections The Reflections instance used for scanning and resolving annotations.\n */\n public ClassPathScannerFactory(Reflections reflections) {\n // Retrieve and initialize ClassPathScanner implementations.\n this.classPathScanners = reflections.getSubTypesOf(ClassPathScanner.class)\n .stream()\n .filter(clazz -> clazz.isAnnotationPresent(BeanProcessor.class))\n .sorted(ORDER_COMPARATOR)\n .map(clazz -> clazz.cast(getConstructorWithOneParameter(clazz, Reflections.class, reflections)))\n .collect(Collectors.toList());\n\n // Retrieve and initialize AnnotationResolver implementations.\n this.annotationResolvers = reflections.getSubTypesOf(AnnotationResolver.class)\n .stream()\n .filter(clazz -> clazz.isAnnotationPresent(BeanProcessor.class))\n .map(clazz -> clazz.cast(getConstructorWithOutParameters(clazz)))\n .collect(Collectors.toList());\n\n // Collect annotations used to identify created beans during scanning.\n this.createdBeanAnnotations = classPathScanners.stream()\n .map(ClassPathScanner::getAnnotation)\n .collect(Collectors.toList());\n\n log.info(\"Register ClassPathScannerFactory {}\", Arrays.toString(classPathScanners.toArray()));\n }\n\n /**\n * Retrieves a set of classes identified as beans to be created by the registered scanners.\n *\n * @return A set of classes to be created based on scanning.\n */\n public Set<Class<?>> getBeansToCreate() {\n return classPathScanners.stream()\n .flatMap(classPathScanner -> classPathScanner.scan().stream())\n .collect(Collectors.toSet());\n }\n\n /**\n * Resolves the bean name for a given class using registered AnnotationResolvers.\n *\n * @param clazz The class for which the bean name is to be resolved.\n * @return The resolved name of the bean.\n */\n public String resolveBeanName(Class<?> clazz) {\n log.info(\"Resolving bean name for class [{}]\", clazz.getName());\n return annotationResolvers.stream()\n .filter(resolver -> resolver.isSupported(clazz))\n .findFirst()\n .map(annotationResolver -> annotationResolver.resolve(clazz))\n .orElse(null);\n }\n\n}" }, { "identifier": "BeanDefinition", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/domain/BeanDefinition.java", "snippet": "@Getter\n@Builder\npublic class BeanDefinition {\n\n private Class<?> beanClass;\n\n private BeanTypeEnum beanType;\n\n private BeanScope scope;\n\n private ProxyMode proxyMode;\n\n private Method method;\n\n private String factoryBeanName;\n\n private boolean isPrimary;\n\n /**\n * Checks if the bean is of type Configuration.\n *\n * @return True if the bean is of type Configuration, otherwise false\n */\n public boolean isConfiguration() {\n return this.beanType == BeanTypeEnum.CONFIGURATION;\n }\n\n /**\n * Checks if the bean is a configuration bean.\n *\n * @return True if the bean is a configuration bean, otherwise false\n */\n public boolean isConfigurationBean() {\n return Objects.nonNull(method);\n }\n\n /**\n * Checks if the bean's scope is set to Prototype.\n *\n * @return True if the bean's scope is Prototype, otherwise false\n */\n public boolean isPrototype() {\n return scope == BeanScope.PROTOTYPE;\n }\n\n /**\n * Checks if the bean is configured for proxying.\n *\n * @return True if the bean is configured for proxying, otherwise false\n */\n public boolean isProxy() {\n return proxyMode == ProxyMode.ON;\n }\n\n}" }, { "identifier": "CyclicBeanException", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/exception/CyclicBeanException.java", "snippet": "public class CyclicBeanException extends RuntimeException {\n\n private static final String MESSAGE = \"Looks like you have cyclic dependency between those beans %s\";\n\n /**\n * Constructs a new CyclicBeanException with a message indicating the classes involved in the cyclic dependency.\n *\n * @param classes Set of class names involved in the cyclic dependency\n */\n public CyclicBeanException(Set<String> classes) {\n super(String.format(MESSAGE, printCyclic(classes)));\n }\n\n /**\n * Generates a formatted string representation of the cyclic dependency involving classes.\n *\n * @param classes Set of class names involved in the cyclic dependency\n * @return A string representation of the cyclic dependency path among classes\n */\n private static String printCyclic(Set<String> classes) {\n if (classes.isEmpty()) {\n return \"[]\";\n }\n\n StringBuilder sb = new StringBuilder();\n Iterator<String> iterator = classes.iterator();\n String first = iterator.next();\n\n sb.append(\"[\").append(first);\n\n while (iterator.hasNext()) {\n String current = iterator.next();\n sb.append(\" -> \").append(current);\n }\n\n sb.append(\" -> \").append(first).append(\"]\");\n return sb.toString();\n }\n}" } ]
import io.github.blyznytsiaorg.bring.core.context.BeanDefinitionRegistry; import io.github.blyznytsiaorg.bring.core.context.BeanRegistry; import io.github.blyznytsiaorg.bring.core.context.scaner.ClassPathScannerFactory; import io.github.blyznytsiaorg.bring.core.domain.BeanDefinition; import io.github.blyznytsiaorg.bring.core.exception.CyclicBeanException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.reflections.Reflections; import java.util.*;
2,116
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Registry class responsible for: * <ol> * <li>Registering beans by bean name and bean definition: The bean name is created using * {@code AnnotationResolver} and is the key of the {@code DefaultBringBeanFactory.beanDefinitionMap}. * The bean definition contains all the necessary information that is needed to create a bean. Depending on the * bean scope, an object or a supplier will be stored in the application context.</li> * * <li>Registering bean definitions: storing bean definitions in {@code DefaultBringBeanFactory.beanDefinitionMap}. * Those will be used in the future to create or retrieve beans.</li> * </ol> * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class AnnotationBringBeanRegistry extends DefaultBringBeanFactory implements BeanRegistry, BeanDefinitionRegistry { @Getter protected ClassPathScannerFactory classPathScannerFactory; private final BeanCreator beanCreator; private final Set<String> currentlyCreatingBeans = new HashSet<>(); @Getter private final Reflections reflections; public AnnotationBringBeanRegistry(Reflections reflections) { this.reflections = reflections; this.classPathScannerFactory = new ClassPathScannerFactory(reflections); this.beanCreator = new BeanCreator(this, classPathScannerFactory); } /** * Registers beans in the application context. Creates and stores singleton bean objects or suppliers for prototype beans. * Also defines the proper way to create beans depending on the type of the bean (annotated class or configuration bean) * and injects dependant beans. * * @param beanName The name of the bean to be registered. * @param beanDefinition The definition of the bean being registered. */ @Override public void registerBean(String beanName, BeanDefinition beanDefinition) { log.info("Registering Bean with name \"{}\" into Bring context...", beanName); Class<?> clazz = beanDefinition.getBeanClass(); if (currentlyCreatingBeans.contains(beanName)) { log.error("Cyclic dependency detected!");
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Registry class responsible for: * <ol> * <li>Registering beans by bean name and bean definition: The bean name is created using * {@code AnnotationResolver} and is the key of the {@code DefaultBringBeanFactory.beanDefinitionMap}. * The bean definition contains all the necessary information that is needed to create a bean. Depending on the * bean scope, an object or a supplier will be stored in the application context.</li> * * <li>Registering bean definitions: storing bean definitions in {@code DefaultBringBeanFactory.beanDefinitionMap}. * Those will be used in the future to create or retrieve beans.</li> * </ol> * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class AnnotationBringBeanRegistry extends DefaultBringBeanFactory implements BeanRegistry, BeanDefinitionRegistry { @Getter protected ClassPathScannerFactory classPathScannerFactory; private final BeanCreator beanCreator; private final Set<String> currentlyCreatingBeans = new HashSet<>(); @Getter private final Reflections reflections; public AnnotationBringBeanRegistry(Reflections reflections) { this.reflections = reflections; this.classPathScannerFactory = new ClassPathScannerFactory(reflections); this.beanCreator = new BeanCreator(this, classPathScannerFactory); } /** * Registers beans in the application context. Creates and stores singleton bean objects or suppliers for prototype beans. * Also defines the proper way to create beans depending on the type of the bean (annotated class or configuration bean) * and injects dependant beans. * * @param beanName The name of the bean to be registered. * @param beanDefinition The definition of the bean being registered. */ @Override public void registerBean(String beanName, BeanDefinition beanDefinition) { log.info("Registering Bean with name \"{}\" into Bring context...", beanName); Class<?> clazz = beanDefinition.getBeanClass(); if (currentlyCreatingBeans.contains(beanName)) { log.error("Cyclic dependency detected!");
throw new CyclicBeanException(currentlyCreatingBeans);
4
2023-11-10 13:42:05+00:00
4k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/hashesfragment/HashesRvAdapter.java
[ { "identifier": "HashInfoEntity", "path": "app/src/main/java/com/johndeweydev/awps/model/data/HashInfoEntity.java", "snippet": "@Entity(tableName = \"hash_information\")\npublic class HashInfoEntity {\n\n @PrimaryKey(autoGenerate = true)\n public int uid;\n @ColumnInfo(name = \"ssid\")\n public String ssid;\n @ColumnInfo(name = \"bssid\")\n public String bssid;\n @ColumnInfo(name = \"client_mac_address\")\n public String clientMacAddress;\n\n // The key type can be either \"PMKID\" in the case of PMKID based attack or \"MIC\" in the case\n // of MIC based attack\n @ColumnInfo(name = \"key_type\")\n public String keyType;\n\n // The anonce or access point nonce from the first eapol message, this is initialized in the\n // case of MIC based attack otherwise its value is \"None\" in the case of PMKID based attack\n @ColumnInfo(name = \"a_nonce\")\n public String aNonce;\n\n // The hash data is where the actual PMKID or MIC is stored\n @ColumnInfo(name = \"hash_data\")\n public String hashData;\n\n // The key data is where the second eapol authentication message is stored in the case of\n // MIC based attack otherwise its value is \"None\"\n @ColumnInfo(name = \"key_data\")\n public String keyData;\n @ColumnInfo(name = \"date_captured\")\n public String dateCaptured;\n\n @ColumnInfo(name = \"latitude\")\n public String latitude;\n @ColumnInfo(name = \"longitude\")\n public String longitude;\n @ColumnInfo(name = \"address\")\n public String address;\n\n public HashInfoEntity(\n @Nullable String ssid,\n @Nullable String bssid,\n @Nullable String clientMacAddress,\n @Nullable String keyType,\n @Nullable String aNonce,\n @Nullable String hashData,\n @Nullable String keyData,\n @Nullable String dateCaptured,\n @Nullable String latitude,\n @Nullable String longitude,\n @Nullable String address\n ) {\n this.ssid = ssid;\n this.bssid = bssid;\n this.clientMacAddress = clientMacAddress;\n this.keyType = keyType;\n this.aNonce = aNonce;\n this.hashData = hashData;\n this.keyData = keyData;\n this.dateCaptured = dateCaptured;\n this.latitude = latitude;\n this.longitude = longitude;\n this.address = address;\n }\n}" }, { "identifier": "HashInfoModalBottomArgs", "path": "app/src/main/java/com/johndeweydev/awps/view/hashinfomodalbottomsheetdialog/HashInfoModalBottomArgs.java", "snippet": "public class HashInfoModalBottomArgs implements Parcelable {\n\n private final String ssid;\n private final String bssid;\n private final String clientMacAddress;\n private final String keyType;\n private final String keyData;\n private final String aNonce;\n private final String hashData;\n\n private final String latitude;\n private final String longitude;\n private final String address;\n\n private final String dateCaptured;\n\n public HashInfoModalBottomArgs(\n String ssid,\n String bssid,\n String clientMacAddress,\n String keyType,\n String keyData,\n String aNonce,\n String hashData,\n String latitude,\n String longitude,\n String address,\n String dateCaptured\n ) {\n this.ssid = ssid;\n this.bssid = bssid;\n this.clientMacAddress = clientMacAddress;\n this.keyType = keyType;\n this.keyData = keyData;\n this.aNonce = aNonce;\n this.hashData = hashData;\n this.latitude = latitude;\n this.longitude = longitude;\n this.address = address;\n this.dateCaptured = dateCaptured;\n }\n\n public String getSsid() {\n return ssid;\n }\n\n public String getBssid() {\n return bssid;\n }\n\n public String getClientMacAddress() {\n return clientMacAddress;\n }\n\n public String getKeyType() {\n return keyType;\n }\n\n public String getKeyData() {\n return keyData;\n }\n\n public String getaNonce() {\n return aNonce;\n }\n\n public String getHashData() {\n return hashData;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public String getAddress() {\n return address;\n }\n\n public String getDateCaptured() {\n return dateCaptured;\n }\n\n protected HashInfoModalBottomArgs(Parcel in) {\n ssid = in.readString();\n bssid = in.readString();\n clientMacAddress = in.readString();\n keyType = in.readString();\n keyData = in.readString();\n aNonce = in.readString();\n hashData = in.readString();\n latitude = in.readString();\n longitude = in.readString();\n address = in.readString();\n dateCaptured = in.readString();\n }\n\n public static final Creator<HashInfoModalBottomArgs> CREATOR = new Creator<>() {\n @Override\n public HashInfoModalBottomArgs createFromParcel(Parcel in) {\n return new HashInfoModalBottomArgs(in);\n }\n\n @Override\n public HashInfoModalBottomArgs[] newArray(int size) {\n return new HashInfoModalBottomArgs[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(ssid);\n dest.writeString(bssid);\n dest.writeString(clientMacAddress);\n dest.writeString(keyType);\n dest.writeString(keyData);\n dest.writeString(aNonce);\n dest.writeString(hashData);\n dest.writeString(latitude);\n dest.writeString(longitude);\n dest.writeString(address);\n dest.writeString(dateCaptured);\n }\n}" } ]
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.card.MaterialCardView; import com.johndeweydev.awps.R; import com.johndeweydev.awps.model.data.HashInfoEntity; import com.johndeweydev.awps.view.hashinfomodalbottomsheetdialog.HashInfoModalBottomArgs; import java.util.ArrayList;
1,608
package com.johndeweydev.awps.view.hashesfragment; public class HashesRvAdapter extends RecyclerView.Adapter<HashesRvAdapter.HashesAdapterViewHolder> { public interface Event {
package com.johndeweydev.awps.view.hashesfragment; public class HashesRvAdapter extends RecyclerView.Adapter<HashesRvAdapter.HashesAdapterViewHolder> { public interface Event {
void onHashInfoClick(HashInfoModalBottomArgs hashInfoModalBottomArgs);
1
2023-11-15 15:54:39+00:00
4k
Samuel-Ricardo/Pic-Pay_simplified
src/test/java/com/picpay/payment/service/transaction/TransactionServiceTest.java
[ { "identifier": "TransactionServiceImpl", "path": "src/main/java/com/picpay/payment/application/service/TransactionServiceImpl.java", "snippet": "@Service\npublic class TransactionServiceImpl implements TransactionService {\n\n @Autowired\n private AuthorizationService authorizationService;\n @Autowired\n private UserService userService;\n\n @Autowired\n private MerchantUserCantTransactPolicy merchantUserCantTransactPolicy;\n @Autowired\n private CannotTransactWithoutSufficientBalancePolicy cannotTransactWithoutSufficientBalancePolicy;\n @Autowired\n private SendNotificationOnTransactPolicy sendNotificationOnTransactPolicy;\n\n @Autowired\n private TransactionUseCase transct;\n @Autowired\n private SaveTransactionUseCase save;\n @Autowired\n private FindAllTransactionsUseCase findAllTransactions;\n\n @Override\n public boolean validate(User sender, BigDecimal amount) throws Exception {\n\n if(merchantUserCantTransactPolicy.execute(sender.getUserType()))\n throw new Exception(\"Merchant User is not authorized to transact\");\n\n if(cannotTransactWithoutSufficientBalancePolicy.execute(sender, amount))\n throw new Exception(\"Balance is not enough\");\n\n if(!authorizationService.isTransactionAuthorized(sender, amount))\n throw new Exception(\"Transaction Not Authorized, try again later...\");\n\n return true;\n }\n\n @Override\n public Transaction transact(TransactionDTO dto) throws Exception {\n\n var sender = userService.findUserById(dto.senderId());\n this.validate(sender, dto.value());\n var receiver = userService.findUserById(dto.receiverId());\n\n var transaction = new Transaction();\n\n transaction.setSender(sender);\n transaction.setReceiver(receiver);\n transaction.setAmount(dto.value());\n\n transaction = transct.execute(transaction);\n transaction = save.execute(transaction);\n\n userService.saveUser(transaction.getSender());\n userService.saveUser(transaction.getReceiver());\n\n sendNotificationOnTransactPolicy.execute(transaction);\n\n return transaction;\n }\n\n @Override\n public List<Transaction> findAll() {\n return findAllTransactions.execute();\n }\n}" }, { "identifier": "SaveTransactionUseCase", "path": "src/main/java/com/picpay/payment/application/usecase/transaction/SaveTransactionUseCase.java", "snippet": "@Component\npublic class SaveTransactionUseCase {\n\n @Autowired\n private TransactionRepository repository;\n\n public Transaction execute(Transaction transaction){\n return repository.save(transaction);\n }\n}" }, { "identifier": "TransactionUseCase", "path": "src/main/java/com/picpay/payment/application/usecase/transaction/TransactionUseCase.java", "snippet": "@Component\npublic class TransactionUseCase {\n public Transaction execute(Transaction transaction){\n var sender = transaction.getSender();\n var receiver = transaction.getReceiver();\n\n sender\n .setBalance(\n sender\n .getBalance()\n .subtract(transaction.getAmount())\n );\n\n receiver\n .setBalance(\n receiver\n .getBalance()\n .add(transaction.getAmount()));\n\n return transaction;\n }\n}" }, { "identifier": "UserData", "path": "src/test/java/com/picpay/payment/data/UserData.java", "snippet": "@ActiveProfiles(\"test\")\npublic class UserData {\n\n public static final UserDTO VALID_COMMON_USER_DATA = new UserDTO(\n \"User\",\n \"Common\",\n \"12345678901\",\n new BigDecimal(1000),\n \"[email protected]\",\n \"123456\",\n COMMON,\n USER\n );\n\n public static final User VALID_COMON_USER = User.from(VALID_COMMON_USER_DATA);\n\n public static UserDTO RANDOM_VALID_COMMON_USER_DATA() {\n return new UserDTO(\n Math.random()+\"\",\n Math.random()+\"\",\n Math.random()+\"\",\n new BigDecimal(2000),\n Math.random()+\"@mail.com\",\n Math.random()+\"\",\n COMMON,\n USER\n );\n }\n\n public static User RANDOM_VALID_COMMON_USER() {\n var user = User.from(RANDOM_VALID_COMMON_USER_DATA());\n user.setId(UUID.randomUUID());\n return user;\n }\n\n public static final UserDTO VALID_MERCHANT_USER_DATA = new UserDTO(\n \"User2\",\n \"Merchant\",\n \"12345678902\",\n new BigDecimal(2000),\n \"[email protected]\",\n \"123456\",\n MERCHANT,\n USER\n );\n\n public static final User VALID_MERCHANT_USER = User.from(VALID_MERCHANT_USER_DATA);\n\n}" }, { "identifier": "TransactionData", "path": "src/test/java/com/picpay/payment/data/TransactionData.java", "snippet": "@ActiveProfiles(\"test\")\npublic class TransactionData {\n\n public static final User SENDER = RANDOM_VALID_COMMON_USER();\n public static final User RECEIVER = RANDOM_VALID_COMMON_USER();\n\n public static final TransactionDTO VALID_TRANSACTION_DATA = new TransactionDTO(\n new BigDecimal(100),\n SENDER.getId(),\n RECEIVER.getId()\n );\n\n public static final Transaction VALID_TRANSACTION = new Transaction(\n UUID.randomUUID(),\n new BigDecimal(1000),\n SENDER,\n RECEIVER,\n LocalDateTime.now()\n );\n\n}" }, { "identifier": "TransactionData", "path": "src/test/java/com/picpay/payment/data/TransactionData.java", "snippet": "@ActiveProfiles(\"test\")\npublic class TransactionData {\n\n public static final User SENDER = RANDOM_VALID_COMMON_USER();\n public static final User RECEIVER = RANDOM_VALID_COMMON_USER();\n\n public static final TransactionDTO VALID_TRANSACTION_DATA = new TransactionDTO(\n new BigDecimal(100),\n SENDER.getId(),\n RECEIVER.getId()\n );\n\n public static final Transaction VALID_TRANSACTION = new Transaction(\n UUID.randomUUID(),\n new BigDecimal(1000),\n SENDER,\n RECEIVER,\n LocalDateTime.now()\n );\n\n}" }, { "identifier": "Transaction", "path": "src/main/java/com/picpay/payment/domain/entities/transaction/Transaction.java", "snippet": "@Entity(name = \"tb_transactions\") @Table(name = \"tb_transactions\")\n@AllArgsConstructor @NoArgsConstructor\n@EqualsAndHashCode(of = \"id\")\n@Getter @Setter\npublic class Transaction {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID id;\n private BigDecimal amount;\n @ManyToOne\n @JoinColumn(name = \"sender_id\")\n private User sender;\n @ManyToOne\n @JoinColumn(name = \"receiver_id\")\n private User receiver;\n @CreatedDate\n private LocalDateTime createdAt;\n}" }, { "identifier": "User", "path": "src/main/java/com/picpay/payment/domain/entities/user/User.java", "snippet": "@Entity(name = \"tb_users\") @Table(name = \"tb_users\")\n@AllArgsConstructor @NoArgsConstructor\n@EqualsAndHashCode(of = \"id\")\n@Getter @Setter\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n private String firstName;\n private String lastName;\n\n @Column(unique = true)\n private String email;\n private String password;\n\n @Column(unique = true)\n private String document;\n private BigDecimal balance;\n @Enumerated(EnumType.STRING)\n private UserType userType;\n\n @Enumerated\n private Role role;\n\n\n public static User from(UserDTO dto) {\n var user = new User();\n BeanUtils.copyProperties(dto, user);\n\n return user;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return role.getAuthorities();\n }\n\n @Override\n public String getUsername() {\n return email;\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}" }, { "identifier": "CannotTransactWithoutSufficientBalancePolicy", "path": "src/main/java/com/picpay/payment/domain/policy/transaction/CannotTransactWithoutSufficientBalancePolicy.java", "snippet": "public interface CannotTransactWithoutSufficientBalancePolicy {\n boolean execute(User sender, BigDecimal amount);\n}" }, { "identifier": "MerchantUserCantTransactPolicy", "path": "src/main/java/com/picpay/payment/domain/policy/transaction/MerchantUserCantTransactPolicy.java", "snippet": "public interface MerchantUserCantTransactPolicy {\n boolean execute(UserType userType);\n}" }, { "identifier": "SendNotificationOnTransactPolicy", "path": "src/main/java/com/picpay/payment/domain/policy/transaction/SendNotificationOnTransactPolicy.java", "snippet": "public interface SendNotificationOnTransactPolicy {\n void execute(Transaction transaction) throws Exception;\n}" }, { "identifier": "AuthorizationService", "path": "src/main/java/com/picpay/payment/domain/services/AuthorizationService.java", "snippet": "public interface AuthorizationService {\n boolean isTransactionAuthorized(User sender, BigDecimal value);\n}" }, { "identifier": "UserService", "path": "src/main/java/com/picpay/payment/domain/services/UserService.java", "snippet": "@Service\npublic interface UserService {\n\n public User findUserById(UUID id) throws Exception;\n\n public User saveUser(UserDTO data);\n\n public User saveUser(User data);\n\n public List<User> findAllUsers();\n\n public Optional<User> findUserByEmail(String email);\n\n}" } ]
import com.picpay.payment.application.service.TransactionServiceImpl; import com.picpay.payment.application.usecase.transaction.SaveTransactionUseCase; import com.picpay.payment.application.usecase.transaction.TransactionUseCase; import static com.picpay.payment.data.UserData.*; import static com.picpay.payment.data.TransactionData.*; import com.picpay.payment.data.TransactionData; import com.picpay.payment.domain.entities.transaction.Transaction; import com.picpay.payment.domain.entities.user.User; import com.picpay.payment.domain.policy.transaction.CannotTransactWithoutSufficientBalancePolicy; import com.picpay.payment.domain.policy.transaction.MerchantUserCantTransactPolicy; import com.picpay.payment.domain.policy.transaction.SendNotificationOnTransactPolicy; import com.picpay.payment.domain.services.AuthorizationService; import com.picpay.payment.domain.services.UserService; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import static org.mockito.MockitoAnnotations.openMocks; import static org.mockito.Mockito.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import java.math.BigDecimal; import java.util.UUID;
2,378
package com.picpay.payment.service.transaction; @ActiveProfiles("test") @SpringBootTest public class TransactionServiceTest {
package com.picpay.payment.service.transaction; @ActiveProfiles("test") @SpringBootTest public class TransactionServiceTest {
@Mock private AuthorizationService authorizationService;
11
2023-11-18 18:00:28+00:00
4k
sondosaabed/Taskaty
app/src/main/java/com/taskaty/taskManagment/FindTasks.java
[ { "identifier": "StatusInform", "path": "app/src/main/java/com/taskaty/informational/StatusInform.java", "snippet": "public class StatusInform extends AppCompatActivity {\n /*\n Attributes\n */\n Button back;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String status = getIntent().getStringExtra(\"status\");\n if (status != null)\n initialize(status);\n }\n\n private void initialize(@NonNull String status) {\n if(getSupportActionBar()!=null)\n getSupportActionBar().hide();\n\n // Based on the status the status layout will be shown\n /*\n replaced to switch sugeested by android studio\n */\n switch (status) {\n case \"completed\":\n setContentView(R.layout.completed);\n break;\n case \"updated\":\n setContentView(R.layout.edited);\n break;\n case \"added\":\n setContentView(R.layout.added);\n break;\n case \"deleted\":\n setContentView(R.layout.deleted);\n break;\n case \"not_found\":\n setContentView(R.layout.not_found);\n break;\n }\n setBack(findViewById(R.id.backHome));\n handle_back(getBack());\n }\n\n private void handle_back(Button back) {\n /*\n When the back button is clicked get back to the main which is TasksList\n */\n back.setOnClickListener(veiw ->{\n Intent intent = new Intent(this, TasksList.class);\n startActivity(intent);\n });\n }\n\n /*\n Getters & Setters\n */\n public void setBack(Button back) {\n this.back = back;\n }\n\n public Button getBack() {\n return back;\n }\n}" }, { "identifier": "Task", "path": "app/src/main/java/com/taskaty/model/Task.java", "snippet": "public class Task {\n /*\n Attributes\n */\n private int id;\n private String title; // The title of the task ex: Shopping For Mom\n private Boolean isDone; // If true then it is done, if false then it's to do\n private String description; // A description of the task I will make it optional\n private String category =\"None\"; // Personal, Work, Shopping, to-read, to-watch, None (I will make it optional\n private LocalDate dueDate; // They can set the due date of the task\n\n /*\n Constructor\n */\n public Task(String title, String description, String category, LocalDate dueDate, Boolean isDone) {\n setTitle(title);\n /*\n Because these are all optional for the user\n So I decided on the constructor, like to use one constructor instead of multi\n */\n if (category != null && !category.isEmpty()) {\n setCategory(category);\n }\n if (description != null && !description.isEmpty()) {\n setDescription(description);\n }\n if (dueDate != null) {\n setDueDate(dueDate);\n }\n setDone(isDone);\n }\n\n public Task(int id, String title, String description, String category, LocalDate dueDate, Boolean isDone) {\n setTitle(title);\n /*\n Because these are all optional for the user\n So I decided on the constructor, like to use one constructor instead of multi\n */\n if (category != null && !category.isEmpty()) {\n setCategory(category);\n }\n if (description != null && !description.isEmpty()) {\n setDescription(description);\n }\n if (dueDate != null) {\n setDueDate(dueDate);\n }\n setDone(isDone);\n setId(id);\n }\n /*\n I Used these icons to indicate it's done or not for better User experience\n */\n @NonNull\n @Override\n public String toString() {\n String title =getTittle();\n if(isDone){\n return \"✔ \" + title ;\n }else{\n return \"⊡ \" + title;\n }\n }\n\n /*\n Getters & Setters\n */\n public String getTittle() {\n return title;\n }\n public void setTitle(String title) {\n this.title = title;\n }\n public Boolean getDone() {\n return isDone;\n }\n public void setDone(Boolean done) {\n isDone = done;\n }\n public String getDescription() {\n return description;\n }\n public void setDescription(String description) {\n this.description = description;\n }\n public String getCategory() {\n return category;\n }\n public void setCategory(String category) {\n this.category = category;\n }\n public LocalDate getDueDate() {\n return dueDate;\n }\n public void setDueDate(LocalDate date) {\n this.dueDate = date;\n }\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n}" }, { "identifier": "Tasks", "path": "app/src/main/java/com/taskaty/model/Tasks.java", "snippet": "public class Tasks {\n private static ArrayList<Task> tasks;\n /*\n Operations on the list\n */\n\n public static void initTasks(Context context){\n tasks = Preferences.loadTasks(context);\n }\n\n public static void addTask(Task task){\n getTaskaty().add(task);\n //When I add a new Task I set the ID of the object Task as their index in the arrayList\n task.setId(getTaskaty().indexOf(task));\n Preferences.saveTaskaty(getTaskaty());\n }\n\n public static void updateTask(int oldID, Task updatedTask) {\n updatedTask.setId(oldID); // Becuase it's ID is suppose to stay the same\n getTaskaty().set(oldID, updatedTask);\n Preferences.saveTaskaty(getTaskaty());\n }\n\n public static void deleteTask(int selectedTaskID) {\n /* Since the user could have removed an elemnt at any index of the arrayylist\n * I need to update the following tasks ID's since I set their id (Object ID) to it's index */\n // if the removed task is not the last elment in the arraylist then the ids has to be updated\n getTaskaty().remove(selectedTaskID);\n getTaskaty().trimToSize();\n\n if(selectedTaskID < getTaskaty().size()){\n for(int i=getTaskaty().size()-1; i>=selectedTaskID; i--){\n getTaskaty().get(i).setId(getTaskaty().get(i).getId()-1);\n }\n }\n Preferences.saveTaskaty(getTaskaty());\n }\n\n public static ArrayList<Task> search(String keyword, String month, String category){\n /*\n I will search like when we use filters\n - If task name contains a keyword\n - Month Filter on the list\n - Category Filter on the list\n */\n ArrayList<Task> foundTasks = new ArrayList<>();\n ArrayList<Task> tasks = Tasks.getTaskaty();\n\n for(Task task: tasks){\n // I make them both lower case\n boolean containsKeyword = task.getTittle().toLowerCase().contains(keyword.toLowerCase());\n boolean inCategory = task.getCategory().equals(category) || category.equals(\"all\");\n LocalDate date =task.getDueDate();\n boolean inMonth = true;\n\n if(date!=null && !month.equals(\"all\")) {\n inMonth = (task.getDueDate().getMonthValue() ==\n LocalDate.parse(month.toUpperCase(Locale.ROOT)).getMonthValue())\n ;\n }\n if(containsKeyword && inCategory && inMonth){\n foundTasks.add(task);\n }\n }\n return foundTasks;\n }\n\n /*\n Getters & Setters\n */\n public static ArrayList<Task> getTaskaty() {\n return tasks;\n }\n}" } ]
import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import androidx.appcompat.app.AppCompatActivity; import com.taskaty.R; import com.taskaty.informational.StatusInform; import com.taskaty.model.Task; import com.taskaty.model.Tasks; import java.util.ArrayList;
2,225
package com.taskaty.taskManagment; /* I have created this activity to enable the user to search for existing tasks Using diffrent attributes: - If the name contains a keyword - If in a specific month - If have a specific category */ public class FindTasks extends AppCompatActivity { /* Attributes */ Button search; EditText keyword; Spinner month; Spinner categorySpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(); } private void initialize() { if(getSupportActionBar()!=null) getSupportActionBar().hide(); setContentView(R.layout.search); setSearch(findViewById(R.id.search)); setKeyword(findViewById(R.id.keyword)); setMonth(findViewById(R.id.monthSpinner)); setCategorySpinner(findViewById(R.id.categorySpinner2)); handle_serach(getSearch()); } /* Buttons Handlers */ private void handle_serach(Button search) { search.setOnClickListener(vewi->{ ArrayList<Task> foundtasks = Tasks.search(getKeyword().getText().toString(), getMonth().getSelectedItem().toString(), getCategorySpinner().getSelectedItem().toString()); if(foundtasks.size()!=0){ Intent intent = new Intent(this, FoundTasks.class); intent.putExtra("keyword",getKeyword().getText().toString()); intent.putExtra("month",getMonth().getSelectedItem().toString()); intent.putExtra("category",getCategorySpinner().getSelectedItem().toString()); startActivity(intent); }else{
package com.taskaty.taskManagment; /* I have created this activity to enable the user to search for existing tasks Using diffrent attributes: - If the name contains a keyword - If in a specific month - If have a specific category */ public class FindTasks extends AppCompatActivity { /* Attributes */ Button search; EditText keyword; Spinner month; Spinner categorySpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(); } private void initialize() { if(getSupportActionBar()!=null) getSupportActionBar().hide(); setContentView(R.layout.search); setSearch(findViewById(R.id.search)); setKeyword(findViewById(R.id.keyword)); setMonth(findViewById(R.id.monthSpinner)); setCategorySpinner(findViewById(R.id.categorySpinner2)); handle_serach(getSearch()); } /* Buttons Handlers */ private void handle_serach(Button search) { search.setOnClickListener(vewi->{ ArrayList<Task> foundtasks = Tasks.search(getKeyword().getText().toString(), getMonth().getSelectedItem().toString(), getCategorySpinner().getSelectedItem().toString()); if(foundtasks.size()!=0){ Intent intent = new Intent(this, FoundTasks.class); intent.putExtra("keyword",getKeyword().getText().toString()); intent.putExtra("month",getMonth().getSelectedItem().toString()); intent.putExtra("category",getCategorySpinner().getSelectedItem().toString()); startActivity(intent); }else{
Intent intent = new Intent(this, StatusInform.class);
0
2023-11-10 13:10:12+00:00
4k
Charles7c/continew-starter
continew-starter-log/continew-starter-log-common/src/main/java/top/charles7c/continew/starter/log/common/model/LogRequest.java
[ { "identifier": "ExceptionUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ExceptionUtils.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExceptionUtils {\n\n /**\n * 打印线程异常信息\n *\n * @param runnable 线程执行内容\n * @param throwable 异常\n */\n public static void printException(Runnable runnable, Throwable throwable) {\n if (null == throwable && runnable instanceof Future<?> future) {\n try {\n if (future.isDone()) {\n future.get();\n }\n } catch (CancellationException e) {\n throwable = e;\n } catch (ExecutionException e) {\n throwable = e.getCause();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n if (null != throwable) {\n log.error(throwable.getMessage(), throwable);\n }\n }\n\n /**\n * 如果有异常,返回 null\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param <T> /\n * @return /\n */\n public static <T> T exToNull(ExSupplier<T> exSupplier) {\n return exToDefault(exSupplier, null);\n }\n\n /**\n * 如果有异常,执行异常处理\n *\n * @param supplier 可能会出现异常的方法执行\n * @param exConsumer 异常处理\n * @param <T> /\n * @return /\n */\n public static <T> T exToNull(ExSupplier<T> supplier, Consumer<Exception> exConsumer) {\n return exToDefault(supplier, null, exConsumer);\n }\n\n /**\n * 如果有异常,返回空字符串\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @return /\n */\n public static String exToBlank(ExSupplier<String> exSupplier) {\n return exToDefault(exSupplier, StringConstants.EMPTY);\n }\n\n /**\n * 如果有异常,返回默认值\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param defaultValue 默认值\n * @param <T> /\n * @return /\n */\n public static <T> T exToDefault(ExSupplier<T> exSupplier, T defaultValue) {\n return exToDefault(exSupplier, defaultValue, null);\n }\n\n /**\n * 如果有异常,执行异常处理,返回默认值\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param defaultValue 默认值\n * @param exConsumer 异常处理\n * @param <T> /\n * @return /\n */\n public static <T> T exToDefault(ExSupplier<T> exSupplier, T defaultValue, Consumer<Exception> exConsumer) {\n try {\n return exSupplier.get();\n } catch (Exception e) {\n if (null != exConsumer) {\n exConsumer.accept(e);\n }\n return defaultValue;\n }\n }\n\n /**\n * 异常提供者\n *\n * @param <T> /\n */\n public interface ExSupplier<T> {\n /**\n * 获取返回值\n *\n * @return /\n * @throws Exception /\n */\n T get() throws Exception;\n }\n}" }, { "identifier": "IpUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/IpUtils.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class IpUtils {\n\n /**\n * 太平洋网开放 API:查询 IP 归属地\n */\n private static final String IP_URL = \"http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true\";\n\n /**\n * 查询 IP 归属地\n *\n * @param ip IP 地址\n * @return IP 归属地\n */\n public static String getAddress(String ip) {\n if (ProjectProperties.IP_ADDR_LOCAL_PARSE_ENABLED) {\n return getAddressByLocal(ip);\n } else {\n return getAddressByHttp(ip);\n }\n }\n\n /**\n * 查询 IP 归属地(网络解析)\n *\n * @param ip IP 地址\n * @return IP 归属地\n */\n public static String getAddressByHttp(String ip) {\n if (isInnerIp(ip)) {\n return \"内网IP\";\n }\n String api = String.format(IP_URL, ip);\n JSONObject object = JSONUtil.parseObj(HttpUtil.get(api));\n return object.get(\"addr\", String.class);\n }\n\n /**\n * 查询 IP 归属地(本地库解析)\n *\n * @param ip IP 地址\n * @return IP 归属地\n */\n public static String getAddressByLocal(String ip) {\n if (isInnerIp(ip)) {\n return \"内网IP\";\n }\n Ip2regionSearcher ip2regionSearcher = SpringUtil.getBean(Ip2regionSearcher.class);\n IpInfo ipInfo = ip2regionSearcher.memorySearch(ip);\n if (null != ipInfo) {\n Set<String> regionSet = CollUtil.newLinkedHashSet(ipInfo.getAddress(), ipInfo.getIsp());\n regionSet.removeIf(StrUtil::isBlank);\n return String.join(StringConstants.SPACE, regionSet);\n }\n return null;\n }\n\n /**\n * 是否为内网 IPv4\n *\n * @param ip IP 地址\n * @return 是否为内网 IP\n */\n public static boolean isInnerIp(String ip) {\n ip = \"0:0:0:0:0:0:0:1\".equals(ip) ? \"127.0.0.1\" : HtmlUtil.cleanHtmlTag(ip);\n return NetUtil.isInnerIP(ip);\n }\n}" }, { "identifier": "ServletUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ServletUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ServletUtils {\n\n /**\n * 获取请求对象\n *\n * @return /\n */\n public static HttpServletRequest getRequest() {\n return getServletRequestAttributes().getRequest();\n }\n\n /**\n * 获取响应对象\n *\n * @return /\n */\n public static HttpServletResponse getResponse() {\n return getServletRequestAttributes().getResponse();\n }\n\n /**\n * 获取浏览器及其版本信息\n *\n * @param request 请求对象\n * @return 浏览器及其版本信息\n */\n public static String getBrowser(HttpServletRequest request) {\n if (null == request) {\n return null;\n }\n return getBrowser(request.getHeader(\"User-Agent\"));\n }\n\n /**\n * 获取浏览器及其版本信息\n *\n * @param userAgentString User-Agent 字符串\n * @return 浏览器及其版本信息\n */\n public static String getBrowser(String userAgentString) {\n UserAgent userAgent = UserAgentUtil.parse(userAgentString);\n return userAgent.getBrowser().getName() + StringConstants.SPACE + userAgent.getVersion();\n }\n\n /**\n * 获取操作系统\n *\n * @param request 请求对象\n * @return 操作系统\n */\n public static String getOs(HttpServletRequest request) {\n if (null == request) {\n return null;\n }\n return getOs(request.getHeader(\"User-Agent\"));\n }\n\n /**\n * 获取操作系统\n *\n * @param userAgentString User-Agent 字符串\n * @return 操作系统\n */\n public static String getOs(String userAgentString) {\n UserAgent userAgent = UserAgentUtil.parse(userAgentString);\n return userAgent.getOs().getName();\n }\n\n /**\n * 获取响应所有的头(header)信息\n *\n * @param response 响应对象{@link HttpServletResponse}\n * @return header值\n */\n public static Map<String, String> getHeaderMap(HttpServletResponse response) {\n final Collection<String> headerNames = response.getHeaderNames();\n final Map<String, String> headerMap = MapUtil.newHashMap(headerNames.size(), true);\n for (String name : headerNames) {\n headerMap.put(name, response.getHeader(name));\n }\n return headerMap;\n }\n\n private static ServletRequestAttributes getServletRequestAttributes() {\n return (ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes());\n }\n}" }, { "identifier": "Include", "path": "continew-starter-log/continew-starter-log-common/src/main/java/top/charles7c/continew/starter/log/common/enums/Include.java", "snippet": "public enum Include {\n\n /**\n * 描述\n */\n DESCRIPTION,\n\n /**\n * 模块\n */\n MODULE,\n\n /**\n * 请求头(默认)\n */\n REQUEST_HEADERS,\n\n /**\n * 请求体(如包含请求体,则请求参数无效)\n */\n REQUEST_BODY,\n\n /**\n * 请求参数(默认)\n */\n REQUEST_PARAM,\n\n /**\n * IP 归属地\n */\n IP_ADDRESS,\n\n /**\n * 浏览器\n */\n BROWSER,\n\n /**\n * 操作系统\n */\n OS,\n\n /**\n * 响应头(默认)\n */\n RESPONSE_HEADERS,\n\n /**\n * 响应体(如包含响应体,则响应参数无效)\n */\n RESPONSE_BODY,\n\n /**\n * 响应参数(默认)\n */\n RESPONSE_PARAM,\n ;\n\n private static final Set<Include> DEFAULT_INCLUDES;\n\n static {\n Set<Include> defaultIncludes = new LinkedHashSet<>();\n defaultIncludes.add(Include.REQUEST_HEADERS);\n defaultIncludes.add(Include.RESPONSE_HEADERS);\n defaultIncludes.add(Include.REQUEST_PARAM);\n defaultIncludes.add(Include.RESPONSE_PARAM);\n DEFAULT_INCLUDES = Collections.unmodifiableSet(defaultIncludes);\n }\n\n /**\n * 获取默认包含信息\n *\n * @return 默认包含信息\n */\n public static Set<Include> defaultIncludes() {\n return DEFAULT_INCLUDES;\n }\n}" } ]
import cn.hutool.core.util.StrUtil; import lombok.Data; import org.springframework.http.HttpHeaders; import top.charles7c.continew.starter.core.util.ExceptionUtils; import top.charles7c.continew.starter.core.util.IpUtils; import top.charles7c.continew.starter.core.util.ServletUtils; import top.charles7c.continew.starter.log.common.enums.Include; import java.net.URI; import java.util.Map; import java.util.Set;
3,184
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * 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.charles7c.continew.starter.log.common.model; /** * 请求信息 * * @author Charles7c * @since 1.1.0 */ @Data public class LogRequest { /** * 请求方式 */ private String method; /** * 请求 URL */ private URI url; /** * IP */ private String ip; /** * 请求头 */ private Map<String, String> headers; /** * 请求体(JSON 字符串) */ private String body; /** * 请求参数 */ private Map<String, Object> param; /** * IP 归属地 */ private String address; /** * 浏览器 */ private String browser; /** * 操作系统 */ private String os; public LogRequest(RecordableHttpRequest request, Set<Include> includes) { this.method = request.getMethod(); this.url = request.getUrl(); this.ip = request.getIp(); this.headers = (includes.contains(Include.REQUEST_HEADERS)) ? request.getHeaders() : null; if (includes.contains(Include.REQUEST_BODY)) { this.body = request.getBody(); } else if (includes.contains(Include.REQUEST_PARAM)) { this.param = request.getParam(); } this.address = (includes.contains(Include.IP_ADDRESS)) ? IpUtils.getAddress(this.ip) : null;
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * 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.charles7c.continew.starter.log.common.model; /** * 请求信息 * * @author Charles7c * @since 1.1.0 */ @Data public class LogRequest { /** * 请求方式 */ private String method; /** * 请求 URL */ private URI url; /** * IP */ private String ip; /** * 请求头 */ private Map<String, String> headers; /** * 请求体(JSON 字符串) */ private String body; /** * 请求参数 */ private Map<String, Object> param; /** * IP 归属地 */ private String address; /** * 浏览器 */ private String browser; /** * 操作系统 */ private String os; public LogRequest(RecordableHttpRequest request, Set<Include> includes) { this.method = request.getMethod(); this.url = request.getUrl(); this.ip = request.getIp(); this.headers = (includes.contains(Include.REQUEST_HEADERS)) ? request.getHeaders() : null; if (includes.contains(Include.REQUEST_BODY)) { this.body = request.getBody(); } else if (includes.contains(Include.REQUEST_PARAM)) { this.param = request.getParam(); } this.address = (includes.contains(Include.IP_ADDRESS)) ? IpUtils.getAddress(this.ip) : null;
String userAgentString = ExceptionUtils.exToNull(() -> this.headers.get(HttpHeaders.USER_AGENT));
0
2023-11-16 15:48:18+00:00
4k
luca-software-developer/CalcolatriceScientificaGruppo04
CalcolatriceScientificaGruppo04/src/test/java/it/unisa/diem/ids2023/rpnpsc/RPNStackTest.java
[ { "identifier": "EmptyStackException", "path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/EmptyStackException.java", "snippet": "public class EmptyStackException extends RPNException {\n\n /**\n * Costruttore della classe {@code EmptyStackException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public EmptyStackException(String headerText, String contentText) {\n super(headerText, contentText);\n }\n\n}" }, { "identifier": "InsufficientArgumentsException", "path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/InsufficientArgumentsException.java", "snippet": "public class InsufficientArgumentsException extends RPNException {\n\n /**\n * Costruttore della classe {@code InsufficientArgumentsException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public InsufficientArgumentsException(String headerText, String contentText) {\n super(headerText, contentText);\n }\n\n}" } ]
import it.unisa.diem.ids2023.rpnpsc.exceptions.EmptyStackException; import it.unisa.diem.ids2023.rpnpsc.exceptions.InsufficientArgumentsException; import javafx.collections.ObservableList; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
2,796
public void testSolve9() throws Exception { System.out.println("solve #9"); RPNStack instance = new RPNStack(); instance.push("-2.51+0.73j"); instance.push("*"); assertThrows(InsufficientArgumentsException.class, () -> { instance.solve(); }); } /** * UT-2.8.10 Test of solve method #10, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve10() throws Exception { System.out.println("solve #10"); RPNStack instance = new RPNStack(); instance.push("-7.61-2.25j"); instance.push("0"); instance.push("/"); assertThrows(ArithmeticException.class, () -> { instance.solve(); }); } /** * UT-2.9.1 Test of isEmpty method #1, of class RPNStack. */ @Test public void testIsEmpty1() { System.out.println("isEmpty #1"); RPNStack instance = new RPNStack(); boolean expResult = true; boolean result = instance.isEmpty(); assertEquals(expResult, result); } /** * UT-2.9.2 Test of isEmpty method #2, of class RPNStack. */ @Test public void testIsEmpty2() { System.out.println("isEmpty #2"); RPNStack instance = new RPNStack(); instance.push("-0.22j"); boolean expResult = false; boolean result = instance.isEmpty(); assertEquals(expResult, result); } /** * UT-2.10.1 Test of push method #1, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPush1() throws Exception { System.out.println("push #1"); String item = "-5.44+3.12j"; RPNStack instance = new RPNStack(); instance.push(item); assertEquals(instance.top(), item); } /** * UT-2.10.2 Test of push method #2, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPush2() throws Exception { System.out.println("push #2"); String item = "+-"; RPNStack instance = new RPNStack(); instance.push(item); assertEquals(instance.top(), item); } /** * UT-2.11.1 Test of pop method #1, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop1() throws Exception { System.out.println("pop #1"); RPNStack instance = new RPNStack(); instance.push("0.75j"); instance.push("-0.22+4.13j"); instance.pop(); assertEquals(instance.size(), 1); assertEquals(instance.top(), "0.75j"); } /** * UT-2.11.2 Test of pop method #2, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop2() throws Exception { System.out.println("pop #2"); RPNStack instance = new RPNStack(); instance.push("-0.22+4.13j"); String expResult = "-0.22+4.13j"; String result = instance.pop(); assertEquals(expResult, result); } /** * UT-2.11.3 Test of pop method #3, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop3() throws Exception { System.out.println("pop #3"); RPNStack instance = new RPNStack();
package it.unisa.diem.ids2023.rpnpsc; public class RPNStackTest { public RPNStackTest() { } @BeforeAll public static void setUpClass() { } @AfterAll public static void tearDownClass() { } @BeforeEach public void setUp() { } @AfterEach public void tearDown() { } /** * UT-2.1.1 Test of getObservableList method #1, of class RPNStack. */ @Test public void testGetObservableList1() { System.out.println("getObservableList #1"); RPNStack instance = new RPNStack(); ObservableList<String> result = instance.getObservableList(); assertTrue(result instanceof ObservableList); } /** * UT-2.1.2 Test of getObservableList method #2, of class RPNStack. */ @Test public void testGetObservableList2() { System.out.println("getObservableList #2"); RPNStack instance = new RPNStack(); ObservableList<String> result = instance.getObservableList(); assertTrue(result.isEmpty()); } /** * UT-2.2.1 Test of isOperand method #1, of class RPNStack. */ @Test public void testIsOperand1() { System.out.println("isOperand #1"); String item = "-0.67j"; boolean expResult = true; boolean result = RPNStack.isOperand(item); assertEquals(expResult, result); } /** * UT-2.2.2 Test of isOperand method #2, of class RPNStack. */ @Test public void testIsOperand2() { System.out.println("isOperand #2"); String item = "+-"; boolean expResult = false; boolean result = RPNStack.isOperand(item); assertEquals(expResult, result); } /** * UT-2.3.1 Test of isBinaryOperator method #1, of class RPNStack. */ @Test public void testIsBinaryOperator1() { System.out.println("isBinaryOperator #1"); String item = "/"; boolean expResult = true; boolean result = RPNStack.isBinaryOperator(item); assertEquals(expResult, result); } /** * UT-2.3.2 Test of isBinaryOperator method #2, of class RPNStack. */ @Test public void testIsBinaryOperator2() { System.out.println("isBinaryOperator #2"); String item = "sqrt"; boolean expResult = false; boolean result = RPNStack.isBinaryOperator(item); assertEquals(expResult, result); } /** * UT-2.4.1 Test of isUnaryOperator method #1, of class RPNStack. */ @Test public void testIsUnaryOperator1() { System.out.println("isUnaryOperator #1"); String item = "+-"; boolean expResult = true; boolean result = RPNStack.isUnaryOperator(item); assertEquals(expResult, result); } /** * UT-2.4.2 Test of isUnaryOperator method #2, of class RPNStack. */ @Test public void testIsUnaryOperator2() { System.out.println("isUnaryOperator #2"); String item = "-"; boolean expResult = false; boolean result = RPNStack.isUnaryOperator(item); assertEquals(expResult, result); } /** * UT-2.5.1 Test of isOperator method #1, of class RPNStack. */ @Test public void testIsOperator1() { System.out.println("isOperator #1"); String item = "sqrt"; boolean expResult = true; boolean result = RPNStack.isOperator(item); assertEquals(expResult, result); } /** * UT-2.5.2 Test of isOperator method #2, of class RPNStack. */ @Test public void testIsOperator2() { System.out.println("isOperator #2"); String item = "*"; boolean expResult = true; boolean result = RPNStack.isOperator(item); assertEquals(expResult, result); } /** * UT-2.5.3 Test of isOperator method #3, of class RPNStack. */ @Test public void testIsOperator3() { System.out.println("isOperator #3"); String item = "-0.36-6.21j"; boolean expResult = false; boolean result = RPNStack.isOperator(item); assertEquals(expResult, result); } /** * UT-2.6.1 Test of isStackManipulation method #1, of class RPNStack. */ @Test public void testIsStackManipulation1() { System.out.println("isStackManipulation #1"); String item = "over"; boolean expResult = true; boolean result = RPNStack.isStackManipulation(item); assertEquals(expResult, result); } /** * UT-2.6.2 Test of isStackManipulation method #2, of class RPNStack. */ @Test public void testIsStackManipulation2() { System.out.println("isStackManipulation #2"); String item = "sqrt"; boolean expResult = false; boolean result = RPNStack.isStackManipulation(item); assertEquals(expResult, result); } /** * UT-2.6.3 Test of isStackManipulation method #3, of class RPNStack. */ @Test public void testIsStackManipulation3() { System.out.println("isStackManipulation #3"); String item = "-1.47+7.11j"; boolean expResult = false; boolean result = RPNStack.isStackManipulation(item); assertEquals(expResult, result); } /** * UT-2.7.1 Test of isVariableOperation method #1, of class RPNStack. */ @Test public void testIsVariableOperation1() { System.out.println("isVariableOperation #1"); String item = "-x"; boolean expResult = true; boolean result = RPNStack.isVariableOperation(item); assertEquals(expResult, result); } /** * UT-2.7.2 Test of isVariableOperation method #2, of class RPNStack. */ @Test public void testIsVariableOperation2() { System.out.println("isVariableOperation #2"); String item = ">y"; boolean expResult = true; boolean result = RPNStack.isVariableOperation(item); assertEquals(expResult, result); } /** * UT-2.7.3 Test of isVariableOperation method #3, of class RPNStack. */ @Test public void testIsVariableOperation3() { System.out.println("isVariableOperation #3"); String item = "z-"; boolean expResult = false; boolean result = RPNStack.isVariableOperation(item); assertEquals(expResult, result); } /** * UT-2.7.4 Test of isVariableOperation method #4, of class RPNStack. */ @Test public void testIsVariableOperation4() { System.out.println("isVariableOperation #4"); String item = "<<"; boolean expResult = false; boolean result = RPNStack.isVariableOperation(item); assertEquals(expResult, result); } /** * UT-2.8.1 Test of solve method #1, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve1() throws Exception { System.out.println("solve #1"); RPNStack instance = new RPNStack(); assertThrows(InsufficientArgumentsException.class, () -> { instance.solve(); }); } /** * UT-2.8.2 Test of solve method #2, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve2() throws Exception { System.out.println("solve #2"); RPNStack instance = new RPNStack(); instance.push("0.46+0.11j"); instance.push("-3.37j"); instance.push("+"); Complex expResult = new Complex(0.46, -3.26); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.3 Test of solve method #3, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve3() throws Exception { System.out.println("solve #3"); RPNStack instance = new RPNStack(); instance.push("-1.73j"); instance.push("4.88-5.94j"); instance.push("-"); Complex expResult = new Complex(-4.88, 4.21); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.4 Test of solve method #4, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve4() throws Exception { System.out.println("solve #4"); RPNStack instance = new RPNStack(); instance.push("2.15+1.26j"); instance.push("-6.68j"); instance.push("*"); Complex expResult = new Complex(8.4168, -14.362); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.5 Test of solve method #5, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve5() throws Exception { System.out.println("solve #5"); RPNStack instance = new RPNStack(); instance.push("-4.57"); instance.push("1.33-2.71j"); instance.push("/"); Complex expResult = new Complex(-0.666970262262702, -1.359014594535279); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.6 Test of solve method #6, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve6() throws Exception { System.out.println("solve #6"); RPNStack instance = new RPNStack(); instance.push("-1.39j"); instance.push("+-"); Complex expResult = new Complex(0, 1.39); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.7 Test of solve method #7, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve7() throws Exception { System.out.println("solve #7"); RPNStack instance = new RPNStack(); instance.push("0.65-3.37j"); instance.push("sqrt"); Complex expResult = new Complex(-1.428655495868592, 1.179430593920444); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.8 Test of solve method #8, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve8() throws Exception { System.out.println("solve #8"); RPNStack instance = new RPNStack(); instance.push("0.67j"); instance.push("-5.28"); instance.push("-"); instance.push("+-"); instance.push("sqrt"); Complex expResult = new Complex(-0.14549864443858, 2.302426949011296); Complex result = instance.solve(); assertEquals(result.getRealPart(), expResult.getRealPart(), 1e-14); assertEquals(result.getImaginaryPart(), expResult.getImaginaryPart(), 1e-14); } /** * UT-2.8.9 Test of solve method #9, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve9() throws Exception { System.out.println("solve #9"); RPNStack instance = new RPNStack(); instance.push("-2.51+0.73j"); instance.push("*"); assertThrows(InsufficientArgumentsException.class, () -> { instance.solve(); }); } /** * UT-2.8.10 Test of solve method #10, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testSolve10() throws Exception { System.out.println("solve #10"); RPNStack instance = new RPNStack(); instance.push("-7.61-2.25j"); instance.push("0"); instance.push("/"); assertThrows(ArithmeticException.class, () -> { instance.solve(); }); } /** * UT-2.9.1 Test of isEmpty method #1, of class RPNStack. */ @Test public void testIsEmpty1() { System.out.println("isEmpty #1"); RPNStack instance = new RPNStack(); boolean expResult = true; boolean result = instance.isEmpty(); assertEquals(expResult, result); } /** * UT-2.9.2 Test of isEmpty method #2, of class RPNStack. */ @Test public void testIsEmpty2() { System.out.println("isEmpty #2"); RPNStack instance = new RPNStack(); instance.push("-0.22j"); boolean expResult = false; boolean result = instance.isEmpty(); assertEquals(expResult, result); } /** * UT-2.10.1 Test of push method #1, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPush1() throws Exception { System.out.println("push #1"); String item = "-5.44+3.12j"; RPNStack instance = new RPNStack(); instance.push(item); assertEquals(instance.top(), item); } /** * UT-2.10.2 Test of push method #2, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPush2() throws Exception { System.out.println("push #2"); String item = "+-"; RPNStack instance = new RPNStack(); instance.push(item); assertEquals(instance.top(), item); } /** * UT-2.11.1 Test of pop method #1, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop1() throws Exception { System.out.println("pop #1"); RPNStack instance = new RPNStack(); instance.push("0.75j"); instance.push("-0.22+4.13j"); instance.pop(); assertEquals(instance.size(), 1); assertEquals(instance.top(), "0.75j"); } /** * UT-2.11.2 Test of pop method #2, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop2() throws Exception { System.out.println("pop #2"); RPNStack instance = new RPNStack(); instance.push("-0.22+4.13j"); String expResult = "-0.22+4.13j"; String result = instance.pop(); assertEquals(expResult, result); } /** * UT-2.11.3 Test of pop method #3, of class RPNStack. * * @throws java.lang.Exception */ @Test public void testPop3() throws Exception { System.out.println("pop #3"); RPNStack instance = new RPNStack();
assertThrows(EmptyStackException.class, () -> {
0
2023-11-17 20:16:14+00:00
4k
SplitfireUptown/datalinkx
datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/service/MessageHubServiceImpl.java
[ { "identifier": "BaseMessageForm", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/bean/form/BaseMessageForm.java", "snippet": "@Data\npublic class BaseMessageForm {\n // 消息组件类型\n private String type;\n // 消费主题\n private String topic;\n // 消费者组\n private String group = \"datalinkx\";\n}" }, { "identifier": "ConsumerAdapterForm", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/bean/form/ConsumerAdapterForm.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ConsumerAdapterForm extends BaseMessageForm {\n\n // 消费者名称,配合消费者组\n private String consumerName = \"datalinkx-consumer\";\n\n // 消费者回调函数名\n private Method invokeMethod;\n\n // 特殊类型需要传递spring bean对象\n private Object bean;\n\n public String getTopic() {\n return MessageHubConstants.getExternalTopicName(super.getType(), super.getTopic());\n }\n}" }, { "identifier": "ProducerAdapterForm", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/bean/form/ProducerAdapterForm.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class ProducerAdapterForm extends BaseMessageForm {\n\n private String message = \"\";\n\n public String getTopic() {\n return MessageHubConstants.getExternalTopicName(super.getType(), super.getTopic());\n }\n}" }, { "identifier": "MessageHubConstants", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MessageHubConstants.java", "snippet": "public class MessageHubConstants {\n\n public static final String WHITE_TOPIC = \"DATALINKX:MESSAGEHUB:TOPIC\";\n\n public static final String REDIS_STREAM_TYPE = \"REDIS_STREAM\";\n public static final String REDIS_PUBSUB_TYPE = \"REDIS_PUBSUB\";\n public static final String REDIS_QUEUE_TYPE = \"REDIS_QUEUE\";\n\n public static final String GLOBAL_PREFIX = \"MESSAGEHUB\";\n public static final String GLOBAL_COMMON_GROUP = \"datalinkx\";\n\n public static final String JOB_PROGRESS_TOPIC = \"JOB_PROGRESS\";\n\n\n /**\n * 白名单中包装的topic\n */\n public static String getInnerTopicName(String type, String topic) {\n return String.format(\"%s:%s\", type, topic);\n }\n\n /**\n * 生产者、消费者保护脏的topic\n */\n public static String getExternalTopicName(String type, String topic) {\n return String.format(\"%s:%s:%s\", GLOBAL_PREFIX, type, topic);\n }\n}" }, { "identifier": "RedisPubSubProcessor", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/service/redis/RedisPubSubProcessor.java", "snippet": "@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)\n@Service(\"redisPubSubProcessor\")\npublic class RedisPubSubProcessor extends MessageHubServiceImpl {\n\n @Resource\n RedisMessageListenerContainer redisPubSubContainer;\n\n @Override\n public void produce(ProducerAdapterForm producerAdapterForm) {\n stringRedisTemplate.convertAndSend(producerAdapterForm.getTopic(), producerAdapterForm.getMessage());\n }\n\n @Override\n public void consume(ConsumerAdapterForm messageForm) {\n MessageListenerAdapter adapter = new MessageListenerAdapter(messageForm.getBean(), messageForm.getInvokeMethod().getName());\n adapter.afterPropertiesSet();\n redisPubSubContainer.addMessageListener(adapter, new PatternTopic(messageForm.getTopic()));\n }\n\n\n @Bean\n public RedisMessageListenerContainer redisPubSubContainer(RedisConnectionFactory connectionFactory) {\n RedisMessageListenerContainer container = new RedisMessageListenerContainer();\n container.setConnectionFactory(connectionFactory);\n return container;\n }\n}" }, { "identifier": "RedisQueueProcessor", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/service/redis/RedisQueueProcessor.java", "snippet": "@Slf4j\n@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)\n@Service(\"redisQueueProcessor\")\npublic class RedisQueueProcessor extends MessageHubServiceImpl {\n\n @Override\n public void produce(ProducerAdapterForm producerAdapterForm) {\n stringRedisTemplate.opsForList().leftPush(producerAdapterForm.getTopic(), producerAdapterForm.getMessage());\n }\n\n /**\n * 照搬python common逻辑\n * @param messageForm\n */\n @Async\n @Override\n public void consume(ConsumerAdapterForm messageForm) {\n String topic = messageForm.getTopic();\n Object consumerBean = messageForm.getBean();\n Method invokeMethod = messageForm.getInvokeMethod();\n\n new Thread(() -> {\n while (true) {\n try {\n boolean isEmpty = stringRedisTemplate.opsForList().size(topic) == 0;\n if (isEmpty) {\n\n Thread.sleep(1000);\n continue;\n }\n\n String message = stringRedisTemplate.opsForList().rightPop(messageForm.getTopic());\n if (ObjectUtils.isEmpty(message)) {\n\n Thread.sleep(1000);\n continue;\n }\n\n invokeMethod.invoke(consumerBean, message);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n\n try {\n Thread.sleep(3000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n }\n }\n }).start();\n }\n}" }, { "identifier": "RedisStreamProcessor", "path": "datalinkx-messagehub/src/main/java/com/datalinkx/messagehub/service/redis/RedisStreamProcessor.java", "snippet": "@Slf4j\n@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)\n@Service(\"redisStreamProcessor\")\npublic class RedisStreamProcessor extends MessageHubServiceImpl {\n\n\n @Override\n public void produce(ProducerAdapterForm producerAdapterForm) {\n ObjectRecord<String, Object> stringObjectRecord = ObjectRecord.create(producerAdapterForm.getTopic(), producerAdapterForm.getMessage());\n stringRedisTemplate.opsForStream().add(stringObjectRecord);\n }\n\n @Async\n @Override\n public void consume(ConsumerAdapterForm messageForm) {\n\n String topic = messageForm.getTopic();\n String group = messageForm.getGroup();\n String consumerName = messageForm.getConsumerName();\n Object consumerBean = messageForm.getBean();\n Method invokeMethod = messageForm.getInvokeMethod();\n\n if (ObjectUtils.isEmpty(group)) {\n throw new Error(\"REDIS_STREAM消费类型未指定消费者组\");\n }\n\n new Thread(() -> {\n String lastOffset = null;\n\n StreamOperations<String, String, Object> streamOperations = this.stringRedisTemplate.opsForStream();\n\n if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(topic))) {\n StreamInfo.XInfoGroups groups = streamOperations.groups(topic);\n\n AtomicReference<Boolean> groupHasKey = new AtomicReference<>(false);\n\n groups.forEach(groupInfo -> {\n if (Objects.equals(group, groupInfo.getRaw().get(\"name\"))) {\n groupHasKey.set(true);\n }\n });\n\n if (groups.isEmpty() || !groupHasKey.get()) {\n String groupName = streamOperations.createGroup(topic, group);\n log.info(\"messagehub stream creatGroup:{}\", groupName);\n }\n } else {\n String groupName = streamOperations.createGroup(topic, group);\n log.info(\"messagehub stream creatGroup:{}\", groupName);\n }\n\n while (true) {\n try {\n ReadOffset readOffset = ReadOffset.lastConsumed();\n List<ObjectRecord<String, String>> messageList = streamOperations.read(\n String.class,\n Consumer.from(group, consumerName),\n StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),\n StreamOffset.create(topic, readOffset));\n\n if (ObjectUtils.isEmpty(messageList)) {\n // 如果为null,说明没有消息,继续下一次循环\n Thread.sleep(1000);\n continue;\n }\n\n ObjectRecord<String, String> record = messageList.get(0);\n lastOffset = record.getId().getValue();\n invokeMethod.invoke(consumerBean, record.getValue());\n\n stringRedisTemplate.opsForStream().acknowledge(group, record);\n } catch (Exception e) {\n log.error(\"messagehub stream consumer {} consume error, last offset: {}\", consumerName, lastOffset);\n log.error(e.getMessage(), e);\n try {\n Thread.sleep(3000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n }\n }\n }).start();\n }\n}" } ]
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import javax.annotation.Resource; import com.datalinkx.messagehub.bean.form.BaseMessageForm; import com.datalinkx.messagehub.bean.form.ConsumerAdapterForm; import com.datalinkx.messagehub.bean.form.ProducerAdapterForm; import com.datalinkx.common.constants.MessageHubConstants; import com.datalinkx.messagehub.service.redis.RedisPubSubProcessor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import com.datalinkx.messagehub.service.redis.RedisQueueProcessor; import com.datalinkx.messagehub.service.redis.RedisStreamProcessor;
2,259
package com.datalinkx.messagehub.service; @Slf4j @Service public class MessageHubServiceImpl implements MessageHubService, ApplicationContextAware { @Resource protected StringRedisTemplate stringRedisTemplate; public Map<String, MessageHubService> messageHubServiceMap = new ConcurrentHashMap<>(); private ApplicationContext applicationContext; @PostConstruct public void init() {
package com.datalinkx.messagehub.service; @Slf4j @Service public class MessageHubServiceImpl implements MessageHubService, ApplicationContextAware { @Resource protected StringRedisTemplate stringRedisTemplate; public Map<String, MessageHubService> messageHubServiceMap = new ConcurrentHashMap<>(); private ApplicationContext applicationContext; @PostConstruct public void init() {
this.messageHubServiceMap.put(MessageHubConstants.REDIS_PUBSUB_TYPE, applicationContext.getBean(RedisPubSubProcessor.class));
3
2023-11-16 02:22:52+00:00
4k
DJ-Raven/raven-dashboard
src/raven/main/Main.java
[ { "identifier": "MyDrawerBuilder", "path": "src/raven/drawer/MyDrawerBuilder.java", "snippet": "public class MyDrawerBuilder extends SimpleDrawerBuilder {\n\n @Override\n public SimpleHeaderData getSimpleHeaderData() {\n return new SimpleHeaderData()\n .setIcon(new AvatarIcon(getClass().getResource(\"/raven/image/profile.png\"), 60, 60, 999))\n .setTitle(\"Ra Ven\")\n .setDescription(\"[email protected]\");\n }\n\n @Override\n public SimpleMenuOption getSimpleMenuOption() {\n String menus[][] = {\n {\"~MAIN~\"},\n {\"Dashboard\"},\n {\"~WEB APP~\"},\n {\"Email\", \"Inbox\", \"Read\", \"Compost\"},\n {\"Chat\"},\n {\"Calendar\"},\n {\"~COMPONENT~\"},\n {\"Advanced UI\", \"Cropper\", \"Owl Carousel\", \"Sweet Alert\"},\n {\"Forms\", \"Basic Elements\", \"Advanced Elements\", \"SEditors\", \"Wizard\"},\n {\"~OTHER~\"},\n {\"Charts\", \"Apex\", \"Flot\", \"Sparkline\"},\n {\"Icons\", \"Feather Icons\", \"Flag Icons\", \"Mdi Icons\"},\n {\"Special Pages\", \"Blank page\", \"Faq\", \"Invoice\", \"Profile\", \"Pricing\", \"Timeline\"},\n {\"Logout\"}};\n\n String icons[] = {\n \"dashboard.svg\",\n \"email.svg\",\n \"chat.svg\",\n \"calendar.svg\",\n \"ui.svg\",\n \"forms.svg\",\n \"chart.svg\",\n \"icon.svg\",\n \"page.svg\",\n \"logout.svg\"};\n\n return new SimpleMenuOption()\n .setMenus(menus)\n .setIcons(icons)\n .setBaseIconPath(\"raven/drawer/icon\")\n .setIconScale(0.45f)\n .addMenuEvent(new MenuEvent() {\n @Override\n public void selected(MenuAction action, int index, int subIndex) {\n if (index == 0) {\n WindowsTabbed.getInstance().addTab(\"Test Form\", new TestForm());\n } else if (index == 9) {\n Main.main.login();\n }\n System.out.println(\"Menu selected \" + index + \" \" + subIndex);\n }\n })\n .setMenuValidation(new MenuValidation() {\n @Override\n public boolean menuValidation(int index, int subIndex) {\n// if(index==0){\n// return false;\n// }else if(index==3){\n// return false;\n// }\n return true;\n }\n\n });\n }\n\n @Override\n public SimpleFooterData getSimpleFooterData() {\n return new SimpleFooterData()\n .setTitle(\"Java Swing Drawer\")\n .setDescription(\"Version 1.1.0\");\n }\n\n @Override\n public int getDrawerWidth() {\n return 275;\n }\n}" }, { "identifier": "Login", "path": "src/raven/login/Login.java", "snippet": "public class Login extends JPanel {\n\n public Login() {\n init();\n }\n\n private void init() {\n setLayout(new MigLayout(\"fill,insets 20\", \"[center]\", \"[center]\"));\n txtUsername = new JTextField();\n txtPassword = new JPasswordField();\n chRememberMe = new JCheckBox(\"Remember me\");\n cmdLogin = new JButton(\"Login\");\n JPanel panel = new JPanel(new MigLayout(\"wrap,fillx,insets 35 45 35 45\", \"fill,250:280\"));\n panel.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"arc:20;\"\n + \"[light]background:darken(@background,3%);\"\n + \"[dark]background:lighten(@background,3%)\");\n\n txtPassword.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"showRevealButton:true\");\n cmdLogin.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"[light]background:darken(@background,10%);\"\n + \"[dark]background:lighten(@background,10%);\"\n + \"margin:4,6,4,6;\"\n + \"borderWidth:0;\"\n + \"focusWidth:0;\"\n + \"innerFocusWidth:0\");\n\n cmdLogin.addActionListener((e) -> {\n // Do action login here\n Main.main.showMainForm();\n });\n txtUsername.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, \"Enter your username or email\");\n txtPassword.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, \"Enter your password\");\n\n JLabel lbTitle = new JLabel(\"Welcome back!\");\n JLabel description = new JLabel(\"Please sign in to access your account\");\n lbTitle.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"font:bold +10\");\n description.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"[light]foreground:lighten(@foreground,30%);\"\n + \"[dark]foreground:darken(@foreground,30%)\");\n\n panel.add(lbTitle);\n panel.add(description);\n panel.add(new JLabel(\"Username\"), \"gapy 8\");\n panel.add(txtUsername);\n panel.add(new JLabel(\"Password\"), \"gapy 8\");\n panel.add(txtPassword);\n panel.add(chRememberMe, \"grow 0\");\n panel.add(cmdLogin, \"gapy 10\");\n add(panel);\n }\n\n private JTextField txtUsername;\n private JPasswordField txtPassword;\n private JCheckBox chRememberMe;\n private JButton cmdLogin;\n}" }, { "identifier": "WindowsTabbed", "path": "src/raven/tabbed/WindowsTabbed.java", "snippet": "public class WindowsTabbed {\n\n private static WindowsTabbed instance;\n private JMenuBar menuBar;\n private PanelTabbed panelTabbed;\n private JPanel body;\n private TabbedForm temp;\n\n public static WindowsTabbed getInstance() {\n if (instance == null) {\n instance = new WindowsTabbed();\n }\n return instance;\n }\n\n public void install(JFrame frame, JPanel body) {\n this.body = body;\n menuBar = new JMenuBar();\n menuBar.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"borderColor:$TitlePane.background;\"\n + \"border:0,0,0,0\");\n panelTabbed = new PanelTabbed();\n panelTabbed.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"background:$TitlePane.background\");\n menuBar.add(createDrawerButton());\n menuBar.add(createScroll(panelTabbed));\n frame.setJMenuBar(menuBar);\n }\n\n public void showTabbed(boolean show) {\n menuBar.setVisible(show);\n if(!show){\n Drawer.getInstance().closeDrawer();\n }\n }\n\n private JButton createDrawerButton() {\n JButton cmd = new JButton(new FlatSVGIcon(\"raven/svg/menu.svg\", 0.9f));\n cmd.addActionListener((ae) -> {\n Drawer.getInstance().showDrawer();\n });\n cmd.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"borderWidth:0;\"\n + \"focusWidth:0;\"\n + \"innerFocusWidth:0;\"\n + \"background:null;\"\n + \"arc:5\");\n return cmd;\n }\n\n private JScrollPane createScroll(Component com) {\n JScrollPane scroll = new JScrollPane(com);\n scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n scroll.getHorizontalScrollBar().putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"width:0\");\n scroll.getHorizontalScrollBar().setUnitIncrement(10);\n scroll.putClientProperty(FlatClientProperties.STYLE, \"\"\n + \"border:0,0,0,0\");\n return scroll;\n }\n\n public void addTab(String title, TabbedForm component) {\n TabbedItem item = new TabbedItem(title, component);\n item.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent ae) {\n showForm(item.component);\n }\n });\n panelTabbed.addTab(item);\n showForm(component);\n item.setSelected(true);\n }\n\n public void removeTab(TabbedItem tab) {\n if (tab.component.formClose()) {\n if (tab.isSelected()) {\n body.removeAll();\n body.revalidate();\n body.repaint();\n }\n panelTabbed.remove(tab);\n panelTabbed.revalidate();\n panelTabbed.repaint();\n }\n }\n\n public void showForm(TabbedForm component) {\n body.removeAll();\n body.add(component);\n body.repaint();\n body.revalidate();\n panelTabbed.repaint();\n panelTabbed.revalidate();\n component.formOpen();\n temp = component;\n }\n}" } ]
import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.fonts.roboto.FlatRobotoFont; import com.formdev.flatlaf.themes.FlatMacDarkLaf; import java.awt.ComponentOrientation; import java.awt.Font; import javax.swing.UIManager; import raven.drawer.Drawer; import raven.drawer.MyDrawerBuilder; import raven.login.Login; import raven.popup.GlassPanePopup; import raven.tabbed.WindowsTabbed; import raven.toast.Notifications;
2,242
package raven.main; /** * * @author RAVEN */ public class Main extends javax.swing.JFrame { public static Main main; private Login loginForm; /** * Creates new form Main */ public Main() { initComponents(); init(); } private void init() { GlassPanePopup.install(this); Notifications.getInstance().setJFrame(this);
package raven.main; /** * * @author RAVEN */ public class Main extends javax.swing.JFrame { public static Main main; private Login loginForm; /** * Creates new form Main */ public Main() { initComponents(); init(); } private void init() { GlassPanePopup.install(this); Notifications.getInstance().setJFrame(this);
MyDrawerBuilder myDrawerBuilder = new MyDrawerBuilder();
0
2023-11-12 14:19:10+00:00
4k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/commands/Flower.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowers() {\n this.flowerManager = new FlowerManager();\n this.languageManager = new LanguageManager();\n }\n\n @Override\n public void onEnable() {\n registerCommands();\n registerListener();\n }\n\n private void registerCommands() {\n final var flowerCommand = getCommand(\"flower\");\n if (flowerCommand != null) {\n flowerCommand.setAliases(List.of(\"f\", \"F\"));\n flowerCommand.setExecutor(new Flower(this));\n }\n\n final var flowerBrushCommand = getCommand(\"flowerbrush\");\n if (flowerBrushCommand != null) {\n flowerBrushCommand.setAliases(List.of(\"fb\", \"Fb\", \"fB\", \"FB\"));\n flowerBrushCommand.setExecutor(new FlowerBrush(this));\n }\n\n final var undoFlowerCommand = getCommand(\"undoflower\");\n if (undoFlowerCommand != null) {\n undoFlowerCommand.setAliases(List.of(\"uf\", \"Uf\", \"uF\", \"UF\"));\n undoFlowerCommand.setExecutor(new UndoFlower(this));\n }\n }\n\n private void registerListener() {\n Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);\n Bukkit.getPluginManager().registerEvents(new CustomFlowerBrushListener(this), this);\n }\n}" }, { "identifier": "FlowerCreationMenu", "path": "src/main/java/com/uroria/betterflowers/menus/FlowerCreationMenu.java", "snippet": "public final class FlowerCreationMenu extends BukkitPlayerInventory {\n\n private final LanguageManager languageManager;\n private final List<FlowerData> personalFlower;\n private final List<Boolean> isGroup;\n private final List<Boolean> randomizer;\n private final Player player;\n private final ItemStack active;\n private final ItemStack notActive;\n private final ItemStack wholeCategoryRan;\n private final ItemStack wholeCategory;\n private final BetterFlowers betterFlowers;\n\n public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) {\n super(betterFlowers.getLanguageManager().getComponent(\"gui.flower.title\"), 6);\n\n this.player = player;\n this.betterFlowers = betterFlowers;\n this.languageManager = betterFlowers.getLanguageManager();\n\n this.personalFlower = new ArrayList<>();\n this.randomizer = new ArrayList<>();\n this.isGroup = new ArrayList<>();\n\n this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.randomizer.yes.no\"))\n .build();\n\n this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.group.no.no\"))\n .build();\n\n this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.randomizer.yes.yes\"))\n .build();\n\n this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.randomizer.no.yes\"))\n .build();\n }\n\n public void open() {\n\n this.closeActions.add(() -> {\n personalFlower.clear();\n randomizer.clear();\n isGroup.clear();\n });\n\n generateCategories();\n openInventory(player);\n }\n\n private void generateFlowerOverlay() {\n\n //generates placeholder\n for (var index = 27; index < 54; index++) {\n if (index >= 36 && index <= 44) continue;\n this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.placeholder\"))\n .build(), this::cancelClick);\n }\n\n //generates the display for the randomizer\n for (var index = 0; index < 9; index++) {\n if (index >= randomizer.size() || index >= isGroup.size()) break;\n if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick);\n if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick);\n if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick);\n if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick);\n }\n\n //generates the chosen list of flowers to display the current flower list\n for (var index = 0; index < personalFlower.size(); index++) {\n final var singleFlower = personalFlower.get(index);\n\n setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay())\n .setName(languageManager.getComponent(\"gui.flower.item.display.flower\", \"%flower%\",singleFlower.getName() + \" ID \" + index))\n .build(), this::cancelClick);\n }\n\n setSlot(29, new ItemBuilder(Material.ECHO_SHARD)\n .setName(languageManager.getComponent(\"gui.flower.item.display.create\"))\n .build(), this::onCreateClick);\n\n setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID)\n .setName(languageManager.getComponent(\"gui.flower.item.display.back\"))\n .build(), this::onBackClick);\n\n setSlot(32, new ItemBuilder(Material.BARRIER)\n .setName(languageManager.getComponent(\"gui.flower.item.display.delete\"))\n .build(), this::onDeleteClick);\n\n setSlot(33, new ItemBuilder(Material.REDSTONE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.remove\"))\n .build(), this::onRemoveClick);\n }\n\n private void generateCategories() {\n\n clearSlots();\n generateFlowerOverlay();\n\n final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList());\n\n for (int index = 0; index < 28; index++) {\n\n if (index > flowers.size()) break;\n if (index == flowers.size()) {\n this.setSlot(index, new ItemBuilder(Material.CANDLE)\n .setName(languageManager.getComponent(\"gui.flower.item.display.candle\")).build(),\n this::createCandleCategories);\n break;\n }\n\n final var currentFlowers = flowers.get(index).getFlowerGroup();\n\n setSlot(index, new ItemBuilder(currentFlowers.getDisplay())\n .setName(languageManager.getComponent(\"gui.flower.item.display.flower\", \"%flower%\", currentFlowers.getDisplayName()))\n .setLore(languageManager.getComponents(\"gui.flower.item.lore.flowers\")).build(),\n inventoryClickEvent -> onCategoryClick(inventoryClickEvent, currentFlowers)\n );\n }\n }\n\n private void createCandleCategories(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n\n clearSlots();\n generateFlowerOverlay();\n\n final var candles = List.copyOf(Arrays.stream(CandleCollection.values()).toList());\n\n for (int index = 0; index < 28; index++) {\n\n if (index >= candles.size()) break;\n final var currentCandle = candles.get(index).getFlowerGroup();\n\n setSlot(index, new ItemBuilder(currentCandle.getDisplay())\n .setName(languageManager.getComponent(\"gui.flower.item.display.flower\", \"%flower%\", currentCandle.getDisplayName()))\n .setLore(languageManager.getComponents(\"gui.flower.item.lore.flowers\")).build(),\n clickEvent -> onCategoryClick(clickEvent, currentCandle)\n );\n }\n }\n\n private void generateSubCategories(FlowerGroup flowerGroup) {\n\n clearSlots();\n generateFlowerOverlay();\n\n for (int index = 0; index < 53; index++) {\n\n if (index >= flowerGroup.getFlowers().size()) break;\n\n final var singleFlower = flowerGroup.getFlowers().get(index);\n\n setSlot(index, new ItemBuilder(singleFlower.getDisplay())\n .setName(languageManager.getComponent(\"gui.flower.item.display.flower\", \"%flower%\", singleFlower.getDisplayName()))\n .setLore(languageManager.getComponents(\"gui.flower.item.lore.flower\")).build(),\n inventoryClickEvent -> onSubCategoryClick(inventoryClickEvent, singleFlower)\n );\n }\n }\n\n private void cancelClick(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n }\n\n private void onCreateClick(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n\n if (personalFlower.isEmpty()) {\n player.getInventory().close();\n return;\n }\n\n final var currentMil = String.valueOf(System.currentTimeMillis());\n final var description = new ArrayList<>(List.copyOf(languageManager.getComponents(\"gui.flower.item.lore.description\")));\n\n for (var singleFlower : personalFlower) {\n final var lore = languageManager.getComponent(\"gui.flower.item.lore.placeholder\", \"%flower%\", singleFlower.getName());\n description.add(lore);\n }\n\n //just takes the current system-time as a display name\n final var placer = new ItemBuilder(Material.BLAZE_POWDER)\n .setName(languageManager.getComponent(\"gui.flower.item.display.name\", \"%id%\", currentMil))\n .setLore(description).build();\n\n player.getInventory().addItem(placer);\n languageManager.sendPlayerMessage(player, \"gui.flower.message.create\");\n\n final var flowerGroupData = new FlowerGroupData(List.copyOf(personalFlower));\n betterFlowers.getFlowerManager().getFlowers().put(placer, flowerGroupData);\n betterFlowers.getFlowerManager().getFlowerRandomizer().put(flowerGroupData, List.copyOf(randomizer));\n\n player.getInventory().close();\n }\n\n private void onBackClick(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n generateCategories();\n }\n\n private void onRemoveClick(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n\n if (!personalFlower.isEmpty() && !randomizer.isEmpty() && !isGroup.isEmpty()) {\n personalFlower.remove(personalFlower.size() - 1);\n randomizer.remove(randomizer.size() - 1);\n isGroup.remove(isGroup.size() - 1);\n }\n\n player.playSound(player.getLocation(), Sound.BLOCK_COMPOSTER_EMPTY, 1, 0);\n generateCategories();\n }\n\n private void onDeleteClick(InventoryClickEvent inventoryClickEvent) {\n inventoryClickEvent.setCancelled(true);\n\n personalFlower.clear();\n randomizer.clear();\n generateCategories();\n }\n\n private void onCategoryClick(InventoryClickEvent inventoryClickEvent, FlowerGroup flowerGroup) {\n final var currentData = new FlowerData(flowerGroup.getFlowers(), flowerGroup.getDisplayName(), flowerGroup.getDisplay());\n\n inventoryClickEvent.setCancelled(true);\n\n if (!inventoryClickEvent.isShiftClick()) {\n generateSubCategories(flowerGroup);\n return;\n }\n\n if (personalFlower.size() > 8) {\n languageManager.sendPlayerMessage(player, \"gui.flower.message.limit\");\n return;\n }\n\n if (inventoryClickEvent.isRightClick()) randomizer.add(true);\n else randomizer.add(false);\n isGroup.add(true);\n\n personalFlower.add(currentData);\n player.playSound(player.getLocation(), Sound.BLOCK_CAVE_VINES_PLACE, 1, 0);\n generateCategories();\n }\n\n private void onSubCategoryClick(InventoryClickEvent inventoryClickEvent, SingleFlower singleFlower) {\n inventoryClickEvent.setCancelled(true);\n\n if (personalFlower.size() > 8) {\n languageManager.sendPlayerMessage(player, \"gui.flower.message.limit\");\n return;\n }\n\n if (inventoryClickEvent.isRightClick()) randomizer.add(true);\n else randomizer.add(false);\n isGroup.add(false);\n\n personalFlower.add(new FlowerData(singleFlower));\n player.playSound(player.getLocation(), Sound.BLOCK_CAVE_VINES_PLACE, 1, 0);\n generateCategories();\n }\n}" } ]
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.menus.FlowerCreationMenu; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull;
3,140
package com.uroria.betterflowers.commands; public record Flower(BetterFlowers betterFlowers) implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { if (!(commandSender instanceof Player player)) return true; if (!player.hasPermission("betterflowers.use")) { betterFlowers.getLanguageManager().sendPlayerMessage(player, "permission.use.error"); return true; }
package com.uroria.betterflowers.commands; public record Flower(BetterFlowers betterFlowers) implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { if (!(commandSender instanceof Player player)) return true; if (!player.hasPermission("betterflowers.use")) { betterFlowers.getLanguageManager().sendPlayerMessage(player, "permission.use.error"); return true; }
new FlowerCreationMenu(player, betterFlowers).open();
1
2023-11-18 16:13:59+00:00
4k
Appu26J/Softuninstall
src/appu26j/gui/screens/GuiSoftuninstall.java
[ { "identifier": "Assets", "path": "src/appu26j/assets/Assets.java", "snippet": "public class Assets\n{\n\tprivate static final String tempDirectory = System.getProperty(\"java.io.tmpdir\");\n\tprivate static final ArrayList<String> assets = new ArrayList<>();\n\t\n\tstatic\n\t{\n\t\tassets.add(\"segoeui.ttf\");\n\t\tassets.add(\"delete.png\");\n\t}\n\t\n\tpublic static void loadAssets()\n\t{\n\t\tFile assetsDirectory = new File(tempDirectory, \"softuninstall\");\n\t\t\n\t\tif (!assetsDirectory.exists())\n\t\t{\n\t\t\tassetsDirectory.mkdirs();\n\t\t}\n\t\t\n\t\tfor (String name : assets)\n\t\t{\n\t\t\tFile asset = new File(assetsDirectory, name);\n\n\t\t\tif (!asset.getParentFile().exists())\n\t\t\t{\n\t\t\t\tasset.getParentFile().mkdirs();\n\t\t\t}\n\n\t\t\tif (!asset.exists())\n\t\t\t{\n\t\t\t\tFileOutputStream fileOutputStream = null;\n\t\t\t\tInputStream inputStream = null;\n\t\t\t\t\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tinputStream = Assets.class.getResourceAsStream(name);\n\t\t\t\t\t\n\t\t\t\t\tif (inputStream == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new NullPointerException();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfileOutputStream = new FileOutputStream(asset);\n\t\t\t\t\tbyte[] bytes = new byte[4096];\n\t\t\t\t int read;\n\t\t\t\t \n\t\t\t\t while ((read = inputStream.read(bytes)) != -1)\n\t\t\t\t {\n\t\t\t\t \tfileOutputStream.write(bytes, 0, read);\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfinally\n\t\t\t\t{\n\t\t\t\t\tif (fileOutputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfileOutputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\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\t\n\t\t\t\t\tif (inputStream != null)\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinputStream.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcatch (Exception e)\n\t\t\t\t\t\t{\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}\n\t\t}\n\t}\n\t\n\tpublic static File getAsset(String name)\n\t{\n\t\treturn new File(tempDirectory, \"softuninstall\" + File.separator + name);\n\t}\n}" }, { "identifier": "Gui", "path": "src/appu26j/gui/Gui.java", "snippet": "public class Gui\n{\n\tpublic static void drawOutlineRect(float x, float y, float width, float height, Color color)\n\t{\n\t\tfloat lineWidth = 1;\n\t\tdrawRect(x, y, x + lineWidth, height, color);\n\t\tdrawRect(x + lineWidth, y, width - lineWidth, y + lineWidth, color);\n\t\tdrawRect(width - lineWidth, y, width, height, color);\n\t\tdrawRect(x + lineWidth, height, width - lineWidth, height - lineWidth, color);\n\t}\n\n\tpublic static void drawRect(float x, float y, float width, float height, Color color)\n\t{\n\t\tGlStateManager.enableAlpha();\n\t\tGlStateManager.enableBlend();\n\t\tGlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);\n\t\tGlStateManager.alphaFunc(516, 0);\n\t\tGlStateManager.color(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F);\n\t\tglBegin(GL_TRIANGLES);\n\t\tglVertex2f(x, y);\n\t\tglVertex2f(x, height);\n\t\tglVertex2f(width, height);\n\t\tglVertex2f(width, height);\n\t\tglVertex2f(width, y);\n\t\tglVertex2f(x, y);\n\t\tglEnd();\n\t\tGlStateManager.disableBlend();\n\t\tGlStateManager.disableAlpha();\n\t}\n\n\tpublic static void drawImage(Texture texture, float x, float y, float u, float v, float width, float height, float renderWidth, float renderHeight)\n\t{\n\t\twidth += x;\n\t\theight += y;\n\t\twidth -= u;\n\t\theight -= v;\n\n\t\tif (texture != null)\n\t\t{\n\t\t\tglBindTexture(GL_TEXTURE_2D, texture.getId());\n\t\t\tGlStateManager.enableTexture2D();\n\t\t\tGlStateManager.enableAlpha();\n\t\t\tGlStateManager.enableBlend();\n\t\t\tGlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);\n\t\t\tGlStateManager.alphaFunc(516, 0);\n\t\t\tGlStateManager.color(1, 1, 1, 1);\n\t\t\tglBegin(GL_TRIANGLES);\n\t\t\tglTexCoord2f(u / texture.getWidth(), v / texture.getHeight());\n\t\t\tglVertex2f(x, y);\n\t\t\tglTexCoord2f(u / texture.getWidth(), 1);\n\t\t\tglVertex2f(x, height);\n\t\t\tglTexCoord2f(1, 1);\n\t\t\tglVertex2f(width, height);\n\t\t\tglTexCoord2f(1, 1);\n\t\t\tglVertex2f(width, height);\n\t\t\tglTexCoord2f(1, v / texture.getHeight());\n\t\t\tglVertex2f(width, y);\n\t\t\tglTexCoord2f(u / texture.getWidth(), v / texture.getHeight());\n\t\t\tglVertex2f(x, y);\n\t\t\tglEnd();\n\t\t\tGlStateManager.disableBlend();\n\t\t\tGlStateManager.disableAlpha();\n\t\t\tGlStateManager.disableTexture2D();\n\t\t\tglBindTexture(GL_TEXTURE_2D, 0);\n\t\t}\n\t}\n\t\n\tpublic static Texture getTexture(File image)\n\t{\n\t\ttry\n\t\t{\n\t\t\tBufferedImage bufferedImage = ImageIO.read(image);\n\t\t\tByteBuffer byteBuffer = getByteBuffer(bufferedImage);\n\t\t int id = glGenTextures();\n\t\t glBindTexture(GL_TEXTURE_2D, id);\n\t\t glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t\t glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);\n\t\t return new Texture(id, bufferedImage.getWidth(), bufferedImage.getHeight());\n\t\t}\n\t\t\n\t\tcatch (Exception e)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static Texture getTexture(BufferedImage bufferedImage)\n\t{\n\t\ttry\n\t\t{\n\t\t\tByteBuffer byteBuffer = getByteBuffer(bufferedImage);\n\t\t\tint id = glGenTextures();\n\t\t\tglBindTexture(GL_TEXTURE_2D, id);\n\t\t\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\t\t\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);\n\t\t\treturn new Texture(id, bufferedImage.getWidth(), bufferedImage.getHeight());\n\t\t}\n\n\t\tcatch (Exception e)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tprivate static ByteBuffer getByteBuffer(BufferedImage bufferedImage)\n\t{\n int[] pixels = new int[bufferedImage.getWidth() * bufferedImage.getHeight()];\n bufferedImage.getRGB(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), pixels, 0, bufferedImage.getWidth());\n ByteBuffer byteBuffer = BufferUtils.createByteBuffer(4 * bufferedImage.getWidth() * bufferedImage.getHeight());\n \n for (int y = 0; y < bufferedImage.getHeight(); y++)\n {\n for (int x = 0; x < bufferedImage.getWidth(); x++)\n {\n int pixel = pixels[y * bufferedImage.getWidth() + x];\n byteBuffer.put((byte) ((pixel >> 16) & 0xFF));\n byteBuffer.put((byte) ((pixel >> 8) & 0xFF));\n byteBuffer.put((byte) (pixel & 0xFF));\n byteBuffer.put((byte) ((pixel >> 24) & 0xFF));\n }\n }\n \n byteBuffer.flip();\n return byteBuffer;\n }\n}" }, { "identifier": "Texture", "path": "src/appu26j/gui/textures/Texture.java", "snippet": "public class Texture\n{\n private final int id, width, height;\n\n public Texture(int id, int width, int height)\n {\n this.id = id;\n this.width = width;\n this.height = height;\n }\n \n public int getId()\n {\n return this.id;\n }\n\n public int getWidth()\n {\n return this.width;\n }\n \n public int getHeight()\n {\n return this.height;\n }\n}" }, { "identifier": "AppUtil", "path": "src/appu26j/utils/AppUtil.java", "snippet": "public class AppUtil\n{\n public static void loadApps()\n {\n Thread thread1 = new Thread(() ->\n {\n try\n {\n loadAppsFromPath(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\");\n }\n\n catch (Exception e)\n {\n ;\n }\n\n GuiSoftuninstall.loading -= 1;\n });\n\n Thread thread2 = new Thread(() ->\n {\n try\n {\n loadAppsFromPath(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\WoW6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\");\n }\n\n catch (Exception e)\n {\n ;\n }\n\n GuiSoftuninstall.loading -= 1;\n });\n\n thread1.setDaemon(true);\n thread2.setDaemon(true);\n thread1.start();\n thread2.start();\n }\n\n private static void loadAppsFromPath(String pathToCheckAppsFrom) throws Exception\n {\n String[] paths = Registry.execute(\"QUERY \\\"\" + pathToCheckAppsFrom + \"\\\"\").split(\"\\n\");\n\n for (String path : paths)\n {\n try\n {\n String keys = Registry.execute(\"QUERY \\\"\" + path + \"\\\"\");\n boolean containsInfo = keys.contains(\"DisplayName \") && keys.contains(\"UninstallString \") && !keys.contains(\"SystemComponent \");\n\n if (!containsInfo)\n {\n continue;\n }\n\n String name = Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v DisplayName\").trim().split(\" {4}\")[3];\n String publisher = keys.contains(\"Publisher\") ? Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v Publisher\").trim().split(\" {4}\")[3] : \"Unknown\";\n String uninstallCmd = Registry.execute(\"QUERY \\\"\" + path + \"\\\" /v UninstallString\").trim().split(\" {4}\")[3];\n GuiSoftuninstall.apps.add(new AppInfo(name, publisher, uninstallCmd, path));\n }\n\n catch (Exception e)\n {\n ;\n }\n }\n }\n}" }, { "identifier": "ScissorUtil", "path": "src/appu26j/utils/ScissorUtil.java", "snippet": "public class ScissorUtil\n{\n public static void scissor(float x, float y, float width, float height)\n {\n GL11.glScissor((int) x, (int) (700 - height), (int) (width - x), (int) (height - y));\n }\n}" }, { "identifier": "AppInfo", "path": "src/appu26j/utils/apps/AppInfo.java", "snippet": "public class AppInfo\n{\n private final String name, publisher, uninstallCmd, registryPath;\n\n public AppInfo(String name, String publisher, String uninstallCmd, String registryPath)\n {\n this.name = name;\n this.publisher = publisher;\n this.uninstallCmd = uninstallCmd;\n this.registryPath = registryPath;\n }\n\n public String getName()\n {\n return this.name;\n }\n\n public String getPublisher()\n {\n return this.publisher;\n }\n\n public String getUninstallCmd()\n {\n return this.uninstallCmd;\n }\n\n public String getRegistryPath()\n {\n return this.registryPath;\n }\n}" } ]
import appu26j.Registry; import appu26j.assets.Assets; import appu26j.gui.Gui; import appu26j.gui.textures.Texture; import appu26j.utils.AppUtil; import appu26j.utils.ScissorUtil; import appu26j.utils.apps.AppInfo; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.ArrayList;
2,960
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen {
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen {
public static final ArrayList<AppInfo> apps = new ArrayList<>();
5
2023-11-13 03:20:19+00:00
4k
DatCoder464/Malumian-Skies
src/main/java/org/valkyrienskies/malumian_skies/MalumianSkies.java
[ { "identifier": "EventHandler", "path": "src/main/java/org/valkyrienskies/malumian_skies/common/ship/EventHandler.java", "snippet": "public class EventHandler {\n\n public static AABB blockPostoAABB(BlockPos blockPos) {\n return new AABB(GravController.vectorBlockPosAdder(new Vector3d(10, 10, 10), blockPos), GravController.vectorBlockPosAdder(new Vector3d(10, 10, 10).mul(-1,-1,-1), blockPos));\n }\n\n @SubscribeEvent\n public static void serverTick(TickEvent.ServerTickEvent event) {\n if(GravitationalRiteType.getAuras() != null) {\n for (Triple<RiteData, ServerLevel, BlockPos> dataTriple : GravitationalRiteType.getAuras()) {\n for (Ship ship : VSGameUtilsKt.getShipsIntersecting(dataTriple.getMiddle(), blockPostoAABB(dataTriple.getRight()))) {\n final ServerShip serverShip = (ServerShip) ship;\n GravController.getOrCreate(serverShip).setRiteType(dataTriple.getLeft());\n // gets called on all ships but only ones created after have \"apply forces\" being called\n // current theory is that this \"GravitationalRiteType.getAuras()\" isnt giving a updated list.\n // mainly it needs to update aabb's\n }\n }\n } else {\n System.out.println(\"Failed to find gravitational auras\");\n }\n\n if (EldritchGravitationalRiteType.getAuras() != null) {\n for (Triple<RiteData, ServerLevel, BlockPos> dataTriple : EldritchGravitationalRiteType.getAuras()) {\n for (Ship ship : VSGameUtilsKt.getShipsIntersecting(dataTriple.getMiddle(), blockPostoAABB(dataTriple.getRight()))) {\n final ServerShip serverShip = (ServerShip) ship;\n GravController.getOrCreate(serverShip).setRiteType(dataTriple.getLeft());\n }\n }\n } else {\n System.out.println(\"Failed to find eldritch gravitational auras\");\n }\n\n }\n}" }, { "identifier": "GravController", "path": "src/main/java/org/valkyrienskies/malumian_skies/common/ship/GravController.java", "snippet": "public class GravController implements ShipForcesInducer {\n public RiteData riteType;\n\n public Vector3d SumVectors(List<Vector3dc> forces) {\n Vector3d forceSum = new Vector3d();\n for(Vector3dc force : forces) {\n forceSum = new Vector3d(forceSum.x + force.x(), forceSum.y + force.y(), forceSum.z + force.z());\n }\n return forceSum;\n }\n\n public static BlockPos vectorBlockPosAdder(Vector3d vectorA, BlockPos vectorB) {\n return new BlockPos(new Vec3(\n vectorA.x +vectorB.getX(),\n vectorA.y +vectorB.getY(),\n vectorA.z +vectorB.getZ()));\n }\n\n public static GravController getOrCreate(ServerShip ship) {\n if (ship.getAttachment(GravController.class) == null) {\n ship.saveAttachment(GravController.class, new GravController());\n }\n return ship.getAttachment(GravController.class);\n }\n\n @Override\n public void applyForces(@NotNull PhysShip physShip) { // only getting called on ships created in the range after activation\n List<Vector3dc> forces = new ArrayList<>();\n if(riteType != null){\n if (!riteType.eldritch) {\n if (!riteType.corrupted) {\n forces.add(new Vector3d(0, 10000, 0));\n } else {\n Vector3d shipPosRelativetoBlockPos = new Vector3d(\n physShip.getTransform().getPositionInWorld().x(),\n physShip.getTransform().getPositionInWorld().y(),\n physShip.getTransform().getPositionInWorld().z());\n Vector3d vectorDirection = new Vector3d(\n shipPosRelativetoBlockPos.x-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.x),\n shipPosRelativetoBlockPos.y-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.y),\n shipPosRelativetoBlockPos.z-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.z));\n forces.add(new Vector3d(vectorDirection.x, vectorDirection.y, vectorDirection.z));\n }\n } else {\n if (!riteType.corrupted) {\n forces.add( new Vector3d(0, 20000, 0));\n } else {\n Vector3d shipPosRelativetoBlockPos = new Vector3d(\n physShip.getTransform().getPositionInWorld().x(),\n physShip.getTransform().getPositionInWorld().y(),\n physShip.getTransform().getPositionInWorld().z());\n Vector3d vectorDirection = new Vector3d(\n shipPosRelativetoBlockPos.x-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.x),\n shipPosRelativetoBlockPos.y-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.y),\n shipPosRelativetoBlockPos.z-(Math.sqrt(Math.sqrt(shipPosRelativetoBlockPos.x*shipPosRelativetoBlockPos.x+shipPosRelativetoBlockPos.y*shipPosRelativetoBlockPos.y)+shipPosRelativetoBlockPos.z)/shipPosRelativetoBlockPos.z));\n forces.add(new Vector3d(-vectorDirection.x, -vectorDirection.y, -vectorDirection.z));\n }\n }\n }\n Vector3d forceSum = SumVectors(forces);\n physShip.applyInvariantForce(forceSum);\n }\n\n public GravController setRiteType(RiteData newRiteType) {\n riteType = newRiteType;\n return this;\n }\n}" }, { "identifier": "MSBlockRegistry", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/block/MSBlockRegistry.java", "snippet": "public class MSBlockRegistry extends Blocks {\n\n\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);\n public static final RegistryObject<CombustionThruster> COMBUSTION_THRUSTER = BLOCKS.register(\"combustion_thruster\", () -> new CombustionThruster(HALLOWED_LEAD()));\n public static final RegistryObject<CombustionTank> COMBUSTION_TANK = BLOCKS.register(\"combustion_tank\", () -> new CombustionTank(HALLOWED_LEAD()));\n public static final RegistryObject<CombustionSilo> COMBUSTION_SILO = BLOCKS.register(\"combustion_silo\", () -> new CombustionSilo(HALLOWED_LEAD()));\n public static final RegistryObject<Block> BLIGHTED_SAND = BLOCKS.register(\"blighted_sand\", () -> new Block(HALLOWED_LEAD()));\n\n public static void register(IEventBus modEventBus) {\n }\n}" }, { "identifier": "MSItemRegistry", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/item/MSItemRegistry.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class MSItemRegistry extends Items {\n\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, MOD_ID);\n\n public static Item.Properties DEFAULT_PROPERTIES() {\n return new Item.Properties().tab(MSTabRegistry.CONTENT);\n }\n\n public static final RegistryObject<Item> VOLATILE_POWDER = ITEMS.register(\"volatile_powder\", () -> new Item(DEFAULT_PROPERTIES()));\n\n public static final RegistryObject<Item> HALLOWED_LEAD_INGOT = ITEMS.register(\"hallowed_lead_ingot\", () -> new Item(DEFAULT_PROPERTIES()));\n public static final RegistryObject<Item> SPECTRAL_INGOT = ITEMS.register(\"spectral_ingot\", () -> new Item(DEFAULT_PROPERTIES()));\n\n public static final RegistryObject<Item> ARCANE_LENSE = ITEMS.register(\"arcane_lense\", () -> new Item(DEFAULT_PROPERTIES()));\n\n public static void register(IEventBus modEventBus) {\n }\n}" }, { "identifier": "MSRiteRegistry", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/rites/MSRiteRegistry.java", "snippet": "public class MSRiteRegistry {\n public static MalumRiteType GRAVITATIONAL_RITE = SpiritRiteRegistry.create(new GravitationalRiteType());\n public static MalumRiteType ELDRITCH_GRAVITATIONAL_RITE = SpiritRiteRegistry.create(new EldritchGravitationalRiteType());\n\n\n public static void init() {\n System.out.print(\"rites_work\");\n }\n}" }, { "identifier": "MSTabRegistry", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/tab/MSTabRegistry.java", "snippet": "public class MSTabRegistry {\n public static final MSTab CONTENT = new MSTab(\"basis_of_magic\", MSItemRegistry.HALLOWED_LEAD_INGOT);\n\n public static void register(IEventBus modEventBus) {\n }\n}" } ]
import com.mojang.logging.LogUtils; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.InterModComms; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent; import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent; import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.slf4j.Logger; import org.valkyrienskies.malumian_skies.common.ship.EventHandler; import org.valkyrienskies.malumian_skies.common.ship.GravController; import org.valkyrienskies.malumian_skies.registry.block.MSBlockRegistry; import org.valkyrienskies.malumian_skies.registry.item.MSItemRegistry; import org.valkyrienskies.malumian_skies.registry.rites.MSRiteRegistry; import org.valkyrienskies.malumian_skies.registry.tab.MSTabRegistry; import java.util.stream.Collectors;
2,818
package org.valkyrienskies.malumian_skies; // The value here should match an entry in the META-INF/mods.toml file @Mod("malumian_skies") public class MalumianSkies { // Directly reference a slf4j logger public static final String MOD_ID = "malumian_skies"; private static final Logger LOGGER = LogUtils.getLogger(); public MalumianSkies() { final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); // Register the setup method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // Register the enqueueIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // Register the processIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
package org.valkyrienskies.malumian_skies; // The value here should match an entry in the META-INF/mods.toml file @Mod("malumian_skies") public class MalumianSkies { // Directly reference a slf4j logger public static final String MOD_ID = "malumian_skies"; private static final Logger LOGGER = LogUtils.getLogger(); public MalumianSkies() { final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); // Register the setup method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // Register the enqueueIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // Register the processIMC method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
MSItemRegistry.register(modEventBus);
3
2023-11-14 20:50:34+00:00
4k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/services/IAtribut_DishService.java
[ { "identifier": "Atribut_Dish", "path": "src/main/java/com/myfood/dto/Atribut_Dish.java", "snippet": "@Entity\n@Table(name = \"atributes_dishes\")\npublic class Atribut_Dish {\n\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\t@ManyToMany(mappedBy = \"atribut_dish\", fetch = FetchType.EAGER)\n\tprivate List<Dish> dishes;\n\n\t@Column(name = \"attributes\", nullable = false)\n\tprivate String attributes;\n\n\tpublic Atribut_Dish(Long id, List<Dish> dishes, String attributes) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.dishes = dishes;\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic Atribut_Dish() {\n\t\tsuper();\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic List<Dish> getDishes() {\n\t\treturn dishes;\n\t}\n\n\tpublic void setDishes(List<Dish> dishes) {\n\t\tthis.dishes = dishes;\n\t}\n\n\tpublic String getAttributes() {\n\t\treturn attributes;\n\t}\n\n\tpublic void setAttributes(String attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Atribut_Dish [id=\" + id + \", dishes=\" + dishes + \", attributes=\" + attributes + \"]\";\n\t}\t\n}" }, { "identifier": "Dish", "path": "src/main/java/com/myfood/dto/Dish.java", "snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable = false)\n\tprivate String name;\n\n\t@Column(name = \"description\", nullable = false)\n\tprivate String description;\n\n\t@Column(name = \"image\")\n\tprivate String image;\n\n\t@Column(name = \"price\", nullable = false)\n\tprivate double price;\n\n\t@Column(name = \"category\", nullable = false)\n\tprivate String category;\n\t\n\t@Column(name = \"attributes\")\n\tprivate List<String> attributes;\n\t\n\t@Column(name = \"visible\")\n private boolean visible = false; \n\t\n\t@ManyToMany(fetch = FetchType.EAGER)\n\t@JoinTable(\n\t name = \"dish_atribut_dish\",\n\t joinColumns = @JoinColumn(name = \"dish_id\"),\n\t inverseJoinColumns = @JoinColumn(name = \"atribut_dish_id\")\n\t)\n\t@JsonIgnore\n\tprivate List<Atribut_Dish> atribut_dish;\n\t\t\n\t@OneToMany(mappedBy = \"dish\", cascade = CascadeType.ALL, orphanRemoval = true)\n @JsonIgnore\n private List<ListOrder> listOrder;\n\t\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JsonIgnore\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\n\t\n\t\n\tpublic Dish(Long id, String name, String description, String image, double price, String category,\n\t\t\tList<String> attributes, boolean visible, List<Atribut_Dish> atribut_dish, List<ListOrder> listOrder,\n\t\t\tMenu menu) {\n\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.image = image;\n\t\tthis.price = price;\n\t\tthis.category = category;\n\t\tthis.attributes = attributes;\n\t\tthis.visible = visible;\n\t\tthis.atribut_dish = atribut_dish;\n\t\tthis.listOrder = listOrder;\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish() {\n\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getImage() {\n\t\treturn image;\n\t}\n\n\tpublic void setImage(String image) {\n\t\tthis.image = image;\n\t}\n\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 String getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\n\n\tpublic void setAttributes(List<String> attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic boolean isVisible() {\n\t\treturn visible;\n\t}\n\n\tpublic void setVisible(boolean visible) {\n\t\tthis.visible = visible;\n\t}\n\n\tpublic List<Atribut_Dish> getAtribut_dish() {\n\t\treturn atribut_dish;\n\t}\n\n\tpublic void setAtribut_dish(List<Atribut_Dish> atribut_dish) {\n\t\tthis.atribut_dish = atribut_dish;\n\t}\n\n\tpublic List<ListOrder> getListOrder() {\n\t\treturn listOrder;\n\t}\n\n\tpublic void setListOrder(List<ListOrder> listOrder) {\n\t\tthis.listOrder = listOrder;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\t\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Dish [id=\" + id + \", name=\" + name + \", description=\" + description + \", image=\" + image + \", price=\"\n\t\t\t\t+ price + \", category=\" + category + \", attributes=\" + attributes + \", visible=\" + visible\n\t\t\t\t+ \", atribut_dish=\" + atribut_dish + \", listOrder=\" + listOrder + \", menu=\" + menu + \"]\";\n\t}\n\n\tpublic String[] getAttributes() {\n\t if (atribut_dish != null && !atribut_dish.isEmpty()) {\n\t return atribut_dish.stream()\n\t .map(Atribut_Dish::getAttributes)\n\t .toArray(String[]::new);\n\t }\n\t return new String[0]; \n\t}\n\n\t\n\n}" } ]
import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.myfood.dto.Atribut_Dish; import com.myfood.dto.Dish;
1,688
package com.myfood.services; public interface IAtribut_DishService { List<Dish> getDishesByAtribut(String atribut);
package com.myfood.services; public interface IAtribut_DishService { List<Dish> getDishesByAtribut(String atribut);
Atribut_Dish createAtribut_Dish(Atribut_Dish entity);
0
2023-11-10 16:09:43+00:00
4k
Artillex-Studios/AxGraves
src/main/java/com/artillexstudios/axgraves/schedulers/TickGraves.java
[ { "identifier": "Grave", "path": "src/main/java/com/artillexstudios/axgraves/grave/Grave.java", "snippet": "public class Grave {\n private final long spawned;\n private final Location location;\n private final OfflinePlayer player;\n private final String playerName;\n private final StorageGui gui;\n private int storedXP;\n private final PacketArmorStand entity;\n private final Hologram hologram;\n\n public Grave(Location loc, @NotNull Player player, @NotNull ItemStack[] itemsAr, int storedXP) {\n this.location = LocationUtils.getCenterOf(loc);\n this.player = player;\n this.playerName = player.getName();\n\n final ItemStack[] items = Arrays.stream(itemsAr).filter(Objects::nonNull).toArray(ItemStack[]::new);\n this.gui = Gui.storage()\n .title(StringUtils.format(MESSAGES.getString(\"gui-name\").replace(\"%player%\", playerName)))\n .rows(items.length % 9 == 0 ? items.length / 9 : 1 + (items.length / 9))\n .create();\n\n this.storedXP = storedXP;\n this.spawned = System.currentTimeMillis();\n\n for (ItemStack it : items) {\n if (it == null) continue;\n if (BlacklistUtils.isBlacklisted(it)) continue;\n\n gui.addItem(it);\n }\n\n entity = (PacketArmorStand) PacketEntityFactory.get().spawnEntity(location.clone().add(0, CONFIG.getFloat(\"head-height\", -1.2f), 0), EntityType.ARMOR_STAND);\n entity.setItem(EquipmentSlot.HELMET, Utils.getPlayerHead(player));\n entity.setSmall(true);\n entity.setInvisible(true);\n entity.setHasBasePlate(false);\n\n if (CONFIG.getBoolean(\"rotate-head-360\", true)) {\n entity.getLocation().setYaw(player.getLocation().getYaw());\n entity.teleport(entity.getLocation());\n } else {\n entity.getLocation().setYaw(LocationUtils.getNearestDirection(player.getLocation().getYaw()));\n entity.teleport(entity.getLocation());\n }\n\n entity.onClick(event -> Scheduler.get().run(task -> interact(event.getPlayer(), event.getHand())));\n\n hologram = HologramFactory.get().spawnHologram(location.clone().add(0, CONFIG.getFloat(\"hologram-height\", 1.2f), 0), Serializers.LOCATION.serialize(location), 0.3);\n\n for (String msg : MESSAGES.getStringList(\"hologram\")) {\n msg = msg.replace(\"%player%\", playerName);\n msg = msg.replace(\"%xp%\", \"\" + storedXP);\n msg = msg.replace(\"%item%\", \"\" + countItems());\n msg = msg.replace(\"%despawn-time%\", StringUtils.formatTime(CONFIG.getInt(\"despawn-time-seconds\", 180) * 1_000L - (System.currentTimeMillis() - spawned)));\n hologram.addLine(StringUtils.format(msg));\n }\n }\n\n public void update() {\n if (CONFIG.getBoolean(\"auto-rotation.enabled\", false)) {\n entity.getLocation().setYaw(entity.getLocation().getYaw() + CONFIG.getFloat(\"auto-rotation.speed\", 10f));\n entity.teleport(entity.getLocation());\n }\n\n int items = countItems();\n\n int dTime = CONFIG.getInt(\"despawn-time-seconds\", 180);\n if (dTime != -1 && (dTime * 1_000L <= (System.currentTimeMillis() - spawned) || items == 0)) {\n remove();\n return;\n }\n\n int ms = MESSAGES.getStringList(\"hologram\").size();\n for (int i = 0; i < ms; i++) {\n String msg = MESSAGES.getStringList(\"hologram\").get(i);\n msg = msg.replace(\"%player%\", playerName);\n msg = msg.replace(\"%xp%\", \"\" + storedXP);\n msg = msg.replace(\"%item%\", \"\" + items);\n msg = msg.replace(\"%despawn-time%\", StringUtils.formatTime(dTime != -1 ? (dTime * 1_000L - (System.currentTimeMillis() - spawned)) : System.currentTimeMillis() - spawned));\n\n if (i > hologram.getLines().size() - 1) {\n hologram.addLine(StringUtils.format(msg));\n } else {\n hologram.setLine(i, StringUtils.format(msg));\n }\n }\n }\n\n public void interact(@NotNull Player player, org.bukkit.inventory.EquipmentSlot slot) {\n if (CONFIG.getBoolean(\"interact-only-own\", false) && !player.getUniqueId().equals(player.getUniqueId()) && !player.hasPermission(\"axgraves.admin\")) {\n MESSAGEUTILS.sendLang(player, \"interact.not-your-grave\");\n return;\n }\n\n final GraveInteractEvent deathChestInteractEvent = new GraveInteractEvent(player, this);\n Bukkit.getPluginManager().callEvent(deathChestInteractEvent);\n if (deathChestInteractEvent.isCancelled()) return;\n\n if (this.storedXP != 0) {\n ExperienceUtils.changeExp(player, this.storedXP);\n this.storedXP = 0;\n }\n\n if (slot.equals(org.bukkit.inventory.EquipmentSlot.HAND) && player.isSneaking()) {\n if (!CONFIG.getBoolean(\"enable-instant-pickup\", true)) return;\n if (CONFIG.getBoolean(\"instant-pickup-only-own\", false) && !player.getUniqueId().equals(player.getUniqueId())) return;\n\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n\n final Collection<ItemStack> ar = player.getInventory().addItem(it).values();\n if (ar.isEmpty()) {\n it.setAmount(0);\n continue;\n }\n\n it.setAmount(ar.iterator().next().getAmount());\n }\n\n update();\n return;\n }\n\n final GraveOpenEvent deathChestOpenEvent = new GraveOpenEvent(player, this);\n Bukkit.getPluginManager().callEvent(deathChestOpenEvent);\n if (deathChestOpenEvent.isCancelled()) return;\n\n gui.open(player);\n }\n\n public void reload() {\n for (int i = 0; i < hologram.getLines().size(); i++) {\n hologram.removeLine(i);\n }\n }\n\n public int countItems() {\n int am = 0;\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n am++;\n }\n return am;\n }\n\n public void remove() {\n SpawnedGrave.removeGrave(Grave.this);\n\n Scheduler.get().runAt(location, scheduledTask -> {\n removeInventory();\n\n entity.remove();\n hologram.remove();\n });\n\n }\n\n public void removeInventory() {\n closeInventory();\n\n if (CONFIG.getBoolean(\"drop-items\", true)) {\n for (ItemStack it : gui.getInventory().getContents()) {\n if (it == null) continue;\n location.getWorld().dropItem(location.clone().add(0, -1.0, 0), it);\n }\n }\n\n if (storedXP == 0) return;\n final ExperienceOrb exp = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB);\n exp.setExperience(storedXP);\n }\n\n private void closeInventory() {\n final List<HumanEntity> viewers = new ArrayList<>(gui.getInventory().getViewers());\n final Iterator<HumanEntity> viewerIterator = viewers.iterator();\n\n while (viewerIterator.hasNext()) {\n viewerIterator.next().closeInventory();\n viewerIterator.remove();\n }\n }\n\n public Location getLocation() {\n return location;\n }\n\n public OfflinePlayer getPlayer() {\n return player;\n }\n\n public long getSpawned() {\n return spawned;\n }\n\n public StorageGui getGui() {\n return gui;\n }\n\n public int getStoredXP() {\n return storedXP;\n }\n\n public PacketArmorStand getEntity() {\n return entity;\n }\n\n public Hologram getHologram() {\n return hologram;\n }\n}" }, { "identifier": "SpawnedGrave", "path": "src/main/java/com/artillexstudios/axgraves/grave/SpawnedGrave.java", "snippet": "public class SpawnedGrave {\n private static final ConcurrentLinkedQueue<Grave> chests = new ConcurrentLinkedQueue<>();\n\n public static void addGrave(Grave grave) {\n chests.add(grave);\n }\n\n public static void removeGrave(Grave grave) {\n chests.remove(grave);\n }\n\n public static ConcurrentLinkedQueue<Grave> getGraves() {\n return chests;\n }\n}" }, { "identifier": "EXECUTOR", "path": "src/main/java/com/artillexstudios/axgraves/AxGraves.java", "snippet": "public static ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(5);" } ]
import com.artillexstudios.axgraves.grave.Grave; import com.artillexstudios.axgraves.grave.SpawnedGrave; import java.util.concurrent.TimeUnit; import static com.artillexstudios.axgraves.AxGraves.EXECUTOR;
2,204
package com.artillexstudios.axgraves.schedulers; public class TickGraves { public void start() { EXECUTOR.scheduleAtFixedRate(() -> {
package com.artillexstudios.axgraves.schedulers; public class TickGraves { public void start() { EXECUTOR.scheduleAtFixedRate(() -> {
for (Grave grave : SpawnedGrave.getGraves()) {
0
2023-11-18 16:37:27+00:00
4k
huzpsb/LC4J
src/org/eu/huzpsb/unichat/Sample.java
[ { "identifier": "Agent", "path": "src/org/eu/huzpsb/unichat/agent/Agent.java", "snippet": "public class Agent implements LLM {\n public final LLM baseLLM;\n public final Transformer transformer;\n\n public Agent(LLM baseLLM, Transformer transformer) {\n this.baseLLM = baseLLM;\n this.transformer = transformer;\n }\n\n @Override\n public Entry Chat(Conversation c) {\n return transformer.afterReceive(baseLLM.Chat(transformer.beforeSend(c)));\n }\n}" }, { "identifier": "LatexTransformer", "path": "src/org/eu/huzpsb/unichat/agent/impl/latex/LatexTransformer.java", "snippet": "@SuppressWarnings(\"ALL\")\n// Mute the annoying \"typo\" warning. Many LaTeX commands are not in the dictionary. Stupid IDE.\npublic class LatexTransformer implements Transformer {\n public static final String instruction = \"\\nThis is a Latex file.\\n\\nmain.tex\\n````TeX\\n\\\\documentclass[UTF8]{ctexart}\\n\\\\pagestyle{plain}\\n\\\\begin{document}\\n \\\\begin{center}\\n \\\\textbf{\\\\huge [YOUR TITLE HERE]}\\n \\\\end{center}\\n \\\\section{\\n [THIS IS THE BLANK]\\n \\\\begingroup\\n \\\\bibliography{main}\\n \\\\bibliographystyle{plain}\\n \\\\endgroup\\n\\\\end{document}\\n````\\n\\nNow fill in the blank of the main.tex with ~1000 characters to meet the requirements above. \\nGive the complete document, including the provided items. \\nAdd \\\\cite{name0} \\\\cite{name1}, etc. at the end of each sentence as placeholder of citations.\\nThere are 20 placeholder entries available. They are named, name0, name1, ..., name19.\\nUse no less than 10 of them, and no more than 20 of them.\\nUse them in the numercial order. Say, only use name3 if you've already used name2.\\nSpread the cites at the end of each sentence. Do not place them all at the end of the paragraph.\\nFor example, \\\"On the one hand, xxxx\\\\cite{name0}, on the other hand, xxxx\\\\cite{name1}. Thus, xxxx\\\\cite{name2}\\\" is good, and \\\"On the one hand, xxxx, on the other hand, xxxx. Thus, xxxx \\\\cite{name0} \\\\cite{name1} \\\\cite{name2}\\\" is bad.\\nUse one placeholder item no more than once.\\nYou don't have to do anything but giving me the generated text in the required format.\\n\";\n\n @Override\n public Conversation beforeSend(Conversation conversation) {\n TransformerException.throwIfNotAu(conversation);\n Conversation newConversation = conversation.clone();\n String pending = newConversation.entries.get(conversation.entries.size() - 1).content;\n Entry entry = new Entry(EntryOwner.USER, pending + instruction);\n newConversation.entries.set(conversation.entries.size() - 1, entry);\n return newConversation;\n }\n\n @Override\n public Entry afterReceive(Entry entry) {\n String pending = entry.content;\n int idxLeft = pending.indexOf(\"\\\\documentclass[UTF8]{ctexart}\");\n if (idxLeft > 0) {\n pending = pending.substring(idxLeft);\n }\n int idxRight = pending.indexOf(\"\\\\end{document}\");\n if (idxRight > 0) {\n idxRight += 14;\n if (idxRight < pending.length() - 1)\n pending = pending.substring(0, idxRight);\n }\n return new Entry(entry.owner, pending);\n }\n}" }, { "identifier": "Conversation", "path": "src/org/eu/huzpsb/unichat/conversation/Conversation.java", "snippet": "public class Conversation {\n public List<Entry> entries = new ArrayList<>();\n\n @SuppressWarnings(\"ALL\")\n @Override\n public Conversation clone() {\n // 1, We don't need to clone entries, because they are immutable.\n // 2, We don't need to call super.clone(), because it's an empty method.\n Conversation conversation = new Conversation();\n conversation.entries.addAll(entries);\n return conversation;\n }\n}" }, { "identifier": "Entry", "path": "src/org/eu/huzpsb/unichat/conversation/Entry.java", "snippet": "public class Entry {\n public final EntryOwner owner;\n public final String content;\n\n public Entry(EntryOwner owner, String content) {\n this.owner = owner;\n this.content = content;\n }\n}" }, { "identifier": "EntryOwner", "path": "src/org/eu/huzpsb/unichat/conversation/EntryOwner.java", "snippet": "public enum EntryOwner {\n USER,\n BOT,\n SYSTEM\n}" }, { "identifier": "Credential", "path": "src/org/eu/huzpsb/unichat/credential/Credential.java", "snippet": "public class Credential {\n public final CredentialType type;\n public final String value;\n public final String additional;\n\n public Credential(CredentialType type, String value) {\n this.type = type;\n this.value = value;\n this.additional = null;\n }\n\n public Credential(CredentialType type, String value, String additional) {\n this.type = type;\n this.value = value;\n this.additional = additional;\n }\n\n public String getValueIfType(CredentialType type) {\n if (this.type == type) {\n return this.value;\n } else {\n throw new CredentialMismatchException(\"Credential type mismatch. (Expected: \" + type + \", Actual: \" + this.type + \")\");\n }\n }\n}" }, { "identifier": "CredentialType", "path": "src/org/eu/huzpsb/unichat/credential/CredentialType.java", "snippet": "public enum CredentialType {\n COOKIE,\n TOKEN,\n USERNAME_PASSWORD,\n AK_SK,\n NONE\n}" }, { "identifier": "CredentialManager", "path": "src/org/eu/huzpsb/unichat/credential/manager/CredentialManager.java", "snippet": "public interface CredentialManager {\n public Credential getCredential();\n}" }, { "identifier": "SimpleCredentialManager", "path": "src/org/eu/huzpsb/unichat/credential/manager/SimpleCredentialManager.java", "snippet": "public class SimpleCredentialManager implements CredentialManager {\n public final Credential credential;\n\n public SimpleCredentialManager(Credential credential) {\n this.credential = credential;\n }\n\n @Override\n public Credential getCredential() {\n return credential;\n }\n}" }, { "identifier": "LLM", "path": "src/org/eu/huzpsb/unichat/llm/LLM.java", "snippet": "public interface LLM {\n Entry Chat(Conversation c);\n}" }, { "identifier": "ChatGPT", "path": "src/org/eu/huzpsb/unichat/llm/impl/ChatGPT.java", "snippet": "public class ChatGPT implements LLM {\n public static final String endpoint = \"https://api.openai.com/v1/chat/completions\";\n public final CredentialManager credentialManager;\n\n public ChatGPT(CredentialManager credentialManager) {\n this.credentialManager = credentialManager;\n }\n\n @Override\n public Entry Chat(Conversation c) {\n StringBuilder sb = new StringBuilder(\"{\\\"model\\\":\\\"gpt-3.5-turbo\\\",\\\"messages\\\":[\");\n for (Entry e : c.entries) {\n String owner = null;\n switch (e.owner) {\n case USER:\n owner = \"user\";\n break;\n case BOT:\n owner = \"assistant\";\n break;\n case SYSTEM:\n owner = \"system\";\n break;\n }\n sb.append(\"{\\\"role\\\":\\\"\");\n sb.append(owner);\n sb.append(\"\\\",\\\"content\\\":\\\"\");\n sb.append(JsonUtils.escape(e.content));\n sb.append(\"\\\"},\");\n }\n String token = credentialManager.getCredential().getValueIfType(CredentialType.TOKEN);\n Properties properties = new Properties();\n properties.setProperty(\"Authorization\", \"Bearer \" + token);\n try {\n NanoJSON obj = new NanoJSON(Request.jsonPost(endpoint, sb.substring(0, sb.length() - 1) + \"]}\", properties));\n String result = obj.getJSONArray(\"choices\").getJSONObject(0).getJSONObject(\"message\").getString(\"content\");\n return new Entry(EntryOwner.BOT, result);\n } catch (Exception ex) {\n return new Entry(EntryOwner.BOT, \"出错了\");\n }\n }\n}" } ]
import org.eu.huzpsb.unichat.agent.Agent; import org.eu.huzpsb.unichat.agent.impl.latex.LatexTransformer; import org.eu.huzpsb.unichat.conversation.Conversation; import org.eu.huzpsb.unichat.conversation.Entry; import org.eu.huzpsb.unichat.conversation.EntryOwner; import org.eu.huzpsb.unichat.credential.Credential; import org.eu.huzpsb.unichat.credential.CredentialType; import org.eu.huzpsb.unichat.credential.manager.CredentialManager; import org.eu.huzpsb.unichat.credential.manager.SimpleCredentialManager; import org.eu.huzpsb.unichat.llm.LLM; import org.eu.huzpsb.unichat.llm.impl.ChatGPT;
2,121
package org.eu.huzpsb.unichat; public class Sample { public static void main(String[] args) { Credential credential = new Credential(CredentialType.TOKEN, "sk-1234567890"); CredentialManager credentialManager = new SimpleCredentialManager(credential);
package org.eu.huzpsb.unichat; public class Sample { public static void main(String[] args) { Credential credential = new Credential(CredentialType.TOKEN, "sk-1234567890"); CredentialManager credentialManager = new SimpleCredentialManager(credential);
LLM llm = new ChatGPT(credentialManager);
10
2023-11-16 11:44:05+00:00
4k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/rest/action/Reader.java
[ { "identifier": "Asaas", "path": "src/main/java/io/github/jpdev/asaassdk/http/Asaas.java", "snippet": "public class Asaas {\n\n private static final String ENDPOINT_PRODUCTION = \"https://www.asaas.com/api/v3\";\n private static final String ENDPOINT_SANDBOX = \"https://sandbox.asaas.com/api/v3\";\n\n private static String token;\n\n public static AsaasRestClient restClient;\n\n public static String baseUrl = ENDPOINT_PRODUCTION;\n\n public static synchronized void init(final String token) {\n Asaas.setToken(token);\n }\n\n public static synchronized void initSandbox(final String token) {\n Asaas.baseUrl = ENDPOINT_SANDBOX;\n Asaas.setToken(token);\n }\n\n public static void setToken(String token) {\n Asaas.token = token;\n }\n\n public static AsaasRestClient getRestClient() {\n if (Asaas.restClient == null) {\n synchronized (Asaas.class) {\n if (Asaas.restClient == null) {\n Asaas.restClient = buildRestClient();\n }\n }\n }\n\n return Asaas.restClient;\n }\n\n public static String getBaseUrl() {\n return Asaas.baseUrl;\n }\n\n private static AsaasRestClient buildRestClient() {\n if (Asaas.token == null) {\n throw new RuntimeException(\n \"AsaasRestClient was used before AuthToken were set, please call Asaas.init()\"\n );\n }\n\n AsaasRestClient.Builder builder = new AsaasRestClient.Builder(Asaas.token);\n\n return builder.build();\n }\n}" }, { "identifier": "AsaasRestClient", "path": "src/main/java/io/github/jpdev/asaassdk/http/AsaasRestClient.java", "snippet": "public class AsaasRestClient {\n\n private final ObjectMapper objectMapper;\n private final String token;\n private final ApacheHttpClient client;\n private final List<String> userAgentExtensions;\n\n public ObjectMapper getObjectMapper() {\n return objectMapper;\n }\n\n public String getToken() {\n return token;\n }\n\n public ApacheHttpClient getClient() {\n return client;\n }\n\n public List<String> getUserAgentExtensions() {\n return userAgentExtensions;\n }\n\n protected AsaasRestClient(Builder b) {\n this.token = b.token;\n this.client = b.httpClient;\n this.objectMapper = buildMapper();\n this.userAgentExtensions = b.userAgentExtensions;\n }\n\n\n public Response post(String url, String body) {\n String completedUrl = Asaas.getBaseUrl() + \"/\" + url;\n return client.post(completedUrl, body);\n }\n\n public Response get(String url) {\n String completedUrl = Asaas.getBaseUrl() + \"/\" + url;\n return client.get(completedUrl);\n }\n\n public Response put(String url, String body) {\n String completedUrl = Asaas.getBaseUrl() + \"/\" + url;\n return client.put(completedUrl, body);\n }\n\n public Response delete(String url, String body) {\n String completedUrl = Asaas.getBaseUrl() + \"/\" + url;\n return client.delete(completedUrl);\n }\n\n public static class Builder {\n private String token;\n\n private ApacheHttpClient httpClient;\n private List<String> userAgentExtensions;\n\n public Builder(final String token) {\n this.token = token;\n }\n\n\n public AsaasRestClient build() {\n if (this.httpClient == null) {\n this.httpClient = new ApacheHttpClient(this.token);\n }\n return new AsaasRestClient(this);\n }\n }\n\n\n private ObjectMapper buildMapper() {\n ObjectMapper mapper = new ObjectMapper();\n SimpleModule module = new SimpleModule();\n\n SimpleDeserializers deserializers = new SimpleDeserializers();\n deserializers.addDeserializer(Date.class, new CustomDateDeserializer());\n module.setDeserializers(deserializers);\n\n mapper.registerModule(module);\n mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n return mapper;\n }\n\n static class CustomDateDeserializer extends com.fasterxml.jackson.databind.JsonDeserializer<Date> {\n private final SimpleDateFormat dateFormatWithTime = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n private final SimpleDateFormat dateFormatWithoutTime = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n @Override\n public Date deserialize(com.fasterxml.jackson.core.JsonParser jsonParser, com.fasterxml.jackson.databind.DeserializationContext deserializationContext)\n throws IOException {\n String date = jsonParser.getText();\n try {\n if (date.contains(\":\")) {\n return dateFormatWithTime.parse(date);\n } else {\n return dateFormatWithoutTime.parse(date);\n }\n } catch (ParseException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n}" }, { "identifier": "Response", "path": "src/main/java/io/github/jpdev/asaassdk/http/Response.java", "snippet": "public class Response {\n\n private final InputStream stream;\n private String content;\n private final int statusCode;\n private final Header[] headers;\n\n /**\n * Create a Response from content string and status code.\n *\n * @param content content string\n * @param statusCode status code\n */\n public Response(final String content, final int statusCode) {\n this(content, statusCode, null);\n }\n\n /**\n * Create a Response from content string, status code, and headers.\n *\n * @param content content string\n * @param statusCode status code\n * @param headers headers\n */\n public Response(final String content, final int statusCode, final Header[] headers) {\n this.stream = null;\n this.content = content;\n this.statusCode = statusCode;\n this.headers = headers;\n }\n\n /**\n * Create a Response from input stream and status code.\n *\n * @param stream input stream\n * @param statusCode status code\n */\n public Response(final InputStream stream, final int statusCode) {\n this(stream, statusCode, null);\n }\n\n /**\n * Create a Response from input stream, status code, and headers.\n *\n * @param stream input stream\n * @param statusCode status code\n * @param headers headers\n */\n public Response(final InputStream stream, final int statusCode, final Header[] headers) {\n this.stream = stream;\n this.content = null;\n this.statusCode = statusCode;\n this.headers = headers;\n }\n\n /**\n * Get the the content of the response.\n *\n * <p>\n * If there is a content string, that will be returned.\n * Otherwise, will get content from input stream\n * </p>\n *\n * @return the content string\n */\n public String getContent() {\n if (content != null) {\n return content;\n }\n\n if (stream != null) {\n Scanner scanner = new Scanner(stream, \"UTF-8\").useDelimiter(\"\\\\A\");\n\n if (!scanner.hasNext()) {\n return \"\";\n }\n\n content = scanner.next();\n scanner.close();\n\n return content;\n }\n\n return \"\";\n }\n\n /**\n * Get response data as stream.\n *\n * @return the response data as a stream\n */\n public InputStream getStream() {\n if (stream != null) {\n return stream;\n }\n try {\n return new ByteArrayInputStream(content.getBytes(\"utf-8\"));\n } catch (final UnsupportedEncodingException e) {\n throw new RuntimeException(\"UTF-8 encoding not supported\", e);\n }\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n\n public Header[] getHeaders() {\n return headers;\n }\n\n public RateLimitData getRateLimit() {\n String limit = findHeaderValue(\"RateLimit-Limit\");\n if (limit != null) {\n String remaining = findHeaderValue(\"RateLimit-Remaining\");\n String reset = findHeaderValue(\"RateLimit-Reset\");\n\n return new RateLimitData(\n Integer.parseInt(limit),\n Integer.parseInt(remaining),\n Integer.parseInt(reset)\n );\n }\n\n return null;\n }\n\n private String findHeaderValue(String key) {\n Optional<Header> headerEncontrado = Arrays.stream(headers)\n .filter(header -> header.getName().equals(key))\n .findFirst();\n return headerEncontrado.map(NameValuePair::getValue).orElse(null);\n }\n}" }, { "identifier": "FilterVO", "path": "src/main/java/io/github/jpdev/asaassdk/rest/action/filter/FilterVO.java", "snippet": "public class FilterVO {\n\n public String propertyName;\n public String filterKey;\n\n public FilterVO(String propertyName, String filterKey) {\n this.propertyName = propertyName;\n this.filterKey = filterKey;\n }\n\n public FilterVO(String propertyName) {\n this.propertyName = propertyName;\n this.filterKey = this.propertyName;\n }\n\n public String getPropertyName() {\n return propertyName;\n }\n\n public String getFilterKey() {\n return filterKey;\n }\n}" }, { "identifier": "CustomDateUtils", "path": "src/main/java/io/github/jpdev/asaassdk/utils/CustomDateUtils.java", "snippet": "public class CustomDateUtils {\n\n public static final SimpleDateFormat DATE = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n public static String toString(Date date, SimpleDateFormat format) {\n try {\n return format.format(date);\n } catch (Exception exception) {\n return null;\n }\n }\n}" } ]
import io.github.jpdev.asaassdk.http.Asaas; import io.github.jpdev.asaassdk.http.AsaasRestClient; import io.github.jpdev.asaassdk.http.Response; import io.github.jpdev.asaassdk.rest.action.filter.FilterVO; import io.github.jpdev.asaassdk.utils.CustomDateUtils; import java.lang.reflect.Field; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List;
2,881
package io.github.jpdev.asaassdk.rest.action; public abstract class Reader<T> { public Integer limit; public Long offset; public List<FilterVO> activeFilters; public Integer getLimit() { return limit; } public Reader<T> setLimit(Integer limit) { this.limit = limit; return this; } public Long getOffset() { return offset; } public Reader<T> setOffset(Long offset) { this.offset = offset; return this; } public ResourceSet<T> read() { return read(Asaas.getRestClient()); } public ResourceSet<T> read(final AsaasRestClient client) { Response response = client.get(buildFullPath()); return ResourceSet.fromJson( "data", response.getContent(), getResourceClass(), client.getObjectMapper() ); } public abstract String getResourceUrl(); public abstract Class<T> getResourceClass(); public void addFilter(String propertyName) { if (activeFilters == null) activeFilters = new ArrayList<>(); activeFilters.add(new FilterVO( propertyName )); } public void addFilter(String propertyName, String filterName) { if (activeFilters == null) activeFilters = new ArrayList<>(); activeFilters.add(new FilterVO( propertyName, filterName )); } private String buildFullPath() { try { String path = getResourceUrl(); if (activeFilters == null || activeFilters.isEmpty()) return path; String pathParams = ""; for (FilterVO filterVO : activeFilters) { pathParams = concatDelimiterFilter(pathParams); Field field = this.getClass().getDeclaredField(filterVO.getPropertyName()); pathParams = pathParams .concat(URLEncoder.encode(filterVO.getFilterKey())) .concat("="); Object value = field.get(this); if (value instanceof String || value instanceof Enum) { pathParams = pathParams .concat(value.toString()); } else if (value instanceof Integer) { pathParams = pathParams .concat(value.toString()); } else if (value instanceof Date) { pathParams = pathParams
package io.github.jpdev.asaassdk.rest.action; public abstract class Reader<T> { public Integer limit; public Long offset; public List<FilterVO> activeFilters; public Integer getLimit() { return limit; } public Reader<T> setLimit(Integer limit) { this.limit = limit; return this; } public Long getOffset() { return offset; } public Reader<T> setOffset(Long offset) { this.offset = offset; return this; } public ResourceSet<T> read() { return read(Asaas.getRestClient()); } public ResourceSet<T> read(final AsaasRestClient client) { Response response = client.get(buildFullPath()); return ResourceSet.fromJson( "data", response.getContent(), getResourceClass(), client.getObjectMapper() ); } public abstract String getResourceUrl(); public abstract Class<T> getResourceClass(); public void addFilter(String propertyName) { if (activeFilters == null) activeFilters = new ArrayList<>(); activeFilters.add(new FilterVO( propertyName )); } public void addFilter(String propertyName, String filterName) { if (activeFilters == null) activeFilters = new ArrayList<>(); activeFilters.add(new FilterVO( propertyName, filterName )); } private String buildFullPath() { try { String path = getResourceUrl(); if (activeFilters == null || activeFilters.isEmpty()) return path; String pathParams = ""; for (FilterVO filterVO : activeFilters) { pathParams = concatDelimiterFilter(pathParams); Field field = this.getClass().getDeclaredField(filterVO.getPropertyName()); pathParams = pathParams .concat(URLEncoder.encode(filterVO.getFilterKey())) .concat("="); Object value = field.get(this); if (value instanceof String || value instanceof Enum) { pathParams = pathParams .concat(value.toString()); } else if (value instanceof Integer) { pathParams = pathParams .concat(value.toString()); } else if (value instanceof Date) { pathParams = pathParams
.concat(CustomDateUtils.toString((Date) value, CustomDateUtils.DATE));
4
2023-11-12 01:19:17+00:00
4k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/maven/BuildFileParser.java
[ { "identifier": "LinuxWindowsPathUnifier", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/utils/LinuxWindowsPathUnifier.java", "snippet": "public class LinuxWindowsPathUnifier {\n\n\tpublic static Path relativize(Path subpath, Path path) {\n\t\tLinuxWindowsPathUnifier linuxWindowsPathUnifier = new LinuxWindowsPathUnifier();\n\t\tString unifiedAbsoluteRootPath = linuxWindowsPathUnifier.unifiedPathString(subpath);\n\t\tString pathUnified = linuxWindowsPathUnifier.unifiedPathString(path);\n\t\treturn Path.of(unifiedAbsoluteRootPath).relativize(Path.of(pathUnified));\n\t}\n\n\tpublic static String unifiedPathString(Path path) {\n\t\treturn unifiedPathString(path.toString());\n\t}\n\n\tpublic static Path unifiedPath(Path path) {\n\t\treturn Path.of(unifiedPathString(path));\n\t}\n\n\tpublic static String unifiedPathString(Resource r) {\n\t\treturn unifiedPathString(ResourceUtil.getPath(r));\n\t}\n\n\tpublic static String unifiedPathString(String path) {\n\t\tpath = StringUtils.cleanPath(path);\n\t\tif (isWindows()) {\n\t\t\tpath = transformToLinuxPath(path);\n\t\t}\n\t\treturn path;\n\t}\n\n\tpublic static Path unifiedPath(String path) {\n\t\treturn Path.of(unifiedPathString(path));\n\t}\n\n\tstatic boolean isWindows() {\n\t\treturn System.getProperty(\"os.name\").contains(\"Windows\");\n\t}\n\n\tprivate static String transformToLinuxPath(String path) {\n\t\treturn path.replaceAll(\"^[\\\\w]+:\\\\/?\", \"/\");\n\t}\n\n\tpublic static boolean pathEquals(Resource r, Path path) {\n\t\treturn unifiedPathString(ResourceUtil.getPath(r)).equals(unifiedPathString(path.normalize()));\n\t}\n\n\tpublic static boolean pathEquals(Path basedir, String parentPomPath) {\n\t\treturn unifiedPathString(basedir).equals(parentPomPath);\n\t}\n\n\tpublic static boolean pathEquals(Path path1, Path path2) {\n\t\treturn unifiedPathString(path1).equals(unifiedPathString(path2));\n\t}\n\n\tpublic static boolean pathStartsWith(Resource r, Path path) {\n\t\treturn ResourceUtil.getPath(r).toString().startsWith(unifiedPathString(path));\n\t}\n\n}" }, { "identifier": "ResourceUtil", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/utils/ResourceUtil.java", "snippet": "public class ResourceUtil {\n\n\tpublic ResourceUtil() {\n\t}\n\n\tpublic static Path getPath(Resource resource) {\n\t\ttry {\n\t\t\treturn resource.getFile().toPath();\n\t\t}\n\t\tcatch (IOException var2) {\n\t\t\tthrow new RuntimeException(var2);\n\t\t}\n\t}\n\n\tpublic static InputStream getInputStream(Resource resource) {\n\t\ttry {\n\t\t\treturn resource.getInputStream();\n\t\t}\n\t\tcatch (IOException var2) {\n\t\t\tthrow new RuntimeException(var2);\n\t\t}\n\t}\n\n\tpublic static void write(Path basePath, List<Resource> resources) {\n\t\tresources.stream().forEach(r -> ResourceUtil.persistResource(basePath, r));\n\t}\n\n\tprivate static void persistResource(Path basePath, Resource r) {\n\t\tPath resourcePath = ResourceUtil.getPath(r);\n\t\tif (resourcePath.isAbsolute()) {\n\t\t\tPath relativize = resourcePath.relativize(basePath);\n\t\t}\n\t\telse {\n\t\t\tresourcePath = basePath.resolve(resourcePath).toAbsolutePath().normalize();\n\t\t}\n\t\tif (resourcePath.toFile().exists()) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (!resourcePath.getParent().toFile().exists()) {\n\t\t\t\tFiles.createDirectories(resourcePath.getParent());\n\t\t\t}\n\t\t\tFiles.writeString(resourcePath, ResourceUtil.getContent(r));\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static String getContent(Resource r) {\n\t\ttry {\n\t\t\treturn new String(getInputStream(r).readAllBytes());\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static long contentLength(Resource resource) {\n\t\ttry {\n\t\t\treturn resource.contentLength();\n\t\t}\n\t\tcatch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n}" } ]
import org.jetbrains.annotations.NotNull; import org.openrewrite.ExecutionContext; import org.openrewrite.Parser; import org.openrewrite.SourceFile; import org.openrewrite.marker.Marker; import org.openrewrite.maven.MavenParser; import org.openrewrite.xml.tree.Xml; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.rewrite.utils.LinuxWindowsPathUnifier; import org.springframework.rewrite.utils.ResourceUtil; import org.springframework.util.Assert; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Collections.emptyList;
1,660
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers.maven; /** * Copies behaviour from rewrite-maven-plugin:5.2.2 * * @author Fabian Krüger */ public class BuildFileParser { private static final Logger LOGGER = LoggerFactory.getLogger(BuildFileParser.class); private final MavenSettingsInitializer mavenSettingsInitilizer; public BuildFileParser(MavenSettingsInitializer mavenSettingsInitilizer) { this.mavenSettingsInitilizer = mavenSettingsInitilizer; } /** * Parse a list of Maven Pom files to a {@code List} of {@link Xml.Document}s. The * {@link Xml.Document}s get marked with * {@link org.openrewrite.maven.tree.MavenResolutionResult} and the provided * provenance markers. * @param baseDir the {@link Path} to the root of the scanned project * @param buildFiles the list of resources for relevant pom files. * @param activeProfiles the active Maven profiles * @param executionContext the ExecutionContext to use * @param skipMavenParsing skip parsing Maven files * @param provenanceMarkers the map of markers to be added */ public List<Xml.Document> parseBuildFiles(Path baseDir, List<Resource> buildFiles, List<String> activeProfiles, ExecutionContext executionContext, boolean skipMavenParsing, Map<Path, List<Marker>> provenanceMarkers) { Assert.notNull(baseDir, "Base directory must be provided but was null."); Assert.notEmpty(buildFiles, "No build files provided."); List<Resource> nonPomFiles = retrieveNonPomFiles(buildFiles); Assert.isTrue(nonPomFiles.isEmpty(), "Provided resources which are not Maven build files: '%s'"
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers.maven; /** * Copies behaviour from rewrite-maven-plugin:5.2.2 * * @author Fabian Krüger */ public class BuildFileParser { private static final Logger LOGGER = LoggerFactory.getLogger(BuildFileParser.class); private final MavenSettingsInitializer mavenSettingsInitilizer; public BuildFileParser(MavenSettingsInitializer mavenSettingsInitilizer) { this.mavenSettingsInitilizer = mavenSettingsInitilizer; } /** * Parse a list of Maven Pom files to a {@code List} of {@link Xml.Document}s. The * {@link Xml.Document}s get marked with * {@link org.openrewrite.maven.tree.MavenResolutionResult} and the provided * provenance markers. * @param baseDir the {@link Path} to the root of the scanned project * @param buildFiles the list of resources for relevant pom files. * @param activeProfiles the active Maven profiles * @param executionContext the ExecutionContext to use * @param skipMavenParsing skip parsing Maven files * @param provenanceMarkers the map of markers to be added */ public List<Xml.Document> parseBuildFiles(Path baseDir, List<Resource> buildFiles, List<String> activeProfiles, ExecutionContext executionContext, boolean skipMavenParsing, Map<Path, List<Marker>> provenanceMarkers) { Assert.notNull(baseDir, "Base directory must be provided but was null."); Assert.notEmpty(buildFiles, "No build files provided."); List<Resource> nonPomFiles = retrieveNonPomFiles(buildFiles); Assert.isTrue(nonPomFiles.isEmpty(), "Provided resources which are not Maven build files: '%s'"
.formatted(nonPomFiles.stream().map(r -> ResourceUtil.getPath(r).toAbsolutePath()).toList()));
1
2023-11-14 23:02:37+00:00
4k
giftorg/gift
gift-scheduler/src/main/java/org/giftorg/scheduler/service/impl/ProjectServiceImpl.java
[ { "identifier": "HDFS", "path": "gift-common/src/main/java/org/giftorg/common/hdfs/HDFS.java", "snippet": "public class HDFS {\n private static final String addr = StringUtil.trimEnd(Config.hdfsConfig.getAddr(), \"/\");\n private static final String reposPath = StringUtil.trimEnd(Config.hdfsConfig.getReposPath(), \"/\");\n\n private static final FileSystem fs;\n\n static {\n try {\n fs = FileSystem.get(new Configuration());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 返回 HDFS 文件路径\n * 如输入 /repos/xxx.txt,返回 hdfs://localhost:9000/repos/xxx.txt\n */\n public static Path hdfsPath(String path) {\n return new Path(addr + path);\n }\n\n /**\n * 返回 HDFS 仓库文件路径\n * 如输入 /xxx.txt,假设配置中指定仓库路径为 /repos,返回 hdfs://localhost:9000/repos/xxx.txt\n */\n public static String hdfsRepoPath(String path) {\n return hdfsPath(hdfsRepoRelPath(path)).toString();\n }\n\n /**\n * 返回 HDFS 仓库文件相对路径\n * 如输入 /xxx.txt,假设配置中指定仓库路径为 /repos,返回 /repos/xxx.txt\n */\n public static String hdfsRepoRelPath(String path) {\n return reposPath + path;\n }\n\n /**\n * 上传文件到 HDFS\n */\n public static void put(String src, String dst) throws IOException {\n fs.copyFromLocalFile(new Path(src), hdfsPath(dst));\n }\n\n /**\n * 深度优先遍历指定 HDFS 路径下所有文件\n */\n private static void dfs(Path path, List<String> list) throws IOException {\n FileStatus[] fileStatuses = fs.listStatus(path);\n\n for (FileStatus status : fileStatuses) {\n if (status.isDirectory()) {\n dfs(status.getPath(), list);\n } else {\n list.add(StringUtil.trimStart(status.getPath().toString(), addr));\n }\n }\n }\n\n /**\n * 获取 HDFS 指定路径下所有文件\n */\n public static List<String> getRepoFiles(String path) throws IOException {\n List<String> result = new ArrayList<>();\n dfs(new Path(path), result);\n\n return result;\n }\n}" }, { "identifier": "GitUtil", "path": "gift-common/src/main/java/org/giftorg/common/utils/GitUtil.java", "snippet": "public class GitUtil {\n /**\n * 克隆 git 项目到指定路径\n */\n public static void gitClone(String remote, String local) throws RuntimeException {\n remote = remote.replace(\"https://github.com/\", \"https://githubfast.com/\");\n String cmd = \"git clone \" + remote + \" \" + local;\n CmdUtil.exec(cmd);\n }\n}" }, { "identifier": "PathUtil", "path": "gift-common/src/main/java/org/giftorg/common/utils/PathUtil.java", "snippet": "public class PathUtil {\n /**\n * 拼接路径,多平台兼容\n */\n public static String join(String first, String... more) {\n return Paths.get(first, more).toString();\n }\n\n /**\n * 获取路径最后的文件名\n */\n public static String base(String path) {\n return Paths.get(URI.create(path).getPath()).getFileName().toString();\n }\n}" }, { "identifier": "Project", "path": "gift-scheduler/src/main/java/org/giftorg/scheduler/entity/Project.java", "snippet": "@Slf4j\n@Data\n@ToString\npublic class Project {\n /**\n * MySQL 记录 ID\n */\n private Integer id;\n\n /**\n * 仓库 ID\n */\n private Integer repoId;\n\n /**\n * 仓库名称\n */\n private String name;\n\n /**\n * 仓库全名\n */\n private String fullName;\n\n /**\n * 仓库 star 数\n */\n private Integer stars;\n\n /**\n * 仓库作者/组织\n */\n private String author;\n\n /**\n * 仓库完整路径\n */\n private String url;\n\n /**\n * 仓库描述\n */\n private String description;\n\n /**\n * 仓库文件大小\n */\n private Integer size;\n\n /**\n * Git 默认分支\n */\n private String defaultBranch;\n\n /**\n * README.md 文档\n */\n private String readme;\n\n /**\n * README.md 文档中文翻译\n */\n private String readmeCn;\n\n /**\n * 仓库关键词列表\n */\n private List<String> tags;\n\n /**\n * 仓库保存在 HDFS 中的路径\n */\n public String hdfsPath;\n}" }, { "identifier": "ProjectMapper", "path": "gift-scheduler/src/main/java/org/giftorg/scheduler/mapper/ProjectMapper.java", "snippet": "public interface ProjectMapper {\n Project selectOne(@Param(\"id\") Integer id);\n\n Project selectOneByRepoId(@Param(\"repoId\") Integer repoId);\n\n List<Project> selectList();\n\n}" }, { "identifier": "ProjectService", "path": "gift-scheduler/src/main/java/org/giftorg/scheduler/service/ProjectService.java", "snippet": "public interface ProjectService {\n /**\n * 拉取 Git项目到 HDFS\n */\n void pullProject(Project project) throws Exception;\n\n /**\n * 根据仓库ID获取项目信息\n */\n Project getProjectByRepoId(Integer repoId);\n}" } ]
import org.giftorg.scheduler.service.ProjectService; import java.io.IOException; import java.io.InputStream; import cn.hutool.core.io.FileUtil; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.giftorg.common.hdfs.HDFS; import org.giftorg.common.utils.GitUtil; import org.giftorg.common.utils.PathUtil; import org.giftorg.scheduler.entity.Project; import org.giftorg.scheduler.mapper.ProjectMapper;
1,878
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.scheduler.service.impl; @Slf4j public class ProjectServiceImpl implements ProjectService { private static final SqlSessionFactory sqlSessionFactory; private static final String MYBATIS_CONFIG = "mybatis-config.xml"; private static final String LOCAL_REPO_TEMP_PATH = "temp_repositories"; static { try { InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } /** * 拉取 Git项目到 HDFS */ public void pullProject(Project project) throws Exception { // clone project String local = FileUtil.getAbsolutePath(PathUtil.join(LOCAL_REPO_TEMP_PATH, project.getFullName()));
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.scheduler.service.impl; @Slf4j public class ProjectServiceImpl implements ProjectService { private static final SqlSessionFactory sqlSessionFactory; private static final String MYBATIS_CONFIG = "mybatis-config.xml"; private static final String LOCAL_REPO_TEMP_PATH = "temp_repositories"; static { try { InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } /** * 拉取 Git项目到 HDFS */ public void pullProject(Project project) throws Exception { // clone project String local = FileUtil.getAbsolutePath(PathUtil.join(LOCAL_REPO_TEMP_PATH, project.getFullName()));
GitUtil.gitClone(project.getUrl(), local);
1
2023-11-15 08:58:35+00:00
4k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/runner/SimpleRunner.java
[ { "identifier": "ContentType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/ContentType.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\n@Getter\npublic enum ContentType {\n\n UNDEFINED {\n @Override\n public boolean matchesMime(String value) {\n return false;\n }\n\n @Override\n boolean matchesExtension(String value) {\n return false;\n }\n },\n\n XML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"xml\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsIgnoreCase(value, \"xml\");\n }\n },\n\n HTML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"html\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"htl\",\n \"html\",\n \"htm\");\n }\n },\n\n TEXT {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"text\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"css\",\n \"csv\",\n \"ecma\",\n \"info\",\n \"java\",\n \"jsp\",\n \"jspx\",\n \"js\",\n \"json\",\n \"log\",\n \"md\",\n \"mf\",\n \"php\",\n \"properties\",\n \"ts\",\n \"txt\");\n }\n };\n\n /**\n * Checks if the given MIME-type is matched by the current content type\n * @param value MIME-type to check\n * @return True or false\n */\n abstract boolean matchesMime(String value);\n\n /**\n * Checks if the given file extension is matched by the current content type\n * @param value File extension to check\n * @return True or false\n */\n abstract boolean matchesExtension(String value);\n\n /**\n * Gets the content type that matches the given MIME type\n * @param value MIME-type\n * @return {@code ContentType} enum value\n */\n public static ContentType fromMimeType(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n String effectiveType = StringUtils.substringBefore(value, \";\");\n for (ContentType contentType : values()) {\n if (contentType.matchesMime(effectiveType)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n\n /**\n * Gets the content type that matches the given file extension\n * @param value File extension\n * @return {@code ContentType} enum value\n */\n public static ContentType fromExtension(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n for (ContentType contentType : values()) {\n if (contentType.matchesExtension(value)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n}" }, { "identifier": "DiffTask", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/comparison/DiffTask.java", "snippet": "@Builder(builderClassName = \"Builder\")\npublic class DiffTask {\n\n private static final UnaryOperator<String> EMPTY_NORMALIZER = StringUtils::defaultString;\n\n private final ContentType contentType;\n\n private final String leftId;\n private String leftLabel;\n private final Object leftContent;\n\n private final String rightId;\n private String rightLabel;\n private final Object rightContent;\n\n private final Predicate<DiffEntry> filter;\n\n private DiffState anticipatedState;\n\n private TaskParameters taskParameters;\n\n /* ------------------\n Property accessors\n ------------------ */\n\n private Preprocessor getPreprocessor(String contentId) {\n return Preprocessor.forType(contentType, taskParameters).withContentId(contentId);\n }\n\n private Postprocessor getPostprocessor() {\n return Postprocessor.forType(contentType, taskParameters);\n }\n\n /* ---------\n Execution\n --------- */\n\n /**\n * Performs the comparison between the left and right content\n * @return {@link Diff} object\n */\n public Diff run() {\n if (Objects.equals(leftContent, rightContent)) {\n return new DiffImpl(leftId, rightId); // This object will report the \"equals\" state\n }\n int columnWidth = taskParameters.getColumnWidth() - 1;\n if (anticipatedState == DiffState.CHANGE) {\n BlockImpl change = BlockImpl\n .builder()\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .lines(Collections.singletonList(new LineImpl(\n new MarkedString(String.valueOf(leftContent)).markPlaceholders(Marker.DELETE),\n new MarkedString(String.valueOf(rightContent)).markPlaceholders(Marker.INSERT)\n )))\n .build(DisparityBlockImpl::new);\n return new DiffImpl(leftId, rightId).withChildren(change);\n }\n if (leftContent == null || anticipatedState == DiffState.LEFT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .left(rightId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n if (rightContent == null || anticipatedState == DiffState.RIGHT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .right(leftId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n return contentType == ContentType.UNDEFINED ? runForBinary() : runForText();\n }\n\n private Diff runForBinary() {\n DiffImpl result = new DiffImpl(leftId, rightId);\n DisparityBlockImpl disparity = DisparityBlockImpl\n .builder()\n .leftContent(leftContent)\n .rightContent(rightContent)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .build(DisparityBlockImpl::new);\n return result.withChildren(disparity);\n }\n\n private Diff runForText() {\n DiffRowGenerator generator = DiffRowGenerator\n .create()\n .ignoreWhiteSpaces(taskParameters.ignoreSpaces())\n .showInlineDiffs(true)\n .oldTag(isStart -> isStart ? Marker.DELETE.toString() : Marker.RESET.toString())\n .newTag(isStart -> isStart ? Marker.INSERT.toString() : Marker.RESET.toString())\n .lineNormalizer(EMPTY_NORMALIZER) // One needs this to override the OOTB preprocessor that spoils HTML\n .inlineDiffBySplitter(SplitterUtil::getTokens)\n .build();\n String leftPreprocessed = getPreprocessor(leftId).apply(leftContent.toString());\n String rightPreprocessed = getPreprocessor(rightId).apply(rightContent.toString());\n List<String> leftLines = StringUtil.splitByNewline(leftPreprocessed);\n List<String> rightLines = StringUtil.splitByNewline(rightPreprocessed);\n List<DiffRow> diffRows = getPostprocessor().apply(generator.generateDiffRows(leftLines, rightLines));\n\n DiffImpl result = new DiffImpl(leftId, rightId);\n List<AbstractBlock> blocks = getDiffBlocks(diffRows)\n .stream()\n .peek(block -> block.setDiff(result))\n .filter(filter != null ? filter : entry -> true)\n .collect(Collectors.toList());\n return result.withChildren(blocks);\n }\n\n private List<AbstractBlock> getDiffBlocks(List<DiffRow> allRows) {\n List<AbstractBlock> result = new ArrayList<>();\n BlockImpl pendingDiffBlock = null;\n for (int i = 0; i < allRows.size(); i++) {\n DiffRow row = allRows.get(i);\n boolean isNeutralRow = row.getTag() == DiffRow.Tag.EQUAL;\n boolean isNonNeutralStreakEnding = isNeutralRow && pendingDiffBlock != null;\n if (isNonNeutralStreakEnding) {\n pendingDiffBlock.addContext(row);\n result.add(pendingDiffBlock);\n pendingDiffBlock = null;\n }\n if (isNeutralRow) {\n continue;\n }\n if (pendingDiffBlock == null) {\n List<DiffRow> lookbehindContext = getLookbehindContext(allRows, i);\n pendingDiffBlock = BlockImpl\n .builder()\n .path(getContextPath(allRows, i))\n .compactify(taskParameters.normalize())\n .contentType(contentType)\n .ignoreSpaces(taskParameters.ignoreSpaces())\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .build(BlockImpl::new);\n pendingDiffBlock.addContext(lookbehindContext);\n }\n pendingDiffBlock.add(row);\n }\n if (pendingDiffBlock != null) {\n result.add(pendingDiffBlock);\n }\n return result;\n }\n\n private String getContextPath(List<DiffRow> allRows, int position) {\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return StringUtils.EMPTY;\n }\n return PathUtil.getPath(allRows, position);\n }\n\n private List<DiffRow> getLookbehindContext(List<DiffRow> allRows, int position) {\n if (position == 0) {\n return null;\n }\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n int nearestTagRowIndex = PathUtil.getPrecedingTagRowIndex(allRows, position - 1);\n if (nearestTagRowIndex >= 0) {\n return truncateContext(allRows.subList(nearestTagRowIndex, position));\n }\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n private static List<DiffRow> truncateContext(List<DiffRow> rows) {\n if (rows.size() <= Constants.MAX_CONTEXT_LENGTH) {\n return rows;\n }\n List<DiffRow> upperPart = rows.subList(0, Constants.MAX_CONTEXT_LENGTH / 2);\n List<DiffRow> lowerPart = rows.subList(rows.size() - Constants.MAX_CONTEXT_LENGTH / 2, rows.size());\n List<DiffRow> result = new ArrayList<>(upperPart);\n result.add(new DiffRow(DiffRow.Tag.EQUAL, Marker.ELLIPSIS, Marker.ELLIPSIS));\n result.addAll(lowerPart);\n return result;\n }\n\n /**\n * Creates a builder for constructing a new {@code DiffTask} object\n * @return {@link DiffTask.Builder} instance\n */\n public static Builder builder() {\n return new InitializingBuilder();\n }\n\n /**\n * Constructs a new {@code DiffTask} instance with critical values initialized\n */\n private static class InitializingBuilder extends DiffTask.Builder {\n @Override\n public DiffTask build() {\n DiffTask result = super.build();\n\n TaskParameters perRequest = result.taskParameters;\n TaskParameters perContentType = TaskParameters.from(result.contentType);\n result.taskParameters = TaskParameters.merge(perContentType, perRequest);\n\n if (result.anticipatedState == null) {\n result.anticipatedState = DiffState.UNCHANGED;\n }\n\n result.leftLabel = StringUtils.defaultIfBlank(result.leftLabel, Constants.LABEL_LEFT);\n result.rightLabel = StringUtils.defaultIfBlank(result.rightLabel, Constants.LABEL_RIGHT);\n\n return result;\n }\n }\n}" }, { "identifier": "Diff", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Diff.java", "snippet": "public interface Diff extends PrintableEntry, EntryHolder {\n\n /**\n * Gets the \"kind\" of difference. E.g., \"change\", \"insertion\", \"deletion\", etc.\n * @return {@link DiffState} instance\n */\n DiffState getState();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}\n * @return Integer value\n */\n int getCount();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}.\n * Counts only the differences that have not been \"silenced\" (accepted) with a {@link Filter}\n * @return Integer value\n */\n int getPendingCount();\n\n /**\n * Gets the left part of the comparison\n * @return String value\n */\n String getLeft();\n\n /**\n * Gets the right part of the comparison\n * @return String value\n */\n String getRight();\n}" } ]
import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.comparison.DiffTask; import com.exadel.etoolbox.anydiff.diff.Diff; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; import java.util.Collections; import java.util.List;
3,336
/* * 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.exadel.etoolbox.anydiff.runner; /** * Extends {@link DiffRunner} to implement extracting data from text strings */ @AllArgsConstructor(access = AccessLevel.PACKAGE) @NoArgsConstructor class SimpleRunner extends DiffRunner { private String left; private String right; @Override
/* * 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.exadel.etoolbox.anydiff.runner; /** * Extends {@link DiffRunner} to implement extracting data from text strings */ @AllArgsConstructor(access = AccessLevel.PACKAGE) @NoArgsConstructor class SimpleRunner extends DiffRunner { private String left; private String right; @Override
public List<Diff> runInternal() {
2
2023-11-16 14:29:45+00:00
4k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/ports/serial/DWSerialPort.java
[ { "identifier": "BasePortDef", "path": "src/main/java/org/thelair/dw4/drivewire/ports/BasePortDef.java", "snippet": "public abstract class BasePortDef implements DWIPortType {\n}" }, { "identifier": "DWIPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPort.java", "snippet": "public interface DWIPort {\n /**\n * Open target port with given definition and register with port handler.\n * @param port definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void openWith(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Modify port from definition.\n * @param port revised definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void setPortDef(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Identify port type.\n * @return port type id.\n */\n int identifyPort();\n\n /**\n * Close port and deregister with port handler.\n */\n void closePort();\n\n /**\n * Serialise port definition as String.\n *\n * @return port definition values\n */\n String getPortDefinition();\n}" }, { "identifier": "DWIPortManager", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortManager.java", "snippet": "public interface DWIPortManager {\n /**\n * Provide a count of all ports recorded.\n * @return total number of ports\n */\n int getPortCount();\n\n /**\n * Provide a count of open ports.\n * @return total number of open ports\n */\n int getOpenPortCount();\n\n /**\n * Provide a count of closed ports.\n * @return total number of closed ports\n */\n int getClosedPortCount();\n /**\n * Register an unused port as open.\n * @param port generic closed port\n */\n void registerOpenPort(DWIPort port);\n\n /**\n * Register a used port as closed.\n * @param port generic open port\n */\n void registerClosedPort(DWIPort port);\n\n /**\n * Create a new port instance.\n * @param portType type of port to create\n * @return unused port\n */\n DWIPort createPortInstance(DWIPortType.DWPortTypeIdentity portType);\n\n /**\n * Dispose of unused port.\n * @param port generic closed port\n */\n void disposePort(DWIPort port);\n\n\n /**\n * Handles context shutdown event.\n * Close all open ports. Dispose of all ports\n *\n * @param event context event\n */\n void contextDestroyed(ServletContextEvent event);\n}" }, { "identifier": "InvalidPortTypeDefinition", "path": "src/main/java/org/thelair/dw4/drivewire/ports/InvalidPortTypeDefinition.java", "snippet": "@Getter\npublic class InvalidPortTypeDefinition extends InvalidObjectException {\n /**\n * Port definition causing the exception.\n */\n private final BasePortDef sourcePortDef;\n /**\n * Constructs an {@code InvalidObjectException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n * @param portDef Causing port definition object\n * @see ObjectInputValidation\n */\n public InvalidPortTypeDefinition(final String reason,\n final BasePortDef portDef) {\n super(reason);\n sourcePortDef = portDef;\n }\n}" }, { "identifier": "DWISerial", "path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/hardware/DWISerial.java", "snippet": "public interface DWISerial {\n /**\n * Adds a SerialPortDataListener to the serial port interface.\n *\n * @param dataListener A SerialPortDataListener,\n * SerialPortDataListenerWithExceptions,\n * SerialPortPacketListener,\n * SerialPortMessageListener, or\n * SerialPortMessageListenerWithExceptions implementation\n * to be used for event-based serial port communications.\n *\n * @return Whether the listener was successfully registered with the serial\n * port\n */\n boolean addDataListener(SerialPortDataListener dataListener);\n\n /**\n * Returns the number of bytes available without blocking if\n * readBytes(byte[], int) were to be called immediately after this method\n * returns.\n *\n * @return The number of bytes currently available to be read, or -1 if the\n * port is not open\n */\n int bytesAvailable();\n\n /**\n * Returns the number of bytes still waiting to be written in the device's\n * output queue.\n *\n * @return The number of bytes currently waiting to be written, or -1 if the\n * port is not open\n */\n int bytesAwaitingWrite();\n\n /**\n * Closes this serial port.\n *\n * @return Whether the port was successfully closed\n */\n boolean closePort();\n\n /**\n * Flushes any already-received data from the registered\n * SerialPortDataListener that has not yet triggered an event.\n */\n void flushDataListener();\n\n /**\n * Flushes the serial port's Rx/Tx device buffers.\n *\n * @return Whether the IO buffers were (or will be) successfully flushed\n */\n boolean flushIOBuffers();\n\n /**\n * Gets the current baud rate of the serial port.\n *\n * @return The current baud rate of the serial port\n */\n int getBaudRate();\n\n /**\n * Gets the current number of data bits per word.\n *\n * @return The current number of data bits per word\n */\n int getDataBits();\n\n /**\n * Returns the flow control settings enabled on this serial port.\n *\n * @return The flow control settings enabled on this serial port\n */\n int getFlowControl();\n\n /**\n * Returns an InputStream object associated with this serial port.\n *\n * @return An InputStream object associated with this serial port\n */\n InputStream getInputStream();\n\n /**\n * Returns an OutputStream object associated with this serial port.\n *\n * @return An OutputStream object associated with this serial port\n */\n OutputStream getOutputStream();\n\n /**\n * Gets the current number of stop bits per word.\n *\n * @return The current number of stop bits per word.\n */\n int getStopBits();\n\n /**\n * Returns whether the port is currently open and available for communication.\n *\n * @return Whether the port is opened\n */\n boolean isOpen();\n\n /**\n * Opens this serial port for reading and writing.\n *\n * @return Whether the port was successfully opened with a valid configuration\n */\n boolean openPort();\n\n /**\n * Reads up to bytesToRead raw data bytes from the serial port and stores\n * them in the buffer.\n *\n * @param buffer The buffer into which the raw data is read\n * @param bytesToRead The number of bytes to read from the serial port\n * @return The number of bytes successfully read, or -1 if there was an error\n * reading from the port\n */\n int readBytes(byte[] buffer, int bytesToRead);\n\n /**\n * Reads up to bytesToRead raw data bytes from the serial port and stores\n * them in the buffer starting at the indicated offset.\n *\n * @param buffer The buffer into which the raw data is read\n * @param bytesToRead The number of bytes to read from the serial port\n * @param offset The read buffer index into which to begin storing data\n * @return The number of bytes successfully read, or -1 if there was an error\n * reading from the port\n */\n int readBytes(byte[] buffer, int bytesToRead, int offset);\n\n /**\n * Removes the associated SerialPortDataListener from the serial port\n * interface.\n */\n void removeDataListener();\n\n /**\n * Sets all serial port parameters at one time.\n *\n * @param newBaudRate The desired baud rate for this serial port\n * @param newDataBits The number of data bits to use per word\n * @param newStopBits The number of stop bits to use\n * @param newParity The type of parity error-checking desired\n * @return Whether the port configuration is valid or disallowed on this\n * system (only meaningful after the port is already opened)\n */\n boolean trySetCommPortParameters(\n int newBaudRate, int newDataBits, int newStopBits, int newParity\n );\n\n /**\n * Writes up to bytesToWrite raw data bytes from the buffer parameter to the\n * serial port.\n *\n * @param buffer The buffer containing the raw data to write to the\n * serial port\n * @param bytesToWrite The number of bytes to write to the serial port\n * @return The number of bytes successfully written, or -1 if there was an\n * error writing to the port\n */\n int writeBytes(byte[] buffer, int bytesToWrite);\n\n /**\n * Writes up to bytesToWrite raw data bytes from the buffer parameter to the\n * serial port starting at the indicated offset.\n *\n * @param buffer The buffer containing the raw data to write to the\n * serial port\n * @param bytesToWrite The number of bytes to write to the serial port\n * @param offset The buffer index from which to begin writing to the\n * serial port\n * @return The number of bytes successfully written, or -1 if there was an\n * error writing to the port\n */\n int writeBytes(byte[] buffer, int bytesToWrite, int offset);\n}" } ]
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.thelair.dw4.drivewire.ports.BasePortDef; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortManager; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition; import org.thelair.dw4.drivewire.ports.serial.hardware.DWISerial; import java.util.Map;
2,757
package org.thelair.dw4.drivewire.ports.serial; /** * RS232 Serial port definition. */ public final class DWSerialPort implements DWIPort { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class); /** * Serial port definition. */ private SerialPortDef portDef; /** * Port manager. */ private final DWIPortManager portManager; /** * concrete com port object. */ private DWISerial comPort; /** * Serial port handler. */ private final SerialPortHardware portHandler; /** * Unique port identifier. */ private final int portId; /** * Create serial port with reference to manager. * @param manager port manager handling this port * @param port identifier * @param hardPorts host serial hardware */ public DWSerialPort( final DWIPortManager manager, final int port, final SerialPortHardware hardPorts ) { this.portManager = manager; this.portId = port; this.portHandler = hardPorts; LOGGER.info("Serial port created " + port); } @Override
package org.thelair.dw4.drivewire.ports.serial; /** * RS232 Serial port definition. */ public final class DWSerialPort implements DWIPort { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class); /** * Serial port definition. */ private SerialPortDef portDef; /** * Port manager. */ private final DWIPortManager portManager; /** * concrete com port object. */ private DWISerial comPort; /** * Serial port handler. */ private final SerialPortHardware portHandler; /** * Unique port identifier. */ private final int portId; /** * Create serial port with reference to manager. * @param manager port manager handling this port * @param port identifier * @param hardPorts host serial hardware */ public DWSerialPort( final DWIPortManager manager, final int port, final SerialPortHardware hardPorts ) { this.portManager = manager; this.portId = port; this.portHandler = hardPorts; LOGGER.info("Serial port created " + port); } @Override
public void openWith(final BasePortDef port)
0
2023-11-18 11:35:16+00:00
4k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/render/entities/GenericProjectileRenderer.java
[ { "identifier": "GenericProjectile", "path": "src/main/java/sheridan/gunscraft/entities/projectile/GenericProjectile.java", "snippet": "public class GenericProjectile extends Entity implements IProjectile, IEntityAdditionalSpawnData {\n public static final float BASE_SPEED_INDEX = 1.4f;\n public static final float BASE_SPREAD_INDEX = 0.008f;\n public LivingEntity shooter;\n public float speed;\n public float spread;\n public float damage;\n public int lifeLength;\n\n private static final Predicate<Entity> PROJECTILE_TARGETS =\n (input) -> input != null && input.canBeCollidedWith() && !input.isSpectator();\n\n\n public GenericProjectile(EntityType<?> entityTypeIn, World worldIn) {\n super(entityTypeIn, worldIn);\n }\n\n @Override\n public void init(LivingEntity shooter, float speed, float spread, float damage, int lifeLength) {\n this.shooter = shooter;\n\n\n this.setPosition(shooter.getPosX(), shooter.getPosY() + shooter.getEyeHeight(shooter.getPose()), shooter.getPosZ());\n this.speed = speed * BASE_SPEED_INDEX;\n this.spread = spread * BASE_SPREAD_INDEX;\n\n this.setRotation(shooter.rotationYaw, shooter.rotationPitch);\n\n double sx = rand.nextGaussian() * this.spread;\n double sy = rand.nextGaussian() * this.spread;\n double sz = rand.nextGaussian() * this.spread;\n double vp = Math.cos(this.rotationPitch * 0.017453292519943295);\n Vector3d motionVec = new Vector3d(\n - Math.sin(this.rotationYaw * 0.017453292519943295) * vp + sx,\n Math.sin(-this.rotationPitch * 0.017453292519943295) + sy,\n Math.cos(this.rotationYaw * 0.017453292519943295) * vp + sz\n );\n motionVec.normalize();\n this.setMotion(motionVec.mul(this.speed, this.speed, this.speed));\n this.damage = damage;\n this.lifeLength = lifeLength;\n }\n\n\n @Override\n protected void registerData() {\n\n }\n\n @Override\n public void tick() {\n if (!this.world.isRemote) {\n if (this.ticksExisted >= lifeLength) {\n this.setDead();\n }\n Vector3d prevPos = this.getPositionVec();\n Vector3d nextPos = prevPos.add(this.getMotion());\n BlockRayTraceResult resultBlock = this.world.rayTraceBlocks(new RayTraceContext(prevPos, nextPos, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, this));\n Vector3d tempEndPos = null;\n boolean mightHitBlock = false;\n if (resultBlock.getType() != RayTraceResult.Type.MISS) {\n tempEndPos = resultBlock.getHitVec();\n mightHitBlock = true;\n }\n EntityRayTraceResult entityResult = tempEndPos == null ? ProjectileHelper.rayTraceEntities(this.world, this, prevPos, nextPos, this.getBoundingBox().expand(this.getMotion()).grow(1.0D), PROJECTILE_TARGETS)\n : ProjectileHelper.rayTraceEntities(this.world, this, prevPos, tempEndPos, this.getBoundingBox().expand(this.getMotion()).grow(1.0D), PROJECTILE_TARGETS);\n if (entityResult != null) {\n if (onHitEntity(entityResult)) {\n this.setDead();\n }\n } else if (mightHitBlock) {\n if (onHitBlock(resultBlock)) {\n this.setDead();\n }\n }\n\n this.setPosition(nextPos.x, nextPos.y, nextPos.z);\n }\n }\n\n public boolean onHitBlock(BlockRayTraceResult result) {\n BlockState state = this.world.getBlockState(result.getPos());\n if (state.getBlock() == Blocks.BELL && this.shooter instanceof PlayerEntity) {\n BellBlock bell = (BellBlock) state.getBlock();\n bell.attemptRing(this.world, state, result, (PlayerEntity) this.shooter, true);\n }\n return !(state.getBlock() instanceof LeavesBlock);\n }\n\n public boolean onHitEntity(EntityRayTraceResult result) {\n if (result.getEntity() == this.shooter) {\n return false;\n }\n Entity entity = result.getEntity();\n entity.hurtResistantTime = 0;\n GenericProjectileDamage source = new GenericProjectileDamage(\"projectile\", this.shooter);\n source.setProjectile();\n return entity.attackEntityFrom(source,damage);\n }\n\n @Override\n public void readAdditional(CompoundNBT compound) {\n\n }\n\n @Override\n public void writeAdditional(CompoundNBT compound) {\n\n }\n\n @Override\n public IPacket<?> createSpawnPacket() {\n return NetworkHooks.getEntitySpawningPacket(this);\n }\n\n @Override\n public void writeSpawnData(PacketBuffer buffer) {\n buffer.writeInt(this.lifeLength);\n buffer.writeFloat(this.speed);\n }\n\n @Override\n public void readSpawnData(PacketBuffer additionalData) {\n this.lifeLength = additionalData.readInt();\n this.speed = additionalData.readFloat();\n }\n\n}" }, { "identifier": "ModelRifleProjectile", "path": "src/main/java/sheridan/gunscraft/model/projectilies/ModelRifleProjectile.java", "snippet": "public class ModelRifleProjectile extends EntityModel<GenericProjectile> {\n private final ModelRenderer bb_main;\n private final ModelRenderer cube_r1;\n private final ModelRenderer cube_r2;\n\n public ModelRifleProjectile() {\n textureWidth = 128;\n textureHeight = 128;\n\n bb_main = new ModelRenderer(this);\n bb_main.setRotationPoint(0.0F, 24.0F, 0.0F);\n\n\n cube_r1 = new ModelRenderer(this);\n cube_r1.setRotationPoint(0.0F, -24.0F, 35.0F);\n bb_main.addChild(cube_r1);\n setRotationAngle(cube_r1, 3.1416F, 0.0F, 0.7854F);\n cube_r1.setTextureOffset(0, 0).addBox(0.0F, -4.0F, 0.0F, 0.0F, 8.0F, 35.0F, 0.0F, false);\n\n cube_r2 = new ModelRenderer(this);\n cube_r2.setRotationPoint(0.0F, -24.0F, 35.0F);\n bb_main.addChild(cube_r2);\n setRotationAngle(cube_r2, 3.1416F, 0.0F, -0.7854F);\n cube_r2.setTextureOffset(0, 0).addBox(0.0F, -4.0F, 0.0F, 0.0F, 8.0F, 35.0F, 0.0F, false);\n\n\n\n }\n\n @Override\n public void setRotationAngles(GenericProjectile entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n\n }\n\n @Override\n public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha){\n bb_main.render(matrixStack, buffer, packedLight, packedOverlay, red, green, blue, alpha);\n }\n\n public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {\n modelRenderer.rotateAngleX = x;\n modelRenderer.rotateAngleY = y;\n modelRenderer.rotateAngleZ = z;\n }\n\n\n}" }, { "identifier": "BASE_SPEED_INDEX", "path": "src/main/java/sheridan/gunscraft/entities/projectile/GenericProjectile.java", "snippet": "public static final float BASE_SPEED_INDEX = 1.4f;" } ]
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Quaternion; import net.minecraft.util.math.vector.Vector3f; import sheridan.gunscraft.entities.projectile.GenericProjectile; import sheridan.gunscraft.model.projectilies.ModelRifleProjectile; import static sheridan.gunscraft.entities.projectile.GenericProjectile.BASE_SPEED_INDEX;
2,059
package sheridan.gunscraft.render.entities; public class GenericProjectileRenderer extends EntityRenderer<GenericProjectile> { public static ResourceLocation RIFLE = new ResourceLocation("gunscraft","textures/projectile/generic_projectile.png"); public static final float BASE_SCALE = 0.2f;
package sheridan.gunscraft.render.entities; public class GenericProjectileRenderer extends EntityRenderer<GenericProjectile> { public static ResourceLocation RIFLE = new ResourceLocation("gunscraft","textures/projectile/generic_projectile.png"); public static final float BASE_SCALE = 0.2f;
public static ModelRifleProjectile modelGenericProjectile = new ModelRifleProjectile();
1
2023-11-14 14:00:55+00:00
4k
zpascual/5419-Arm-Example
src/main/java/com/team5419/lib/io/Xbox.java
[ { "identifier": "Rotation2d", "path": "src/main/java/com/team254/lib/geometry/Rotation2d.java", "snippet": "public class Rotation2d implements IRotation2d<Rotation2d> {\n protected static final Rotation2d kIdentity = new Rotation2d();\n\n public static final Rotation2d identity() {\n return kIdentity;\n }\n\n protected final double cos_angle_;\n protected final double sin_angle_;\n protected double theta_degrees = 0;\n protected double theta_radians = 0;\n\n public Rotation2d() {\n this(1, 0, false);\n }\n\n public Rotation2d(double x, double y, boolean normalize) {\n if (normalize) {\n // From trig, we know that sin^2 + cos^2 == 1, but as we do math on this object we might accumulate rounding errors.\n // Normalizing forces us to re-scale the sin and cos to reset rounding errors.\n double magnitude = Math.hypot(x, y);\n if (magnitude > kEpsilon) {\n sin_angle_ = y / magnitude;\n cos_angle_ = x / magnitude;\n } else {\n sin_angle_ = 0;\n cos_angle_ = 1;\n }\n } else {\n cos_angle_ = x;\n sin_angle_ = y;\n }\n\t theta_degrees = Math.toDegrees(Math.atan2(sin_angle_, cos_angle_));\n }\n\n public Rotation2d(final Rotation2d other) {\n cos_angle_ = other.cos_angle_;\n sin_angle_ = other.sin_angle_;\n theta_degrees = Math.toDegrees(Math.atan2(sin_angle_, cos_angle_));\n }\n \n public Rotation2d(double theta_degrees){\n \tcos_angle_ = Math.cos(Math.toRadians(theta_degrees));\n \tsin_angle_ = Math.sin(Math.toRadians(theta_degrees));\n \tthis.theta_degrees = theta_degrees;\n }\n\n public Rotation2d(final Translation2d direction, boolean normalize) {\n this(direction.x(), direction.y(), normalize);\n }\n\n public static Rotation2d fromRadians(double angle_radians) {\n return new Rotation2d(Math.cos(angle_radians), Math.sin(angle_radians), false);\n }\n\n public static Rotation2d fromDegrees(double angle_degrees) {\n return new Rotation2d(angle_degrees);\n }\n\n public double cos() {\n return cos_angle_;\n }\n\n public double sin() {\n return sin_angle_;\n }\n\n public double tan() {\n if (Math.abs(cos_angle_) < kEpsilon) {\n if (sin_angle_ >= 0.0) {\n return Double.POSITIVE_INFINITY;\n } else {\n return Double.NEGATIVE_INFINITY;\n }\n }\n return sin_angle_ / cos_angle_;\n }\n\n public double getRadians() {\n return Math.atan2(sin_angle_, cos_angle_);\n }\n\n public double getDegrees() {\n return Math.toDegrees(getRadians());\n }\n \n public double getUnboundedDegrees(){\n \treturn theta_degrees;\n }\n\n /**\n * We can rotate this Rotation2d by adding together the effects of it and another rotation.\n *\n * @param other The other rotation. See: https://en.wikipedia.org/wiki/Rotation_matrix\n * @return This rotation rotated by other.\n */\n public Rotation2d rotateBy(final Rotation2d other) {\n return new Rotation2d(cos_angle_ * other.cos_angle_ - sin_angle_ * other.sin_angle_,\n cos_angle_ * other.sin_angle_ + sin_angle_ * other.cos_angle_, true);\n }\n\n public Rotation2d minus(final Rotation2d other) {\n return this.rotateBy(other.inverse());\n }\n\n public Rotation2d normal() {\n return new Rotation2d(-sin_angle_, cos_angle_, false);\n }\n\n /**\n * Multiplies the current rotation by a scalar.\n *\n * @param scalar The scalar.\n * @return The new scaled Rotation2d.\n */\n public Rotation2d times(double scalar) {\n return Rotation2d.fromRadians(getRadians() * scalar);\n }\n\n /**\n * The inverse of a Rotation2d \"undoes\" the effect of this rotation.\n *\n * @return The opposite of this rotation.\n */\n public Rotation2d inverse() {\n return new Rotation2d(cos_angle_, -sin_angle_, false);\n }\n\n public boolean isParallel(final Rotation2d other) {\n return Util.epsilonEquals(Translation2d.cross(toTranslation(), other.toTranslation()), 0.0);\n }\n\n public Translation2d toTranslation() {\n return new Translation2d(cos_angle_, sin_angle_);\n }\n \n /**\n * @return The pole nearest to this rotation.\n */\n public Rotation2d nearestPole(){\n \tdouble pole_sin = 0.0;\n \tdouble pole_cos = 0.0;\n \tif(Math.abs(cos_angle_) > Math.abs(sin_angle_)){\n \t\tpole_cos = Math.signum(cos_angle_);\n \t\tpole_sin = 0.0;\n \t}else{\n \t\tpole_cos = 0.0;\n \t\tpole_sin = Math.signum(sin_angle_);\n \t}\n \treturn new Rotation2d(pole_cos, pole_sin, false);\n }\n\n public Rotation2d mirrorAboutX() {\n return new Rotation2d(-cos_angle_, sin_angle_, false);\n }\n\n public Rotation2d mirrorAboutY() {\n return new Rotation2d(cos_angle_, -sin_angle_, false);\n }\n\n @Override\n public Rotation2d interpolate(final Rotation2d other, double x) {\n if (x <= 0) {\n return new Rotation2d(this);\n } else if (x >= 1) {\n return new Rotation2d(other);\n }\n double angle_diff = inverse().rotateBy(other).getRadians();\n return this.rotateBy(Rotation2d.fromRadians(angle_diff * x));\n }\n\n @Override\n public String toString() {\n final DecimalFormat fmt = new DecimalFormat(\"#0.000\");\n return \"(\" + fmt.format(getDegrees()) + \" deg)\";\n }\n\n @Override\n public String toCSV() {\n final DecimalFormat fmt = new DecimalFormat(\"#0.000\");\n return fmt.format(getDegrees());\n }\n\n @Override\n public double distance(final Rotation2d other) {\n return inverse().rotateBy(other).getRadians();\n }\n\n @Override\n public boolean equals(final Object other) {\n if (other == null || !(other instanceof Rotation2d)) return false;\n return Math.abs(distance((Rotation2d)other)) < Util.kEpsilon;\n }\n\n @Override\n public Rotation2d getRotation() {\n return this;\n }\n}" }, { "identifier": "Util", "path": "src/main/java/com/team5419/lib/util/Util.java", "snippet": "public class Util {\n\n public static final double kEpsilon = 1e-12;\n\n /** Prevent this class from being instantiated. */\n private Util() {\n }\n\n /**\n * Limits the given input to the given magnitude.\n */\n public static double limit(double v, double maxMagnitude) {\n return limit(v, -maxMagnitude, maxMagnitude);\n }\n\n public static double limit(double v, double min, double max) {\n return Math.min(max, Math.max(min, v));\n }\n\n public static String joinStrings(String delim, List<?> strings) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < strings.size(); ++i) {\n sb.append(strings.get(i).toString());\n if (i < strings.size() - 1) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n public static boolean epsilonEquals(double a, double b, double epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean epsilonEquals(double a, double b) {\n return epsilonEquals(a, b, kEpsilon);\n }\n\n public static boolean allCloseTo(List<Double> list, double value, double epsilon) {\n boolean result = true;\n for (Double value_in : list) {\n result &= epsilonEquals(value_in, value, epsilon);\n }\n return result;\n }\n \n public static double normalize(double current, double test){\n \tif(current > test) return current;\n \treturn test;\n }\n \n public static double boundAngleNeg180to180Degrees(double angle){\n // Naive algorithm\n while(angle >= 180.0) {angle -= 360.0;}\n while(angle < -180.0) {angle += 360.0;}\n return angle;\n }\n \n public static double boundAngle0to360Degrees(double angle){\n // Naive algorithm\n while(angle >= 360.0) {angle -= 360.0;}\n while(angle < 0.0) {angle += 360.0;}\n return angle;\n }\n \n public static double boundToScope(double scopeFloor, double scopeCeiling, double argument){\n \tdouble stepSize = scopeCeiling - scopeFloor;\n \twhile(argument >= scopeCeiling) {argument -= stepSize;}\n \twhile(argument < scopeFloor) {argument += stepSize;}\n \treturn argument;\n }\n \n public static double placeInAppropriate0To360Scope(double scopeReference, double newAngle){\n \tdouble lowerBound;\n double upperBound;\n double lowerOffset = scopeReference % 360;\n if(lowerOffset >= 0){\n \tlowerBound = scopeReference - lowerOffset;\n \tupperBound = scopeReference + (360 - lowerOffset);\n }else{\n \tupperBound = scopeReference - lowerOffset; \n \tlowerBound = scopeReference - (360 + lowerOffset);\n }\n while(newAngle < lowerBound){\n \tnewAngle += 360; \n }\n while(newAngle > upperBound){\n \tnewAngle -= 360; \n }\n if(newAngle - scopeReference > 180){\n \tnewAngle -= 360;\n }else if(newAngle - scopeReference < -180){\n \tnewAngle += 360;\n }\n return newAngle;\n }\n\n public static boolean shouldReverse(Rotation2d goalAngle, Rotation2d currentAngle) {\n double angleDifference = Math.abs(goalAngle.distance(currentAngle));\n double reversedAngleDifference = Math.abs(goalAngle.distance(currentAngle.rotateBy(Rotation2d.fromDegrees(180.0))));\n return reversedAngleDifference < angleDifference;\n }\n \n public static double deadBand(double val, double deadband){\n return (Math.abs(val) > Math.abs(deadband)) ? val : 0.0;\n }\n\n public static double scaledDeadband(double value, double maxValue, double deadband){\n double deadbandedValue = deadBand(value, deadband);\n if(epsilonEquals(deadbandedValue, 0.0))\n return 0.0;\n return Math.signum(deadbandedValue) * ((Math.abs(deadbandedValue) - deadband) / (maxValue - deadband));\n }\n\n public static boolean isInRange(double value, double rangeLimit1, double rangeLimit2) {\n double min, max;\n if (rangeLimit1 < rangeLimit2) {\n min = rangeLimit1;\n max = rangeLimit2;\n } else {\n min = rangeLimit2;\n max = rangeLimit1;\n }\n\n return min <= value && value <= max;\n }\n}" } ]
import com.team254.lib.geometry.Rotation2d; import com.team5419.lib.util.Util; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.XboxController;
3,577
package com.team5419.lib.io; public class Xbox extends XboxController{ private static final double PRESS_THRESHOLD = 0.05; private double DEAD_BAND = 0.15; private boolean rumbling = false; public ButtonCheck aButton, bButton, xButton, yButton, startButton, backButton, leftBumper, rightBumper, leftCenterClick, rightCenterClick, leftTrigger, rightTrigger, POV0, POV90, POV180, POV270, POV135, POV225; public static final int A_BUTTON = 1; public static final int B_BUTTON = 2; public static final int X_BUTTON = 3; public static final int Y_BUTTON = 4; public static final int LEFT_BUMPER = 5; public static final int RIGHT_BUMPER = 6; public static final int BACK_BUTTON = 7; public static final int START_BUTTON = 8; public static final int LEFT_CENTER_CLICK = 9; public static final int RIGHT_CENTER_CLICK = 10; public static final int LEFT_TRIGGER = -2; public static final int RIGHT_TRIGGER = -3; public static final int POV_0 = -4; public static final int POV_90 = -5; public static final int POV_180 = -6; public static final int POV_270 = -7; public static final int POV_135 = -8; public static final int POV_225 = -9; public void setDeadband(double deadband){ DEAD_BAND = deadband; } public Xbox(int usb) { super(usb); aButton = new ButtonCheck(A_BUTTON); bButton = new ButtonCheck(B_BUTTON); xButton = new ButtonCheck(X_BUTTON); yButton = new ButtonCheck(Y_BUTTON); startButton = new ButtonCheck(START_BUTTON); backButton = new ButtonCheck(BACK_BUTTON); leftBumper = new ButtonCheck(LEFT_BUMPER); rightBumper = new ButtonCheck(RIGHT_BUMPER); leftCenterClick = new ButtonCheck(LEFT_CENTER_CLICK); rightCenterClick = new ButtonCheck(RIGHT_CENTER_CLICK); leftTrigger = new ButtonCheck(LEFT_TRIGGER); rightTrigger = new ButtonCheck(RIGHT_TRIGGER); POV0 = new ButtonCheck(POV_0); POV90 = new ButtonCheck(POV_90); POV180 = new ButtonCheck(POV_180); POV270 = new ButtonCheck(POV_270); POV135 = new ButtonCheck(POV_135); POV225 = new ButtonCheck(POV_225); } @Override public double getLeftX() { return Util.deadBand(getRawAxis(0), DEAD_BAND); } @Override public double getRightX() { return Util.deadBand(getRawAxis(4), DEAD_BAND); } @Override public double getLeftY() { return Util.deadBand(getRawAxis(1), DEAD_BAND); } @Override public double getRightY() { return Util.deadBand(getRawAxis(5), DEAD_BAND); } @Override public double getLeftTriggerAxis() { return Util.deadBand(getRawAxis(2), PRESS_THRESHOLD); } @Override public double getRightTriggerAxis() { return Util.deadBand(getRawAxis(3), PRESS_THRESHOLD); }
package com.team5419.lib.io; public class Xbox extends XboxController{ private static final double PRESS_THRESHOLD = 0.05; private double DEAD_BAND = 0.15; private boolean rumbling = false; public ButtonCheck aButton, bButton, xButton, yButton, startButton, backButton, leftBumper, rightBumper, leftCenterClick, rightCenterClick, leftTrigger, rightTrigger, POV0, POV90, POV180, POV270, POV135, POV225; public static final int A_BUTTON = 1; public static final int B_BUTTON = 2; public static final int X_BUTTON = 3; public static final int Y_BUTTON = 4; public static final int LEFT_BUMPER = 5; public static final int RIGHT_BUMPER = 6; public static final int BACK_BUTTON = 7; public static final int START_BUTTON = 8; public static final int LEFT_CENTER_CLICK = 9; public static final int RIGHT_CENTER_CLICK = 10; public static final int LEFT_TRIGGER = -2; public static final int RIGHT_TRIGGER = -3; public static final int POV_0 = -4; public static final int POV_90 = -5; public static final int POV_180 = -6; public static final int POV_270 = -7; public static final int POV_135 = -8; public static final int POV_225 = -9; public void setDeadband(double deadband){ DEAD_BAND = deadband; } public Xbox(int usb) { super(usb); aButton = new ButtonCheck(A_BUTTON); bButton = new ButtonCheck(B_BUTTON); xButton = new ButtonCheck(X_BUTTON); yButton = new ButtonCheck(Y_BUTTON); startButton = new ButtonCheck(START_BUTTON); backButton = new ButtonCheck(BACK_BUTTON); leftBumper = new ButtonCheck(LEFT_BUMPER); rightBumper = new ButtonCheck(RIGHT_BUMPER); leftCenterClick = new ButtonCheck(LEFT_CENTER_CLICK); rightCenterClick = new ButtonCheck(RIGHT_CENTER_CLICK); leftTrigger = new ButtonCheck(LEFT_TRIGGER); rightTrigger = new ButtonCheck(RIGHT_TRIGGER); POV0 = new ButtonCheck(POV_0); POV90 = new ButtonCheck(POV_90); POV180 = new ButtonCheck(POV_180); POV270 = new ButtonCheck(POV_270); POV135 = new ButtonCheck(POV_135); POV225 = new ButtonCheck(POV_225); } @Override public double getLeftX() { return Util.deadBand(getRawAxis(0), DEAD_BAND); } @Override public double getRightX() { return Util.deadBand(getRawAxis(4), DEAD_BAND); } @Override public double getLeftY() { return Util.deadBand(getRawAxis(1), DEAD_BAND); } @Override public double getRightY() { return Util.deadBand(getRawAxis(5), DEAD_BAND); } @Override public double getLeftTriggerAxis() { return Util.deadBand(getRawAxis(2), PRESS_THRESHOLD); } @Override public double getRightTriggerAxis() { return Util.deadBand(getRawAxis(3), PRESS_THRESHOLD); }
public Rotation2d getPOVDirection() {
0
2023-11-14 06:44:40+00:00
4k
Ouest-France/querydsl-postgrest
src/main/java/fr/ouestfrance/querydsl/postgrest/model/impl/OrderFilter.java
[ { "identifier": "FilterVisitor", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/builders/FilterVisitor.java", "snippet": "public interface FilterVisitor {\n\n /**\n * Visitor function\n *\n * @param visitor visitor to handle.\n */\n void accept(QueryFilterVisitor visitor);\n\n /**\n * Get the filter string representation\n * @return the filterString\n */\n default String getFilterString() {\n QueryFilterVisitor visitor = new QueryFilterVisitor();\n accept(visitor);\n return visitor.getValue();\n }\n}" }, { "identifier": "QueryFilterVisitor", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/builders/QueryFilterVisitor.java", "snippet": "public final class QueryFilterVisitor {\n\n private static final String DOT = \".\";\n private static final String OPEN_PARENTHESIS = \"(\";\n private static final String CLOSE_PARENTHESIS = \")\";\n private static final String COMA = \",\";\n private static final String EMPTY_STRING = \"\";\n\n /**\n * StringBuilder\n */\n private final StringBuilder builder = new StringBuilder();\n\n /**\n * Transform SimpleFilter to Query\n *\n * @param filter simple filter\n */\n public void visit(QueryFilter filter) {\n builder.append(filter.getOperator()).append(QueryFilterVisitor.DOT).append(filter.getValue());\n }\n\n /**\n * Transform OrderFilter to Query\n *\n * @param filter order filter\n */\n public void visit(OrderFilter filter) {\n builder.append(filter.getSort().getOrders().stream().map(\n x -> x.getProperty()\n + (Sort.Direction.ASC.equals(x.getDirection()) ? EMPTY_STRING : DOT + \"desc\")\n + (switch (x.getNullHandling()) {\n case NATIVE -> EMPTY_STRING;\n case NULLS_FIRST -> DOT + \"nullsfirst\";\n case NULLS_LAST -> DOT + \"nullslast\";\n })).collect(Collectors.joining(COMA)));\n }\n\n /**\n * Transform a Select filter to Query\n *\n * @param filter select filter\n */\n public void visit(SelectFilter filter) {\n builder.append(\"*,\");\n builder.append(filter.getSelectAttributes().stream().map(\n x -> x.getAlias().isEmpty() ? x.getValue() : x.getAlias() + \":\" + x.getValue())\n .collect(Collectors.joining(\",\")));\n }\n\n /**\n * Transform a Composite filter to Query\n *\n * @param filter composite filter\n */\n public void visit(CompositeFilter filter) {\n // Check items aliases\n Filter lastElement = getLastElement(filter.getFilters());\n\n builder.append(OPEN_PARENTHESIS);\n filter.getFilters().forEach(item -> {\n builder.append(item.getKey());\n if (item instanceof QueryFilter) {\n builder.append(DOT);\n }\n item.accept(this);\n if (!item.equals(lastElement)) {\n builder.append(COMA);\n }\n });\n builder.append(CLOSE_PARENTHESIS);\n }\n\n /**\n * Return the last element of a list\n *\n * @param filters list of filters\n * @return last element\n */\n private Filter getLastElement(List<Filter> filters) {\n return filters.get(filters.size() - 1);\n }\n\n /**\n * Return string representation of the queryString\n *\n * @return string representation of the queryString\n */\n public String getValue() {\n return builder.toString();\n }\n}" }, { "identifier": "Sort", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Sort.java", "snippet": "@Getter\n@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Sort {\n\n /**\n * List of orders queries\n */\n private final List<Order> orders;\n\n /**\n * Create sort from list of properties\n *\n * @param properties list of ordered keys to sort\n * @return Sort object with ascending direction\n */\n public static Sort by(String... properties) {\n return by(Direction.ASC, properties);\n }\n\n /**\n * Create sort from list of properties and direction\n *\n * @param direction direction (ASC, DESC)\n * @param properties list of ordered keys to sort\n * @return Sort object with specified direction\n */\n public static Sort by(Direction direction, String... properties) {\n return new Sort(Arrays.stream(properties)\n .map(x -> new Order(x, direction, NullHandling.NATIVE))\n .toList());\n }\n\n /**\n * Create sort from list of Order\n *\n * @param orders list of orders\n * @return Sort object with specified orders\n */\n public static Sort by(Sort.Order... orders) {\n return new Sort(Arrays.stream(orders).toList());\n }\n\n\n /**\n * Transform a sort to ascending sort\n *\n * @return ascending sort\n */\n public Sort ascending() {\n orders.forEach(x -> x.direction = Direction.ASC);\n return this;\n }\n\n /**\n * Transform a sort to descending sort\n *\n * @return descending sort\n */\n public Sort descending() {\n orders.forEach(x -> x.direction = Direction.DESC);\n return this;\n }\n\n /**\n * Sort direction\n */\n public enum Direction {\n /**\n * Ascending : from A to Z\n */\n ASC,\n /**\n * Descending : from Z to A\n */\n DESC\n }\n\n /**\n * Null Handling sort gesture\n */\n public enum NullHandling {\n /**\n * No null handling\n */\n NATIVE,\n /**\n * get nulls on top positions\n */\n NULLS_FIRST,\n /**\n * get nulls on last position\n */\n NULLS_LAST\n }\n\n /**\n * Order representation\n */\n @Getter\n @AllArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Order {\n /**\n * property to filter\n */\n private final String property;\n /**\n * sort direction\n */\n private Direction direction;\n /**\n * Null Handling gesture\n */\n private NullHandling nullHandling;\n\n /**\n * Create ascending sort on property\n *\n * @param property property to sort\n * @return ascending sort\n */\n public static Order asc(String property) {\n return new Order(property, Direction.ASC, NullHandling.NATIVE);\n }\n\n /**\n * Create descending sort on property\n *\n * @param property property to sort\n * @return descending sort\n */\n public static Order desc(String property) {\n return new Order(property, Direction.DESC, NullHandling.NATIVE);\n }\n\n /**\n * Allow to retrieve nulls values first\n *\n * @return order\n */\n public Order nullsFirst() {\n nullHandling = NullHandling.NULLS_FIRST;\n return this;\n }\n\n /**\n * Allow to retrieve nulls values last\n *\n * @return order\n */\n public Order nullsLast() {\n nullHandling = NullHandling.NULLS_LAST;\n return this;\n }\n\n }\n\n}" }, { "identifier": "Filter", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Filter.java", "snippet": "public interface Filter extends FilterVisitor {\n\n /**\n * Get the filter key\n * @return filter key\n */\n String getKey();\n\n}" } ]
import fr.ouestfrance.querydsl.postgrest.builders.FilterVisitor; import fr.ouestfrance.querydsl.postgrest.builders.QueryFilterVisitor; import fr.ouestfrance.querydsl.postgrest.model.Sort; import fr.ouestfrance.querydsl.postgrest.model.Filter; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor;
1,956
package fr.ouestfrance.querydsl.postgrest.model.impl; /** * Order filter allow to describe a pagination sort */ @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
package fr.ouestfrance.querydsl.postgrest.model.impl; /** * Order filter allow to describe a pagination sort */ @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class OrderFilter implements Filter, FilterVisitor {
0
2023-11-14 10:45:54+00:00
4k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/dialogs/ExportOptionsDialog.java
[ { "identifier": "ExportApp", "path": "app/src/main/java/com/threethan/questpatcher/utils/tasks/ExportApp.java", "snippet": "public class ExportApp extends sExecutor {\n\n private final Context mContext;\n private ProgressDialog mProgressDialog;\n private final String mPackageName;\n\n public ExportApp(String packageName, Context context) {\n mPackageName = packageName;\n mContext = context;\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPreExecute() {\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.exporting, sPackageUtils.getAppName(mPackageName, mContext)));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIcon(R.mipmap.ic_launcher);\n mProgressDialog.setTitle(R.string.app_name);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n if (!APKData.getExportAPKsPath(mContext).exists()) {\n sFileUtils.mkdir(APKData.getExportAPKsPath(mContext));\n }\n }\n\n @Override\n public void doInBackground() {\n if (APKData.isAppBundle(sPackageUtils.getSourceDir(mPackageName, mContext))) {\n File mParent = new File(APKData.getExportAPKsPath(mContext) , mPackageName);\n if (mParent.exists()) {\n sFileUtils.delete(mParent);\n }\n sFileUtils.mkdir(mParent);\n for (String mSplits : APKData.splitApks(sPackageUtils.getSourceDir(mPackageName, mContext))) {\n if (mSplits.endsWith(\".apk\")) {\n sFileUtils.copy(new File(mSplits), new File(mParent, new File(mSplits).getName()));\n }\n }\n } else {\n sFileUtils.copy(new File(sPackageUtils.getSourceDir(mPackageName, mContext)), new File(APKData.getExportAPKsPath(mContext), mPackageName + \".apk\"));\n }\n }\n\n @Override\n public void onPostExecute() {\n try {\n mProgressDialog.dismiss();\n } catch (IllegalArgumentException ignored) {\n }\n }\n\n}" }, { "identifier": "ResignAPKs", "path": "app/src/main/java/com/threethan/questpatcher/utils/tasks/ResignAPKs.java", "snippet": "public class ResignAPKs extends sExecutor {\n\n private final Activity mActivity;\n private final boolean mExit, mInstall;\n private final String mPackageName;\n private File mParent = null;\n private ProgressDialog mProgressDialog;\n private String mDetectedPackageName = null;\n\n public ResignAPKs(String packageName, boolean install, boolean exit, Activity activity) {\n mPackageName = packageName;\n mInstall = install;\n mExit = exit;\n mActivity = activity;\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPreExecute() {\n mProgressDialog = new ProgressDialog(mActivity);\n mProgressDialog.setMessage(mPackageName != null ? mActivity.getString(R.string.signing, sPackageUtils.getAppName(\n mPackageName, mActivity)) : mActivity.getString(R.string.resigning_apks));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIcon(R.mipmap.ic_launcher);\n mProgressDialog.setTitle(R.string.app_name);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n\n mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n }\n\n @Override\n public void doInBackground() {\n if (mPackageName == null) {\n // Find package name from the selected APKs\n mDetectedPackageName = APKData.findPackageName(mActivity);\n }\n\n if (mPackageName != null) {\n Common.getAPKList().clear();\n if (APKData.isAppBundle(sPackageUtils.getSourceDir(mPackageName, mActivity))) {\n Common.getAPKList().addAll(APKData.splitApks(sPackageUtils.getSourceDir(mPackageName, mActivity)));\n } else {\n Common.getAPKList().add(sPackageUtils.getSourceDir(mPackageName, mActivity));\n }\n }\n if (mDetectedPackageName != null || mPackageName != null) {\n String apkNameString;\n if (mPackageName != null) {\n apkNameString = mPackageName;\n } else {\n apkNameString = mDetectedPackageName;\n }\n if (Common.getAPKList().size() > 1) {\n if (mInstall) {\n mParent = new File(mActivity.getExternalCacheDir(), \"aee-signed\");\n } else {\n mParent = new File(APKData.getExportAPKsPath(mActivity), apkNameString + \"_aee-signed\");\n }\n if (mParent.exists()) {\n sFileUtils.delete(mParent);\n }\n sFileUtils.mkdir(mParent);\n for (String mSplits : Common.getAPKList()) {\n APKData.signApks(new File(mSplits), new File(mParent, new File(mSplits).getName()), mActivity);\n }\n } else {\n if (mInstall) {\n mParent = new File(mActivity.getCacheDir(), \"aee-signed.apk\");\n } else {\n mParent = new File(APKData.getExportAPKsPath(mActivity), apkNameString + \"_aee-signed.apk\");\n }\n if (mParent.exists()) {\n sFileUtils.delete(mParent);\n }\n APKData.signApks(new File(Common.getAPKList().get(0)), mParent, mActivity);\n }\n }\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPostExecute() {\n try {\n mProgressDialog.dismiss();\n } catch (IllegalArgumentException ignored) {\n }\n if (mDetectedPackageName == null && mPackageName == null) {\n sCommonUtils.snackBar(mActivity.findViewById(android.R.id.content), mActivity.getString(R.string.installation_status_bad_apks)).show();\n } else {\n if (mPackageName == null) {\n mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n if (mInstall) {\n if (Common.getAPKList().size() > 1) {\n List<String> signedAPKs = new ArrayList<>();\n for (File apkFile : Objects.requireNonNull(mParent.listFiles())) {\n signedAPKs.add(apkFile.getAbsolutePath());\n }\n SplitAPKInstaller.installSplitAPKs(mExit, signedAPKs, null, mActivity);\n } else {\n SplitAPKInstaller.installAPK(mExit, mParent, mActivity);\n }\n } else {\n new MaterialAlertDialogBuilder(mActivity)\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.app_name)\n .setMessage(mActivity.getString(R.string.resigned_apks_path, mParent.getAbsolutePath()))\n .setCancelable(false)\n .setPositiveButton(R.string.cancel, (dialog, id) -> {\n Common.isReloading(true);\n if (mExit) {\n mActivity.finish();\n }\n }\n ).show();\n }\n }\n }\n if (!Common.isFinished()) {\n Common.setFinishStatus(true);\n }\n }\n\n}" } ]
import android.app.Activity; import com.threethan.questpatcher.R; import com.threethan.questpatcher.utils.tasks.ExportApp; import com.threethan.questpatcher.utils.tasks.ResignAPKs; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.Dialog.sSingleItemDialog;
1,915
package com.threethan.questpatcher.utils.dialogs; /* * Created by APK Explorer & Editor <[email protected]> on January 30, 2023 */ public class ExportOptionsDialog extends sSingleItemDialog { private final Activity mActivity; private final boolean mExit; private final String mPackageName; public ExportOptionsDialog(String packageName, boolean exit, Activity activity) { super(0, null, new String[] { activity.getString(R.string.export_storage), activity.getString(R.string.export_resign) }, activity); mPackageName = packageName; mExit = exit; mActivity = activity; } @Override public void onItemSelected(int position) { if (position == 0) {
package com.threethan.questpatcher.utils.dialogs; /* * Created by APK Explorer & Editor <[email protected]> on January 30, 2023 */ public class ExportOptionsDialog extends sSingleItemDialog { private final Activity mActivity; private final boolean mExit; private final String mPackageName; public ExportOptionsDialog(String packageName, boolean exit, Activity activity) { super(0, null, new String[] { activity.getString(R.string.export_storage), activity.getString(R.string.export_resign) }, activity); mPackageName = packageName; mExit = exit; mActivity = activity; } @Override public void onItemSelected(int position) { if (position == 0) {
new ExportApp(mPackageName, mActivity).execute();
0
2023-11-18 15:13:30+00:00
4k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookStep.java
[ { "identifier": "Severity", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Severity.java", "snippet": "public enum Severity {\n None(\"None\"),\n Unknown(\"Unknown\"),\n Negligible(\"Negligible\"),\n Low(\"Low\"),\n Medium(\"Medium\"),\n High(\"High\"),\n Critical(\"Critical\");\n\n @JsonValue\n private final String severity;\n\n Severity(String severity) {\n this.severity = severity;\n }\n\n public String getSeverity() {\n return severity;\n }\n}" }, { "identifier": "HarborPluginGlobalConfiguration", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborPluginGlobalConfiguration.java", "snippet": "@Extension\npublic class HarborPluginGlobalConfiguration extends GlobalConfiguration implements Serializable {\n private static final Logger logger = Logger.getLogger(HarborPluginGlobalConfiguration.class.getName());\n\n private List<HarborServer> servers;\n\n public HarborPluginGlobalConfiguration() {\n load();\n }\n\n public static HarborPluginGlobalConfiguration get() {\n return GlobalConfiguration.all().get(HarborPluginGlobalConfiguration.class);\n }\n\n public static HarborServer getHarborServerByName(String name) {\n return get().getServers().stream()\n .filter(harborServer -> StringUtils.equals(name, harborServer.getName()))\n .findFirst()\n .orElseThrow(() -> new HarborException(\"The Harbor Server Name Is Invalid\"));\n }\n\n public List<HarborServer> getServers() {\n return servers;\n }\n\n public void setServers(List<HarborServer> servers) {\n this.servers = servers;\n }\n\n @Override\n public boolean configure(StaplerRequest req, JSONObject json) throws FormException {\n req.bindJSON(this, json);\n save();\n return true;\n }\n}" }, { "identifier": "HarborServer", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborServer.java", "snippet": "public class HarborServer extends AbstractDescribableImpl<HarborServer> implements Serializable {\n private static final long serialVersionUID = 1L;\n private static final Logger logger = Logger.getLogger(HarborServer.class.getName());\n private String name;\n private String baseUrl;\n private String webhookSecretId;\n private boolean skipTlsVerify = false;\n private boolean debugLogging = false;\n\n @DataBoundConstructor\n public HarborServer(\n String name, String baseUrl, String webhookSecretId, boolean skipTlsVerify, boolean debugLogging) {\n this.name = name;\n this.baseUrl = baseUrl;\n this.webhookSecretId = webhookSecretId;\n this.skipTlsVerify = skipTlsVerify;\n this.debugLogging = debugLogging;\n }\n\n public String getName() {\n return name;\n }\n\n @DataBoundSetter\n public void setName(String name) {\n this.name = name;\n }\n\n public String getBaseUrl() {\n return baseUrl;\n }\n\n @DataBoundSetter\n public void setBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n }\n\n public String getWebhookSecretId() {\n return webhookSecretId;\n }\n\n @DataBoundSetter\n public void setWebhookSecretId(String webhookSecretId) {\n this.webhookSecretId = webhookSecretId;\n }\n\n public boolean isSkipTlsVerify() {\n return skipTlsVerify;\n }\n\n @DataBoundSetter\n public void setSkipTlsVerify(boolean skipTlsVerify) {\n this.skipTlsVerify = skipTlsVerify;\n }\n\n public boolean isDebugLogging() {\n return debugLogging;\n }\n\n @DataBoundSetter\n public void setDebugLogging(boolean debugLogging) {\n this.debugLogging = debugLogging;\n }\n\n @Extension\n public static class DescriptorImpl extends Descriptor<HarborServer> {\n /**\n * Checks that the supplied URL is valid.\n *\n * @param value the URL to check.\n * @return the validation results.\n */\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public static FormValidation doCheckBaseUrl(@QueryParameter String value) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return FormValidation.error(\"You do not have sufficient permissions.\");\n }\n\n try {\n new URL(value);\n } catch (MalformedURLException e) {\n return FormValidation.error(\"Invalid URL: \" + e.getMessage());\n }\n return FormValidation.ok();\n }\n\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return new StandardListBoxModel().includeCurrentValue(webhookSecretId);\n }\n\n return new StandardListBoxModel()\n .includeEmptyValue()\n .includeMatchingAs(\n ACL.SYSTEM,\n Jenkins.get(),\n StringCredentials.class,\n Collections.emptyList(),\n CredentialsMatchers.always());\n }\n\n @Override\n public String getDisplayName() {\n return \"Harbor Server\";\n }\n }\n}" } ]
import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials; import com.google.common.collect.ImmutableSet; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Item; import hudson.model.Run; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.util.ListBoxModel; import io.jenkins.plugins.harbor.client.models.Severity; import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration; import io.jenkins.plugins.harbor.configuration.HarborServer; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Logger; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
2,048
package io.jenkins.plugins.harbor.steps; public class WaitForHarborWebhookStep extends Step implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName()); private String server; private String credentialsId; private String fullImageName; private Severity severity; private boolean abortPipeline = true; @DataBoundConstructor public WaitForHarborWebhookStep( String server, String credentialsId, String fullImageName, Severity severity, boolean abortPipeline) { this.server = server; this.credentialsId = credentialsId; this.fullImageName = fullImageName; this.severity = severity; this.abortPipeline = abortPipeline; } public String getServer() { return server; } @DataBoundSetter public void setServer(String server) { this.server = server; } public String getCredentialsId() { return credentialsId; } @DataBoundSetter public void setCredentialsId(String credentialsId) { this.credentialsId = credentialsId; } public Severity getSeverity() { return severity; } @DataBoundSetter public void setSeverity(Severity severity) { this.severity = severity; } public String getFullImageName() { return fullImageName; } @DataBoundSetter public void setFullImageName(String fullImageName) { this.fullImageName = fullImageName; } public boolean isAbortPipeline() { return abortPipeline; } @DataBoundSetter public void setAbortPipeline(boolean abortPipeline) { this.abortPipeline = abortPipeline; } @Override public StepExecution start(StepContext context) throws Exception { return new WaitForHarborWebhookExecution(context, this); } @Extension public static class DescriptorImpl extends StepDescriptor { @Override public String getFunctionName() { return "waitForHarborWebHook"; } @Override public Set<Class<?>> getRequiredContext() { return ImmutableSet.of(FilePath.class, TaskListener.class, Run.class, Launcher.class, EnvVars.class); } @SuppressWarnings({"unused", "lgtm[jenkins/csrf]", "lgtm[jenkins/no-permission-check]"}) public ListBoxModel doFillServerItems() { StandardListBoxModel result = new StandardListBoxModel();
package io.jenkins.plugins.harbor.steps; public class WaitForHarborWebhookStep extends Step implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName()); private String server; private String credentialsId; private String fullImageName; private Severity severity; private boolean abortPipeline = true; @DataBoundConstructor public WaitForHarborWebhookStep( String server, String credentialsId, String fullImageName, Severity severity, boolean abortPipeline) { this.server = server; this.credentialsId = credentialsId; this.fullImageName = fullImageName; this.severity = severity; this.abortPipeline = abortPipeline; } public String getServer() { return server; } @DataBoundSetter public void setServer(String server) { this.server = server; } public String getCredentialsId() { return credentialsId; } @DataBoundSetter public void setCredentialsId(String credentialsId) { this.credentialsId = credentialsId; } public Severity getSeverity() { return severity; } @DataBoundSetter public void setSeverity(Severity severity) { this.severity = severity; } public String getFullImageName() { return fullImageName; } @DataBoundSetter public void setFullImageName(String fullImageName) { this.fullImageName = fullImageName; } public boolean isAbortPipeline() { return abortPipeline; } @DataBoundSetter public void setAbortPipeline(boolean abortPipeline) { this.abortPipeline = abortPipeline; } @Override public StepExecution start(StepContext context) throws Exception { return new WaitForHarborWebhookExecution(context, this); } @Extension public static class DescriptorImpl extends StepDescriptor { @Override public String getFunctionName() { return "waitForHarborWebHook"; } @Override public Set<Class<?>> getRequiredContext() { return ImmutableSet.of(FilePath.class, TaskListener.class, Run.class, Launcher.class, EnvVars.class); } @SuppressWarnings({"unused", "lgtm[jenkins/csrf]", "lgtm[jenkins/no-permission-check]"}) public ListBoxModel doFillServerItems() { StandardListBoxModel result = new StandardListBoxModel();
for (HarborServer harborServer :
2
2023-11-11 14:54:53+00:00
4k
someElseIsHere/potato-golem
common/src/main/java/org/theplaceholder/potatogolem/mixin/ItemEntityMixin.java
[ { "identifier": "PotatoGolemEntity", "path": "common/src/main/java/org/theplaceholder/potatogolem/PotatoGolemEntity.java", "snippet": "public class PotatoGolemEntity extends IronGolem implements OwnableEntity {\n protected static final EntityDataAccessor<Optional<UUID>> DATA_OWNERUUID_ID = SynchedEntityData.defineId(PotatoGolemEntity.class, EntityDataSerializers.OPTIONAL_UUID);;\n\n public PotatoGolemEntity(EntityType<PotatoGolemEntity> entityType, Level level) {\n super(entityType, level);\n }\n\n @Override\n protected void playStepSound(BlockPos blockPos, BlockState blockState) {\n this.playSound(PotatoGolemSounds.STEP.get(), 1.0F, 1.0F);\n }\n\n @Override\n public boolean hurt(DamageSource damageSource, float f) {\n Crackiness crackiness = this.getCrackiness();\n boolean bl = super.hurt(damageSource, f);\n if (bl && this.getCrackiness() != crackiness) {\n this.playSound(PotatoGolemSounds.DAMAGE.get(), 1.0F, 1.0F);\n }\n return bl;\n }\n\n @Override\n protected void defineSynchedData() {\n super.defineSynchedData();\n this.entityData.define(DATA_OWNERUUID_ID, Optional.empty());\n }\n\n @Override\n public boolean doHurtTarget(Entity entity) {\n this.attackAnimationTick = 17;\n this.level().broadcastEntityEvent(this, (byte)4);\n float f = this.getAttackDamage();\n float g = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f;\n boolean bl = entity.hurt(this.damageSources().mobAttack(this), g);\n if (bl) {\n double d;\n if (entity instanceof LivingEntity livingEntity) {\n d = livingEntity.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE);\n } else {\n d = 0.0;\n }\n double e = Math.max(0.0, 1.0 - d);\n entity.setDeltaMovement(entity.getDeltaMovement().add(0.0, 0.4000000059604645 * e, 0.0));\n this.doEnchantDamageEffects(this, entity);\n }\n\n this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);\n return bl;\n }\n\n @Override\n protected @NotNull InteractionResult mobInteract(Player player, InteractionHand interactionHand) {\n ItemStack itemStack = player.getItemInHand(interactionHand);\n\n if (itemStack.is(Items.DIRT) && !isTamed()) {\n setOwnerUUID(player.getUUID());\n if(!player.isCreative())\n itemStack.shrink(1);\n spawnTamingParticles();\n }\n\n if (!itemStack.is(Items.POTATO)) {\n return InteractionResult.PASS;\n } else {\n float f = this.getHealth();\n this.heal(25.0F);\n if (this.getHealth() == f) {\n return InteractionResult.PASS;\n } else {\n float g = 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F;\n this.playSound(PotatoGolemSounds.REPAIR.get(), 1.0F, g);\n if (!player.getAbilities().instabuild) {\n itemStack.shrink(1);\n }\n\n return InteractionResult.sidedSuccess(this.level().isClientSide);\n }\n }\n }\n\n @Override\n public void handleEntityEvent(byte b) {\n if (b == 4) {\n this.attackAnimationTick = 17;\n this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);\n } else {\n super.handleEntityEvent(b);\n }\n }\n\n @Override\n protected void registerGoals() {\n this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0, true));\n this.goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.9, 32.0F));\n this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F));\n this.goalSelector.addGoal(8, new RandomLookAroundGoal(this));\n this.targetSelector.addGoal(2, new HurtByTargetGoal(this));\n this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, false, false, (livingEntity) -> livingEntity instanceof Enemy && !(livingEntity instanceof Creeper)));\n this.targetSelector.addGoal(5, new PotatoOwnerHurtByTargetGoal(this));\n this.targetSelector.addGoal(6, new PotatoOwnerHurtTargetGoal(this));\n }\n\n @Override\n protected SoundEvent getDeathSound() {\n return PotatoGolemSounds.DEATH.get();\n }\n\n @Override\n protected SoundEvent getHurtSound(DamageSource damageSource) {\n return PotatoGolemSounds.HURT.get();\n }\n\n @Nullable\n @Override\n public UUID getOwnerUUID() {\n return this.entityData.get(DATA_OWNERUUID_ID).orElse(null);\n }\n\n public void setOwnerUUID(@Nullable UUID uUID) {\n this.entityData.set(DATA_OWNERUUID_ID, Optional.ofNullable(uUID));\n }\n\n @Override\n public void addAdditionalSaveData(CompoundTag compoundTag) {\n super.addAdditionalSaveData(compoundTag);\n if (this.getOwnerUUID() != null) {\n compoundTag.putUUID(\"Owner\", this.getOwnerUUID());\n }\n }\n\n @Override\n public void readAdditionalSaveData(CompoundTag compoundTag) {\n super.readAdditionalSaveData(compoundTag);\n UUID uUID;\n if (compoundTag.hasUUID(\"Owner\")) {\n uUID = compoundTag.getUUID(\"Owner\");\n } else {\n String string = compoundTag.getString(\"Owner\");\n uUID = OldUsersConverter.convertMobOwnerIfNecessary(this.getServer(), string);\n }\n\n if (uUID != null) {\n try {\n this.setOwnerUUID(uUID);\n } catch (Throwable ignored) {}\n }\n }\n\n public boolean isOwnedBy(LivingEntity livingEntity) {\n return livingEntity == this.getOwner();\n }\n\n @Override\n public boolean canAttack(LivingEntity livingEntity) {\n return !this.isOwnedBy(livingEntity) && super.canAttack(livingEntity);\n }\n\n protected void spawnTamingParticles() {\n ParticleOptions particleOptions = ParticleTypes.HEART;\n\n for(int i = 0; i < 7; ++i) {\n double d = this.random.nextGaussian() * 0.02;\n double e = this.random.nextGaussian() * 0.02;\n double f = this.random.nextGaussian() * 0.02;\n this.level().addParticle(particleOptions, this.getRandomX(1.0), this.getRandomY() + 0.5, this.getRandomZ(1.0), d, e, f);\n }\n\n }\n\n public boolean isTamed() {\n return this.getOwnerUUID() != null;\n }\n}" }, { "identifier": "PotatoGolemMod", "path": "common/src/main/java/org/theplaceholder/potatogolem/PotatoGolemMod.java", "snippet": "public class PotatoGolemMod {\n\tpublic static final String MOD_ID = \"potato_golem\";\n\tpublic static final ResourceLocation LOCATION = new ResourceLocation(MOD_ID, MOD_ID);\n\tpublic static final Supplier<RegistrarManager> MANAGER = Suppliers.memoize(() -> RegistrarManager.get(MOD_ID));\n\t\n\tpublic static final Registrar<EntityType<?>> ENTITIES = MANAGER.get().get(Registries.ENTITY_TYPE);\n\tpublic static final RegistrySupplier<EntityType<PotatoGolemEntity>> POTATO_GOLEM = ENTITIES.register(LOCATION, () -> EntityType.Builder.of(PotatoGolemEntity::new, MobCategory.MISC).sized(2.5F, 5.75F).clientTrackingRange(10).build(\"potato_golem\"));\n\n\tpublic static void init() {\n\t\tEntityAttributeRegistry.register(POTATO_GOLEM, PotatoGolemEntity::createAttributes);\n\t\tPotatoGolemSounds.init();\n\t}\n}" } ]
import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.TraceableEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.theplaceholder.potatogolem.PotatoGolemEntity; import org.theplaceholder.potatogolem.PotatoGolemMod;
2,318
package org.theplaceholder.potatogolem.mixin; @Mixin(ItemEntity.class) public abstract class ItemEntityMixin extends Entity implements TraceableEntity { @Shadow public abstract ItemStack getItem(); public ItemEntityMixin(EntityType<?> entityType, Level level) { super(entityType, level); } @Inject(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/item/ItemEntity;discard()V")) public void onHurt(DamageSource damageSource, float f, CallbackInfoReturnable<Boolean> cir){ if (damageSource != this.damageSources().lightningBolt() || !this.getItem().is(Items.POTATO)) return;
package org.theplaceholder.potatogolem.mixin; @Mixin(ItemEntity.class) public abstract class ItemEntityMixin extends Entity implements TraceableEntity { @Shadow public abstract ItemStack getItem(); public ItemEntityMixin(EntityType<?> entityType, Level level) { super(entityType, level); } @Inject(method = "hurt", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/item/ItemEntity;discard()V")) public void onHurt(DamageSource damageSource, float f, CallbackInfoReturnable<Boolean> cir){ if (damageSource != this.damageSources().lightningBolt() || !this.getItem().is(Items.POTATO)) return;
PotatoGolemEntity potatoGolemEntity = new PotatoGolemEntity(PotatoGolemMod.POTATO_GOLEM.get(), this.level());
1
2023-11-12 10:44:12+00:00
4k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/controller/CustomerController.java
[ { "identifier": "Customer", "path": "src/main/java/com/example/servingwebcontent/entity/Customer.java", "snippet": "public class Customer {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.550902+09:00\", comments = \"Source field: public.customer.id\")\n\tprivate String id;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552784+09:00\", comments = \"Source field: public.customer.username\")\n\tprivate String username;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552893+09:00\", comments = \"Source field: public.customer.email\")\n\tprivate String email;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552994+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tprivate String phoneNumber;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553138+09:00\", comments = \"Source field: public.customer.post_code\")\n\tprivate String postCode;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.55244+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552729+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552823+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552861+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552927+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552962+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553027+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic String getPhoneNumber() {\n\t\treturn phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553091+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic void setPhoneNumber(String phoneNumber) {\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553186+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic String getPostCode() {\n\t\treturn postCode;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553235+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic void setPostCode(String postCode) {\n\t\tthis.postCode = postCode;\n\t}\n}" }, { "identifier": "CustomerForm", "path": "src/main/java/com/example/servingwebcontent/form/CustomerForm.java", "snippet": "@Data\npublic class CustomerForm {\n \n @NotBlank(message = \"ID should not be blank\")\n private String id;\n @NotBlank(message = \"Name should not be blank\")\n private String username;\n private String postCode;\n @Email(message = \"Email should be valid\")\n @NotBlank(message = \"Email should not be blank\")\n private String email;\n private String phoneNumber;\n \n public CustomerForm() {\n }\n \n public CustomerForm(String id,String name, String postcode, String email, String phone) {\n this.id = id;\n this.username = name;\n this.postCode = postcode;\n this.email = email;\n this.phoneNumber = phone;\n }\n}" }, { "identifier": "CustomerMapper", "path": "src/main/java/com/example/servingwebcontent/repository/CustomerMapper.java", "snippet": "@Mapper\npublic interface CustomerMapper\n\t\textends CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<Customer>, CommonUpdateMapper {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.561917+09:00\", comments = \"Source Table: public.customer\")\n\tBasicColumn[] selectList = BasicColumn.columnList(id, username, email, phoneNumber, postCode);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556923+09:00\", comments = \"Source Table: public.customer\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@Results(id = \"CustomerResult\", value = {\n\t\t\t@Result(column = \"id\", property = \"id\", jdbcType = JdbcType.VARCHAR, id = true),\n\t\t\t@Result(column = \"username\", property = \"username\", jdbcType = JdbcType.VARCHAR),\n\t\t\t@Result(column = \"email\", property = \"email\", jdbcType = JdbcType.VARCHAR),\n\t\t\t@Result(column = \"phone_number\", property = \"phoneNumber\", jdbcType = JdbcType.VARCHAR),\n\t\t\t@Result(column = \"post_code\", property = \"postCode\", jdbcType = JdbcType.VARCHAR) })\n\tList<Customer> selectMany(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.557921+09:00\", comments = \"Source Table: public.customer\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@ResultMap(\"CustomerResult\")\n\tOptional<Customer> selectOne(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.55819+09:00\", comments = \"Source Table: public.customer\")\n\tdefault long count(CountDSLCompleter completer) {\n\t\treturn MyBatis3Utils.countFrom(this::count, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.558451+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int delete(DeleteDSLCompleter completer) {\n\t\treturn MyBatis3Utils.deleteFrom(this::delete, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.558923+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int deleteByPrimaryKey(String id_) {\n\t\treturn delete(c -> c.where(id, isEqualTo(id_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.559228+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int insert(Customer row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, customer,\n\t\t\t\tc -> c.map(id).toProperty(\"id\").map(username).toProperty(\"username\").map(email).toProperty(\"email\")\n\t\t\t\t\t\t.map(phoneNumber).toProperty(\"phoneNumber\").map(postCode).toProperty(\"postCode\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.560406+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int insertMultiple(Collection<Customer> records) {\n\t\treturn MyBatis3Utils.insertMultiple(this::insertMultiple, records, customer,\n\t\t\t\tc -> c.map(id).toProperty(\"id\").map(username).toProperty(\"username\").map(email).toProperty(\"email\")\n\t\t\t\t\t\t.map(phoneNumber).toProperty(\"phoneNumber\").map(postCode).toProperty(\"postCode\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.560877+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int insertSelective(Customer row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, customer,\n\t\t\t\tc -> c.map(id).toPropertyWhenPresent(\"id\", row::getId).map(username)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"username\", row::getUsername).map(email)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"email\", row::getEmail).map(phoneNumber)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"phoneNumber\", row::getPhoneNumber).map(postCode)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"postCode\", row::getPostCode));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.562416+09:00\", comments = \"Source Table: public.customer\")\n\tdefault Optional<Customer> selectOne(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectOne(this::selectOne, selectList, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.562686+09:00\", comments = \"Source Table: public.customer\")\n\tdefault List<Customer> select(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectList(this::selectMany, selectList, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.562919+09:00\", comments = \"Source Table: public.customer\")\n\tdefault List<Customer> selectDistinct(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectDistinct(this::selectMany, selectList, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.563139+09:00\", comments = \"Source Table: public.customer\")\n\tdefault Optional<Customer> selectByPrimaryKey(String id_) {\n\t\treturn selectOne(c -> c.where(id, isEqualTo(id_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.563346+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int update(UpdateDSLCompleter completer) {\n\t\treturn MyBatis3Utils.update(this::update, customer, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.563588+09:00\", comments = \"Source Table: public.customer\")\n\tstatic UpdateDSL<UpdateModel> updateAllColumns(Customer row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(id).equalTo(row::getId).set(username).equalTo(row::getUsername).set(email).equalTo(row::getEmail)\n\t\t\t\t.set(phoneNumber).equalTo(row::getPhoneNumber).set(postCode).equalTo(row::getPostCode);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.563879+09:00\", comments = \"Source Table: public.customer\")\n\tstatic UpdateDSL<UpdateModel> updateSelectiveColumns(Customer row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(id).equalToWhenPresent(row::getId).set(username).equalToWhenPresent(row::getUsername).set(email)\n\t\t\t\t.equalToWhenPresent(row::getEmail).set(phoneNumber).equalToWhenPresent(row::getPhoneNumber)\n\t\t\t\t.set(postCode).equalToWhenPresent(row::getPostCode);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.564305+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int updateByPrimaryKey(Customer row) {\n\t\treturn update(c -> c.set(username).equalTo(row::getUsername).set(email).equalTo(row::getEmail).set(phoneNumber)\n\t\t\t\t.equalTo(row::getPhoneNumber).set(postCode).equalTo(row::getPostCode).where(id, isEqualTo(row::getId)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.564916+09:00\", comments = \"Source Table: public.customer\")\n\tdefault int updateByPrimaryKeySelective(Customer row) {\n\t\treturn update(c -> c.set(username).equalToWhenPresent(row::getUsername).set(email)\n\t\t\t\t.equalToWhenPresent(row::getEmail).set(phoneNumber).equalToWhenPresent(row::getPhoneNumber)\n\t\t\t\t.set(postCode).equalToWhenPresent(row::getPostCode).where(id, isEqualTo(row::getId)));\n\t}\n}" } ]
import java.util.List; import java.util.Optional; import org.mybatis.dynamic.sql.select.SelectDSLCompleter; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; 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.ResponseBody; import com.example.servingwebcontent.entity.Customer; import com.example.servingwebcontent.form.CustomerForm; import com.example.servingwebcontent.repository.CustomerMapper; import com.google.gson.Gson;
3,565
package com.example.servingwebcontent.controller; /** * This class represents a controller for managing customers. It handles HTTP requests and responses related to customers. * The class includes methods for displaying a list of customers, displaying a table of customers, and returning a JSON formatted string representation of the list of customers. */ @Controller public class CustomerController { @Autowired
package com.example.servingwebcontent.controller; /** * This class represents a controller for managing customers. It handles HTTP requests and responses related to customers. * The class includes methods for displaying a list of customers, displaying a table of customers, and returning a JSON formatted string representation of the list of customers. */ @Controller public class CustomerController { @Autowired
private CustomerMapper mapper;
2
2023-11-12 08:22:27+00:00
4k
thewaterfall/fluent-request
src/main/java/com/thewaterfall/request/FluentRequest.java
[ { "identifier": "FluentHttpMethod", "path": "src/main/java/com/thewaterfall/request/misc/FluentHttpMethod.java", "snippet": "public enum FluentHttpMethod {\n GET,\n HEAD,\n POST,\n PUT,\n PATCH,\n DELETE,\n OPTIONS,\n TRACE\n}" }, { "identifier": "FluentIOException", "path": "src/main/java/com/thewaterfall/request/misc/FluentIOException.java", "snippet": "public class FluentIOException extends RuntimeException {\n /**\n * Constructs a FluentIOException with no specified detail message.\n */\n public FluentIOException() {\n }\n\n /**\n * Constructs a FluentIOException with the specified detail message.\n *\n * @param message The detail message.\n */\n public FluentIOException(String message) {\n super(message);\n }\n\n /**\n * Constructs a FluentIOException with the specified detail message and cause.\n *\n * @param message The detail message.\n * @param cause The cause of the exception.\n */\n public FluentIOException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a FluentIOException with the specified cause.\n *\n * @param cause The cause of the exception.\n */\n public FluentIOException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "FluentMappingException", "path": "src/main/java/com/thewaterfall/request/misc/FluentMappingException.java", "snippet": "public class FluentMappingException extends RuntimeException {\n /**\n * Constructs a FluentMappingException with no specified detail message.\n */\n public FluentMappingException() {\n }\n\n /**\n * Constructs a FluentMappingException with the specified detail message.\n *\n * @param message The detail message.\n */\n public FluentMappingException(String message) {\n super(message);\n }\n\n /**\n * Constructs a FluentMappingException with the specified detail message and cause.\n *\n * @param message The detail message.\n * @param cause The cause of the exception.\n */\n public FluentMappingException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a FluentMappingException with the specified cause.\n *\n * @param cause The cause of the exception.\n */\n public FluentMappingException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "FluentResponse", "path": "src/main/java/com/thewaterfall/request/misc/FluentResponse.java", "snippet": "public class FluentResponse<T> {\n private final T body;\n private final Response response;\n\n /**\n * Constructs a FluentResponse with the specified body and response.\n *\n * @param body The typed body of the response.\n * @param response The raw HTTP response.\n */\n public FluentResponse(T body, Response response) {\n this.body = body;\n this.response = response;\n }\n\n /**\n * Gets the typed body of the response.\n *\n * @return The typed body of the response.\n */\n public T getBody() {\n return body;\n }\n\n /**\n * Gets the raw OkHttp response.\n *\n * @return The raw HTTP response.\n */\n public Response getResponse() {\n return response;\n }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.thewaterfall.request.misc.FluentHttpMethod; import com.thewaterfall.request.misc.FluentIOException; import com.thewaterfall.request.misc.FluentMappingException; import com.thewaterfall.request.misc.FluentResponse; import okhttp3.*; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit;
2,928
package com.thewaterfall.request; /** * <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface * for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods, * request body types, headers, and authentication methods.</p> * * <p>It uses a predefined OkHttpClient and if it needs to be customized and configured, * use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper, * use {@link FluentRequest#overrideMapper(ObjectMapper)}</p> * * <p>Example usage:</p> * <pre>{@code FluentRequest.request("https://api.example.com", Example.class) * .bearer(EXAMPLE_TOKEN) * .body(body) * .post();}</pre> */ public class FluentRequest { private static OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS) .build(); private static ObjectMapper mapper = new ObjectMapper(); /** * Overrides the default OkHttpClient used for making HTTP requests. * * @param newClient The OkHttpClient to use for HTTP requests. */ private static void overrideClient(OkHttpClient newClient) { client = newClient; } /** * Overrides the default ObjectMapper used for JSON serialization and deserialization. * * @param newMapper The ObjectMapper to use for JSON processing. */ private static void overrideMapper(ObjectMapper newMapper) { mapper = newMapper; } /** * Initiates a new HTTP request builder with the specified URL and response type. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object). * * @param url The URL for the HTTP request. * @param client The OkHttpClient to use for this specific request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url, OkHttpClient client) { return new Builder<>(url, Object.class, client); } /** * Initiates a new HTTP request builder with the specified URL and response type, * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object), * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url) { return new Builder<>(url, Object.class, client); } /** * The Builder class is an inner class of FluentRequest and represents the actual builder * for constructing FluentRequest instances with specific configurations. * * @param <T> The type of the expected response. */ public static class Builder<T> { private OkHttpClient client; private final String url; private final Class<T> responseType; private final Map<String, String> headers; private final Map<String, Object> urlVariables; private final Map<String, Object> queryParameters; private RequestBody body; public Builder(String url, Class<T> responseType) { this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Constructs a new Builder instance with the specified URL, response type, and OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. */ public Builder(String url, Class<T> responseType, OkHttpClient client) { this.client = client; this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Sets the request body for the HTTP request. * * @param body The request body object. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body object to JSON. */ public Builder<T> body(Object body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using key-value pairs. * * @param body The map representing the request body. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body map to JSON. */ public Builder<T> body(Map<String, String> body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using a custom RequestBody. Use * {@link FluentRequest.Builder#multipart()} to build multipart body and * {@link FluentRequest.Builder#form()} to build form body. * * @param body The custom RequestBody. * @return The Builder instance for method chaining. * @see FluentRequest.Builder#multipart() * @see FluentRequest.Builder#form() */ public Builder<T> body(RequestBody body) { this.body = body; return this; } /** * Adds a URL variable to the request. * * @param name The name of the URL variable. * @param value The value of the URL variable. * @return The Builder instance for method chaining. */ public Builder<T> variable(String name, Object value) { if (Objects.nonNull(value)) { this.urlVariables.put(name, String.valueOf(value)); } return this; } /** * Adds multiple URL variables to the request. * * @param variables The map of URL variables. * @return The Builder instance for method chaining. */ public Builder<T> variables(Map<String, Object> variables) { this.urlVariables.putAll(variables); return this; } /** * Adds a query parameter to the request. * * @param name The name of the query parameter. * @param value The value of the query parameter. * @return The Builder instance for method chaining. */ public Builder<T> parameter(String name, Object value) { if (Objects.nonNull(value)) { this.queryParameters.put(name, Collections.singletonList(String.valueOf(value))); } return this; } /** * Adds multiple query parameters to the request. * * @param parameters The map of query parameters. * @return The Builder instance for method chaining. */ public Builder<T> parameters(Map<String, Object> parameters) { this.queryParameters.putAll(parameters); return this; } /** * Adds a header to the request. * * @param name The name of the header. * @param value The value of the header. * @return The Builder instance for method chaining. */ public Builder<T> header(String name, String value) { headers.put(name, value); return this; } /** * Adds a bearer token to the request for bearer authentication. * * @param token The bearer token. * @return The Builder instance for method chaining. */ public Builder<T> bearer(String token) { this.headers.put("Authorization", "Bearer " + token); return this; } /** * Adds basic authentication to the request. * * @param name The username for basic authentication. * @param password The password for basic authentication. * @return The Builder instance for method chaining. */ public Builder<T> basic(String name, String password) { this.headers.put("Authorization", Credentials.basic(name, password)); return this; } /** * Initiates a multipart form data request. * * @return A FluentMultipartBody instance for configuring multipart form data. * @see FluentMultipartBody */ public FluentMultipartBody<T> multipart() { return new FluentMultipartBody<>(this); } /** * Initiates a form-urlencoded request. * * @return A FluentFormBody instance for configuring form-urlencoded parameters. * @see FluentFormBody */ public FluentFormBody<T> form() { return new FluentFormBody<>(this); } /** * Sends a GET request synchronously and returns the response. * * @return The FluentResponse containing the response body and HTTP response details. */
package com.thewaterfall.request; /** * <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface * for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods, * request body types, headers, and authentication methods.</p> * * <p>It uses a predefined OkHttpClient and if it needs to be customized and configured, * use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper, * use {@link FluentRequest#overrideMapper(ObjectMapper)}</p> * * <p>Example usage:</p> * <pre>{@code FluentRequest.request("https://api.example.com", Example.class) * .bearer(EXAMPLE_TOKEN) * .body(body) * .post();}</pre> */ public class FluentRequest { private static OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS) .build(); private static ObjectMapper mapper = new ObjectMapper(); /** * Overrides the default OkHttpClient used for making HTTP requests. * * @param newClient The OkHttpClient to use for HTTP requests. */ private static void overrideClient(OkHttpClient newClient) { client = newClient; } /** * Overrides the default ObjectMapper used for JSON serialization and deserialization. * * @param newMapper The ObjectMapper to use for JSON processing. */ private static void overrideMapper(ObjectMapper newMapper) { mapper = newMapper; } /** * Initiates a new HTTP request builder with the specified URL and response type. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object). * * @param url The URL for the HTTP request. * @param client The OkHttpClient to use for this specific request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url, OkHttpClient client) { return new Builder<>(url, Object.class, client); } /** * Initiates a new HTTP request builder with the specified URL and response type, * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object), * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url) { return new Builder<>(url, Object.class, client); } /** * The Builder class is an inner class of FluentRequest and represents the actual builder * for constructing FluentRequest instances with specific configurations. * * @param <T> The type of the expected response. */ public static class Builder<T> { private OkHttpClient client; private final String url; private final Class<T> responseType; private final Map<String, String> headers; private final Map<String, Object> urlVariables; private final Map<String, Object> queryParameters; private RequestBody body; public Builder(String url, Class<T> responseType) { this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Constructs a new Builder instance with the specified URL, response type, and OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. */ public Builder(String url, Class<T> responseType, OkHttpClient client) { this.client = client; this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Sets the request body for the HTTP request. * * @param body The request body object. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body object to JSON. */ public Builder<T> body(Object body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using key-value pairs. * * @param body The map representing the request body. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body map to JSON. */ public Builder<T> body(Map<String, String> body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using a custom RequestBody. Use * {@link FluentRequest.Builder#multipart()} to build multipart body and * {@link FluentRequest.Builder#form()} to build form body. * * @param body The custom RequestBody. * @return The Builder instance for method chaining. * @see FluentRequest.Builder#multipart() * @see FluentRequest.Builder#form() */ public Builder<T> body(RequestBody body) { this.body = body; return this; } /** * Adds a URL variable to the request. * * @param name The name of the URL variable. * @param value The value of the URL variable. * @return The Builder instance for method chaining. */ public Builder<T> variable(String name, Object value) { if (Objects.nonNull(value)) { this.urlVariables.put(name, String.valueOf(value)); } return this; } /** * Adds multiple URL variables to the request. * * @param variables The map of URL variables. * @return The Builder instance for method chaining. */ public Builder<T> variables(Map<String, Object> variables) { this.urlVariables.putAll(variables); return this; } /** * Adds a query parameter to the request. * * @param name The name of the query parameter. * @param value The value of the query parameter. * @return The Builder instance for method chaining. */ public Builder<T> parameter(String name, Object value) { if (Objects.nonNull(value)) { this.queryParameters.put(name, Collections.singletonList(String.valueOf(value))); } return this; } /** * Adds multiple query parameters to the request. * * @param parameters The map of query parameters. * @return The Builder instance for method chaining. */ public Builder<T> parameters(Map<String, Object> parameters) { this.queryParameters.putAll(parameters); return this; } /** * Adds a header to the request. * * @param name The name of the header. * @param value The value of the header. * @return The Builder instance for method chaining. */ public Builder<T> header(String name, String value) { headers.put(name, value); return this; } /** * Adds a bearer token to the request for bearer authentication. * * @param token The bearer token. * @return The Builder instance for method chaining. */ public Builder<T> bearer(String token) { this.headers.put("Authorization", "Bearer " + token); return this; } /** * Adds basic authentication to the request. * * @param name The username for basic authentication. * @param password The password for basic authentication. * @return The Builder instance for method chaining. */ public Builder<T> basic(String name, String password) { this.headers.put("Authorization", Credentials.basic(name, password)); return this; } /** * Initiates a multipart form data request. * * @return A FluentMultipartBody instance for configuring multipart form data. * @see FluentMultipartBody */ public FluentMultipartBody<T> multipart() { return new FluentMultipartBody<>(this); } /** * Initiates a form-urlencoded request. * * @return A FluentFormBody instance for configuring form-urlencoded parameters. * @see FluentFormBody */ public FluentFormBody<T> form() { return new FluentFormBody<>(this); } /** * Sends a GET request synchronously and returns the response. * * @return The FluentResponse containing the response body and HTTP response details. */
public FluentResponse<T> get() throws FluentIOException {
1
2023-11-14 12:53:50+00:00
4k
wangxianhui111/xuechengzaixian
xuecheng-plus-learning/xuecheng-plus-learning-service/src/test/java/com/xuecheng/learning/LearningApplicationTest.java
[ { "identifier": "PageResult", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/model/PageResult.java", "snippet": "@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PageResult<T> implements Serializable {\n\n /**\n * 数据列表\n */\n private List<T> items;\n\n /**\n * 总记录数\n */\n private long counts;\n\n /**\n * 当前页码\n */\n private long page;\n\n /**\n * 每页记录数\n */\n private long pageSize;\n\n}" }, { "identifier": "CoursePublish", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublish.java", "snippet": "@Data\n@TableName(\"course_publish\")\npublic class CoursePublish implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键(课程id)\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 发布时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 上架时间\n */\n private LocalDateTime onlineDate;\n\n /**\n * 下架时间\n */\n private LocalDateTime offlineDate;\n\n /**\n * 发布状态<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "ContentServiceClient", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/feignclient/ContentServiceClient.java", "snippet": "@FeignClient(value = \"content-api\", fallbackFactory = ContentServiceClient.ContentServiceClientFallbackFactory.class)\npublic interface ContentServiceClient {\n\n @ResponseBody\n @GetMapping(\"/content/r/coursepublish/{courseId}\")\n CoursePublish getCoursePublish(@PathVariable(\"courseId\") Long courseId);\n\n /**\n * 内容管理服务远程接口降级类\n */\n @Slf4j\n class ContentServiceClientFallbackFactory implements FallbackFactory<ContentServiceClient> {\n\n @Override\n public ContentServiceClient create(Throwable cause) {\n log.error(\"调用内容管理服务接口熔断:{}\", cause.getMessage());\n return null;\n }\n }\n}" }, { "identifier": "MyCourseTableItemDto", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/MyCourseTableItemDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@ToString\npublic class MyCourseTableItemDto extends XcCourseTables {\n\n /**\n * 最近学习时间\n */\n private LocalDateTime learnDate;\n\n /**\n * 学习时长\n */\n private Long learnLength;\n\n /**\n * 章节id\n */\n private Long teachplanId;\n\n /**\n * 章节名称\n */\n private String teachplanName;\n\n}" }, { "identifier": "MyCourseTableParams", "path": "xuecheng-plus-learning/xuecheng-plus-learning-model/src/main/java/com/xuecheng/learning/model/dto/MyCourseTableParams.java", "snippet": "@Data\n@ToString\npublic class MyCourseTableParams {\n\n /**\n * 用户id\n */\n private String userId;\n\n /**\n * 课程类型 [{\"code\":\"700001\",\"desc\":\"免费课程\"},{\"code\":\"700002\",\"desc\":\"收费课程\"}]\n */\n private String courseType;\n\n /**\n * 排序 1按学习时间进行排序 2按加入时间进行排序\n */\n private String sortType;\n\n /**\n * 1 即将过期、2 已经过期\n */\n private String expiresType;\n\n /**\n * 页码\n */\n int page = 1;\n\n /**\n * 开始索引\n */\n int startIndex;\n\n /**\n * 每页大小\n */\n int size = 4;\n\n}" }, { "identifier": "MyCourseTablesService", "path": "xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/MyCourseTablesService.java", "snippet": "public interface MyCourseTablesService {\n\n /**\n * 添加选课\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.dto.XcChooseCourseDto}\n * @author Wuxy\n * @since 2022/10/24 17:33\n */\n XcChooseCourseDto addChooseCourse(String userId, Long courseId);\n\n /**\n * 添加免费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addFreeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加收费课程\n *\n * @param userId 用户 id\n * @param coursePublish 课程发布信息\n * @return 选课信息\n */\n XcChooseCourse addChargeCourse(String userId, CoursePublish coursePublish);\n\n /**\n * 添加到我的课程表\n *\n * @param chooseCourse 选课记录\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/3 11:24\n */\n XcCourseTables addCourseTables(XcChooseCourse chooseCourse);\n\n /**\n * 根据课程和用户查询我的课程表中某一门课程\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link com.xuecheng.learning.model.po.XcCourseTables}\n * @author Wuxy\n * @since 2022/10/2 17:07\n */\n XcCourseTables getXcCourseTables(String userId, Long courseId);\n\n /**\n * 判断学习资格\n * <pre>\n * 学习资格状态 [{\"code\":\"702001\",\"desc\":\"正常学习\"},\n * {\"code\":\"702002\",\"desc\":\"没有选课或选课后没有支付\"},\n * {\"code\":\"702003\",\"desc\":\"已过期需要申请续期或重新支付\"}]\n * </pre>\n *\n * @param userId 用户 id\n * @param courseId 课程 id\n * @return {@link XcCourseTablesDto}\n * @author Wuxy\n * @since 2022/10/3 7:37\n */\n XcCourseTablesDto getLearningStatus(String userId, Long courseId);\n\n boolean saveChooseCourseStatus(String chooseCourseId);\n\n PageResult<MyCourseTableItemDto> myCourseTables(MyCourseTableParams params);\n\n}" } ]
import com.xuecheng.base.model.PageResult; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.learning.feignclient.ContentServiceClient; import com.xuecheng.learning.model.dto.MyCourseTableItemDto; import com.xuecheng.learning.model.dto.MyCourseTableParams; import com.xuecheng.learning.service.MyCourseTablesService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
2,453
package com.xuecheng.learning; /** * @author Mr.M * @version 1.0 * @description TODO * @date 2022/10/2 10:32 */ @SpringBootTest public class LearningApplicationTest { @Autowired ContentServiceClient contentServiceClient; @Autowired
package com.xuecheng.learning; /** * @author Mr.M * @version 1.0 * @description TODO * @date 2022/10/2 10:32 */ @SpringBootTest public class LearningApplicationTest { @Autowired ContentServiceClient contentServiceClient; @Autowired
MyCourseTablesService myCourseTablesService;
5
2023-11-13 11:39:35+00:00
4k
dynatrace-research/ShuffleBench
shuffle-kstreams/src/main/java/com/dynatrace/research/shufflebench/KafkaStreamsShuffle.java
[ { "identifier": "AdvancedStateConsumer", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/AdvancedStateConsumer.java", "snippet": "public class AdvancedStateConsumer implements StatefulConsumer {\n\n private static final long serialVersionUID = 0L;\n\n private static final int DEFAULT_STATE_SIZE = 4 * Long.BYTES;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AdvancedStateConsumer.class);\n\n private final String name;\n\n private final int outputRate;\n\n private final int stateSizeInBytes;\n\n private final boolean initCountRandom;\n\n private final Hasher64 hasher;\n\n public AdvancedStateConsumer(String name, int outputRate) {\n this(name, outputRate, DEFAULT_STATE_SIZE);\n }\n\n public AdvancedStateConsumer(String name, int outputRate, int stateSizeInBytes) {\n this(name, outputRate, stateSizeInBytes, false, 0);\n }\n\n public AdvancedStateConsumer(String name, int outputRate, int stateSizeInBytes, boolean initCountRandom, long seed) {\n this.name = requireNonNull(name);\n this.outputRate = outputRate;\n this.stateSizeInBytes = requireStateSizeGteDefault(stateSizeInBytes);\n this.initCountRandom = initCountRandom;\n this.hasher = Hashing.komihash4_3(seed);\n }\n\n @Override\n public ConsumerResult accept(TimestampedRecord record, State state) {\n if (state == null) {\n state = new State();\n }\n\n byte[] data = state.getData();\n long countInit = -1; // No count init per default\n if (data == null) {\n data = new byte[stateSizeInBytes];\n state.setData(data);\n\n if (initCountRandom) {\n // Take first 32 bytes of record (or less if record is smaller) as seed for random\n final long seedForRandom = hasher.hashBytesToLong(record.getData(), 0, Math.min(record.getData().length, 32));\n final SplittableRandom random = new SplittableRandom(seedForRandom);\n countInit = random.nextInt(outputRate);\n }\n\n }\n\n final ByteBuffer stateBuffer = ByteBuffer.wrap(data);\n final long count = ((countInit == -1) ? stateBuffer.getLong() : countInit) + 1;\n final long sum = stateBuffer.getLong();\n\n stateBuffer.rewind();\n stateBuffer.putLong(count);\n stateBuffer.putLong(sum + ByteBuffer.wrap(record.getData()).getLong()); // Is allowed to overflow\n if (count == 1) {\n stateBuffer.putLong(record.getTimestamp()); // start timestamp\n } else {\n stateBuffer.position(stateBuffer.position() + Long.BYTES); // start timestamp\n }\n stateBuffer.putLong(record.getTimestamp()); // end timestamp\n final int bytesToCopy = Math.min(stateBuffer.remaining(), record.getData().length);\n stateBuffer.put(record.getData(), 0, bytesToCopy); // fill with data from record\n\n LOGGER.debug(\"{}: count = {}\", name, count);\n\n if (count == this.outputRate) {\n final ConsumerEvent event = new ConsumerEvent(Arrays.copyOf(data, data.length));\n Arrays.fill(data, (byte) 0); // reset the state byte buffer to 0s\n return new ConsumerResult(state, event);\n } else {\n return new ConsumerResult(state);\n }\n }\n\n private static int requireStateSizeGteDefault(int stateSize) {\n if (stateSize < DEFAULT_STATE_SIZE) {\n throw new IllegalArgumentException(\"State size must be at least \" + DEFAULT_STATE_SIZE + \".\");\n }\n return stateSize;\n }\n\n}" }, { "identifier": "StatefulConsumer", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/StatefulConsumer.java", "snippet": "@FunctionalInterface\npublic interface StatefulConsumer extends Serializable {\n\n /**\n * @param record a new data record\n * @param state the current state\n * @return the updated state\n */\n ConsumerResult accept(TimestampedRecord record, State state);\n}" }, { "identifier": "MatcherService", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/matcher/MatcherService.java", "snippet": "public interface MatcherService<T extends Record> {\n\n /**\n * Adds a new matching rule\n *\n * @param id an ID for the matching rule\n * @param matchingRule the matching rule\n */\n void addMatchingRule(String id, MatchingRule matchingRule);\n\n /**\n * Removes a matching rule\n *\n * @param id the ID of the matching rule to be deleted\n * @return true if a round was found deleted, false otherwise\n */\n boolean removeMatchingRule(String id);\n\n /**\n * Finds the IDs of all corresponding consumers for this record.\n *\n * @param record The record to be matched\n */\n Collection<Map.Entry<String, T>> match(T record);\n}" }, { "identifier": "SimpleMatcherService", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/matcher/SimpleMatcherService.java", "snippet": "public class SimpleMatcherService<T extends Record> implements MatcherService<T> {\n\n private final Map<String, MatchingRule> matchingRuleEntries = new HashMap<>();\n\n private final RangeBasedMatchingRuleIndex rangeBasedMatchingRuleIndex = new RangeBasedMatchingRuleIndex();\n\n\n @Override\n public void addMatchingRule(String id, MatchingRule matchingRule) {\n if (matchingRule instanceof RangeBasedMatchingRule) {\n matchingRuleEntries.remove(id);\n rangeBasedMatchingRuleIndex.add(id, (RangeBasedMatchingRule) matchingRule);\n } else {\n rangeBasedMatchingRuleIndex.remove(id);\n matchingRuleEntries.put(id, matchingRule);\n }\n }\n\n @Override\n public boolean removeMatchingRule(String id) {\n return (matchingRuleEntries.remove(id) != null) || rangeBasedMatchingRuleIndex.remove(id);\n }\n\n @Override\n public Collection<Map.Entry<String, T>> match(T record) {\n List<Map.Entry<String, T>> result = new ArrayList<>();\n\n rangeBasedMatchingRuleIndex.forEachMatchingConsumer(record, id -> result.add(Map.entry(id, record)));\n\n for (Map.Entry<String, MatchingRule> entry : matchingRuleEntries.entrySet()) {\n if (entry.getValue().test(record)) {\n result.add(Map.entry(entry.getKey(), record));\n }\n }\n\n return result;\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromZipf(\n final int numRules,\n final double totalSelectivity,\n final double s,\n final long seed\n ) {\n double weightsTotal = 0.0;\n final double[] weigths = new double[numRules];\n for (int k = 1; k <= numRules; k++) {\n weigths[k - 1] = 1 / Math.pow(k, s);\n weightsTotal += weigths[k - 1];\n }\n final double finalWeightsTotal = weightsTotal;\n final Stream<Map.Entry<Double, Integer>> frequencyStream = IntStream.range(0, numRules)\n .mapToObj(ruleId -> Map.entry(\n (weigths[ruleId] / finalWeightsTotal) * totalSelectivity, // selectivity\n 1 // frequency\n ));\n return createFromFrequencyStream(frequencyStream, seed);\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromFrequencyMap(Map<Double, Integer> selectivities, final long seed) {\n return createFromFrequencyStream(selectivities.entrySet().stream(), seed);\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromFrequencyStream(Stream<Map.Entry<Double, Integer>> selectivities, final long seed) {\n final SimpleMatcherService<T> matcherService = new SimpleMatcherService<>();\n final AtomicInteger ruleCounter = new AtomicInteger(0);\n selectivities.forEach(entry -> {\n final int numRules = entry.getValue();\n final double selectivity = entry.getKey();\n for (int i = 0; i < numRules; i++) {\n final int ruleNumber = ruleCounter.getAndIncrement();\n matcherService.addMatchingRule(\n \"consumer_\" + ruleNumber,\n new RangeBasedMatchingRule(Hashing.komihash4_3().hashStream().putLong(seed).putInt(ruleNumber).getAsLong(), selectivity));\n }\n });\n return matcherService;\n }\n\n}" } ]
import com.dynatrace.research.shufflebench.consumer.AdvancedStateConsumer; import com.dynatrace.research.shufflebench.consumer.StatefulConsumer; import com.dynatrace.research.shufflebench.matcher.MatcherService; import com.dynatrace.research.shufflebench.matcher.SimpleMatcherService; import com.dynatrace.research.shufflebench.record.*; import io.smallrye.config.SmallRyeConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.*; import org.apache.kafka.streams.kstream.Consumed; import org.apache.kafka.streams.kstream.Produced; import org.apache.kafka.streams.kstream.Repartitioned; import org.eclipse.microprofile.config.ConfigProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*;
2,414
package com.dynatrace.research.shufflebench; public class KafkaStreamsShuffle { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaStreamsShuffle.class); private static final String APPLICATION_ID = "shufflebench-kstreams"; private final KafkaStreams kafkaStreamsApp; public KafkaStreamsShuffle() { final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class); Properties props = new Properties(); props.put( StreamsConfig.APPLICATION_ID_CONFIG, APPLICATION_ID); props.put( StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, config.getValue("kafka.bootstrap.servers", String.class)); props.putAll( config.getOptionalValues("kafkastreams", String.class, String.class).orElse(Map.of())); final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class); final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class); final Optional<Map<Double, Integer>> selectivities = config.getOptionalValues("matcher.selectivities", Double.class, Integer.class); final MatcherService<TimestampedRecord> matcherService; if (selectivities.isPresent()) {
package com.dynatrace.research.shufflebench; public class KafkaStreamsShuffle { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaStreamsShuffle.class); private static final String APPLICATION_ID = "shufflebench-kstreams"; private final KafkaStreams kafkaStreamsApp; public KafkaStreamsShuffle() { final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class); Properties props = new Properties(); props.put( StreamsConfig.APPLICATION_ID_CONFIG, APPLICATION_ID); props.put( StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, config.getValue("kafka.bootstrap.servers", String.class)); props.putAll( config.getOptionalValues("kafkastreams", String.class, String.class).orElse(Map.of())); final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class); final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class); final Optional<Map<Double, Integer>> selectivities = config.getOptionalValues("matcher.selectivities", Double.class, Integer.class); final MatcherService<TimestampedRecord> matcherService; if (selectivities.isPresent()) {
matcherService = SimpleMatcherService.createFromFrequencyMap(selectivities.get(), 0x2e3fac4f58fc98b4L);
3
2023-11-17 08:53:15+00:00
4k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java
[ { "identifier": "Command", "path": "src/main/java/dev/kafein/interactivenpcs/command/Command.java", "snippet": "public interface Command {\n CommandProperties getProperties();\n\n String getName();\n\n List<String> getAliases();\n\n boolean isAlias(@NotNull String alias);\n\n String getDescription();\n\n String getUsage();\n\n @Nullable String getPermission();\n\n List<Command> getSubCommands();\n\n Command findSubCommand(@NotNull String sub);\n\n Command findSubCommand(@NotNull String... subs);\n\n int findSubCommandIndex(@NotNull String... subs);\n\n List<RegisteredTabCompletion> getTabCompletions();\n\n List<RegisteredTabCompletion> getTabCompletions(int index);\n\n void execute(@NotNull CommandSender sender, @NotNull String[] args);\n}" }, { "identifier": "InteractionCommand", "path": "src/main/java/dev/kafein/interactivenpcs/commands/InteractionCommand.java", "snippet": "public final class InteractionCommand extends AbstractCommand {\n private final InteractiveNpcs plugin;\n\n public InteractionCommand(InteractiveNpcs plugin) {\n super(CommandProperties.newBuilder()\n .name(\"interaction\")\n .usage(\"/interaction\")\n .description(\"Command for InteractiveNpcs plugin\")\n .permission(\"interactions.admin\")\n .build(),\n ImmutableList.of(\n new ReloadCommand(plugin)\n ));\n this.plugin = plugin;\n }\n\n @Override\n public void execute(@NotNull CommandSender sender, @NotNull String[] args) {\n\n }\n}" }, { "identifier": "Compatibility", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/Compatibility.java", "snippet": "public interface Compatibility {\n void initialize();\n}" }, { "identifier": "CompatibilityFactory", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityFactory.java", "snippet": "public final class CompatibilityFactory {\n private CompatibilityFactory() {\n }\n\n public static Compatibility createCompatibility(@NotNull CompatibilityType type, @NotNull InteractiveNpcs plugin) {\n switch (type) {\n case VAULT:\n return new VaultCompatibility(plugin);\n case CITIZENS:\n return new CitizensCompatibility(plugin);\n default:\n return null;\n }\n }\n}" }, { "identifier": "CompatibilityType", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityType.java", "snippet": "public enum CompatibilityType {\n VAULT(\"Vault\"),\n PLACEHOLDER_API(\"PlaceholderAPI\"),\n CITIZENS(\"Citizens\");\n\n private final String pluginName;\n\n CompatibilityType(String pluginName) {\n this.pluginName = pluginName;\n }\n\n public String getPluginName() {\n return this.pluginName;\n }\n}" }, { "identifier": "Config", "path": "src/main/java/dev/kafein/interactivenpcs/configuration/Config.java", "snippet": "public final class Config {\n private final ConfigType type;\n private final ConfigurationNode node;\n private final @Nullable Path path;\n\n public Config(ConfigType type, ConfigurationNode node, @Nullable Path path) {\n this.node = node;\n this.type = type;\n this.path = path;\n }\n\n public ConfigType getType() {\n return this.type;\n }\n\n public ConfigurationNode getNode() {\n return this.node;\n }\n\n public @Nullable Path getPath() {\n return this.path;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Config)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n\n Config config = (Config) obj;\n return Objects.equals(this.type, config.type)\n && Objects.equals(this.node, config.node)\n && Objects.equals(this.path, config.path);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.type, this.node, this.path);\n }\n\n @Override\n public String toString() {\n return \"Config{\" +\n \"type=\" + this.type +\n \", node=\" + this.node +\n \", path=\" + this.path +\n '}';\n }\n}" }, { "identifier": "ConfigVariables", "path": "src/main/java/dev/kafein/interactivenpcs/configuration/ConfigVariables.java", "snippet": "public final class ConfigVariables {\n private ConfigVariables() {}\n\n public static final ConfigKey<String> OFFSET_SYMBOL = ConfigKey.of(\"%img_offset_-1%\", \"offset-symbol\");\n\n public static final ConfigKey<List<String>> SPEECH_BUBBLE_LINES_FONTS = ConfigKey.of(ImmutableList.of(), \"speech\", \"bubble-lines\", \"fonts\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_COLOR = ConfigKey.of(\"<black>\", \"speech\", \"bubble-lines\", \"default-color\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_OFFSET = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"default-offset\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_SYMBOL = ConfigKey.of(\"%img_bubble%\", \"speech\", \"bubble-lines\", \"image\", \"default-symbol\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_WIDTH = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"image\", \"default-width\");\n}" }, { "identifier": "ConversationManager", "path": "src/main/java/dev/kafein/interactivenpcs/conversation/ConversationManager.java", "snippet": "public final class ConversationManager {\n private final InteractiveNpcs plugin;\n\n private final Cache<Integer, InteractiveEntity> interactiveEntities;\n private final Cache<UUID, Conversation> conversations;\n\n public ConversationManager(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.interactiveEntities = CacheBuilder.newBuilder()\n .build();\n this.conversations = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n\n }\n\n public void interact(@NotNull UUID interactantUniqueId) {\n Player player = Bukkit.getPlayer(interactantUniqueId);\n if (player != null) {\n this.interact(player);\n }\n }\n\n public void interact(@NotNull Player player) {\n\n }\n\n public void interact(@NotNull Conversation conversation) {\n\n }\n\n public Cache<Integer, InteractiveEntity> getInteractiveEntities() {\n return this.interactiveEntities;\n }\n\n public InteractiveEntity getInteractiveEntity(int name) {\n return this.interactiveEntities.getIfPresent(name);\n }\n\n public void putInteractiveEntity(@NotNull InteractiveEntity interactiveEntity) {\n this.interactiveEntities.put(interactiveEntity.getId(), interactiveEntity);\n }\n\n public void removeInteractiveEntity(int name) {\n this.interactiveEntities.invalidate(name);\n }\n\n public Cache<UUID, Conversation> getConversations() {\n return this.conversations;\n }\n\n public Conversation getConversation(@NotNull UUID uuid) {\n return this.conversations.getIfPresent(uuid);\n }\n\n public void putConversation(@NotNull Conversation conversation) {\n this.conversations.put(conversation.getInteractantUniqueId(), conversation);\n }\n\n public void removeConversation(@NotNull UUID uuid) {\n this.conversations.invalidate(uuid);\n }\n}" }, { "identifier": "CharWidthMap", "path": "src/main/java/dev/kafein/interactivenpcs/conversation/text/font/CharWidthMap.java", "snippet": "public final class CharWidthMap {\n public static final int DEFAULT_WIDTH = 3;\n\n private final InteractiveNpcs plugin;\n private final Cache<Character, Integer> widths;\n\n public CharWidthMap(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.widths = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n CharWidth[] values = CharWidth.values();\n for (CharWidth value : values) {\n this.widths.put(value.getCharacter(), value.getWidth());\n }\n\n //load from configs\n\n this.plugin.getLogger().info(\"CharWidthMap initialized.\");\n }\n\n public Cache<Character, Integer> getWidths() {\n return this.widths;\n }\n\n public int get(Character character) {\n return Optional.ofNullable(this.widths.getIfPresent(character))\n .orElse(DEFAULT_WIDTH);\n }\n\n public void put(Character character, int width) {\n this.widths.put(character, width);\n }\n\n public void remove(Character character) {\n this.widths.invalidate(character);\n }\n}" }, { "identifier": "AbstractBukkitPlugin", "path": "src/main/java/dev/kafein/interactivenpcs/plugin/AbstractBukkitPlugin.java", "snippet": "public abstract class AbstractBukkitPlugin implements BukkitPlugin {\n private final Plugin plugin;\n\n private ConfigManager configManager;\n private CommandManager commandManager;\n private BukkitAudiences bukkitAudiences;\n private ProtocolManager protocolManager;\n\n protected AbstractBukkitPlugin(Plugin plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void load() {\n onLoad();\n }\n\n public abstract void onLoad();\n\n @Override\n public void enable() {\n getLogger().info(\"Loading configs...\");\n this.configManager = new ConfigManager(getDataPath());\n loadConfigs();\n\n onEnable();\n\n this.bukkitAudiences = BukkitAudiences.create(this.plugin);\n\n getLogger().info(\"Starting tasks...\");\n startTasks();\n\n getLogger().info(\"Registering commands...\");\n this.commandManager = new CommandManager(this.plugin);\n registerCommands();\n\n getLogger().info(\"Registering listeners...\");\n registerListeners();\n\n this.protocolManager = ProtocolLibrary.getProtocolManager();\n }\n\n public abstract void onEnable();\n\n @Override\n public void disable() {\n onDisable();\n\n this.bukkitAudiences.close();\n }\n\n public abstract void onDisable();\n\n @Override\n public void registerCommands() {\n getCommands().forEach(command -> getCommandManager().registerCommand(command));\n }\n\n public abstract Set<Command> getCommands();\n\n @Override\n public void registerListeners() {\n ListenerRegistrar.register(this, getListeners());\n }\n\n public abstract Set<Class<?>> getListeners();\n\n @Override\n public Plugin getPlugin() {\n return this.plugin;\n }\n\n @Override\n public Path getDataPath() {\n return this.plugin.getDataFolder().toPath().toAbsolutePath();\n }\n\n @Override\n public Logger getLogger() {\n return this.plugin.getLogger();\n }\n\n @Override\n public ConfigManager getConfigManager() {\n return this.configManager;\n }\n\n @Override\n public CommandManager getCommandManager() {\n return this.commandManager;\n }\n\n @Override\n public BukkitAudiences getBukkitAudiences() {\n return this.bukkitAudiences;\n }\n\n @Override\n public ProtocolManager getProtocolManager() {\n return this.protocolManager;\n }\n}" }, { "identifier": "MovementControlTask", "path": "src/main/java/dev/kafein/interactivenpcs/tasks/MovementControlTask.java", "snippet": "public final class MovementControlTask implements Runnable {\n private final InteractiveNpcs plugin;\n\n public MovementControlTask(InteractiveNpcs plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void run() {\n/* Cache<UUID, Interaction> interactionCache = this.plugin.getInteractionManager().getInteractions();\n interactionCache.asMap().forEach((uuid, interact) -> {\n Player player = Bukkit.getPlayer(uuid);\n if (player == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n NpcProperties npcProperties = interact.getNpcProperties();\n\n InteractiveNpc interactiveNpc = this.plugin.getInteractionManager().getNpcs().getIfPresent(npcProperties.getId());\n if (interactiveNpc == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Focus focus = interactiveNpc.getFocus();\n Location playerLocation = player.getLocation().clone();\n if (playerLocation.distance(interact.getFirstLocation()) > focus.getMaxDistance()) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Location playerLastLocation = interact.getLastLocation();\n interact.setLastLocation(playerLocation);\n if (playerLocation.distance(playerLastLocation) > 0.1\n || playerLastLocation.getYaw() != playerLocation.getYaw()\n || playerLastLocation.getPitch() != playerLocation.getPitch()) {\n return;\n }\n\n if (player.hasMetadata(\"npc-interaction\")) {\n return;\n }\n\n Location npcEyeLocation = npcProperties.getEyeLocation().clone();\n Direction direction = new Direction(playerLocation);\n Direction targetDirection = new Direction(playerLocation, npcEyeLocation);\n\n if (!targetDirection.isNearly(direction)) {\n player.setMetadata(\"npc-interaction\", new FixedMetadataValue(this.plugin.getPlugin(), true));\n\n BukkitRunnable bukkitRunnable = new DirectionAdjuster(this.plugin.getPlugin(), player, targetDirection, focus.getSpeed());\n bukkitRunnable.runTaskTimer(this.plugin.getPlugin(), 0L, 1L);\n }\n });*/\n }\n}" } ]
import com.google.common.collect.ImmutableSet; import dev.kafein.interactivenpcs.command.Command; import dev.kafein.interactivenpcs.commands.InteractionCommand; import dev.kafein.interactivenpcs.compatibility.Compatibility; import dev.kafein.interactivenpcs.compatibility.CompatibilityFactory; import dev.kafein.interactivenpcs.compatibility.CompatibilityType; import dev.kafein.interactivenpcs.configuration.Config; import dev.kafein.interactivenpcs.configuration.ConfigVariables; import dev.kafein.interactivenpcs.conversation.ConversationManager; import dev.kafein.interactivenpcs.conversation.text.font.CharWidthMap; import dev.kafein.interactivenpcs.plugin.AbstractBukkitPlugin; import dev.kafein.interactivenpcs.tasks.MovementControlTask; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; import java.util.Set;
3,527
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override
public Set<Command> getCommands() {
0
2023-11-18 10:12:16+00:00
4k
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-user/user-biz/src/main/java/com/liyz/boot3/service/user/provider/RemoteUserLoginLogServiceImpl.java
[ { "identifier": "PageBO", "path": "dubbo-common/dubbo-common-remote/src/main/java/com/liyz/boot3/common/remote/page/PageBO.java", "snippet": "@Getter\n@Setter\npublic class PageBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 页码\n */\n private Long pageNum = 1L;\n\n /**\n * 每页条数\n */\n private Long pageSize = 10L;\n}" }, { "identifier": "RemotePage", "path": "dubbo-common/dubbo-common-remote/src/main/java/com/liyz/boot3/common/remote/page/RemotePage.java", "snippet": "public class RemotePage<T> implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n public static <T> RemotePage<T> of() {\n return new RemotePage<>(List.of(), 0, 1, 10);\n }\n\n public static <T> RemotePage<T> of(List<T> list, long total, long pageNum, long pageSize) {\n return new RemotePage<>(list, total, pageNum, pageSize);\n }\n\n public RemotePage(List<T> list, long total, long pageNum, long pageSize) {\n this.list = list;\n this.total = total;\n this.pageNum = pageNum;\n this.pageSize = pageSize;\n }\n\n /**\n * 结果集\n */\n private List<T> list;\n\n /**\n * 总记录数\n */\n private long total;\n\n /**\n * 当前页\n */\n private long pageNum;\n\n /**\n * 每页的数量\n */\n private long pageSize;\n\n public List<T> getList() {\n return list;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n public long getTotal() {\n return total;\n }\n\n public void setTotal(long total) {\n this.total = total;\n }\n\n public long getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(long pageNum) {\n this.pageNum = Math.max(1L, pageNum);\n }\n\n public long getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(long pageSize) {\n this.pageSize = Math.max(1L, pageSize);\n }\n\n public long getPages() {\n return this.total % this.pageSize == 0 ? this.total / this.pageSize : this.total / this.pageSize + 1;\n }\n\n public boolean isHasNextPage() {\n return getPages() > pageNum;\n }\n}" }, { "identifier": "BeanUtil", "path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java", "snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier) {\n return copyProperties(source, targetSupplier, null);\n }\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(source)) {\n return null;\n }\n T target = targetSupplier.get();\n BeanUtils.copyProperties(source, target);\n if (Objects.nonNull(ext)) {\n ext.accept(source, target);\n }\n return target;\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier) {\n return copyList(sources, targetSupplier, null);\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (CollectionUtils.isEmpty(sources)) {\n return List.of();\n }\n return sources\n .stream()\n .map(source -> copyProperties(source, targetSupplier, ext))\n .collect(Collectors.toList());\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier) {\n return copyRemotePage(pageSource, targetSupplier, null);\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(pageSource)) {\n return RemotePage.of();\n }\n return new RemotePage<>(\n copyList(pageSource.getList(), targetSupplier, ext),\n pageSource.getTotal(),\n pageSource.getPageNum(),\n pageSource.getPageSize()\n );\n }\n}" }, { "identifier": "JsonMapperUtil", "path": "dubbo-common/dubbo-common-util/src/main/java/com/liyz/boot3/common/util/JsonMapperUtil.java", "snippet": "@UtilityClass\npublic class JsonMapperUtil {\n\n private static final ObjectMapper OBJECT_MAPPER = Jackson2ObjectMapperBuilder\n .json()\n .createXmlMapper(false)\n .dateFormat(new SimpleDateFormat(DateUtil.PATTERN_DATE_TIME))\n .timeZone(TimeZone.getTimeZone(DateUtil.TIME_ZONE_GMT8))\n .build()\n .enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN)\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)\n .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false)\n .registerModule(new SimpleModule()\n .addSerializer(Long.class, ToStringSerializer.instance)\n .addSerializer(Long.TYPE, ToStringSerializer.instance)\n .addSerializer(Double.class, new DoubleSerializer())\n .addSerializer(Double.TYPE, new DoubleSerializer())\n );\n\n private static final ObjectWriter OBJECT_WRITER = OBJECT_MAPPER.writerWithDefaultPrettyPrinter();\n\n public static ObjectMapper getObjectMapper() {\n return OBJECT_MAPPER;\n }\n\n @SneakyThrows\n public static String toJSONString(Object obj) {\n if (Objects.isNull(obj)) {\n return null;\n }\n return OBJECT_MAPPER.writeValueAsString(obj);\n }\n\n @SneakyThrows\n public static String toJSONPrettyString(Object obj) {\n if (Objects.isNull(obj)) {\n return null;\n }\n return OBJECT_WRITER.writeValueAsString(obj);\n }\n\n @SneakyThrows\n public static <T> T readValue(String content, Class<T> clazz) {\n if (StringUtils.isBlank(content) || Objects.isNull(clazz)) {\n return null;\n }\n return OBJECT_MAPPER.readValue(content, clazz);\n }\n\n @SneakyThrows\n public static <T> T readValue(InputStream inputStream, Class<T> clazz) {\n if (ObjectUtils.anyNull(inputStream, clazz)) {\n return null;\n }\n return OBJECT_MAPPER.readValue(inputStream, clazz);\n }\n\n @SneakyThrows\n public static <T> T readValue(JsonNode jsonNode, Class<T> clazz) {\n if (ObjectUtils.anyNull(jsonNode, clazz)) {\n return null;\n }\n return OBJECT_MAPPER.treeToValue(jsonNode, clazz);\n }\n\n @SneakyThrows\n public static void writeValue(OutputStream out, Object value) {\n OBJECT_MAPPER.writeValue(out, value);\n }\n\n @SneakyThrows\n public static JsonNode readTree(Object obj) {\n if (Objects.isNull(obj)) {\n return null;\n }\n if (obj.getClass() == String.class) {\n return OBJECT_MAPPER.readTree((String) obj);\n }\n return OBJECT_MAPPER.readTree(OBJECT_MAPPER.writeValueAsString(obj));\n }\n}" }, { "identifier": "UserLoginLogBO", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/bo/UserLoginLogBO.java", "snippet": "@Getter\n@Setter\npublic class UserLoginLogBO implements Serializable {\n @Serial\n private static final long serialVersionUID = -8978119199629210583L;\n\n private Long userId;\n\n /**\n * 登录方式:1:手机;2:邮箱\n */\n private Integer loginType;\n\n private Integer device;\n\n private Date loginTime;\n\n private String ip;\n}" }, { "identifier": "UserLoginLogDO", "path": "dubbo-service/dubbo-service-user/user-dao/src/main/java/com/liyz/boot3/service/user/model/UserLoginLogDO.java", "snippet": "@Getter\n@Setter\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(\"user_login_log\")\npublic class UserLoginLogDO extends BaseDO implements Serializable {\n @Serial\n private static final long serialVersionUID = 3070437801653890936L;\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n private Long userId;\n\n /**\n * 登录方式:1:手机;2:邮箱\n */\n private Integer loginType;\n\n private Integer device;\n\n private Date loginTime;\n\n @Desensitization(value = DesensitizationType.SELF_DEFINITION, beginIndex = 2, endIndex = 5)\n private String ip;\n}" }, { "identifier": "RemoteUserLoginLogService", "path": "dubbo-service/dubbo-service-user/user-remote/src/main/java/com/liyz/boot3/service/user/remote/RemoteUserLoginLogService.java", "snippet": "public interface RemoteUserLoginLogService {\n\n /**\n * 根据userId分页查询登录日志\n *\n * @param userId 用户ID\n * @param pageBO 分页参数\n * @return 用户登录日志\n */\n RemotePage<UserLoginLogBO> page(@NotNull Long userId, @NotNull PageBO pageBO);\n\n /**\n * 根据userId分页流式查询登录日志\n *\n * @param userId 用户ID\n * @param pageBO 分页参数\n * @return 用户登录日志\n */\n RemotePage<UserLoginLogBO> pageStream(@NotNull Long userId, @NotNull PageBO pageBO);\n}" }, { "identifier": "UserLoginLogService", "path": "dubbo-service/dubbo-service-user/user-biz/src/main/java/com/liyz/boot3/service/user/service/UserLoginLogService.java", "snippet": "public interface UserLoginLogService extends IService<UserLoginLogDO> {\n\n /**\n * 获取上次登录时间\n *\n * @param userId 员工ID\n * @param device 设备类型\n * @return 上次登录时间\n */\n Date lastLoginTime(Long userId, Device device);\n\n /**\n * 流式查询\n *\n * @param page 分页\n * @param queryWrapper 查询条件\n * @param resultHandler 流式结果\n */\n void pageStream(IPage<UserLoginLogDO> page, Wrapper<UserLoginLogDO> queryWrapper, ResultHandler<UserLoginLogDO> resultHandler);\n}" } ]
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.liyz.boot3.common.remote.page.PageBO; import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.common.util.JsonMapperUtil; import com.liyz.boot3.service.user.bo.UserLoginLogBO; import com.liyz.boot3.service.user.model.UserLoginLogDO; import com.liyz.boot3.service.user.remote.RemoteUserLoginLogService; import com.liyz.boot3.service.user.service.UserLoginLogService; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboService; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List;
3,354
package com.liyz.boot3.service.user.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/10 10:50 */ @Slf4j @DubboService public class RemoteUserLoginLogServiceImpl implements RemoteUserLoginLogService { @Resource
package com.liyz.boot3.service.user.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/10 10:50 */ @Slf4j @DubboService public class RemoteUserLoginLogServiceImpl implements RemoteUserLoginLogService { @Resource
private UserLoginLogService userLoginLogService;
7
2023-11-13 01:28:21+00:00
4k
glowingstone124/QAPI3
src/main/java/org/qo/UserProcess.java
[ { "identifier": "AvatarCache", "path": "src/main/java/org/qo/server/AvatarCache.java", "snippet": "public class AvatarCache {\n public static final String CachePath = \"avatars/\";\n public static void init() throws IOException {\n if (!Files.exists(Path.of(CachePath))){\n Files.createDirectory(Path.of(CachePath));\n }\n }\n public static boolean has(String name){\n return Files.exists(Path.of(CachePath + name + \".png\"));\n }\n public static void cache(String url, String name) throws Exception{\n Request.Download(url,CachePath + name);\n }\n}" }, { "identifier": "LogLevel", "path": "src/main/java/org/qo/Logger.java", "snippet": "public enum LogLevel {\n INFO, WARNING, ERROR, UNKNOWN\n}" }, { "identifier": "hashSHA256", "path": "src/main/java/org/qo/Algorithm.java", "snippet": "public static String hashSHA256(String input) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));\n\n StringBuilder hexString = new StringBuilder();\n for (byte hashByte : hashBytes) {\n String hex = Integer.toHexString(0xff & hashByte);\n if (hex.length() == 1) hexString.append('0');\n hexString.append(hex);\n }\n\n return hexString.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n}" } ]
import jakarta.servlet.http.HttpServletRequest; import org.json.JSONException; import org.json.JSONObject; import org.qo.server.AvatarCache; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.*; import java.util.Calendar; import java.util.Objects; import static org.qo.Logger.LogLevel.*; import static org.qo.Algorithm.hashSHA256;
2,778
return null; } } public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception { String ArticleSheet; switch (ArticleSheets){ case 0: ArticleSheet = "serverArticles"; break; case 1: ArticleSheet = "commandArticles"; break; case 2: ArticleSheet = "attractionsArticles"; break; case 3: ArticleSheet = "noticeArticles"; break; default: ArticleSheet = null; break; } try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setInt(1, ArticleID); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { String resultName = resultSet.getString("Name"); return resultName; } else { return null; } } } } } public static String queryReg(String name) throws Exception{ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM users WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Long uid = resultSet.getLong("uid"); Boolean frozen = resultSet.getBoolean("frozen"); int eco = resultSet.getInt("economy"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("frozen", frozen); responseJson.put("qq", uid); responseJson.put("economy", eco); return responseJson.toString(); } resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("qq", -1); return responseJson.toString(); } public static void regforum(String username, String password) throws Exception{ // 解析JSON数据为JSONArray Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的 int day = calendar.get(Calendar.DAY_OF_MONTH); String date = year + "-" + month + "-" + day; String EncryptedPswd = hashSHA256(password); Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); // 准备插入语句 String insertQuery = "INSERT INTO forum (username, date, password, premium, donate, firstLogin, linkto) VALUES (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); // 设置参数值 preparedStatement.setString(1, username); preparedStatement.setString(2, date); preparedStatement.setString(3, EncryptedPswd); preparedStatement.setBoolean(4, false); preparedStatement.setBoolean(5, false); preparedStatement.setBoolean(6, true); preparedStatement.setString(7, "EMPTY"); preparedStatement.executeUpdate(); // 关闭资源 preparedStatement.close(); connection.close(); } public static String regMinecraftUser(String name, Long uid, HttpServletRequest request){ if (!UserProcess.dumplicateUID(uid) && name != null && uid != null) { try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String insertQuery = "INSERT INTO users (username, uid,frozen, remain, economy) VALUES (?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); preparedStatement.setString(1, name);preparedStatement.setLong(2, uid); preparedStatement.setBoolean(3, false); preparedStatement.setInt(4, 3);preparedStatement.setInt(5,0); int rowsAffected = preparedStatement.executeUpdate(); System.out.println(rowsAffected + " row(s) inserted." + "from " + IPUtil.getIpAddr(request)); System.out.println(name + " Registered."); preparedStatement.close(); connection.close();UserProcess.insertIp(IPUtil.getIpAddr(request)); return ReturnInterface.success("Success!"); } catch (Exception e) { e.printStackTrace(); return ReturnInterface.failed("FAILED"); } } return ReturnInterface.failed("FAILED"); } public static String AvatarTrans(String name) throws Exception{ String apiURL = "https://api.mojang.com/users/profiles/minecraft/" + name; String avatarURL = "https://playerdb.co/api/player/minecraft/";
package org.qo; public class UserProcess { public static final String CODE = "users/recoverycode/index.json"; private static final String FILE_PATH = "usermap.json"; private static final String SERVER_FILE_PATH = "playermap.json"; public static final String SQL_CONFIGURATION = "data/sql/info.json"; public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static String firstLoginSearch(String name, HttpServletRequest request) { try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM forum WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Boolean first = resultSet.getBoolean("firstLogin"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("first", first); resultSet.close(); preparedStatement.close(); return responseJson.toString(); } String updateQuery = "UPDATE forum SET firstLogin = ? WHERE username = ?"; PreparedStatement apreparedStatement = connection.prepareStatement(updateQuery); apreparedStatement.setBoolean(1, false); apreparedStatement.setString(2, name); Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin.", INFO); int rowsAffected = apreparedStatement.executeUpdate(); apreparedStatement.close(); connection.close(); resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("first", -1); Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin but unsuccessful.", INFO); return responseJson.toString(); } public static String fetchMyinfo(String name, HttpServletRequest request) throws Exception { String date; Boolean premium; Boolean donate; if (name.isEmpty()) { } try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM forum WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { date = resultSet.getString("date"); premium = resultSet.getBoolean("premium"); donate = resultSet.getBoolean("donate"); String linkto = resultSet.getString("linkto"); JSONObject responseJson = new JSONObject(); responseJson.put("date", date); responseJson.put("premium", premium); responseJson.put("donate", donate); responseJson.put("code", 0); responseJson.put("linkto", linkto); responseJson.put("username", name); Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo.", INFO); return responseJson.toString(); } else { // No rows found for the given username JSONObject responseJson = new JSONObject(); responseJson.put("code", -1); Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo, but unsuccessful.", INFO); return responseJson.toString(); } } catch (SQLException e) { e.printStackTrace(); JSONObject responseJson = new JSONObject(); Logger.log("username " + name + " qureied myinfo, but unsuccessful.", INFO); responseJson.put("code", -1); return responseJson.toString(); } } public static String getDatabaseInfo(String type) { JSONObject sqlObject = null; try { sqlObject = new JSONObject(Files.readString(Path.of(SQL_CONFIGURATION))); } catch (IOException e) { Logger.log("ERROR: SQL CONFIG NOT FOUND",ERROR); } switch (type){ case "password": return sqlObject.getString("password"); case "username": return sqlObject.getString("username"); case "url": return sqlObject.getString("url"); default: return null; } } public static void handleTime(String name, int time){ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "INSERT INTO timeTables (name, time) VALUES (?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); preparedStatement.setInt(2, time); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public static JSONObject getTime(String username) { JSONObject result = null; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { result = new JSONObject(); String query = "SELECT * FROM timeTables WHERE name = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, username); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { int time = resultSet.getInt("time"); result.put("name", username); result.put("time", time); } else { result.put("error", -1); } resultSet.close(); preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); result.put("error", e.getMessage()); } return result; } public static boolean SQLAvliable() { boolean success = true; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){ } catch (SQLException e){ success = false; } return success; } public static boolean queryForum(String username) throws Exception { boolean resultExists = false; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM forum WHERE username = ?"; Logger.log(selectQuery, INFO); try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setString(1, username); try (ResultSet resultSet = preparedStatement.executeQuery()) { resultExists = resultSet.next(); } } } return resultExists; } public static String queryHash(String hash) throws Exception { String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8); JSONObject codeObject = new JSONObject(jsonContent); if (codeObject.has(hash)) { String username = codeObject.getString(hash); String finalOutput = username; // codeObject.remove(hash); Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8)); System.out.println(username); return finalOutput; } else { System.out.println("mismatched"); return null; } } public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception { String ArticleSheet; switch (ArticleSheets){ case 0: ArticleSheet = "serverArticles"; break; case 1: ArticleSheet = "commandArticles"; break; case 2: ArticleSheet = "attractionsArticles"; break; case 3: ArticleSheet = "noticeArticles"; break; default: ArticleSheet = null; break; } try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setInt(1, ArticleID); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { String resultName = resultSet.getString("Name"); return resultName; } else { return null; } } } } } public static String queryReg(String name) throws Exception{ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM users WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Long uid = resultSet.getLong("uid"); Boolean frozen = resultSet.getBoolean("frozen"); int eco = resultSet.getInt("economy"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("frozen", frozen); responseJson.put("qq", uid); responseJson.put("economy", eco); return responseJson.toString(); } resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("qq", -1); return responseJson.toString(); } public static void regforum(String username, String password) throws Exception{ // 解析JSON数据为JSONArray Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的 int day = calendar.get(Calendar.DAY_OF_MONTH); String date = year + "-" + month + "-" + day; String EncryptedPswd = hashSHA256(password); Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); // 准备插入语句 String insertQuery = "INSERT INTO forum (username, date, password, premium, donate, firstLogin, linkto) VALUES (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); // 设置参数值 preparedStatement.setString(1, username); preparedStatement.setString(2, date); preparedStatement.setString(3, EncryptedPswd); preparedStatement.setBoolean(4, false); preparedStatement.setBoolean(5, false); preparedStatement.setBoolean(6, true); preparedStatement.setString(7, "EMPTY"); preparedStatement.executeUpdate(); // 关闭资源 preparedStatement.close(); connection.close(); } public static String regMinecraftUser(String name, Long uid, HttpServletRequest request){ if (!UserProcess.dumplicateUID(uid) && name != null && uid != null) { try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String insertQuery = "INSERT INTO users (username, uid,frozen, remain, economy) VALUES (?, ?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); preparedStatement.setString(1, name);preparedStatement.setLong(2, uid); preparedStatement.setBoolean(3, false); preparedStatement.setInt(4, 3);preparedStatement.setInt(5,0); int rowsAffected = preparedStatement.executeUpdate(); System.out.println(rowsAffected + " row(s) inserted." + "from " + IPUtil.getIpAddr(request)); System.out.println(name + " Registered."); preparedStatement.close(); connection.close();UserProcess.insertIp(IPUtil.getIpAddr(request)); return ReturnInterface.success("Success!"); } catch (Exception e) { e.printStackTrace(); return ReturnInterface.failed("FAILED"); } } return ReturnInterface.failed("FAILED"); } public static String AvatarTrans(String name) throws Exception{ String apiURL = "https://api.mojang.com/users/profiles/minecraft/" + name; String avatarURL = "https://playerdb.co/api/player/minecraft/";
if (!AvatarCache.has(name)) {
0
2023-11-15 13:38:53+00:00
4k
RaniAgus/java-docker-tutorial
src/main/java/io/github/raniagus/example/Application.java
[ { "identifier": "Bootstrap", "path": "src/main/java/io/github/raniagus/example/bootstrap/Bootstrap.java", "snippet": "public class Bootstrap implements Runnable, WithSimplePersistenceUnit {\n private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);\n\n public static void main(String[] args) {\n Application.startDatabaseConnection();\n new Bootstrap().run();\n }\n\n @Override\n public void run() {\n log.info(\"Iniciando reinicio de base de datos...\");\n try (var reader = new CsvReader<>(UserDto.class, \"/data/users.csv\")){\n var users = reader.readAll().stream().map(UserDto::toEntity).toList();\n\n withTransaction(() -> {\n RepositorioDeUsuarios.INSTANCE.eliminarTodos();\n users.forEach(RepositorioDeUsuarios.INSTANCE::guardar);\n });\n\n users.forEach(user -> log.info(\"Usuario insertado: {}\", user));\n }\n }\n}" }, { "identifier": "Routes", "path": "src/main/java/io/github/raniagus/example/constants/Routes.java", "snippet": "public abstract class Routes {\n public static final String HOME = \"/\";\n public static final String LOGIN = \"/login\";\n public static final String LOGOUT = \"/logout\";\n\n private Routes() {}\n}" }, { "identifier": "ErrorController", "path": "src/main/java/io/github/raniagus/example/controller/ErrorController.java", "snippet": "public enum ErrorController {\n INSTANCE;\n\n public void handleShouldLogin(Context ctx) {\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, ctx.path())\n ));\n }\n\n public void handleNotFound(Context ctx) {\n new ErrorView(\"404\", \"No pudimos encontrar la página que estabas buscando.\").render(ctx);\n }\n\n public void handleError(Context ctx) {\n new ErrorView(\"¡Oops!\", \"Algo salió mal. Vuelve a intentarlo más tarde.\").render(ctx);\n }\n}" }, { "identifier": "HomeController", "path": "src/main/java/io/github/raniagus/example/controller/HomeController.java", "snippet": "public enum HomeController {\n INSTANCE;\n\n public void renderHome(Context ctx) {\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n new HomeView(usuario.getNombre(), usuario.getApellido()).render(ctx);\n }\n}" }, { "identifier": "LoginController", "path": "src/main/java/io/github/raniagus/example/controller/LoginController.java", "snippet": "public enum LoginController {\n INSTANCE;\n\n public void handleSession(Context ctx) {\n if (ctx.routeRoles().isEmpty()) {\n return;\n }\n\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n if (usuario == null) {\n throw new ShouldLoginException();\n } else if (!ctx.routeRoles().contains(usuario.getRol())) {\n throw new UserNotAuthorizedException();\n }\n }\n\n public void renderLogin(Context ctx) {\n var email = ctx.queryParamAsClass(Params.EMAIL, String.class).getOrDefault(\"\");\n var origin = ctx.queryParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n var errors = ctx.queryParamAsClass(Params.ERRORS, String.class).getOrDefault(\"\");\n\n if (ctx.sessionAttribute(Session.USER) != null) {\n ctx.redirect(origin);\n return;\n }\n\n new LoginView(email, origin, errors.isEmpty() ? Set.of() : Set.of(errors.split(\",\"))).render(ctx);\n }\n\n public void performLogin(Context ctx) {\n var email = ctx.formParamAsClass(Params.EMAIL, String.class)\n .check(s -> s.matches(\".+@.+\\\\..+\"), \"INVALID_EMAIL\");\n var password = ctx.formParamAsClass(Params.PASSWORD, String.class)\n .check(s -> s.length() >= 8, \"INVALID_PASSWORD\");\n var origin = ctx.formParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n\n try {\n RepositorioDeUsuarios.INSTANCE.buscarPorEmail(email.get())\n .filter(u -> u.getPassword().matches(password.get()))\n .ifPresentOrElse(usuario -> {\n ctx.sessionAttribute(Session.USER, usuario);\n ctx.redirect(origin);\n }, () ->\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.get()),\n HtmlUtil.encode(Params.ERRORS, String.join(\",\", Params.EMAIL, Params.PASSWORD))\n ))\n );\n } catch (ValidationException e) {\n var errors = Validation.collectErrors(email, password);\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.errors().isEmpty() ? email.get() : \"\"),\n HtmlUtil.encode(Params.ERRORS, errors.keySet())\n ));\n }\n }\n\n public void performLogout(Context ctx) {\n ctx.consumeSessionAttribute(Session.USER);\n ctx.redirect(Routes.HOME);\n }\n}" }, { "identifier": "ShouldLoginException", "path": "src/main/java/io/github/raniagus/example/exception/ShouldLoginException.java", "snippet": "public class ShouldLoginException extends RuntimeException {\n}" }, { "identifier": "UserNotAuthorizedException", "path": "src/main/java/io/github/raniagus/example/exception/UserNotAuthorizedException.java", "snippet": "public class UserNotAuthorizedException extends RuntimeException {\n}" }, { "identifier": "Rol", "path": "src/main/java/io/github/raniagus/example/model/Rol.java", "snippet": "public enum Rol implements RouteRole {\n ADMIN,\n USER\n}" } ]
import gg.jte.ContentType; import gg.jte.TemplateEngine; import gg.jte.output.StringOutput; import gg.jte.resolve.DirectoryCodeResolver; import io.github.flbulgarelli.jpa.extras.simple.WithSimplePersistenceUnit; import io.github.raniagus.example.bootstrap.Bootstrap; import io.github.raniagus.example.constants.Routes; import io.github.raniagus.example.controller.ErrorController; import io.github.raniagus.example.controller.HomeController; import io.github.raniagus.example.controller.LoginController; import io.github.raniagus.example.exception.ShouldLoginException; import io.github.raniagus.example.exception.UserNotAuthorizedException; import io.github.raniagus.example.model.Rol; import io.javalin.Javalin; import io.javalin.http.staticfiles.Location; import java.nio.file.Path; import java.time.LocalDate;
1,607
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) { new Bootstrap().run(); } startServer(); } public static void startDatabaseConnection() { WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties())); WithSimplePersistenceUnit.dispose(); } @SuppressWarnings("java:S2095") public static void startServer() { var app = Javalin.create(config -> { var templateEngine = createTemplateEngine(); config.fileRenderer((filePath, model, ctx) -> { var output = new StringOutput(); templateEngine.render(filePath, model.get("view"), output); return output.toString(); }); config.staticFiles.add("public", Location.CLASSPATH); config.validation.register(LocalDate.class, LocalDate::parse); }); app.beforeMatched(LoginController.INSTANCE::handleSession);
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) { new Bootstrap().run(); } startServer(); } public static void startDatabaseConnection() { WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties())); WithSimplePersistenceUnit.dispose(); } @SuppressWarnings("java:S2095") public static void startServer() { var app = Javalin.create(config -> { var templateEngine = createTemplateEngine(); config.fileRenderer((filePath, model, ctx) -> { var output = new StringOutput(); templateEngine.render(filePath, model.get("view"), output); return output.toString(); }); config.staticFiles.add("public", Location.CLASSPATH); config.validation.register(LocalDate.class, LocalDate::parse); }); app.beforeMatched(LoginController.INSTANCE::handleSession);
app.get(Routes.HOME, HomeController.INSTANCE::renderHome, Rol.USER, Rol.ADMIN);
3
2023-11-12 15:14:24+00:00
4k
innogames/flink-real-time-crm-ui
src/main/java/com/innogames/analytics/rtcrmui/controller/IndexController.java
[ { "identifier": "Campaign", "path": "src/main/java/com/innogames/analytics/rtcrmui/entity/Campaign.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Campaign {\n\n\tprivate int campaignId;\n\tprivate boolean enabled;\n\tprivate String game;\n\tprivate String eventName;\n\tprivate String startDate;\n\tprivate String endDate;\n\tprivate String filter;\n\n\tpublic Campaign() {\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic void setEnabled(final boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\n\tpublic int getCampaignId() {\n\t\treturn campaignId;\n\t}\n\n\tpublic void setCampaignId(final int campaignId) {\n\t\tthis.campaignId = campaignId;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tpublic void setStartDate(final String startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\tpublic String getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tpublic void setEndDate(final String endDate) {\n\t\tthis.endDate = endDate;\n\t}\n\n\tpublic String getFilter() {\n\t\treturn filter;\n\t}\n\n\tpublic void setFilter(final String filter) {\n\t\tthis.filter = filter;\n\t}\n\n}" }, { "identifier": "TrackingEvent", "path": "src/main/java/com/innogames/analytics/rtcrmui/entity/TrackingEvent.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class TrackingEvent {\n\n\tprivate String schemaVersion;\n\tprivate String eventId;\n\tprivate String systemType;\n\tprivate String systemName;\n\tprivate String game;\n\tprivate String market;\n\tprivate Integer playerId;\n\tprivate String eventType;\n\tprivate String eventName;\n\tprivate String eventScope;\n\tprivate String createdAt;\n\tprivate String receivedAt;\n\tprivate String hostname;\n\n\tprivate Map<String, Object> context;\n\n\tprivate Map<String, Object> data;\n\n\tpublic TrackingEvent() {\n\t}\n\n\tpublic String getSchemaVersion() {\n\t\treturn schemaVersion;\n\t}\n\n\tpublic void setSchemaVersion(final String schemaVersion) {\n\t\tthis.schemaVersion = schemaVersion;\n\t}\n\n\tpublic String getEventId() {\n\t\treturn eventId;\n\t}\n\n\tpublic void setEventId(final String eventId) {\n\t\tthis.eventId = eventId;\n\t}\n\n\tpublic String getSystemType() {\n\t\treturn systemType;\n\t}\n\n\tpublic void setSystemType(final String systemType) {\n\t\tthis.systemType = systemType;\n\t}\n\n\tpublic String getSystemName() {\n\t\treturn systemName;\n\t}\n\n\tpublic void setSystemName(final String systemName) {\n\t\tthis.systemName = systemName;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getMarket() {\n\t\treturn market;\n\t}\n\n\tpublic void setMarket(final String market) {\n\t\tthis.market = market;\n\t}\n\n\tpublic Integer getPlayerId() {\n\t\treturn playerId;\n\t}\n\n\tpublic void setPlayerId(final Integer playerId) {\n\t\tthis.playerId = playerId;\n\t}\n\n\tpublic String getEventType() {\n\t\treturn eventType;\n\t}\n\n\tpublic void setEventType(final String eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getEventScope() {\n\t\treturn eventScope;\n\t}\n\n\tpublic void setEventScope(final String eventScope) {\n\t\tthis.eventScope = eventScope;\n\t}\n\n\tpublic String getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(final String createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic String getReceivedAt() {\n\t\treturn receivedAt;\n\t}\n\n\tpublic void setReceivedAt(final String receivedAt) {\n\t\tthis.receivedAt = receivedAt;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic void setHostname(final String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\tpublic Map<String, Object> getContext() {\n\t\treturn context;\n\t}\n\n\tpublic void setContext(final Map<String, Object> context) {\n\t\tthis.context = context;\n\t}\n\n\tpublic Map<String, Object> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(final Map<String, Object> data) {\n\t\tthis.data = data;\n\t}\n\n}" }, { "identifier": "StringProducer", "path": "src/main/java/com/innogames/analytics/rtcrmui/kafka/StringProducer.java", "snippet": "@Component\npublic class StringProducer {\n\n\tprivate final Properties properties;\n\tprivate Producer<String, String> producer;\n\n\tpublic StringProducer(@Value(\"${spring.kafka.bootstrap-servers}\") final String kafkaBootstrapServers) {\n\t\tthis.properties = new Properties();\n\n\t\tthis.properties.put(\"bootstrap.servers\", kafkaBootstrapServers);\n\t\tthis.properties.put(\"acks\", \"all\");\n\t\tthis.properties.put(\"buffer.memory\", 33554432);\n\t\tthis.properties.put(\"compression.type\", \"snappy\");\n\t\tthis.properties.put(\"retries\", 3);\n\t\tthis.properties.put(\"batch.size\", 16384);\n\t\tthis.properties.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\t\tthis.properties.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\n\t\tthis.producer = new KafkaProducer<>(this.properties);\n\t}\n\n\t@PreDestroy\n\tpublic void destroy() {\n\t\tthis.flush();\n\t\tthis.producer.close();\n\t}\n\n\tpublic void flush() {\n\t\tthis.producer.flush();\n\t}\n\n\tpublic Future<RecordMetadata> send(ProducerRecord<String, String> record) {\n\t\treturn this.producer.send(record);\n\t}\n\n\tpublic Future<RecordMetadata> send(String topic, String message) {\n\t\treturn this.send(new ProducerRecord<>(topic, message));\n\t}\n\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrmui.entity.Campaign; import com.innogames.analytics.rtcrmui.entity.TrackingEvent; import com.innogames.analytics.rtcrmui.kafka.StringProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.servlet.view.RedirectView;
1,952
package com.innogames.analytics.rtcrmui.controller; @Controller public class IndexController { private static final ObjectMapper objectMapper = new ObjectMapper(); @Autowired private StringProducer stringProducer; @Autowired private SimpMessagingTemplate template; @GetMapping("/") public String home(final Model model) { model.addAttribute("module", "index"); return "index"; } @PostMapping("/event") public RedirectView sendEvent(@RequestBody final String eventJson) { try { final TrackingEvent trackingEvent = objectMapper.readValue(eventJson, TrackingEvent.class); stringProducer.send("events-valid", objectMapper.writeValueAsString(trackingEvent)); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } return new RedirectView("/", false); } @PostMapping("/campaign") public RedirectView sendCampaign(@RequestBody final String campaignJson) { try {
package com.innogames.analytics.rtcrmui.controller; @Controller public class IndexController { private static final ObjectMapper objectMapper = new ObjectMapper(); @Autowired private StringProducer stringProducer; @Autowired private SimpMessagingTemplate template; @GetMapping("/") public String home(final Model model) { model.addAttribute("module", "index"); return "index"; } @PostMapping("/event") public RedirectView sendEvent(@RequestBody final String eventJson) { try { final TrackingEvent trackingEvent = objectMapper.readValue(eventJson, TrackingEvent.class); stringProducer.send("events-valid", objectMapper.writeValueAsString(trackingEvent)); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } return new RedirectView("/", false); } @PostMapping("/campaign") public RedirectView sendCampaign(@RequestBody final String campaignJson) { try {
final Campaign campaign = objectMapper.readValue(campaignJson, Campaign.class);
0
2023-11-12 18:07:20+00:00
4k
heldermartins4/RPG_Pokemon
src/main/java/interfaces/GamePanel.java
[ { "identifier": "KeyHandler", "path": "src/main/java/controllers/controls/KeyHandler.java", "snippet": "public class KeyHandler implements KeyListener {\n\n public boolean up, down, left, right;\n\n public KeyHandler() {\n up = down = left = right = false;\n }\n\n @Override\n public void keyTyped(KeyEvent e) {\n \n // char keyChar = e.getKeyChar();\n // System.out.println(\"Key Typed: \" + keyChar);\n } \n\n @Override\n public void keyPressed(KeyEvent e) {\n\n int code = e.getKeyCode();\n\n switch (code) {\n case KeyEvent.VK_W:\n up = true;\n break;\n case KeyEvent.VK_A:\n left = true;\n break;\n case KeyEvent.VK_S:\n down = true;\n break;\n case KeyEvent.VK_D:\n right = true;\n break;\n \n default:\n break;\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n\n int code = e.getKeyCode();\n\n switch (code) {\n case KeyEvent.VK_W:\n up = false;\n break;\n case KeyEvent.VK_A:\n left = false;\n break;\n case KeyEvent.VK_S:\n down = false;\n break;\n case KeyEvent.VK_D:\n right = false;\n break;\n \n default:\n break;\n }\n }\n}" }, { "identifier": "Player", "path": "src/main/java/controllers/entity/Player.java", "snippet": "public class Player extends Entity {\n\n GamePanel gp;\n KeyHandler key;\n Map map;\n Start start_panel;\n\n Sprites[] player_sprite;\n Sprites player_direction = new Sprites();\n\n // private int player_sprites_amount;\n // private int player_direction_indexes;\n // private String player_sprites_path;\n\n int sprite_timer = 0;\n\n int next_x, next_y;\n\n private boolean is_walking = false;\n\n public Player(GamePanel gp, KeyHandler key) {\n\n this.gp = gp;\n this.key = key;\n this.start_panel = gp.getStartPanel();\n\n // this.player_sprites_amount = 12;\n // this.player_direction_indexes = 3;\n\n player_sprite = new Sprites[12]; // inicializa o array\n\n getImagePlayer(this.start_panel.getPlayer().getCharater());\n }\n\n public void setDefaultValues(int x, int y, int width, int height, int speed) {\n \n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.speed = speed;\n this.sprite = 3;\n \n this.sprite_counting = 0;\n \n // define a limiter for the next position\n this.next_x = x;\n this.next_y = y;\n player_direction.direction = \"down\";\n \n // Define a posição inicial aleatória\n // setRandomInitialPosition();\n }\n\n public void setMapToPlayer(Map map) {\n this.map = map;\n }\n\n public void getImagePlayer(String player_chosen) {\n\n final String relative_path = player_chosen; // path to the image folder\n\n try {\n for (int i = 0; i < 12; i++) {\n\n player_sprite[i] = new Sprites(); // initialize each element\n\n if (i < 3)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/u\" + (i + 1) + \".png\"));\n else if (i < 6)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/d\" + (i - 2) + \".png\"));\n else if (i < 9)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/l\" + (i - 5) + \".png\"));\n else if (i < 12)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/r\" + (i - 8) + \".png\"));\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void setRandomInitialPosition() {\n // Loop até encontrar uma posição válida\n do {\n // Gere coordenadas aleatórias\n int randomX = (int) (Math.random() * map.map_x);\n int randomY = (int) (Math.random() * map.map_y);\n \n // Converta as coordenadas do array para as coordenadas do mapa\n int mapX = randomX * map.tile_size;\n int mapY = randomY * map.tile_size;\n \n // Verifique se a posição é válida\n if (isValidPosition(mapX, mapY)) {\n // Defina a posição do jogador\n setDefaultValues(mapX, mapY, map.tile_size, map.tile_size, speed);\n return;\n }\n // Se a posição não for válida, tente novamente\n } while (true);\n }\n \n private boolean isValidPosition(int x, int y) {\n // Converte as coordenadas do mapa para as coordenadas do array\n int arrayX = x / map.tile_size;\n int arrayY = y / map.tile_size;\n \n // Verifica se as coordenadas estão dentro dos limites do mapa\n if (arrayX >= 0 && arrayX < map.map_x && arrayY >= 0 && arrayY < map.map_y) {\n // Verifica se a célula correspondente no mapa não é colisiva\n return map.map_data[arrayX][arrayY] == 0;\n }\n \n // Se as coordenadas estão fora dos limites do mapa, considera como posição inválida\n return false;\n }\n\n public void update() {\n\n if (!is_walking) {\n if (key.up) {\n\n next_y = y - map.tile_size;\n player_direction.direction = \"up\";\n is_walking = true;\n\n } else if (key.down) {\n\n next_y = y + map.tile_size;\n player_direction.direction = \"down\";\n is_walking = true;\n\n } else if (key.left) {\n\n next_x = x - map.tile_size;\n player_direction.direction = \"left\";\n is_walking = true;\n\n } else if (key.right) {\n\n next_x = x + map.tile_size;\n player_direction.direction = \"right\";\n is_walking = true;\n\n }\n\n this.sprite_counting = 0;\n } else {\n \n if (isValidMove(next_x, next_y)) {\n if (y != next_y) {\n y += speed * Integer.signum(next_y - y);\n }\n else if (x != next_x) {\n x += speed * Integer.signum(next_x - x);\n }\n else if (x == next_x && y == next_y) {\n is_walking = false;\n }\n\n if (sprite_timer >= sprite) { // Ajuste o valor 10 conforme necessário para definir a velocidade da animação\n this.sprite_counting++;\n if (this.sprite_counting >= this.sprite) {\n this.sprite_counting = 0;\n }\n sprite_timer = 0;\n } else {\n sprite_timer++;\n }\n } else {\n is_walking = false;\n if (player_direction.direction == \"up\") {\n next_y = y;\n } else if (player_direction.direction == \"down\") {\n next_y = y;\n } else if (player_direction.direction == \"left\") {\n next_x = x;\n } else if (player_direction.direction == \"right\") {\n next_x = x;\n }\n }\n }\n }\n\n private boolean isValidMove(int nextX, int nextY) {\n // Converte as coordenadas do mapa para as coordenadas do array\n int arrayX = nextX / map.tile_size;\n int arrayY = nextY / map.tile_size;\n \n // Verifica se as coordenadas estão dentro dos limites do mapa\n if (arrayX >= 0 && arrayX < map.map_x && arrayY >= 0 && arrayY < map.map_y) {\n // Verifica se a célula correspondente no mapa não é colisiva\n return map.map_data[arrayX][arrayY] == 0;\n }\n \n // Se as coordenadas estão fora dos limites do mapa, considera como movimento inválido\n return false;\n }\n\n public void draw(Graphics2D g2d) {\n\n // g2d.setColor(java.awt.Color.white);\n // g2d.fillRect(x, y, map.tile_size, map.tile_size);\n\n BufferedImage img = null; // set default image\n\n // set image based on direction\n switch (player_direction.direction) {\n case \"up\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[0].sprite_img;\n break;\n case 1:\n img = player_sprite[1].sprite_img;\n break;\n case 2:\n img = player_sprite[2].sprite_img;\n break;\n }\n break;\n case \"down\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[3].sprite_img;\n break;\n case 1:\n img = player_sprite[4].sprite_img;\n break;\n case 2:\n img = player_sprite[5].sprite_img;\n break;\n }\n break;\n case \"left\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[6].sprite_img;\n break;\n case 1:\n img = player_sprite[7].sprite_img;\n break;\n case 2:\n img = player_sprite[8].sprite_img;\n break;\n }\n break;\n case \"right\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[9].sprite_img;\n break;\n case 1:\n img = player_sprite[10].sprite_img;\n break;\n case 2:\n img = player_sprite[11].sprite_img;\n break;\n }\n break;\n }\n\n g2d.drawImage(img, x, y, map.tile_size, map.tile_size, null);\n }\n}" }, { "identifier": "Map", "path": "src/main/java/interfaces/map/Map.java", "snippet": "public class Map extends MapDataManager {\n\n TileManager tm;\n\n final int scale = 3;\n\n public int max_screen_col = 16;\n public int max_screen_row = 12;\n\n private int original_tile_size = 16;\n public int tile_size = original_tile_size * scale; \n\n public int screen_width = tile_size * max_screen_col;\n public int screen_height = tile_size * max_screen_row;\n public BufferedImage map;\n\n public Map(String mapName) {\n\n super(mapName);\n tm = new TileManager(this); // Passa a instância atual de Map para TileManager\n }\n\n public void loadMap(Graphics2D g2d) {\n try {\n map = ImageIO.read(getClass().getResource(\"/sprites/map/map.png\"));\n } catch (IOException e) {\n e.printStackTrace();\n };\n\n g2d.drawImage(map, 0, 0, null);\n }\n}" }, { "identifier": "Start", "path": "src/main/java/interfaces/start/Start.java", "snippet": "public class Start extends JPanel {\n\n private GamePanel screen;\n private Trainer player;\n private Trainer rival;\n private ChooseSkin ChooseSkin;\n\n public Start(GamePanel screen) {\n this.screen = screen;\n this.player = new Trainer(null, null);\n this.rival = new Trainer(null, null);\n this.ChooseSkin = new ChooseSkin();\n add(ChooseSkin);\n }\n\n public void runStartSequence() {\n\n namePlayer();\n nameRival();\n chooseCharacter();\n }\n\n public void namePlayer() {\n \n String playerName = JOptionPane.showInputDialog(screen, \"Enter your name:\");\n player.setNome(playerName);\n }\n\n public void nameRival() {\n\n String rivalName = JOptionPane.showInputDialog(screen, \"Enter your rival's name:\");\n rival.setNome(rivalName);\n }\n\n public void chooseCharacter() {\n\n JOptionPane.showMessageDialog(screen, ChooseSkin, \"Who are you?\", JOptionPane.PLAIN_MESSAGE);\n\n String selectedSkin = ChooseSkin.getSelectedSkin();\n\n player.setCharacter(selectedSkin);\n rival.setCharacter(selectedSkin.equals(\"/sprites/characters/zeze/\") ? \"/sprites/characters/heldin/\" : \"/sprites/characters/zeze/\");\n }\n\n public Trainer getPlayer() {\n return player;\n }\n\n public Trainer getRival() {\n return rival;\n }\n}" } ]
import javax.swing.JPanel; import controllers.controls.KeyHandler; import controllers.entity.Player; import interfaces.map.Map; import interfaces.start.Start; import java.awt.*;
3,226
package interfaces; public class GamePanel extends JPanel implements Runnable { Map map = new Map("map_1"); public KeyHandler key = new KeyHandler();
package interfaces; public class GamePanel extends JPanel implements Runnable { Map map = new Map("map_1"); public KeyHandler key = new KeyHandler();
Player player;
1
2023-11-12 16:44:00+00:00
4k
penyoofficial/HerbMS
src/main/java/com/penyo/herbms/controller/PrescriptionController.java
[ { "identifier": "Prescription", "path": "src/main/java/com/penyo/herbms/pojo/Prescription.java", "snippet": "public class Prescription extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 中草药处方 ID(外键)\n */\n private int prescriptionId;\n /**\n * 中草药 ID(外键)\n */\n private int herbId;\n /**\n * 用量\n */\n private String dosage;\n /**\n * 用法\n */\n private String usage;\n\n public Prescription() {\n }\n\n public Prescription(int id, int prescriptionId, int herbId, String dosage, String usage) {\n this.id = id;\n this.prescriptionId = prescriptionId;\n this.herbId = herbId;\n this.dosage = dosage;\n this.usage = usage;\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getPrescriptionId() {\n return prescriptionId;\n }\n\n public void setPrescriptionID(int prescriptionId) {\n this.prescriptionId = prescriptionId;\n }\n\n public int getHerbId() {\n return herbId;\n }\n\n public void setHerbId(int herbId) {\n this.herbId = herbId;\n }\n\n public String getDosage() {\n return dosage;\n }\n\n public void setDosage(String dosage) {\n this.dosage = dosage;\n }\n\n public String getUsage() {\n return usage;\n }\n\n public void setUsage(String usage) {\n this.usage = usage;\n }\n}" }, { "identifier": "PrescriptionInfo", "path": "src/main/java/com/penyo/herbms/pojo/PrescriptionInfo.java", "snippet": "public class PrescriptionInfo extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 名称\n */\n private String name;\n /**\n * 别名\n */\n private String nickname;\n /**\n * 解释\n */\n private String description;\n\n public PrescriptionInfo() {\n }\n\n public PrescriptionInfo(int id, String name, String nickname, String description) {\n this.id = id;\n this.name = name;\n this.nickname = nickname;\n this.description = description;\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n public void setId(int 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 getNickname() {\n return nickname;\n }\n\n public void setNickname(String nickname) {\n this.nickname = nickname;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n}" }, { "identifier": "ReturnDataPack", "path": "src/main/java/com/penyo/herbms/pojo/ReturnDataPack.java", "snippet": "public class ReturnDataPack<T> extends GenericBean {\n /**\n * 影响行数\n */\n private int affectedRows = -114514;\n /**\n * 结果\n */\n private List<T> objs;\n\n public ReturnDataPack() {\n }\n\n public ReturnDataPack(List<T> objs) {\n this.objs = objs;\n }\n\n public ReturnDataPack(int affectedRows, List<T> objs) {\n this.affectedRows = affectedRows;\n this.objs = objs;\n }\n\n public int getAffectedRows() {\n return affectedRows;\n }\n\n public void setAffectedRows(int affectedRows) {\n this.affectedRows = affectedRows;\n }\n\n public List<T> getObjs() {\n return objs;\n }\n\n public void setObjs(List<T> objs) {\n this.objs = objs;\n }\n}" }, { "identifier": "HerbService", "path": "src/main/java/com/penyo/herbms/service/HerbService.java", "snippet": "@Service\npublic class HerbService extends GenericService<Herb> {\n @Override\n public int add(Herb o) {\n return herbDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return herbDAO.delete(id);\n }\n\n @Override\n public int update(Herb o) {\n return herbDAO.update(o);\n }\n\n @Override\n public Herb selectById(int id) {\n return herbDAO.selectById(id);\n }\n\n @Override\n public List<Herb> selectByFields(List<String> fields) {\n return herbDAO.selectByFields(fields);\n }\n\n /**\n * 根据中草药使用心得 ID 查询单个中草药名称。\n */\n public String selectNameByExperienceId(int id) {\n return herbDAO.selectByExperienceId(id).getName();\n }\n\n /**\n * 根据处方 ID 查找多个中草药名称和解释。\n */\n public List<String> selectNamesAndDescriptionsByPrescriptionId(int id) {\n List<String> names = new ArrayList<>();\n\n for (Herb o : herbDAO.selectByPrescriptionId(id))\n names.add(o.getName() + \"/\" + o.getDescription());\n return names;\n }\n}" }, { "identifier": "PrescriptionService", "path": "src/main/java/com/penyo/herbms/service/PrescriptionService.java", "snippet": "@Service\npublic class PrescriptionService extends GenericService<Prescription> {\n @Override\n public int add(Prescription o) {\n return prescriptionDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return prescriptionDAO.delete(id);\n }\n\n @Override\n public int update(Prescription o) {\n return prescriptionDAO.update(o);\n }\n\n @Override\n public Prescription selectById(int id) {\n return prescriptionDAO.selectById(id);\n }\n\n @Override\n public List<Prescription> selectByFields(List<String> fields) {\n return prescriptionDAO.selectByFields(fields);\n }\n\n /**\n * 根据处方 ID 查找处方概要。\n */\n public PrescriptionInfo selectPrescriptionInfoByPrescriptionId(int id) {\n return prescriptionInfoDAO.selectByPrescriptionId(id);\n }\n}" } ]
import com.penyo.herbms.pojo.Prescription; import com.penyo.herbms.pojo.PrescriptionInfo; import com.penyo.herbms.pojo.ReturnDataPack; import com.penyo.herbms.service.HerbService; import com.penyo.herbms.service.PrescriptionService; import java.util.ArrayList; import java.util.List; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
1,939
package com.penyo.herbms.controller; /** * 处方的控制器代理 * * @author Penyo * @see Prescription * @see GenericController */ @Controller public class PrescriptionController extends GenericController<Prescription> { @Override @RequestMapping("/use-prescriptions") @ResponseBody public String requestMain(HttpServletRequest request) { return requestMain(toMap(request), getService(PrescriptionService.class)).toString(); } @Override @RequestMapping("/use-prescriptions-specific") @ResponseBody public String requestSub(HttpServletRequest request) { List<String> annotations = new ArrayList<>(); ReturnDataPack<Prescription> ps = requestMain(toMap(request), getService(PrescriptionService.class)); for (Prescription o : ps.getObjs()) { StringBuilder annoTemp = new StringBuilder("\"");
package com.penyo.herbms.controller; /** * 处方的控制器代理 * * @author Penyo * @see Prescription * @see GenericController */ @Controller public class PrescriptionController extends GenericController<Prescription> { @Override @RequestMapping("/use-prescriptions") @ResponseBody public String requestMain(HttpServletRequest request) { return requestMain(toMap(request), getService(PrescriptionService.class)).toString(); } @Override @RequestMapping("/use-prescriptions-specific") @ResponseBody public String requestSub(HttpServletRequest request) { List<String> annotations = new ArrayList<>(); ReturnDataPack<Prescription> ps = requestMain(toMap(request), getService(PrescriptionService.class)); for (Prescription o : ps.getObjs()) { StringBuilder annoTemp = new StringBuilder("\"");
annoTemp.append(getService(HerbService.class).selectNamesAndDescriptionsByPrescriptionId(o.getId())).append("/");
3
2023-11-13 16:40:05+00:00
4k
martin-bian/DimpleBlog
dimple-blog/src/main/java/com/dimple/service/impl/CommentServiceImpl.java
[ { "identifier": "Comment", "path": "dimple-blog/src/main/java/com/dimple/domain/Comment.java", "snippet": "@Data\n@Entity\n@Table(name = \"bg_comment\")\npublic class Comment extends BaseEntity implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"comment_id\")\n private Long id;\n\n private String nickName;\n\n private String email;\n\n private String requestIp;\n\n private String address;\n\n private String os;\n\n private String browser;\n\n private Long parentId;\n\n private String qqNum;\n\n private String avatar;\n\n private Long pageId;\n\n private String requestUrl;\n\n private Boolean display;\n\n private Long good;\n\n private Long bad;\n\n private String content;\n\n private String htmlContent;\n\n private Boolean reply;\n\n private Boolean adminReply;\n\n}" }, { "identifier": "CommentMapper", "path": "dimple-blog/src/main/java/com/dimple/mapstruct/CommentMapper.java", "snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface CommentMapper extends BaseMapper<CommentDTO, Comment> {\n}" }, { "identifier": "CommentRepository", "path": "dimple-blog/src/main/java/com/dimple/repository/CommentRepository.java", "snippet": "public interface CommentRepository extends JpaRepository<Comment, Long>, JpaSpecificationExecutor<Comment> {\n void deleteAllByIdIn(Set<Long> ids);\n}" }, { "identifier": "CommentService", "path": "dimple-blog/src/main/java/com/dimple/service/CommentService.java", "snippet": "public interface CommentService {\n Map<String, Object> queryAll(CommentCriteria criteria, Pageable pageable);\n\n Comment findById(Long id);\n\n void create(Comment comment);\n\n void update(Comment comment);\n\n void delete(Set<Long> ids);\n}" }, { "identifier": "CommentCriteria", "path": "dimple-blog/src/main/java/com/dimple/service/Dto/CommentCriteria.java", "snippet": "@Data\npublic class CommentCriteria {\n @Query(blurry = \"content,description\")\n private String blurry;\n}" }, { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) {\n super(msg);\n }\n\n public BadRequestException(HttpStatus status, String msg) {\n super(msg);\n this.status = status.value();\n }\n}" }, { "identifier": "PageUtil", "path": "dimple-common/src/main/java/com/dimple/utils/PageUtil.java", "snippet": "public class PageUtil extends cn.hutool.core.util.PageUtil {\n\n /**\n * List 分页\n */\n public static List toPage(int page, int size, List list) {\n int fromIndex = page * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n return new ArrayList();\n } else if (toIndex >= list.size()) {\n return list.subList(fromIndex, list.size());\n } else {\n return list.subList(fromIndex, toIndex);\n }\n }\n\n /**\n * Page 数据处理,预防redis反序列化报错\n */\n public static Map<String, Object> toPage(Page page) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", page.getContent());\n map.put(\"totalElements\", page.getTotalElements());\n return map;\n }\n\n /**\n * 自定义分页\n */\n public static Map<String, Object> toPage(Object object, Object totalElements) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", object);\n map.put(\"totalElements\", totalElements);\n return map;\n }\n\n}" }, { "identifier": "QueryHelp", "path": "dimple-common/src/main/java/com/dimple/utils/QueryHelp.java", "snippet": "@Slf4j\n@SuppressWarnings({\"unchecked\", \"all\"})\npublic class QueryHelp {\n\n public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {\n List<Predicate> list = new ArrayList<>();\n if (query == null) {\n return cb.and(list.toArray(new Predicate[0]));\n }\n try {\n List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());\n for (Field field : fields) {\n boolean accessible = field.isAccessible();\n // 设置对象的访问权限,保证对private的属性的访\n field.setAccessible(true);\n Query q = field.getAnnotation(Query.class);\n if (q != null) {\n String propName = q.propName();\n String joinName = q.joinName();\n String blurry = q.blurry();\n String attributeName = isBlank(propName) ? field.getName() : propName;\n Class<?> fieldType = field.getType();\n Object val = field.get(query);\n if (ObjectUtil.isNull(val) || \"\".equals(val)) {\n continue;\n }\n Join join = null;\n // 模糊多字段\n if (ObjectUtil.isNotEmpty(blurry)) {\n String[] blurrys = blurry.split(\",\");\n List<Predicate> orPredicate = new ArrayList<>();\n for (String s : blurrys) {\n orPredicate.add(cb.like(root.get(s)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n }\n Predicate[] p = new Predicate[orPredicate.size()];\n list.add(cb.or(orPredicate.toArray(p)));\n continue;\n }\n if (ObjectUtil.isNotEmpty(joinName)) {\n String[] joinNames = joinName.split(\">\");\n for (String name : joinNames) {\n switch (q.join()) {\n case LEFT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.LEFT);\n } else {\n join = root.join(name, JoinType.LEFT);\n }\n break;\n case RIGHT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.RIGHT);\n } else {\n join = root.join(name, JoinType.RIGHT);\n }\n break;\n default:\n break;\n }\n }\n }\n switch (q.type()) {\n case EQUAL:\n list.add(cb.equal(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), val));\n break;\n case GREATER_THAN:\n list.add(cb.greaterThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN:\n list.add(cb.lessThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN_NQ:\n list.add(cb.lessThan(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case INNER_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n break;\n case LEFT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString()));\n break;\n case RIGHT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), val.toString() + \"%\"));\n break;\n case IN:\n if (CollUtil.isNotEmpty((Collection<Long>) val)) {\n list.add(getExpression(attributeName, join, root).in((Collection<Long>) val));\n }\n break;\n case NOT_EQUAL:\n list.add(cb.notEqual(getExpression(attributeName, join, root), val));\n break;\n case NOT_NULL:\n list.add(cb.isNotNull(getExpression(attributeName, join, root)));\n break;\n case IS_NULL:\n list.add(cb.isNull(getExpression(attributeName, join, root)));\n break;\n case BETWEEN:\n List<Object> between = new ArrayList<>((List<Object>) val);\n list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),\n (Comparable) between.get(0), (Comparable) between.get(1)));\n break;\n default:\n break;\n }\n }\n field.setAccessible(accessible);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n int size = list.size();\n return cb.and(list.toArray(new Predicate[size]));\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {\n if (ObjectUtil.isNotEmpty(join)) {\n return join.get(attributeName);\n } else {\n return root.get(attributeName);\n }\n }\n\n private static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n public static List<Field> getAllFields(Class clazz, List<Field> fields) {\n if (clazz != null) {\n fields.addAll(Arrays.asList(clazz.getDeclaredFields()));\n getAllFields(clazz.getSuperclass(), fields);\n }\n return fields;\n }\n}" } ]
import com.dimple.domain.Comment; import com.dimple.mapstruct.CommentMapper; import com.dimple.repository.CommentRepository; import com.dimple.service.CommentService; import com.dimple.service.Dto.CommentCriteria; import com.dimple.exception.BadRequestException; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Set;
2,532
package com.dimple.service.impl; /** * @className: CommentServiceImpl * @description: * @author: Dimple * @date: 06/19/20 */ @Service @Slf4j @RequiredArgsConstructor public class CommentServiceImpl implements CommentService { private final CommentRepository commentRepository; private final CommentMapper commentMapper; @Override public Map<String, Object> queryAll(CommentCriteria criteria, Pageable pageable) { Page<Comment> commentPage = commentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(commentPage.map(commentMapper::toDto)); } @Override public Comment findById(Long id) {
package com.dimple.service.impl; /** * @className: CommentServiceImpl * @description: * @author: Dimple * @date: 06/19/20 */ @Service @Slf4j @RequiredArgsConstructor public class CommentServiceImpl implements CommentService { private final CommentRepository commentRepository; private final CommentMapper commentMapper; @Override public Map<String, Object> queryAll(CommentCriteria criteria, Pageable pageable) { Page<Comment> commentPage = commentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); return PageUtil.toPage(commentPage.map(commentMapper::toDto)); } @Override public Comment findById(Long id) {
return commentRepository.findById(id).orElseThrow(() -> new BadRequestException("comment 不存在,Id为" + id));
5
2023-11-10 03:30:36+00:00
4k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/proj/stostr/operation/containerput/deserializer/AdditionalSetTypeFolderModelDeserializer.java
[ { "identifier": "AdditionalSetTypeFolderModel", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/proj/stostr/operation/containerput/AdditionalSetTypeFolderModel.java", "snippet": "@Data\npublic class AdditionalSetTypeFolderModel extends AbstractCodeControlPaneModel {\n\t/**\n\t * 该类的containerList废弃不用\n\t */\n\n\t@JSONField(deserializeUsing = AdditionalSetTypeContainerModelListDeserializer.class)\n\tprivate ArrayList<AdditionalSetTypeContainerModel> additionalSetTypeContainerModelList = new ArrayList<AdditionalSetTypeContainerModel>();\n\n\tpublic AdditionalSetTypeFolderModel() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetCodeControlPaneType(ADDITIONAL_TYPE_CODE_CONTROL_PANE);\n\t}\n\n}" }, { "identifier": "JsonUtil", "path": "utils/src/main/java/com/lazycoder/utils/JsonUtil.java", "snippet": "public class JsonUtil {\n\n private static final Logger log = LoggerFactory.getLogger(\"json工具类文件操作方法\");\n\n private static final SerializeConfig CONFIG;\n private static final SerializerFeature[] FEATURES = {SerializerFeature.WriteMapNullValue, // 输出空置字段\n SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null\n SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null\n SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null\n SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为\"\",而不是null\n };\n\n static {\n CONFIG = new SerializeConfig();\n CONFIG.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式\n CONFIG.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式\n }\n\n /**\n * 把字符串转成 JSONObject\n *\n * @param str\n * @return\n */\n public static JSONObject strToJSONObject(String str) {\n return JSONObject.parseObject(str);\n }\n\n /**\n * 获取解析前后对应字符串都是固定的json字符串()\n *\n * @param object\n * @return\n */\n//\tpublic static String getFixedSortingJsonStr(Object object) {\n//\t\tLinkedHashMap<String, Object> json = JSON.parseObject(\n//\t\t\t\tJSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect), LinkedHashMap.class,\n//\t\t\t\tFeature.OrderedField);\n//\t\tJSONObject jsonObject = new JSONObject(true);\n//\t\tjsonObject.putAll(json);\n//\t\treturn JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);\n//\t}\n\n /**\n * 获取对应的json字符串\n *\n * @param object\n * @return\n */\n public static String getJsonStr(Object object) {\n return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);\n }\n\n public static void writeFile(File file, Object object) {\n try {\n if (!file.getParentFile().isDirectory()) {\n file.getParentFile().mkdirs();\n }\n if (!file.exists()) {\n file.createNewFile();\n }\n OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), \"UTF-8\");\n BufferedWriter writer = new BufferedWriter(write);\n\n JSON.writeJSONString(writer, object, SerializerFeature.DisableCircularReferenceDetect);\n if(writer!=null) {\n writer.close();\n }\n if(write!=null) {\n write.close();\n }\n } catch (Exception e) {\n log.error(\"writeFile方法报错:\" + e.getMessage());\n e.printStackTrace();\n }\n }\n\n /**\n * 根据jSONObject还原\n *\n * @param jSONObject\n * @param clazz\n * @return\n */\n public static <T> T restoreByJSONObject(JSONObject jSONObject, Class<T> clazz) {\n return JSON.toJavaObject(jSONObject, clazz);\n }\n\n /**\n * 根据字符串还原成某个类\n *\n * @param string\n * @param clazz\n * @return\n */\n public static <T> List<T> restoreArrayByStr(String string, Class<T> clazz) {\n return JSON.parseArray(string, clazz);\n }\n\n\n /////////////////\n public static String toJSONString(Object object) {\n return JSON.toJSONString(object, CONFIG, FEATURES);\n }\n\n public static String toJSONNoFeatures(Object object) {\n return JSON.toJSONString(object, CONFIG);\n }\n\n\n public static Object toBean(String text) {\n return JSON.parse(text);\n }\n\n public static <T> T fileToBean(String path, Class<T> clazz) {\n try {\n InputStream is = new FileInputStream(path);\n return JSON.parseObject(is, clazz);//SerializerFeature\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public static <T> T toBean(String text, Class<T> clazz) {\n return JSON.parseObject(text, clazz);\n }\n\n // 转换为数组\n public static <T> Object[] toArray(String text) {\n return toArray(text, null);\n }\n\n // 转换为数组\n public static <T> Object[] toArray(String text, Class<T> clazz) {\n return JSON.parseArray(text, clazz).toArray();\n }\n\n // 转换为List\n public static <T> List<T> toList(String text, Class<T> clazz) {\n return JSON.parseArray(text, clazz);\n }\n\n /**\n * 将javabean转化为序列化的json字符串\n *\n * @param keyvalue\n * @return\n */\n public static Object beanToJson(KeyValue keyvalue) {\n String textJson = JSON.toJSONString(keyvalue);\n Object objectJson = JSON.parse(textJson);\n return objectJson;\n }\n\n /**\n * 将string转化为序列化的json字符串\n *\n * @param\n * @return\n */\n public static Object textToJson(String text) {\n Object objectJson = JSON.parse(text);\n return objectJson;\n }\n\n /**\n * json字符串转化为map\n *\n * @param s\n * @return\n */\n public static Map stringToCollect(String s) {\n Map m = JSONObject.parseObject(s);\n return m;\n }\n\n /**\n * 将map转化为string\n *\n * @param m\n * @return\n */\n public static String collectToString(Map m) {\n String s = JSONObject.toJSONString(m);\n return s;\n }\n\n\n}" } ]
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.AdditionalSetTypeFolderModel; import com.lazycoder.utils.JsonUtil; import java.lang.reflect.Type;
1,796
package com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.deserializer; public class AdditionalSetTypeFolderModelDeserializer implements ObjectDeserializer { @Override
package com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.deserializer; public class AdditionalSetTypeFolderModelDeserializer implements ObjectDeserializer { @Override
public AdditionalSetTypeFolderModel deserialze(DefaultJSONParser parser, Type type, Object o) {
0
2023-11-16 11:55:06+00:00
4k
hardingadonis/miu-shop
src/main/java/io/hardingadonis/miu/controller/admin/AddNewProduct.java
[ { "identifier": "Product", "path": "src/main/java/io/hardingadonis/miu/model/Product.java", "snippet": "public class Product {\n\n private int ID;\n private String brand;\n private String name;\n private int categoryID;\n private String origin;\n private String expiryDate;\n private String weight;\n private String preservation;\n private long price;\n private int amount;\n private String thumbnail;\n private List<String> images;\n private LocalDateTime createAt;\n private LocalDateTime updateAt;\n private LocalDateTime deleteAt;\n\n public Product() {\n }\n\n public Product(String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images) {\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n }\n\n public Product(String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images, LocalDateTime createAt, LocalDateTime updateAt, LocalDateTime deleteAt) {\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n this.createAt = createAt;\n this.updateAt = updateAt;\n this.deleteAt = deleteAt;\n }\n\n public Product(int ID, String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images, LocalDateTime createAt, LocalDateTime updateAt, LocalDateTime deleteAt) {\n this.ID = ID;\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n this.createAt = createAt;\n this.updateAt = updateAt;\n this.deleteAt = deleteAt;\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 String getBrand() {\n return brand;\n }\n\n public void setBrand(String brand) {\n this.brand = brand;\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 getCategoryID() {\n return categoryID;\n }\n\n public void setCategoryID(int categoryID) {\n this.categoryID = categoryID;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n }\n\n public String getExpiryDate() {\n return expiryDate;\n }\n\n public void setExpiryDate(String expiryDate) {\n this.expiryDate = expiryDate;\n }\n\n public String getWeight() {\n return weight;\n }\n\n public void setWeight(String weight) {\n this.weight = weight;\n }\n\n public String getPreservation() {\n return preservation;\n }\n\n public void setPreservation(String preservation) {\n this.preservation = preservation;\n }\n\n public long getPrice() {\n return price;\n }\n\n public void setPrice(long price) {\n this.price = price;\n }\n\n public int getAmount() {\n return amount;\n }\n\n public void setAmount(int amount) {\n this.amount = amount;\n }\n\n public String getThumbnail() {\n return thumbnail;\n }\n\n public void setThumbnail(String thumbnail) {\n this.thumbnail = thumbnail;\n }\n\n public List<String> getImages() {\n return images;\n }\n\n public void setImages(List<String> images) {\n this.images = images;\n }\n\n public LocalDateTime getCreateAt() {\n return createAt;\n }\n\n public void setCreateAt(LocalDateTime createAt) {\n this.createAt = createAt;\n }\n\n public LocalDateTime getUpdateAt() {\n return updateAt;\n }\n\n public void setUpdateAt(LocalDateTime updateAt) {\n this.updateAt = updateAt;\n }\n\n public LocalDateTime getDeleteAt() {\n return deleteAt;\n }\n\n public void setDeleteAt(LocalDateTime deleteAt) {\n this.deleteAt = deleteAt;\n }\n\n @Override\n public String toString() {\n return \"Product{\" + \"ID=\" + ID + \", brand=\" + brand + \", name=\" + name + \", categoryID=\" + categoryID + \", origin=\" + origin + \", expiryDate=\" + expiryDate + \", weight=\" + weight + \", preservation=\" + preservation + \", price=\" + price + \", amount=\" + amount + \", thumbnail=\" + thumbnail + \", images=\" + images + \", createAt=\" + createAt + \", updateAt=\" + updateAt + \", deleteAt=\" + deleteAt + '}';\n }\n}" }, { "identifier": "Singleton", "path": "src/main/java/io/hardingadonis/miu/services/Singleton.java", "snippet": "public class Singleton {\n\n public static DBContext dbContext;\n\n public static Email email;\n \n public static AdminDAO adminDAO;\n \n public static CategoryDAO categoryDAO;\n \n public static OrderDAO orderDAO;\n \n public static OrderDataDAO orderDataDAO;\n \n public static ProductDAO productDAO;\n \n public static UserDAO userDAO;\n\n static {\n dbContext = new DBContextMySQLImpl();\n\n email = new EmailGmailImpl();\n \n adminDAO = new AdminDAOMySQLImpl();\n \n categoryDAO = new CategoryDAOMySQLImpl();\n \n orderDAO = new OrderDAOMySQLImpl();\n \n orderDataDAO = new OrderDataDAOMySQLImpl();\n \n productDAO = new ProductDAOMySQLImpl();\n \n userDAO = new UserDAOMySQLImpl();\n }\n}" } ]
import io.hardingadonis.miu.model.Product; import io.hardingadonis.miu.services.Singleton; import java.io.*; import java.time.LocalDateTime; import java.util.Collections; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*;
1,927
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"}) public class AddNewProduct extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String nameProduct = request.getParameter("productName"); String productBrand = request.getParameter("productBrand"); int Category_ID = Integer.parseInt(request.getParameter("productCategoryID")); String productOrigin = request.getParameter("productOrigin"); String productExpiry = request.getParameter("productExpiry"); String productWeight = request.getParameter("productWeight"); String productPreservation = request.getParameter("productPreservation"); long productPrice = Long.parseLong(request.getParameter("productPrice")); int productAmount = Integer.parseInt(request.getParameter("productAmount"));
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"}) public class AddNewProduct extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String nameProduct = request.getParameter("productName"); String productBrand = request.getParameter("productBrand"); int Category_ID = Integer.parseInt(request.getParameter("productCategoryID")); String productOrigin = request.getParameter("productOrigin"); String productExpiry = request.getParameter("productExpiry"); String productWeight = request.getParameter("productWeight"); String productPreservation = request.getParameter("productPreservation"); long productPrice = Long.parseLong(request.getParameter("productPrice")); int productAmount = Integer.parseInt(request.getParameter("productAmount"));
Product product = new Product();
0
2023-11-16 07:15:44+00:00
4k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/device/GasValveView.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put new string value to a property */\n public void put(String name, String value) {\n put(new PropertyValue<String>(name, value));\n }\n\n /** Put new boolean value to a property */\n public void put(String name, boolean value) {\n put(new PropertyValue<Boolean>(name, value));\n }\n\n /** Put new integer value to a property */\n public void put(String name, int value) {\n put(new PropertyValue<Integer>(name, value));\n }\n\n /** Put new long value to a property */\n public void put(String name, long value) {\n put(new PropertyValue<Long>(name, value));\n }\n\n /** Put new float value to a property */\n public void put(String name, float value) {\n put(new PropertyValue<Float>(name, value));\n }\n\n /** Put new double value to a property */\n public void put(String name, double value) {\n put(new PropertyValue<Double>(name, value));\n }\n\n /** Put only bits of value in mask to a property */\n public void putBit(String name, int mask, boolean set) {\n int current = get(name, Integer.class);\n if (set) {\n current |= mask;\n } else {\n current &= ~mask;\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBit(String name, long mask, boolean set) {\n long current = get(name, Long.class);\n if (set) {\n current |= mask;\n } else {\n current &= ~mask;\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBits(String name, int mask, int value) {\n int current = get(name, Integer.class);\n for (int i=0; i<Integer.SIZE; i++) {\n int indexBit = (1 << i);\n if ((mask & indexBit) != 0) {\n if ((value & indexBit) != 0)\n current |= indexBit;\n else\n current &= ~indexBit;\n }\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBits(String name, long mask, long value) {\n long current = get(name, Long.class);\n for (int i=0; i<Long.SIZE; i++) {\n long indexBit = (1 << i);\n if ((mask & indexBit) != 0) {\n if ((value & indexBit) != 0)\n current |= indexBit;\n else\n current &= ~indexBit;\n }\n }\n put(name, current);\n }\n\n /** Get all the property values as list */\n public List<PropertyValue> getAll() {\n // TODO: Consider to return cached list if not changed.\n return getAllInternal();\n }\n\n /** Get all the property values as map */\n public Map<String, PropertyValue> toMap() {\n final List<PropertyValue> props = getAll();\n Map<String, PropertyValue> map = new ArrayMap<>(props.size());\n for (PropertyValue prop : props) {\n map.put(prop.getName(), prop);\n }\n return map;\n }\n\n /** Put all the property value from other map */\n public void putAll(PropertyMap map) {\n putAll(map.getAll());\n }\n\n /** Put all the property value from other map */\n public void putAll(Map<String, PropertyValue> map) {\n putAll(map.values());\n }\n\n /** Put all the property value from other collection */\n public void putAll(Collection<PropertyValue> props) {\n for (PropertyValue prop : props) {\n put(prop);\n }\n }\n\n /** Get a property value */\n public PropertyValue get(String name) {\n return getInternal(name);\n }\n\n /** Put a property value */\n public void put(PropertyValue prop) {\n boolean changed = putInternal(prop);\n if (changed) onChanged();\n }\n\n private long mVersion = 1L;\n private List<WeakReference<Runnable>> mChangeRunnables = new ArrayList<>();\n\n /** @hide */\n public long version() {\n return mVersion;\n }\n\n /** @hide */\n public void addChangeRunnable(Runnable changeRunnable) {\n synchronized (mChangeRunnables) {\n mChangeRunnables.add(new WeakReference<>(changeRunnable));\n }\n }\n\n protected void onChanged() {\n mVersion++;\n\n List<WeakReference<Runnable>> runnables;\n synchronized (mChangeRunnables) {\n runnables = new ArrayList<>(mChangeRunnables);\n }\n\n ListIterator<WeakReference<Runnable>> iter = runnables.listIterator();\n while(iter.hasNext()){\n WeakReference<Runnable> runnable = iter.next();\n if (runnable.get() != null) {\n runnable.get().run();\n } else {\n iter.remove();\n }\n }\n }\n\n protected abstract PropertyValue getInternal(String name);\n protected abstract List<PropertyValue> getAllInternal();\n protected abstract boolean putInternal(PropertyValue prop);\n}" }, { "identifier": "HomeDeviceView", "path": "app/src/main/java/kr/or/kashi/hde/widget/HomeDeviceView.java", "snippet": "public class HomeDeviceView<T extends HomeDevice> extends LinearLayout implements HomeDevice.Callback {\n private static final String TAG = HomeDeviceView.class.getSimpleName();\n private final Context mContext;\n protected T mDevice;\n protected boolean mIsSlave;\n\n public HomeDeviceView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n mContext = context;\n mIsSlave = (LocalPreferences.getInt(LocalPreferences.Pref.MODE_INDEX) == 1);\n }\n\n public boolean isMaster() {\n return !isSlave();\n }\n\n public boolean isSlave() {\n return mIsSlave;\n }\n\n @Override\n protected void onFinishInflate () {\n super.onFinishInflate();\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n\n if (mDevice != null) {\n mDevice.addCallback(this);\n final PropertyMap props = mDevice.getReadPropertyMap();\n onUpdateProperty(props, props);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n\n if (mDevice != null) {\n mDevice.removeCallback(this);\n }\n }\n\n @Override\n public void onPropertyChanged(HomeDevice device, PropertyMap props) {\n onUpdateProperty(mDevice.getReadPropertyMap(), props);\n }\n\n @Override\n public void onErrorOccurred(HomeDevice device, int error) {\n // No operation\n }\n\n public void onUpdateProperty(PropertyMap props, PropertyMap changed) {\n // Override it\n }\n\n protected T device() {\n return mDevice;\n }\n\n public void setDevice(T device) {\n mDevice = device;\n }\n}" } ]
import android.content.Context; import android.util.AttributeSet; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.RadioGroup; import androidx.annotation.Nullable; import kr.or.kashi.hde.R; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.widget.HomeDeviceView;
2,763
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; public class GasValveView extends HomeDeviceView<GasValve> { private static final String TAG = GasValveView.class.getSimpleName(); private final Context mContext; private CheckBox mGasValveCheck; private RadioGroup mGasValveGroup; private RadioButton mGasValveClosedRadio; private RadioButton mGasValveOpenedRadio; private CheckBox mInductionCheck; private RadioGroup mInductionGroup; private RadioButton mInductionOffRadio; private RadioButton mInductionOnRadio; private CheckBox mExtinguisherCheck; private RadioGroup mExtinguisherGroup; private RadioButton mExtinguisherNormalRadio; private RadioButton mExtinguisherBuzzingRadio; private CheckBox mGasLeakageCheck; private RadioGroup mGasLeakageGroup; private RadioButton mGasLeakageNormalRadio; private RadioButton mGasLeakageDetectedRadio; public GasValveView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; } @Override protected void onFinishInflate () { super.onFinishInflate(); mGasValveCheck = findViewById(R.id.gas_valve_check); mGasValveCheck.setEnabled(isSlave()); mGasValveCheck.setOnClickListener(v -> setSupports()); mGasValveGroup = findViewById(R.id.gas_valve_group); mGasValveClosedRadio = findViewById(R.id.gas_valve_closed_radio); mGasValveClosedRadio.setOnClickListener(v -> setStates()); mGasValveOpenedRadio = findViewById(R.id.gas_valve_opened_radio); mGasValveOpenedRadio.setOnClickListener(v -> setStates()); mInductionCheck = findViewById(R.id.induction_check); mInductionCheck.setEnabled(isSlave()); mInductionCheck.setOnClickListener(v -> setSupports()); mInductionGroup = findViewById(R.id.induction_group); mInductionOffRadio = findViewById(R.id.induction_off_radio); mInductionOffRadio.setOnClickListener(v -> setStates()); mInductionOnRadio = findViewById(R.id.induction_on_radio); mInductionOnRadio.setOnClickListener(v -> setStates()); mExtinguisherCheck = findViewById(R.id.extinguisher_check); mExtinguisherCheck.setEnabled(isSlave()); mExtinguisherCheck.setOnClickListener(v -> setSupports()); mExtinguisherGroup = findViewById(R.id.extinguisher_group); mExtinguisherNormalRadio = findViewById(R.id.extinguisher_normal_radio); mExtinguisherNormalRadio.setOnClickListener(v -> setAlarms()); mExtinguisherBuzzingRadio = findViewById(R.id.extinguisher_buzzing_radio); mExtinguisherBuzzingRadio.setOnClickListener(v -> setAlarms()); mGasLeakageCheck = findViewById(R.id.gas_leakage_check); mGasLeakageCheck.setEnabled(isSlave()); mGasLeakageCheck.setOnClickListener(v -> setSupports()); mGasLeakageGroup = findViewById(R.id.gas_leakage_group); mGasLeakageNormalRadio = findViewById(R.id.gas_leakage_normal_radio); mGasLeakageNormalRadio.setOnClickListener(v -> setAlarms()); mGasLeakageDetectedRadio = findViewById(R.id.gas_leakage_detected_radio); mGasLeakageDetectedRadio.setOnClickListener(v -> setAlarms()); } @Override
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; public class GasValveView extends HomeDeviceView<GasValve> { private static final String TAG = GasValveView.class.getSimpleName(); private final Context mContext; private CheckBox mGasValveCheck; private RadioGroup mGasValveGroup; private RadioButton mGasValveClosedRadio; private RadioButton mGasValveOpenedRadio; private CheckBox mInductionCheck; private RadioGroup mInductionGroup; private RadioButton mInductionOffRadio; private RadioButton mInductionOnRadio; private CheckBox mExtinguisherCheck; private RadioGroup mExtinguisherGroup; private RadioButton mExtinguisherNormalRadio; private RadioButton mExtinguisherBuzzingRadio; private CheckBox mGasLeakageCheck; private RadioGroup mGasLeakageGroup; private RadioButton mGasLeakageNormalRadio; private RadioButton mGasLeakageDetectedRadio; public GasValveView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; } @Override protected void onFinishInflate () { super.onFinishInflate(); mGasValveCheck = findViewById(R.id.gas_valve_check); mGasValveCheck.setEnabled(isSlave()); mGasValveCheck.setOnClickListener(v -> setSupports()); mGasValveGroup = findViewById(R.id.gas_valve_group); mGasValveClosedRadio = findViewById(R.id.gas_valve_closed_radio); mGasValveClosedRadio.setOnClickListener(v -> setStates()); mGasValveOpenedRadio = findViewById(R.id.gas_valve_opened_radio); mGasValveOpenedRadio.setOnClickListener(v -> setStates()); mInductionCheck = findViewById(R.id.induction_check); mInductionCheck.setEnabled(isSlave()); mInductionCheck.setOnClickListener(v -> setSupports()); mInductionGroup = findViewById(R.id.induction_group); mInductionOffRadio = findViewById(R.id.induction_off_radio); mInductionOffRadio.setOnClickListener(v -> setStates()); mInductionOnRadio = findViewById(R.id.induction_on_radio); mInductionOnRadio.setOnClickListener(v -> setStates()); mExtinguisherCheck = findViewById(R.id.extinguisher_check); mExtinguisherCheck.setEnabled(isSlave()); mExtinguisherCheck.setOnClickListener(v -> setSupports()); mExtinguisherGroup = findViewById(R.id.extinguisher_group); mExtinguisherNormalRadio = findViewById(R.id.extinguisher_normal_radio); mExtinguisherNormalRadio.setOnClickListener(v -> setAlarms()); mExtinguisherBuzzingRadio = findViewById(R.id.extinguisher_buzzing_radio); mExtinguisherBuzzingRadio.setOnClickListener(v -> setAlarms()); mGasLeakageCheck = findViewById(R.id.gas_leakage_check); mGasLeakageCheck.setEnabled(isSlave()); mGasLeakageCheck.setOnClickListener(v -> setSupports()); mGasLeakageGroup = findViewById(R.id.gas_leakage_group); mGasLeakageNormalRadio = findViewById(R.id.gas_leakage_normal_radio); mGasLeakageNormalRadio.setOnClickListener(v -> setAlarms()); mGasLeakageDetectedRadio = findViewById(R.id.gas_leakage_detected_radio); mGasLeakageDetectedRadio.setOnClickListener(v -> setAlarms()); } @Override
public void onUpdateProperty(PropertyMap props, PropertyMap changed) {
0
2023-11-10 01:19:44+00:00
4k
Bug1312/dm_locator
src/main/java/com/bug1312/dm_locator/mixins/TriggerWaypointWrite.java
[ { "identifier": "Register", "path": "src/main/java/com/bug1312/dm_locator/Register.java", "snippet": "public class Register {\n\t// Items\n\tpublic static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID);\n\tpublic static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, \"locator_data_writer\", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1)));\n\tpublic static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, \"locator_attachment\", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS)));\n\t\n\t// Tiles\n\tpublic static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<TileEntityType<?>> FLIGHT_PANEL_TILE = register(TILE_ENTITIES, \"flight_panel\", () -> Builder.of(FlightPanelTileEntity::new, DMBlocks.FLIGHT_PANEL.get()).build(null));\n\n // Loot Modifiers\n\tpublic static final DeferredRegister<GlobalLootModifierSerializer<?>> LOOT_MODIFIERS = DeferredRegister.create(ForgeRegistries.LOOT_MODIFIER_SERIALIZERS, ModMain.MOD_ID);\n public static final RegistryObject<FlightPanelLootModifier.Serializer> FLIGHT_PANEL_LOOT_MODIFIER = register(LOOT_MODIFIERS, \"flight_panel\", FlightPanelLootModifier.Serializer::new);\n\n\t// Particles\n\tpublic static final DeferredRegister<ParticleType<?>> PARTICLE_TYPES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<ParticleType<LocateParticleData>> LOCATE_PARTICLE = register(PARTICLE_TYPES, \"locate\", () -> \n\t\tnew ParticleType<LocateParticleData>(false, LocateParticleData.DESERIALIZER) {\n\t\t\tpublic Codec<LocateParticleData> codec() { return LocateParticleData.CODEC;\t}\n\t\t}\n\t);\n\t\n\t// Advancement Triggers\n\tpublic static final WriteModuleTrigger TRIGGER_WRITE = CriteriaTriggers.register(new WriteModuleTrigger());\n\tpublic static final UseLocatorTrigger TRIGGER_USE = CriteriaTriggers.register(new UseLocatorTrigger());\n\n\t// Key Binds\n public static final KeyBinding KEYBIND_LOCATE = new KeyBinding(String.format(\"%s.keybinds.locate_blast\", ModMain.MOD_ID), 66, \"Dalek Mod\"); // B\n \n // Translations\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_SWAP_MODE = (m) -> new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.swap_mode.%s\", ModMain.MOD_ID, m));\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_TOOLTIP_MODE = (m) -> new TranslationTextComponent(String.format(\"item.%s.locator_data_writer.hover.mode.%s\", ModMain.MOD_ID, m));\n public static final TranslationTextComponent TEXT_INSUFFICIENT_FUEL = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.insufficient_fuel\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_structure\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_biome\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_WAYPOINT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_waypoint\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_MODULE = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_module\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_structures\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_biome\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_MODULES = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_modules\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_MODULE_WRITTEN = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.module_written\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_LOAD = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.load\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_EJECT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.eject\", ModMain.MOD_ID));\n public static final Supplier<TranslationTextComponent> TEXT_USE_BUTTON = () -> new TranslationTextComponent(String.format(\"overlay.%s.flight_mode.use_button\", ModMain.MOD_ID), new KeybindTextComponent(Register.KEYBIND_LOCATE.getName()));\n public static final BiFunction<LocatorDataWriterMode, String, TranslationTextComponent> TEXT_MODULE_NAME = (m, s) -> new TranslationTextComponent(String.format(\"name.%s.structure_module.%s\", ModMain.MOD_ID, m), s);\n\n // Register Method\n\tpublic static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> register(final DeferredRegister<T> register, final String name, final Supplier<U> supplier) {\n\t\treturn register.register(name, supplier);\n\t}\n}" }, { "identifier": "WriteModuleType", "path": "src/main/java/com/bug1312/dm_locator/triggers/WriteModuleTrigger.java", "snippet": "public static enum WriteModuleType {\n\tWAYPOINT(\"waypoint\"),\n\tSTRUCTURE(\"structure\"),\n\tBIOME(\"biome\");\n\t\t\n\tprivate String string;\n\tprivate WriteModuleType(String string) { this.string = string; }\n\tpublic String toString() { return string; }\n\t\t\n public static WriteModuleType fromString(String string) {\n for (WriteModuleType enumValue : WriteModuleType.values()) {\n if (enumValue.toString().equalsIgnoreCase(string)) return enumValue;\n }\n return null;\n }\n}" } ]
import java.util.function.Supplier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.bug1312.dm_locator.Register; import com.bug1312.dm_locator.triggers.WriteModuleTrigger.WriteModuleType; import com.swdteam.common.init.DMDimensions; import com.swdteam.common.init.DMItems; import com.swdteam.common.init.DMTardis; import com.swdteam.common.tardis.TardisData; import com.swdteam.common.tileentity.tardis.DataWriterTileEntity; import com.swdteam.network.packets.PacketEjectWaypointCartridge; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketDirection; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.server.ServerWorld; import net.minecraftforge.fml.network.NetworkEvent.Context;
2,024
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator.mixins; @Mixin(PacketEjectWaypointCartridge.class) public abstract class TriggerWaypointWrite implements IPacketEjectWaypointCartridgeAccessor { // An alternative to a mixin is Forge's event for picking up an item. // Or maybe there is a smarter way to mixin where you check Context#enqueueWork only in // PacketEjectWaypointCartridge that checks PacketEjectWaypointCartridge::addLocation @Inject(at = @At("HEAD"), method = "handle", cancellable = false, remap = false) private static void handle(final PacketEjectWaypointCartridge msg, final Supplier<Context> ctx, final CallbackInfo ci) { IPacketEjectWaypointCartridgeAccessor mixinMsg = (IPacketEjectWaypointCartridgeAccessor) ((Object) msg); ctx.get().enqueueWork(() -> { if (ctx.get().getNetworkManager().getDirection() != PacketDirection.SERVERBOUND) return; ServerPlayerEntity player = ctx.get().getSender(); ServerWorld world = player.getServer().getLevel(DMDimensions.TARDIS); if (player == null || world == null) return; TardisData data = DMTardis.getTardisFromInteriorPos(mixinMsg.getBlockPos()); if (data == null || data.getCurrentLocation() == null) return; TileEntity te = world.getBlockEntity(mixinMsg.getBlockPos()); if (te == null || !(te instanceof DataWriterTileEntity)) return; DataWriterTileEntity writer = (DataWriterTileEntity) te; ItemStack stack = writer.cartridge; if (stack != null && stack.getItem() == DMItems.DATA_MODULE.get() && stack.getOrCreateTag().getBoolean("written")) return; if (mixinMsg.getName().startsWith("/")) { String[] args = mixinMsg.getName().split(" ");
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator.mixins; @Mixin(PacketEjectWaypointCartridge.class) public abstract class TriggerWaypointWrite implements IPacketEjectWaypointCartridgeAccessor { // An alternative to a mixin is Forge's event for picking up an item. // Or maybe there is a smarter way to mixin where you check Context#enqueueWork only in // PacketEjectWaypointCartridge that checks PacketEjectWaypointCartridge::addLocation @Inject(at = @At("HEAD"), method = "handle", cancellable = false, remap = false) private static void handle(final PacketEjectWaypointCartridge msg, final Supplier<Context> ctx, final CallbackInfo ci) { IPacketEjectWaypointCartridgeAccessor mixinMsg = (IPacketEjectWaypointCartridgeAccessor) ((Object) msg); ctx.get().enqueueWork(() -> { if (ctx.get().getNetworkManager().getDirection() != PacketDirection.SERVERBOUND) return; ServerPlayerEntity player = ctx.get().getSender(); ServerWorld world = player.getServer().getLevel(DMDimensions.TARDIS); if (player == null || world == null) return; TardisData data = DMTardis.getTardisFromInteriorPos(mixinMsg.getBlockPos()); if (data == null || data.getCurrentLocation() == null) return; TileEntity te = world.getBlockEntity(mixinMsg.getBlockPos()); if (te == null || !(te instanceof DataWriterTileEntity)) return; DataWriterTileEntity writer = (DataWriterTileEntity) te; ItemStack stack = writer.cartridge; if (stack != null && stack.getItem() == DMItems.DATA_MODULE.get() && stack.getOrCreateTag().getBoolean("written")) return; if (mixinMsg.getName().startsWith("/")) { String[] args = mixinMsg.getName().split(" ");
if (args.length > 1 && args[0].equalsIgnoreCase("/add")) Register.TRIGGER_WRITE.trigger(player, WriteModuleType.WAYPOINT);
1
2023-11-13 03:42:37+00:00
4k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/ConfigServerAdapterConfiguration.java
[ { "identifier": "YoungImException", "path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java", "snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImException(final Throwable e) {\n super(e);\n }\n}" }, { "identifier": "ConfigServerConfigurationBind", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/bind/ConfigServerConfigurationBind.java", "snippet": "@AllArgsConstructor\npublic class ConfigServerConfigurationBind implements BeanPostProcessor {\n\n private final ConfigServerRepository configServerRepository;\n\n private final ApplicationContextHolder contextHolder;\n\n /**\n * 实例化前对注解进行处理\n */\n @Override\n public Object postProcessBeforeInitialization(Object bean, @NonNull String beanName) throws BeansException {\n // 1. 提取注解\n ConfigServerConfigurationProperties annotation =\n AnnotationUtils.findAnnotation(bean.getClass(), ConfigServerConfigurationProperties.class);\n\n // 2. 排除非配置 Bean\n if (Objects.isNull(annotation)) {\n return bean;\n }\n\n // 3. 存在注解开始绑定\n bind(bean, beanName, annotation);\n\n return bean;\n }\n\n /**\n * 属性与系统绑定\n */\n\n private void bind(final Object bean, final String beanName,\n final ConfigServerConfigurationProperties annotation) {\n\n // 1. 提取属性\n final String dataId = annotation.configKey();\n final String groupId = annotation.groupId();\n final String type = deduceConfigType(annotation);\n final ConfigRefreshCallBack callBack =\n (ConfigRefreshCallBack) contextHolder.getContext().getBean(annotation.callbackClazz());\n\n // 2. 解析属性\n String content = configServerRepository.getConfig(dataId, groupId);\n\n // 把配置文件塞进属性 (handler) + callback\n IConfigParseHandler handler = ConfigParseFactory.acquireHandler(type);\n handler.parse(content, bean);\n\n // 3. 自动刷新监听器注册\n if (annotation.autoRefreshed()) {\n try {\n configServerRepository.getConfigService().addListener(dataId, groupId, new AbstractListener() {\n final String _beanName = beanName;\n final ApplicationContextHolder _contextHolder = contextHolder;\n final ConfigRefreshCallBack _callBack = callBack;\n final String _type = type;\n\n @Override\n public void receiveConfigInfo(String configInfo) {\n // 1. 提取配置 Bean\n Object originBean = _contextHolder.getContext().getBean(_beanName);\n\n // 2. 提取处理器\n IConfigParseHandler handler = ConfigParseFactory.acquireHandler(_type);\n\n // 3. 执行处理\n handler.parse(configInfo, originBean);\n\n // 4. 触发回调\n _callBack.refresh();\n }\n });\n } catch (NacosException e) {\n throw new YoungImException(\"listener init occur error, config bean is :\" + beanName);\n }\n }\n }\n\n /**\n * 推断 Config Type\n */\n private String deduceConfigType(final ConfigServerConfigurationProperties annotation) {\n String type;\n ConfigType configType = annotation.type();\n\n // 处理未设情况 (尝)\n if (ConfigType.UNSET.equals(configType)) {\n String dataId = annotation.configKey();\n // 没有设置就取ConfigKey的后缀名,没有直接报错\n int dotIndex = dataId.lastIndexOf(\".\");\n if (dotIndex == -1) {\n throw new YoungImException(\"please set config type with @\" + ConfigServerConfigurationProperties.class.getName());\n }\n // 判断 dataId 截取后缀的合法性\n String subjectType = dataId.substring(dotIndex + 1);\n type = ConfigType.isValidType(subjectType) ? subjectType : ConfigType.getDefaultType().getType();\n } else {\n type = configType.getType();\n }\n return type;\n }\n}" }, { "identifier": "EmptyConfigRefreshCallBack", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/callback/EmptyConfigRefreshCallBack.java", "snippet": "public class EmptyConfigRefreshCallBack implements ConfigRefreshCallBack {\n /**\n * 当配置刷新以后没有特殊的设置回调方法\n * 会走当前空的回调实现\n */\n @Override\n public void refresh() {\n }\n}" }, { "identifier": "ConfigServerRepository", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/repository/ConfigServerRepository.java", "snippet": "public interface ConfigServerRepository {\n\n String getConfig(String configKey, String groupId);\n\n\n ConfigService getConfigService();\n}" }, { "identifier": "NacosConfigServerRepository", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/repository/NacosConfigServerRepository.java", "snippet": "@Slf4j\n@AllArgsConstructor\npublic class NacosConfigServerRepository implements ConfigServerRepository {\n\n private final ConfigService configService;\n\n @Override\n public String getConfig(String configKey, String groupId) {\n try {\n return configService.getConfig(configKey, groupId, 5000);\n } catch (NacosException e) {\n log.error(e.getErrMsg(), e);\n }\n return null;\n }\n\n @Override\n public ConfigService getConfigService() {\n return configService;\n }\n}" }, { "identifier": "ApplicationContextHolder", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-extension/src/main/java/cn/young/im/springboot/starter/extension/spring/ApplicationContextHolder.java", "snippet": "@Data\npublic class ApplicationContextHolder implements ApplicationContextAware {\n\n /**\n * Application Context\n */\n private ApplicationContext context;\n\n @Override\n public void setApplicationContext(ApplicationContext context) throws BeansException {\n this.context = context;\n }\n}" } ]
import cn.young.im.common.exception.YoungImException; import cn.young.im.springboot.starter.adapter.config.bind.ConfigServerConfigurationBind; import cn.young.im.springboot.starter.adapter.config.callback.EmptyConfigRefreshCallBack; import cn.young.im.springboot.starter.adapter.config.repository.ConfigServerRepository; import cn.young.im.springboot.starter.adapter.config.repository.NacosConfigServerRepository; import cn.young.im.springboot.starter.extension.spring.ApplicationContextHolder; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties;
1,997
package cn.young.im.springboot.starter.adapter.config; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 配置中心适配层自动装配 * @date 2023/12/16 */ @Slf4j @Configuration public class ConfigServerAdapterConfiguration { /** * 配置中心仓储 */ @Bean public ConfigServerRepository configServerRepository( @Value("${young.im.config.configServerType}") String configServerType) { ConfigServerRepository repository = null; switch (configServerType) { case "nacos": repository = new NacosConfigServerRepository(createNacosConfigService()); break; case "apollo": break; } return repository; } /** * 配置绑定器 */ @Bean public ConfigServerConfigurationBind configServerConfigurationBind( ObjectProvider<ConfigServerRepository> repositoryProvider, ApplicationContextHolder contextHolder) { return new ConfigServerConfigurationBind(repositoryProvider.getIfAvailable(), contextHolder); } /** * 空的配置文件回调实现 */ @Bean
package cn.young.im.springboot.starter.adapter.config; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 配置中心适配层自动装配 * @date 2023/12/16 */ @Slf4j @Configuration public class ConfigServerAdapterConfiguration { /** * 配置中心仓储 */ @Bean public ConfigServerRepository configServerRepository( @Value("${young.im.config.configServerType}") String configServerType) { ConfigServerRepository repository = null; switch (configServerType) { case "nacos": repository = new NacosConfigServerRepository(createNacosConfigService()); break; case "apollo": break; } return repository; } /** * 配置绑定器 */ @Bean public ConfigServerConfigurationBind configServerConfigurationBind( ObjectProvider<ConfigServerRepository> repositoryProvider, ApplicationContextHolder contextHolder) { return new ConfigServerConfigurationBind(repositoryProvider.getIfAvailable(), contextHolder); } /** * 空的配置文件回调实现 */ @Bean
public EmptyConfigRefreshCallBack emptyConfigRefreshCallBack() {
2
2023-11-10 06:21:17+00:00
4k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java
[ { "identifier": "WidgetManager", "path": "src/main/java/io/xlorey/FluxLoader/client/core/WidgetManager.java", "snippet": "public class WidgetManager {\n /**\n * Pointer to the game window\n */\n private static final long windowHandler = Display.getWindow();\n\n /**\n * Implementation of ImGui GLFW\n */\n private final static ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw();\n\n /**\n * Implementation of ImGui GL3\n */\n private final static ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3();\n\n /**\n * Flag indicating the initialization state of ImGui\n */\n private static boolean isImGuiInit = false;\n\n /**\n * A register of all UI elements that should be rendered\n */\n public static ArrayList<IWidget> widgetsRegistry = new ArrayList<>();\n\n /**\n * Flag showing mouse capture for ImGui widgets (prevents events for standard UI)\n */\n private static boolean isMouseCapture = false;\n\n /**\n * Change mouse capture state for ImGui widgets. Used only inside widgets via the captureMouseFocus method\n */\n public static void captureMouse() {\n isMouseCapture = true;\n }\n\n /**\n * Returns the value of the mouse capture flag.\n * @return true if the mouse is captured, false otherwise.\n */\n public static boolean isMouseCapture() {\n return isMouseCapture;\n }\n\n /**\n * Release the mouse from being captured by ImGui widgets\n */\n public static void releaseMouse() {\n isMouseCapture = false;\n }\n\n /**\n * Initializing the UI Manager\n */\n public static void init(){\n RenderThread.invokeOnRenderContext(WidgetManager::initImGui);\n loadPluginsMenu();\n }\n\n /**\n * Initializing the ImGui context\n */\n private static void initImGui() {\n ImGui.createContext();\n\n ImGuiIO io = ImGui.getIO();\n // Preventing UI Elements from Saving State\n io.setIniFilename(null);\n\n imGuiGlfw.init(windowHandler, true);\n imGuiGl3.init(\"#version 130\");\n\n isImGuiInit = true;\n }\n\n /**\n * Loading a custom plugin management menu\n */\n private static void loadPluginsMenu() {\n MainMenuButton screenMenuButton = new MainMenuButton();\n screenMenuButton.addToScreenDraw();\n\n PluginMenu pluginMenu = new PluginMenu();\n pluginMenu.addToScreenDraw();\n }\n /**\n * FluxLoader credits rendering update\n */\n public static void drawCredits(){\n UIFont font = UIFont.Small;\n int margin = 15;\n int screenHeight = Core.getInstance().getScreenHeight();\n int fontHeight = TextTools.getFontHeight(font);\n String creditsText = String.format(\"Modded with %s (v%s)\", Constants.FLUX_NAME, Constants.FLUX_VERSION);\n TextTools.drawText(creditsText, font, margin, screenHeight - fontHeight - margin, 1f, 1f, 1f, 0.5f);\n }\n\n /**\n * Updating the UI manager to render its components\n */\n public static void update() {\n if (GameWindow.states.current instanceof MainScreenState){\n drawCredits();\n }\n }\n\n /**\n * Handling drawing of ImGui elements\n */\n public static void drawImGui() {\n if (!isImGuiInit) return;\n\n imGuiGlfw.newFrame();\n ImGui.newFrame();\n\n boolean isScreenWidgetHovered = false;\n\n for (IWidget widget : widgetsRegistry) {\n widget.update();\n\n if (widget.isVisible()) {\n widget.render();\n }\n if (widget instanceof ScreenWidget screenWidget) {\n if(screenWidget.isWidgetHovered()) {\n isScreenWidgetHovered = true;\n captureMouse();\n }\n }\n }\n\n if (!isScreenWidgetHovered) {\n releaseMouse();\n }\n\n ImGui.render();\n\n imGuiGl3.renderDrawData(ImGui.getDrawData());\n }\n}" }, { "identifier": "IWidget", "path": "src/main/java/io/xlorey/FluxLoader/interfaces/IWidget.java", "snippet": "public interface IWidget {\n /**\n * Update the widget state.\n * This method is called before the main rendering of the widget\n */\n void update();\n /**\n * Render the widget.\n * This method should contain the logic for drawing the widget on the screen.\n */\n void render();\n\n /**\n * Check if the widget is currently visible on the screen.\n * This method should return true if the widget is visible and false otherwise.\n * @return boolean - true if the widget is visible, false if it is not.\n */\n boolean isVisible();\n\n /**\n * Set the visibility of the widget.\n * @param visible boolean - the desired visibility state of the widget.\n * True to make the widget visible, false to hide it.\n */\n void setVisible(boolean visible);\n}" } ]
import imgui.ImGui; import imgui.ImVec2; import io.xlorey.FluxLoader.client.core.WidgetManager; import io.xlorey.FluxLoader.interfaces.IWidget; import java.util.ArrayList;
1,648
package io.xlorey.FluxLoader.client.ui; /** * A basic UI widget class that can be added to display on screen independently of other widgets */ public class ScreenWidget implements IWidget { /** * Flag indicating whether the mouse cursor is inside the widget */ private boolean isWidgetHovered = false; /** * Flag indicating whether the widget is displayed */ private boolean isVisible = true; /** * Registry of child widgets, in which the state update method will be called */ private final ArrayList<ComponentWidget> registryChildWidgets = new ArrayList<>(); /** * Adding a widget to the registry of child components to update its state (call the update method) * @param widget custom component widget */ public void addChild(ComponentWidget widget) { registryChildWidgets.add(widget); } /** * Removing a widget from the registry of child components so as not to update its state (call the update method) * @param widget custom component widget */ public void removeChild(ComponentWidget widget) { registryChildWidgets.add(widget); } /** * Update the widget state. * This method is called before the main rendering of the widget */ @Override public void update() { if (!isVisible()) { isWidgetHovered = false; } for (ComponentWidget widget : registryChildWidgets) { widget.update(); } } /** * Rendering a custom element */ @Override public void render() { } /** * Add this widget to the screen draw queue. * Invoking this method will schedule the widget for rendering on the screen. * It should be used to register the widget in a way that it becomes visible and active. */ public void addToScreenDraw() {
package io.xlorey.FluxLoader.client.ui; /** * A basic UI widget class that can be added to display on screen independently of other widgets */ public class ScreenWidget implements IWidget { /** * Flag indicating whether the mouse cursor is inside the widget */ private boolean isWidgetHovered = false; /** * Flag indicating whether the widget is displayed */ private boolean isVisible = true; /** * Registry of child widgets, in which the state update method will be called */ private final ArrayList<ComponentWidget> registryChildWidgets = new ArrayList<>(); /** * Adding a widget to the registry of child components to update its state (call the update method) * @param widget custom component widget */ public void addChild(ComponentWidget widget) { registryChildWidgets.add(widget); } /** * Removing a widget from the registry of child components so as not to update its state (call the update method) * @param widget custom component widget */ public void removeChild(ComponentWidget widget) { registryChildWidgets.add(widget); } /** * Update the widget state. * This method is called before the main rendering of the widget */ @Override public void update() { if (!isVisible()) { isWidgetHovered = false; } for (ComponentWidget widget : registryChildWidgets) { widget.update(); } } /** * Rendering a custom element */ @Override public void render() { } /** * Add this widget to the screen draw queue. * Invoking this method will schedule the widget for rendering on the screen. * It should be used to register the widget in a way that it becomes visible and active. */ public void addToScreenDraw() {
if (WidgetManager.widgetsRegistry.contains(this)) return;
0
2023-11-16 09:05:44+00:00
4k
EmonerRobotics/2023Robot
src/main/java/frc/robot/subsystems/LiftSubsystem.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final double GROUNDH = 0;\n public static final double MIDH = 0.46; \n public static final double TOPH = 1.45;\n public static final double HUMANPH = 1.37;\n public static final double LiftAllowedError = 0.005;\n }\n\n public final class IntakeMeasurements{\n public static final double IntakeClosedD = 0;\n public static final double IntakeHalfOpenD = 3.5;\n public static final double IntakeStraightOpenD = 7.6;\n public static final double IntakeStraightOpenHD = 8;\n public static final double IntakeAllowedError = 0.05;\n }\n\n public final class Limelight{\n public static final double BetweenHuman = 0.85;\n }\n\n public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n }\n\n\n public static final class DriveConstants {\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n public static final double MAX_SPEED_METERS_PER_SECOND = 4.8;\n public static final double MAX_ANGULAR_SPEED = 2 * Math.PI; // radians per second\n\n // Chassis configuration\n public static final double TRACK_WIDTH = Units.inchesToMeters(22.5);\n // Distance between centers of right and left wheels on robot\n public static final double WHEEL_BASE = Units.inchesToMeters(24.5);\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics DRIVE_KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(WHEEL_BASE / 2, -TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, -TRACK_WIDTH / 2));\n\n // Angular offsets of the modules relative to the chassis in radians\n public static final double FRONT_LEFT_CHASSIS_ANGULAR_OFFSET = -Math.PI / 2;\n public static final double FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET = 0;\n public static final double REAR_LEFT_CHASSIS_ANGULAR_OFFSET = Math.PI;\n public static final double REAR_RIGHT_CHASSIS_ANGULAR_OFFSET = Math.PI / 2;\n\n // Charge Station Constants\n public static final double CHARGE_TIPPING_ANGLE= Math.toRadians(12);\n public static final double CHARGE_TOLERANCE = Math.toRadians(2.5);\n public static final double CHARGE_MAX_SPEED = 0.8;\n public static final double CHARGE_REDUCED_SPEED = 0.70;\n\n // Delay between reading the gyro and using the value used to aproximate exact angle while spinning (0.02 is one loop)\n public static final double GYRO_READ_DELAY = 0.02;\n\n // SPARK MAX CAN IDs\n public static final int FRONT_LEFT_DRIVING_CAN_ID = 7; //7\n public static final int REAR_LEFT_DRIVING_CAN_ID = 4; //4\n public static final int FRONT_RIGHT_DRIVING_CAN_ID = 10; //10\n public static final int REAR_RIGHT_DRIVING_CAN_ID = 8; //8\n\n public static final int FRONT_LEFT_TURNING_CAN_ID = 2; //2\n public static final int REAR_LEFT_TURNING_CAN_ID = 1; //1\n public static final int FRONT_RIGHT_TURNING_CAN_ID = 3; //3\n public static final int REAR_RIGHT_TURNING_CAN_ID = 6; //6\n\n public static final boolean GYRO_REVERSED = false;\n public static final Rotation3d GYRO_ROTATION = new Rotation3d(0, 0, - Math.PI / 2);\n\n public static final Vector<N3> ODOMETRY_STD_DEV = VecBuilder.fill(0.05, 0.05, 0.01);\n }\n\n\n public static final class ModuleConstants {\n // The MAXSwerve module can be configured with one of three pinion gears: 12T, 13T, or 14T.\n // This changes the drive speed of the module (a pinion gear with more teeth will result in a\n // robot that drives faster).\n public static final int DRIVING_MOTOR_PINION_TEETH = 12;\n\n // Invert the turning encoder, since the output shaft rotates in the opposite direction of\n // the steering motor in the MAXSwerve Module.\n public static final boolean TURNING_ENCODER_INVERTED = true;\n\n // Calculations required for driving motor conversion factors and feed forward\n public static final double DRIVING_MOTOR_FREE_SPEED_RPS = NeoMotorConstants.FREE_SPEED_RPM / 60;\n public static final double WHEEL_DIAMETER_METERS = Units.inchesToMeters(3);\n public static final double WHEEL_CIRCUMFERENCE_METERS = WHEEL_DIAMETER_METERS * Math.PI;\n // 45 teeth on the wheel's bevel gear, 22 teeth on the first-stage spur gear, 15 teeth on the bevel pinion\n public static final double DRIVING_MOTOR_REDUCTION = (45.0 * 22) / (DRIVING_MOTOR_PINION_TEETH * 15);\n public static final double DRIVE_WHEEL_FREE_SPEED_RPS = (DRIVING_MOTOR_FREE_SPEED_RPS * WHEEL_CIRCUMFERENCE_METERS)\n / DRIVING_MOTOR_REDUCTION;\n\n public static final double DRIVING_ENCODER_POSITION_FACTOR = WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION; // meters\n public static final double DRIVING_ENCODER_VELOCITY_FACTOR = (WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION) / 60.0; // meters per second\n\n public static final double TURNING_ENCODER_POSITION_FACTOR = (2 * Math.PI); // radians\n public static final double TURNING_ENCODER_VELOCITY_FACTOR = (2 * Math.PI) / 60.0; // radians per second\n\n public static final double TURNING_ENCODER_POSITION_PID_MIN_INPUT = 0; // radians\n public static final double TURNING_ENCODER_POSITION_PID_MAX_INPUT = TURNING_ENCODER_POSITION_FACTOR; // radians\n\n public static final double DRIVING_P = 0.04;\n public static final double DRIVING_I = 0;\n public static final double DRIVING_D = 0;\n public static final double DRIVING_FF = 1 / DRIVE_WHEEL_FREE_SPEED_RPS;\n public static final double DRIVING_MIN_OUTPUT = -1;\n public static final double DRIVING_MAX_OUTPUT = 1;\n\n public static final double TURNING_P = 2;\n public static final double TURNING_I = 0;\n public static final double TURNING_D = 0;\n public static final double TURNING_FF = 0;\n public static final double TURNING_MIN_OUTPUT = -1;\n public static final double TURNING_MAX_OUTPUT = 1;\n\n public static final CANSparkMax.IdleMode DRIVING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n public static final CANSparkMax.IdleMode TURNING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n\n public static final int DRIVING_MOTOR_CURRENT_LIMIT = 20; // amps\n public static final int TURNING_MOTOR_CURRENT_LIMIT = 15; // amps\n }\n\n public static final class NeoMotorConstants {\n public static final double FREE_SPEED_RPM = 5676;\n }\n\n public static class FieldConstants {\n public static final double fieldLength = Units.inchesToMeters(651.25);\n public static final double fieldWidth = Units.inchesToMeters(315.5);\n public static final double tapeWidth = Units.inchesToMeters(2.0);\n public static final double aprilTagWidth = Units.inchesToMeters(6.0);\n }\n \n public static class VisionConstants {\n // FIXME: actually measure these constants\n\n public static final Transform3d PHOTONVISION_TRANSFORM = new Transform3d(\n new Translation3d(0.205697, -0.244475, 0.267365),\n new Rotation3d(0, Units.degreesToRadians(15), 0)\n );\n\n public static final Vector<N3> PHOTONVISION_STD_DEV = VecBuilder.fill(0.7, 0.7, 0.5);\n\n public static final Vector<N3> LIMELIGHT_STD_DEV = VecBuilder.fill(0.9, 0.9, 0.9);\n\n public static final double AMBIGUITY_FILTER = 0.05;\n }\n\n public static final class AutoConstants {\n public static final HashMap<String, Command> autoEventMap = new HashMap<>();\n public static final double MAX_SPEED_METERS_PER_SECOND = 3;\n public static final double MAX_ACCELERATION_METERS_PER_SECOND_SQUARED = 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND = Math.PI * 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED = Math.PI * 2;\n\n public static final double P_TRANSLATION_PATH_CONTROLLER = 1;\n public static final double P_THETA_PATH_CONTROLLER = 1;\n\n public static final double P_TRANSLATION_POINT_CONTROLLER = 4;\n public static final double P_THETA_POINT_CONTROLLER = 6;\n\n public static final double TRANSLATION_TOLERANCE = 0.02;\n public static final Rotation2d THETA_TOLERANCE = Rotation2d.fromDegrees(1);\n\n // Constraint for the motion profiled robot angle controller\n public static final TrapezoidProfile.Constraints THETA_CONTROLLER_CONSTRAINTS = new TrapezoidProfile.Constraints(\n MAX_ANGULAR_SPEED_RADIANS_PER_SECOND, MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED);\n\n public static final Transform2d NODE_HIGH_TRANSFORM = new Transform2d(\n new Translation2d(-1, 0),\n Rotation2d.fromRadians(Math.PI)\n );\n}\n}" }, { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n}" } ]
import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.Constants.IntakeConstants;
3,375
// 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.subsystems; public class LiftSubsystem extends SubsystemBase { private PWMVictorSPX liftMotor; private Encoder liftEncoder; public LiftSubsystem() { //redline motor
// 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.subsystems; public class LiftSubsystem extends SubsystemBase { private PWMVictorSPX liftMotor; private Encoder liftEncoder; public LiftSubsystem() { //redline motor
liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1);
1
2023-11-18 14:02:20+00:00
4k
backend-source/ecommerce-microservice-architecture
favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/service/impl/FavouriteServiceImpl.java
[ { "identifier": "AppConstant", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/constant/AppConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic abstract class AppConstant {\n public static final String LOCAL_DATE_FORMAT = \"dd-MM-yyyy\";\n public static final String LOCAL_DATE_TIME_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n public static final String ZONED_DATE_TIME_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n public static final String INSTANT_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public abstract static class DiscoveredDomainsApi {\n\n public static final String USER_SERVICE_HOST = \"http://USER-SERVICE/user-service\";\n public static final String USER_SERVICE_API_URL = \"http://USER-SERVICE/user-service/api/users\";\n\n public static final String PRODUCT_SERVICE_HOST = \"http://PRODUCT-SERVICE/product-service\";\n public static final String PRODUCT_SERVICE_API_URL = \"http://PRODUCT-SERVICE/product-service/api/products\";\n\n public static final String ORDER_SERVICE_HOST = \"http://ORDER-SERVICE/order-service\";\n public static final String ORDER_SERVICE_API_URL = \"http://ORDER-SERVICE/order-service/api/orders\";\n\n public static final String FAVOURITE_SERVICE_HOST = \"http://FAVOURITE-SERVICE/favourite-service\";\n public static final String FAVOURITE_SERVICE_API_URL = \"http://FAVOURITE-SERVICE/favourite-service/api/favourites\";\n\n public static final String PAYMENT_SERVICE_HOST = \"http://PAYMENT-SERVICE/payment-service\";\n public static final String PAYMENT_SERVICE_API_URL = \"http://PAYMENT-SERVICE/payment-service/api/payments\";\n\n public static final String SHIPPING_SERVICE_HOST = \"http://SHIPPING-SERVICE/shipping-service\";\n public static final String SHIPPING_SERVICE_API_URL = \"http://SHIPPING-SERVICE/shipping-service/api/shippings\";\n }\n}" }, { "identifier": "FavouriteId", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/domain/id/FavouriteId.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\npublic class FavouriteId implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @NotNull\n private Integer userId;\n\n @NotNull\n private Integer productId;\n\n @NotNull\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT, shape = Shape.STRING)\n @DateTimeFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT)\n private LocalDateTime likeDate;\n\n}" }, { "identifier": "FavouriteDto", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/dto/FavouriteDto.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class FavouriteDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @NotNull(message = \"Field must not be NULL\")\n private Integer userId;\n\n @NotNull(message = \"Field must not be NULL\")\n private Integer productId;\n\n @NotNull(message = \"Field must not be NULL\")\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING)\n @DateTimeFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT)\n private LocalDateTime likeDate;\n\n @JsonProperty(\"user\")\n @JsonInclude(Include.NON_NULL)\n private UserDto userDto;\n\n @JsonProperty(\"product\")\n @JsonInclude(Include.NON_NULL)\n private ProductDto productDto;\n\n}" }, { "identifier": "ProductDto", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/dto/ProductDto.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class ProductDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n private Integer productId;\n private String productTitle;\n private String imageUrl;\n private String sku;\n private Double priceUnit;\n private Integer quantity;\n\n @JsonInclude(Include.NON_NULL)\n private Set<FavouriteDto> favouriteDtos;\n\n}" }, { "identifier": "UserDto", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/dto/UserDto.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer userId;\n private String firstName;\n private String lastName;\n private String imageUrl;\n private String email;\n private String phone;\n\n @JsonInclude(Include.NON_NULL)\n private Set<FavouriteDto> favouriteDtos;\n\n}" }, { "identifier": "FavouriteNotFoundException", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/exception/wrapper/FavouriteNotFoundException.java", "snippet": "public class FavouriteNotFoundException extends RuntimeException {\n @Serial\n private static final long serialVersionUID = 1L;\n\n public FavouriteNotFoundException() {\n super();\n }\n\n public FavouriteNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public FavouriteNotFoundException(String message) {\n super(message);\n }\n\n public FavouriteNotFoundException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "FavouriteMappingHelper", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/helper/FavouriteMappingHelper.java", "snippet": "public class FavouriteMappingHelper {\n\n // mapping Favourite -> FavouriteDto\n public static FavouriteDto map(final Favourite favourite) {\n return FavouriteDto.builder()\n .userId(favourite.userId())\n .productId(favourite.productId())\n .likeDate(favourite.likeDate())\n .userDto(\n UserDto.builder()\n .userId(favourite.userId())\n .build())\n .productDto(\n ProductDto.builder()\n .productId(favourite.productId())\n .build())\n .build();\n }\n\n // mapping FavouriteDto -> Favourites\n public static Favourite map(final FavouriteDto favouriteDto) {\n return Favourite.builder()\n .userId(favouriteDto.getUserId())\n .productId(favouriteDto.getProductId())\n .likeDate(favouriteDto.getLikeDate())\n .build();\n }\n\n\n\n}" }, { "identifier": "FavouriteRepository", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/repository/FavouriteRepository.java", "snippet": "public interface FavouriteRepository extends JpaRepository<Favourite, FavouriteId> {\n\n}" }, { "identifier": "FavouriteService", "path": "favourite-service/src/main/java/com/hoangtien2k3qx1/favouriteservice/service/FavouriteService.java", "snippet": "public interface FavouriteService {\n List<FavouriteDto> findAll();\n FavouriteDto findById(final FavouriteId favouriteId);\n FavouriteDto save(final FavouriteDto favouriteDto);\n FavouriteDto update(final FavouriteDto favouriteDto);\n void deleteById(final FavouriteId favouriteId);\n}" } ]
import java.util.List; import java.util.stream.Collectors; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.hoangtien2k3qx1.favouriteservice.constant.AppConstant; import com.hoangtien2k3qx1.favouriteservice.domain.id.FavouriteId; import com.hoangtien2k3qx1.favouriteservice.dto.FavouriteDto; import com.hoangtien2k3qx1.favouriteservice.dto.ProductDto; import com.hoangtien2k3qx1.favouriteservice.dto.UserDto; import com.hoangtien2k3qx1.favouriteservice.exception.wrapper.FavouriteNotFoundException; import com.hoangtien2k3qx1.favouriteservice.helper.FavouriteMappingHelper; import com.hoangtien2k3qx1.favouriteservice.repository.FavouriteRepository; import com.hoangtien2k3qx1.favouriteservice.service.FavouriteService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
2,277
package com.hoangtien2k3qx1.favouriteservice.service.impl; @Service @Transactional @Slf4j @RequiredArgsConstructor public class FavouriteServiceImpl implements FavouriteService { private final FavouriteRepository favouriteRepository; private final RestTemplate restTemplate; @Override public List<FavouriteDto> findAll() { log.info("FavouriteDto List, service; fetch all favourites"); return this.favouriteRepository.findAll() .stream() .map(FavouriteMappingHelper::map) .map(f -> { f.setUserDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .USER_SERVICE_API_URL + "/" + f.getUserId(), UserDto.class)); f.setProductDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .PRODUCT_SERVICE_API_URL + "/" + f.getProductId(), ProductDto.class)); return f; }) .distinct() .collect(Collectors.toUnmodifiableList()); // immutable } @Override public FavouriteDto findById(final FavouriteId favouriteId) { log.info("FavouriteDto, service; fetch favourite by id"); return this.favouriteRepository.findById(favouriteId) .map(FavouriteMappingHelper::map) .map(f -> { f.setUserDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .USER_SERVICE_API_URL + "/" + f.getUserId(), UserDto.class)); f.setProductDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .PRODUCT_SERVICE_API_URL + "/" + f.getProductId(), ProductDto.class)); return f; })
package com.hoangtien2k3qx1.favouriteservice.service.impl; @Service @Transactional @Slf4j @RequiredArgsConstructor public class FavouriteServiceImpl implements FavouriteService { private final FavouriteRepository favouriteRepository; private final RestTemplate restTemplate; @Override public List<FavouriteDto> findAll() { log.info("FavouriteDto List, service; fetch all favourites"); return this.favouriteRepository.findAll() .stream() .map(FavouriteMappingHelper::map) .map(f -> { f.setUserDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .USER_SERVICE_API_URL + "/" + f.getUserId(), UserDto.class)); f.setProductDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .PRODUCT_SERVICE_API_URL + "/" + f.getProductId(), ProductDto.class)); return f; }) .distinct() .collect(Collectors.toUnmodifiableList()); // immutable } @Override public FavouriteDto findById(final FavouriteId favouriteId) { log.info("FavouriteDto, service; fetch favourite by id"); return this.favouriteRepository.findById(favouriteId) .map(FavouriteMappingHelper::map) .map(f -> { f.setUserDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .USER_SERVICE_API_URL + "/" + f.getUserId(), UserDto.class)); f.setProductDto(this.restTemplate .getForObject(AppConstant.DiscoveredDomainsApi .PRODUCT_SERVICE_API_URL + "/" + f.getProductId(), ProductDto.class)); return f; })
.orElseThrow(() -> new FavouriteNotFoundException(
5
2023-11-13 04:24:52+00:00
4k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/player/sub/ActionBarManager.java
[ { "identifier": "PlayerManager", "path": "src/main/java/com/sweattypalms/skyblock/core/player/PlayerManager.java", "snippet": "public abstract class PlayerManager {\n protected final SkyblockPlayer skyblockPlayer;\n\n public PlayerManager(SkyblockPlayer skyblockPlayer) {\n this.skyblockPlayer = skyblockPlayer;\n }\n\n public SkyblockPlayer getSkyblockPlayer() {\n return this.skyblockPlayer;\n }\n}" }, { "identifier": "SkyblockPlayer", "path": "src/main/java/com/sweattypalms/skyblock/core/player/SkyblockPlayer.java", "snippet": "@Getter\npublic class SkyblockPlayer {\n private static final HashMap<UUID, SkyblockPlayer> players = new HashMap<>();\n\n private final Random random = new Random();\n private final StatsManager statsManager;\n private final InventoryManager inventoryManager;\n private final BonusManager bonusManager;\n private final CooldownManager cooldownManager;\n private final ActionBarManager actionBarManager;\n private final ScoreboardManager scoreboardManager;\n private final SlayerManager slayerManager;\n private final SkillManager skillManager;\n private final CurrencyManager currencyManager;\n private final Player player;\n private BukkitTask tickRunnable;\n\n @Getter @Setter\n private Regions lastKnownRegion = null;\n\n /**\n * This is used to get last use time of abilities\n */\n private final Map<String, Long> cooldowns = new HashMap<>();\n\n public SkyblockPlayer(Player player) {\n this.player = player;\n\n this.statsManager = new StatsManager(this);\n this.inventoryManager = new InventoryManager(this);\n this.bonusManager = new BonusManager(this);\n this.cooldownManager = new CooldownManager(this);\n this.actionBarManager = new ActionBarManager(this);\n this.slayerManager = new SlayerManager(this);\n this.skillManager = new SkillManager(this);\n this.currencyManager = new CurrencyManager(this);\n // Should be last because it uses the other managers\n this.scoreboardManager = new ScoreboardManager(this);\n\n players.put(player.getUniqueId(), this);\n init();\n }\n\n public static SkyblockPlayer getSkyblockPlayer(Player player) {\n return players.get(player.getUniqueId());\n }\n\n public static void newPlayer(Player player) {\n new SkyblockPlayer(player);\n }\n\n private void init() {\n\n String displayName = \"$c[OWNER] \" + this.player.getName();\n displayName = PlaceholderFormatter.format(displayName);\n this.player.setDisplayName(displayName);\n\n this.tickRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n tick();\n }\n }.runTaskTimerAsynchronously(SkyBlock.getInstance(), 0, 1);\n\n this.statsManager.initHealth();\n }\n\n private int tickCount = 0;\n private void tick() {\n if (!this.player.isOnline()) {\n SkyblockPlayer.players.remove(this.player.getUniqueId());\n this.tickRunnable.cancel();\n }\n if (this.player.isDead()){\n return;\n }\n this.tickCount++;\n\n if (this.tickCount % 20 != 0) return;\n\n this.bonusManager.cleanupExpiredBonuses();\n this.statsManager.tick();\n this.actionBarManager.tick();\n\n this.scoreboardManager.updateScoreboard();\n RegionManager.updatePlayerRegion(this);\n }\n\n /**\n * Damage the player\n * TODO: Add various damage types\n * @param damage Damage to deal (With reduction)\n */\n public void damage(double damage) {\n if (this.player.getGameMode() != GameMode.SURVIVAL)\n return;\n this.player.setHealth(\n Math.max(\n this.player.getHealth() - damage,\n 0\n )\n );\n }\n\n public void damageWithReduction(double damage){\n double defense = this.statsManager.getMaxStats().get(Stats.DEFENSE);\n double finalDamage = DamageCalculator.calculateDamageReduction(defense, damage);\n this.damage(finalDamage);\n }\n\n /**\n * Send auto formatted message to player\n * @param s Message to send\n */\n public void sendMessage(String s) {\n this.player.sendMessage(PlaceholderFormatter.format(s));\n }\n\n public long getLastUseTime(String key){\n return this.cooldowns.getOrDefault(key, 0L);\n }\n\n public void setLastUseTime(String key, long time){\n this.cooldowns.put(key, time);\n }\n}" }, { "identifier": "Stats", "path": "src/main/java/com/sweattypalms/skyblock/core/player/sub/stats/Stats.java", "snippet": "@Getter\npublic enum Stats {\n DAMAGE(ChatColor.RED + \"❁\", \"Damage\", 0, false, ChatColor.RED),\n STRENGTH(ChatColor.RED + \"❁\", \"Strength\", 0, false, ChatColor.RED),\n CRIT_DAMAGE(ChatColor.BLUE + \"☠\", \"Crit Damage\", 0, true, ChatColor.RED),\n CRIT_CHANCE(ChatColor.BLUE + \"☣\", \"Crit Chance\", 0, true, ChatColor.RED),\n FEROCITY(ChatColor.RED + \"⫽\", \"Ferocity\", 0, false, ChatColor.RED),\n BONUS_ATTACK_SPEED(ChatColor.YELLOW + \"⚔\", \"Bonus Attack Speed\", 0, false, ChatColor.YELLOW),\n\n /* ---------------------------- */\n\n HEALTH(ChatColor.RED + \"❤\", \"Health\", 100, false, ChatColor.GREEN),\n DEFENSE(ChatColor.GREEN + \"❈\", \"Defence\", 0, false, ChatColor.GREEN),\n INTELLIGENCE(ChatColor.AQUA + \"✎\", \"Intelligence\", 100, false, ChatColor.GREEN),\n SPEED(ChatColor.WHITE + \"✦\", \"Speed\", 100, false, ChatColor.GREEN),\n\n /* ---------------------------- */\n\n HEALTH_REGEN(ChatColor.RED + \"❣\", \"Health Regen\", 100, false, ChatColor.RED, true),\n MANA_REGEN(ChatColor.AQUA + \"❉\", \"Mana Regen\", 100, false, ChatColor.AQUA, true),\n\n\n /* ---------------------------- */\n BOW_PULL(ChatColor.WHITE + \"⇧\", \"Bow Pull\", 0, false, ChatColor.WHITE, true), // => For bow crit calculation.\n SHORTBOW_SHOT_COOLDOWN( \"?\", \"Shot Cooldown\", 0, false, ChatColor.WHITE, true), // => For Short bow cooldown.\n\n CUSTOM(\"?\", \"Custom\", 0, false, ChatColor.WHITE, true) // => For bonuses variable management.\n ;\n private final String symbol;\n private final String name;\n private final double baseValue;\n private final boolean isPercentage;\n private final String itemBuilderColor;\n private boolean privateField = false;\n\n <T> Stats(String symbol, String name, double baseValue, boolean isPercentage, T itemBuilderColor) {\n this.symbol = symbol;\n this.name = name;\n this.baseValue = baseValue;\n this.isPercentage = isPercentage;\n if (itemBuilderColor instanceof ChatColor)\n this.itemBuilderColor = ((ChatColor) itemBuilderColor).toString();\n else\n this.itemBuilderColor = (String) itemBuilderColor;\n }\n <T> Stats(String symbol, String name, double baseValue, boolean isPercentage, T itemBuilderColor, boolean privateField){\n this(symbol, name, baseValue, isPercentage, itemBuilderColor);\n this.privateField = privateField;\n }\n\n static double get(SkyblockPlayer skyblockPlayer, Stats stat) {\n return skyblockPlayer.getStatsManager().getMaxStats().get(stat);\n }\n}" }, { "identifier": "formatDouble", "path": "src/main/java/com/sweattypalms/skyblock/core/helpers/PlaceholderFormatter.java", "snippet": "public static String formatDouble(double v1) {\n return formatDouble(v1, 1);\n}" } ]
import com.sweattypalms.skyblock.core.player.PlayerManager; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import net.minecraft.server.v1_8_R3.IChatBaseComponent; import net.minecraft.server.v1_8_R3.PacketPlayOutChat; import org.bukkit.ChatColor; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; import static com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter.formatDouble;
2,172
package com.sweattypalms.skyblock.core.player.sub; public class ActionBarManager extends PlayerManager { public ActionBarManager(SkyblockPlayer player) { super(player); } /** * Triggered every 20 ticks */ public void tick() { String space = " "; String healthComponent = getHealthComponent(); String defenceComponent = getDefenceComponent(); defenceComponent = defenceComponent.isEmpty() ? "" : space + defenceComponent; String intelligenceComponent = space + getIntelligenceComponent(); final PacketPlayOutChat packet = new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a("{\"text\":\"" + healthComponent + defenceComponent + intelligenceComponent + "\"}"), (byte) 2); ((CraftPlayer) this.skyblockPlayer.getPlayer()).getHandle().playerConnection.sendPacket(packet); } private String getHealthComponent() {
package com.sweattypalms.skyblock.core.player.sub; public class ActionBarManager extends PlayerManager { public ActionBarManager(SkyblockPlayer player) { super(player); } /** * Triggered every 20 ticks */ public void tick() { String space = " "; String healthComponent = getHealthComponent(); String defenceComponent = getDefenceComponent(); defenceComponent = defenceComponent.isEmpty() ? "" : space + defenceComponent; String intelligenceComponent = space + getIntelligenceComponent(); final PacketPlayOutChat packet = new PacketPlayOutChat(IChatBaseComponent.ChatSerializer.a("{\"text\":\"" + healthComponent + defenceComponent + intelligenceComponent + "\"}"), (byte) 2); ((CraftPlayer) this.skyblockPlayer.getPlayer()).getHandle().playerConnection.sendPacket(packet); } private String getHealthComponent() {
double maxHealth = this.skyblockPlayer.getStatsManager().getMaxStats().get(Stats.HEALTH);
2
2023-11-15 15:05:58+00:00
4k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/MessageUtils.java
[ { "identifier": "ServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/ServiceMessageSource.java", "snippet": "public interface ServiceMessageSource {\n\n /**\n * Common internationalizing message sources\n */\n String COMMON_SOURCE = \"common\";\n\n /**\n * Initialize the life cycle\n */\n void init();\n\n /**\n * Destruction life cycle\n */\n void destroy();\n\n /**\n * Getting international Messages\n *\n * @param code message Code\n * @param locale {@link Locale}\n * @param args the argument of message pattern\n * @return 如果获取到,返回器内容,获取不到,返回 <code>null</code>\n */\n @Nullable\n String getMessage(String code, Locale locale, Object... args);\n\n default String getMessage(String code, Object... args) {\n return getMessage(code, getLocale(), args);\n }\n\n /**\n * Get the runtime {@link Locale}\n *\n * @return {@link Locale}\n */\n @NonNull\n default Locale getLocale() {\n Locale locale = LocaleContextHolder.getLocale();\n return locale == null ? getDefaultLocale() : locale;\n }\n\n /**\n * Get the default {@link Locale}\n *\n * @return {@link Locale#SIMPLIFIED_CHINESE} as default\n */\n @NonNull\n default Locale getDefaultLocale() {\n return Locale.SIMPLIFIED_CHINESE;\n }\n\n /**\n * Gets a list of supported {@link Locale}\n *\n * @return Non-null {@link List}, simplified Chinese and English by default\n */\n @NonNull\n default List<Locale> getSupportedLocales() {\n return asList(getDefaultLocale(), Locale.ENGLISH);\n }\n\n /**\n * Message service source\n *\n * @return The application name or {@link #COMMON_SOURCE}\n */\n default String getSource() {\n return COMMON_SOURCE;\n }\n}" }, { "identifier": "I18nConstants", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/constants/I18nConstants.java", "snippet": "public interface I18nConstants {\n\n String PROPERTY_NAME_PREFIX = \"microsphere.i18n.\";\n\n /**\n * Enabled Configuration Name\n */\n String ENABLED_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"enabled\";\n\n /**\n * Enabled By Default\n */\n boolean DEFAULT_ENABLED = true;\n\n /**\n * Default {@link Locale} property name\n */\n String DEFAULT_LOCALE_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"default-locale\";\n\n /**\n * Supported {@link Locale} list property names\n */\n String SUPPORTED_LOCALES_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"supported-locales\";\n\n /**\n * Message Code pattern prefix\n */\n String MESSAGE_PATTERN_PREFIX = \"{\";\n\n /**\n * Message Code pattern suffix\n */\n String MESSAGE_PATTERN_SUFFIX = \"}\";\n\n /**\n * Generic {@link ServiceMessageSource} bean name\n */\n String COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME = \"commonServiceMessageSource\";\n\n /**\n * Generic {@link ServiceMessageSource} Bean Priority\n */\n int COMMON_SERVICE_MESSAGE_SOURCE_ORDER = 500;\n\n /**\n * Primary {@link ServiceMessageSource} Bean\n */\n String SERVICE_MESSAGE_SOURCE_BEAN_NAME = \"serviceMessageSource\";\n}" }, { "identifier": "serviceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/I18nUtils.java", "snippet": "public static ServiceMessageSource serviceMessageSource() {\n if (serviceMessageSource == null) {\n logger.warn(\"serviceMessageSource is not initialized, EmptyServiceMessageSource will be used\");\n return EmptyServiceMessageSource.INSTANCE;\n }\n return serviceMessageSource;\n}" } ]
import io.microsphere.i18n.ServiceMessageSource; import io.microsphere.i18n.constants.I18nConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Locale; import static io.microsphere.i18n.util.I18nUtils.serviceMessageSource; import static org.apache.commons.lang3.StringUtils.substringBetween; import static org.springframework.util.StringUtils.hasText;
1,797
package io.microsphere.i18n.util; /** * Message Utilities class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public abstract class MessageUtils { private static final Logger logger = LoggerFactory.getLogger(MessageUtils.class); private MessageUtils() { } /** * Get I18n Message * * @param messagePattern Message or Message Pattern * @param args the arguments of Message Pattern * @return Internationalized Message returns the original message if it exists */ public static String getLocalizedMessage(String messagePattern, Object... args) { ServiceMessageSource serviceMessageSource = serviceMessageSource(); Locale locale = serviceMessageSource.getLocale(); return getLocalizedMessage(messagePattern, locale, args); } /** * Get I18n Message * <pre> * // Testing Simplified Chinese * // null * assertEquals(null, MessageUtils.getLocalizedMessage(null)); * // If the message argument is "a", the pattern "{" "}" is not included, and the original content is returned * assertEquals("a", MessageUtils.getLocalizedMessage("a")); * // "{a}" is the Message Code template, where "a" is Message Code * assertEquals("测试-a", MessageUtils.getLocalizedMessage("{a}")); * * // The same is true for overloaded methods with Message Pattern arguments * assertEquals("hello", MessageUtils.getLocalizedMessage("hello", "World")); * assertEquals("您好,World", MessageUtils.getLocalizedMessage("{hello}", "World")); * * // If message code does not exist, return the original content of message * assertEquals("{code-not-found}", MessageUtils.getLocalizedMessage("{code-not-found}")); * assertEquals("code-not-found", MessageUtils.getLocalizedMessage("{microsphere-test.code-not-found}")); * assertEquals("code-not-found", MessageUtils.getLocalizedMessage("{common.code-not-found}")); * * // The test of English * assertEquals("hello", MessageUtils.getLocalizedMessage("hello", Locale.ENGLISH, "World")); * assertEquals("Hello,World", MessageUtils.getLocalizedMessage("{hello}", Locale.ENGLISH, "World")); * </pre> * * @param messagePattern Message or Message Pattern * @param locale {@link Locale} * @param args the arguments of Message Pattern * @return Internationalized Message returns the original message if it exists */ public static String getLocalizedMessage(String messagePattern, Locale locale, Object... args) { if (messagePattern == null) { return null; } String messageCode = resolveMessageCode(messagePattern); if (messageCode == null) { logger.debug("Message code not found in messagePattern'{}", messagePattern); return messagePattern; } ServiceMessageSource serviceMessageSource = serviceMessageSource(); String localizedMessage = serviceMessageSource.getMessage(messageCode, locale, args); if (hasText(localizedMessage)) { logger.debug("Message Pattern ['{}'] corresponds to Locale ['{}'] with MessageSage:'{}'", messagePattern, locale, localizedMessage); } else { int afterDotIndex = messageCode.indexOf(".") + 1; if (afterDotIndex > 0 && afterDotIndex < messageCode.length()) { localizedMessage = messageCode.substring(afterDotIndex); } else { localizedMessage = messagePattern; } logger.debug("No Message['{}'] found for Message Pattern ['{}'], returned: {}", messagePattern, locale, localizedMessage); } return localizedMessage; } public static String resolveMessageCode(String messagePattern) {
package io.microsphere.i18n.util; /** * Message Utilities class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public abstract class MessageUtils { private static final Logger logger = LoggerFactory.getLogger(MessageUtils.class); private MessageUtils() { } /** * Get I18n Message * * @param messagePattern Message or Message Pattern * @param args the arguments of Message Pattern * @return Internationalized Message returns the original message if it exists */ public static String getLocalizedMessage(String messagePattern, Object... args) { ServiceMessageSource serviceMessageSource = serviceMessageSource(); Locale locale = serviceMessageSource.getLocale(); return getLocalizedMessage(messagePattern, locale, args); } /** * Get I18n Message * <pre> * // Testing Simplified Chinese * // null * assertEquals(null, MessageUtils.getLocalizedMessage(null)); * // If the message argument is "a", the pattern "{" "}" is not included, and the original content is returned * assertEquals("a", MessageUtils.getLocalizedMessage("a")); * // "{a}" is the Message Code template, where "a" is Message Code * assertEquals("测试-a", MessageUtils.getLocalizedMessage("{a}")); * * // The same is true for overloaded methods with Message Pattern arguments * assertEquals("hello", MessageUtils.getLocalizedMessage("hello", "World")); * assertEquals("您好,World", MessageUtils.getLocalizedMessage("{hello}", "World")); * * // If message code does not exist, return the original content of message * assertEquals("{code-not-found}", MessageUtils.getLocalizedMessage("{code-not-found}")); * assertEquals("code-not-found", MessageUtils.getLocalizedMessage("{microsphere-test.code-not-found}")); * assertEquals("code-not-found", MessageUtils.getLocalizedMessage("{common.code-not-found}")); * * // The test of English * assertEquals("hello", MessageUtils.getLocalizedMessage("hello", Locale.ENGLISH, "World")); * assertEquals("Hello,World", MessageUtils.getLocalizedMessage("{hello}", Locale.ENGLISH, "World")); * </pre> * * @param messagePattern Message or Message Pattern * @param locale {@link Locale} * @param args the arguments of Message Pattern * @return Internationalized Message returns the original message if it exists */ public static String getLocalizedMessage(String messagePattern, Locale locale, Object... args) { if (messagePattern == null) { return null; } String messageCode = resolveMessageCode(messagePattern); if (messageCode == null) { logger.debug("Message code not found in messagePattern'{}", messagePattern); return messagePattern; } ServiceMessageSource serviceMessageSource = serviceMessageSource(); String localizedMessage = serviceMessageSource.getMessage(messageCode, locale, args); if (hasText(localizedMessage)) { logger.debug("Message Pattern ['{}'] corresponds to Locale ['{}'] with MessageSage:'{}'", messagePattern, locale, localizedMessage); } else { int afterDotIndex = messageCode.indexOf(".") + 1; if (afterDotIndex > 0 && afterDotIndex < messageCode.length()) { localizedMessage = messageCode.substring(afterDotIndex); } else { localizedMessage = messagePattern; } logger.debug("No Message['{}'] found for Message Pattern ['{}'], returned: {}", messagePattern, locale, localizedMessage); } return localizedMessage; } public static String resolveMessageCode(String messagePattern) {
String messageCode = substringBetween(messagePattern, I18nConstants.MESSAGE_PATTERN_PREFIX, I18nConstants.MESSAGE_PATTERN_SUFFIX);
1
2023-11-17 11:35:59+00:00
4k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/index/CreateBicBitModFluids.java
[ { "identifier": "FryingOilFluid", "path": "src/main/java/createbicyclesbitterballen/fluid/FryingOilFluid.java", "snippet": "public abstract class FryingOilFluid extends ForgeFlowingFluid {\n public static final ForgeFlowingFluid.Properties PROPERTIES = (new ForgeFlowingFluid.Properties(() -> {\n return (FluidType)FluidTypesRegistry.FRYING_OIL_TYPE.get();\n }, () -> {\n return (Fluid)CreateBicBitModFluids.FRYING_OIL.get();\n }, () -> {\n return (Fluid)CreateBicBitModFluids.FLOWING_FRYING_OIL.get();\n })).explosionResistance(100.0F).tickRate(4).levelDecreasePerBlock(2).slopeFindDistance(8).bucket(() -> {\n return (Item) CreateBicBitModItems.FRYING_OIL_BUCKET.get();\n });\n\n private FryingOilFluid() {\n super(PROPERTIES);\n }\n\n public static class Flowing extends FryingOilFluid {\n public Flowing() {\n }\n\n protected void createFluidStateDefinition(StateDefinition.Builder<Fluid, FluidState> builder) {\n super.createFluidStateDefinition(builder);\n builder.add(LEVEL);\n }\n\n\n public int getAmount(FluidState state) {\n return state.getValue(LEVEL);\n }\n\n public boolean isSource(FluidState state) {\n return false;\n }\n }\n\n public static class Source extends FryingOilFluid {\n public Source() {\n }\n\n public int getAmount(FluidState state) {\n return 8;\n }\n\n public boolean isSource(FluidState state) {\n return true;\n }\n }\n}" }, { "identifier": "StamppotFluid", "path": "src/main/java/createbicyclesbitterballen/fluid/StamppotFluid.java", "snippet": "@Mod.EventBusSubscriber(modid = \"create_bic_bit\")\npublic abstract class StamppotFluid extends ForgeFlowingFluid {\n public static final ForgeFlowingFluid.Properties PROPERTIES = new ForgeFlowingFluid.Properties(FluidTypesRegistry.STAMPPOT_TYPE, CreateBicBitModFluids.STAMPPOT, CreateBicBitModFluids.FLOWING_STAMPPOT)\n .explosionResistance(100f).tickRate(1).slopeFindDistance(1);\n\n private StamppotFluid() {\n\n super(PROPERTIES);\n }\n\n public static class Flowing extends StamppotFluid {\n public Flowing() {\n }\n\n protected void createFluidStateDefinition(StateDefinition.Builder<Fluid, FluidState> builder) {\n super.createFluidStateDefinition(builder);\n builder.add(LEVEL);\n }\n\n\n public int getAmount(FluidState state) {\n return state.getValue(LEVEL);\n }\n\n public boolean isSource(FluidState state) {\n return false;\n }\n }\n\n public static class Source extends StamppotFluid {\n public Source() {\n }\n\n public int getAmount(FluidState state) {\n return 8;\n }\n\n public boolean isSource(FluidState state) {\n return true;\n }\n }\n\n\n @SubscribeEvent\n public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {\n BlockPos pos = event.getPos();\n BlockState state = event.getLevel().getBlockState(pos);\n\n if (state.getBlock() == AllBlocks.BASIN.get()) {\n BlockEntity blockEntity = event.getLevel().getBlockEntity(pos);\n Player player = event.getEntity();\n InteractionHand hand = event.getHand();\n ItemStack heldItem = player.getItemInHand(hand);\n\n if (blockEntity instanceof BasinBlockEntity basinEntity && heldItem.getItem() == Items.BOWL) {\n SmartFluidTank tank = basinEntity.getTanks().getSecond().getPrimaryHandler();\n FluidStack fluidInOutputTank = tank.getFluid();\n float totalUnits = fluidInOutputTank.getAmount();\n\n if (fluidInOutputTank.getFluid()!= CreateBicBitModFluids.STAMPPOT.get() || totalUnits < 250) return;\n\n heldItem.shrink(1);\n if (!player.getInventory().add(new ItemStack(CreateBicBitModItems.STAMPPOT_BOWL.get()))) {\n player.drop(new ItemStack(CreateBicBitModItems.STAMPPOT_BOWL.get()), false);\n }\n\n tank.drain(250, IFluidHandler.FluidAction.EXECUTE);\n }\n }\n }\n}" }, { "identifier": "CreateBicBitMod", "path": "src/main/java/createbicyclesbitterballen/CreateBicBitMod.java", "snippet": "@Mod(\"create_bic_bit\")\npublic class CreateBicBitMod {\n\n\n\tpublic static final Logger LOGGER = LogManager.getLogger(CreateBicBitMod.class);\n\tpublic static final String MODID = \"create_bic_bit\";\n\tpublic static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID);\n\t@Deprecated\n\tpublic static final Random RANDOM = new Random();\n\n\tstatic {\n\t\tREGISTRATE.setTooltipModifierFactory(item -> {\n\t\t\treturn new ItemDescription.Modifier(item, Palette.STANDARD_CREATE)\n\t\t\t\t\t.andThen(TooltipModifier.mapNull(KineticStats.create(item)));\n\t\t});\n\t}\n\tpublic CreateBicBitMod() {\n\t\tIEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n\t\tIEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();\n\t\tIEventBus forgeEventBus = MinecraftForge.EVENT_BUS;\n\t\tMinecraftForge.EVENT_BUS.register(this);\n\n\t\t// Register components using Registrate\n\n\t\tSoundsRegistry.prepare();\n\t\tBlockRegistry.register();\n\t\tCreateBicBitModItems.register();\n\t\tCreateBicBitModTabs.register(modEventBus);\n\t\tRecipeRegistry.register(modEventBus);\n\t\tBlockEntityRegistry.register();\n\t\tPonderIndex.register();\n\t\tCreateBicBitModFluids.REGISTRY.register(bus);\n\t\tFluidTypesRegistry.REGISTRY.register(bus);\n\t\tDistExecutor.unsafeRunWhenOn(Dist.CLIENT,\n\t\t\t\t() -> PartialsRegistry::load);\n\t\tmodEventBus.addListener(SoundsRegistry::register);\n\n\n\t\tModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ConfigRegistry.SERVER_SPEC, \"create_bic_bit-server.toml\");\n\t\tMinecraftForge.EVENT_BUS.register(this);\n\t\tREGISTRATE.registerEventListeners(modEventBus);\n\n\n\n\n\t}\n\tpublic static ResourceLocation asResource(String path) {\n\t\treturn new ResourceLocation(MODID, path);\n\t}\n}" } ]
import createbicyclesbitterballen.fluid.FryingOilFluid; import net.minecraftforge.registries.RegistryObject; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.api.distmarker.Dist; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.ItemBlockRenderTypes; import createbicyclesbitterballen.fluid.StamppotFluid; import createbicyclesbitterballen.CreateBicBitMod;
1,836
package createbicyclesbitterballen.index; public class CreateBicBitModFluids { public static final DeferredRegister<Fluid> REGISTRY = DeferredRegister.create(ForgeRegistries.FLUIDS, CreateBicBitMod.MODID); public static final RegistryObject<FlowingFluid> FRYING_OIL = REGISTRY.register("frying_oil", () -> new FryingOilFluid.Source()); public static final RegistryObject<FlowingFluid> FLOWING_FRYING_OIL = REGISTRY.register("flowing_frying_oil", () -> new FryingOilFluid.Flowing());
package createbicyclesbitterballen.index; public class CreateBicBitModFluids { public static final DeferredRegister<Fluid> REGISTRY = DeferredRegister.create(ForgeRegistries.FLUIDS, CreateBicBitMod.MODID); public static final RegistryObject<FlowingFluid> FRYING_OIL = REGISTRY.register("frying_oil", () -> new FryingOilFluid.Source()); public static final RegistryObject<FlowingFluid> FLOWING_FRYING_OIL = REGISTRY.register("flowing_frying_oil", () -> new FryingOilFluid.Flowing());
public static final RegistryObject<FlowingFluid> STAMPPOT = REGISTRY.register("stamppot", () -> new StamppotFluid.Source());
1
2023-11-12 13:05:18+00:00
4k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFBuilderTest.java
[ { "identifier": "PDFH1", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFH1.java", "snippet": "public class PDFH1 extends PDFText{\n public static float fontSize = 32;\n\n public PDFH1(String text){\n super(text);\n this.bufferPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));\n this.bufferPaint.setTextSize(fontSize * Zoomable.getInstance().density);\n }\n public PDFH1(String text, TextPaint paint){\n super(text, paint);\n }\n\n public static PDFH1 build(String text){return new PDFH1(text);}\n}" }, { "identifier": "PDFH3", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFH3.java", "snippet": "public class PDFH3 extends PDFText{\n public static float fontSize = 18.72f;\n\n public PDFH3(String text){\n super(text);\n this.bufferPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));\n this.bufferPaint.setTextSize(fontSize * Zoomable.getInstance().density);\n }\n public PDFH3(String text, TextPaint paint){\n super(text, paint);\n }\n\n public static PDFH3 build(String text){return new PDFH3(text);}\n}" }, { "identifier": "PDFLinearLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFLinearLayout.java", "snippet": "public class PDFLinearLayout extends PDFLayout {\n @Orientation.OrientationInt\n int orientation = Orientation.Column;\n\n private final ArrayList<Integer> gaps = new ArrayList<>();\n\n public PDFLinearLayout(){\n super();\n child = new ArrayList<>();\n }\n public PDFLinearLayout(int length){\n super();\n child = new ArrayList<>(length);\n for(int i = 0; i < length; i++){\n child.add(PDFEmpty.build().setParent(this));\n }\n }\n\n @Override\n public void measure(float x, float y) {\n super.measure(x, y);\n\n int i;\n int gap = 0;\n int totalAxis = 0;\n int lastWidth = Math.round (measureWidth - border.size.left - padding.left\n - border.size.right - padding.right);\n switch (orientation){\n case Orientation.Column:\n for(i = 0; i < child.size(); i++){\n child.get(i).width = lastWidth - child.get(i).margin.left - child.get(i).margin.right;\n child.get(i).measure(0,totalAxis);\n gap = child.get(i).getTotalHeight();\n child.get(i).force(lastWidth ,gap, null);\n totalAxis += gap;\n }\n break;\n case Orientation.Row:\n int zero_count = 0;\n int maxHeight = 0;\n // 가로 길이 자동 조절\n for(i = 0; i < child.size(); i++) {\n if(gaps.get(i) > lastWidth) gaps.set(i, 0);\n lastWidth -= child.get(i).margin.left + child.get(i).margin.right;\n if(lastWidth < 0) gaps.set(i, 0);\n if(gaps.get(i) == 0){\n zero_count += 1;\n }else{\n lastWidth -= gaps.get(i);\n }\n }\n for(i = 0; i < child.size(); i++) {\n if(gaps.get(i) == 0){\n gaps.set(i, lastWidth/zero_count);\n lastWidth -= lastWidth/zero_count;\n zero_count -= 1;\n }\n }\n\n for(i = 0; i < child.size(); i++){\n gap = gaps.get(i);\n child.get(i).width = gap;\n child.get(i).measure(totalAxis,0);\n if (maxHeight < child.get(i).measureHeight) {\n maxHeight = child.get(i).measureHeight;\n }\n totalAxis += gap + child.get(i).margin.left + child.get(i).margin.right;\n }\n totalAxis = 0;\n for(i = 0; i < child.size(); i++){\n gap = gaps.get(i);\n child.get(i).width = gap;\n child.get(i).measure(totalAxis,0);\n child.get(i).force(gap, maxHeight, null);\n totalAxis += gap + child.get(i).margin.left + child.get(i).margin.right;\n }\n break;\n }\n }\n\n\n @Override\n public void draw(Canvas canvas) {\n super.draw(canvas);\n\n for(int i = 0; i < child.size(); i++) {\n child.get(i).draw(canvas);\n }\n }\n\n /**\n * 레이아웃에 자식 추가<br>\n * Add children to layout\n * @param component 자식 컴포넌트\n * @return 자기자신\n */\n @Override\n public PDFLinearLayout addChild(PDFComponent component){\n return addChild(component, 0);\n }\n\n /**\n * 레이아웃에 자식 추가<br>\n * Add children to layout\n * @param component 자식 컴포넌트\n * @param width 자식 컴포넌트가 차지하는 가로 길이\n * @return 자기자신\n */\n public PDFLinearLayout addChild(PDFComponent component, int width){\n if(width < 0) width = 0;\n gaps.add(Math.round(width * Zoomable.getInstance().density));\n super.addChild(component);\n return this;\n }\n\n /**\n * 레이아웃의 방향 설정<br>\n * Setting the orientation of the layout\n * @param orientation 방향\n * @return 자기자신\n */\n public PDFLinearLayout setOrientation(@Orientation.OrientationInt int orientation){\n this.orientation = orientation;\n return this;\n }\n\n @Override\n public PDFLinearLayout setSize(Float width, Float height) {\n super.setSize(width, height);\n return this;\n }\n\n @Override\n public PDFLinearLayout setBackgroundColor(int color) {\n super.setBackgroundColor(color);\n return this;\n }\n\n @Override\n public PDFLinearLayout setMargin(Rect margin) {\n super.setMargin(margin);\n return this;\n }\n\n @Override\n public PDFLinearLayout setMargin(int left, int top, int right, int bottom) {\n super.setMargin(left, top, right, bottom);\n return this;\n }\n\n @Override\n public PDFLinearLayout setMargin(int all) {\n super.setMargin(all);\n return this;\n }\n\n @Override\n public PDFLinearLayout setMargin(int horizontal, int vertical) {\n super.setMargin(horizontal, vertical);\n return this;\n }\n\n @Override\n public PDFLinearLayout setPadding(int all) {\n super.setPadding(all);\n return this;\n }\n\n @Override\n public PDFLinearLayout setPadding(int horizontal, int vertical) {\n super.setPadding(horizontal, vertical);\n return this;\n }\n\n @Override\n public PDFLinearLayout setPadding(Rect padding) {\n super.setPadding(padding);\n return this;\n }\n\n @Override\n public PDFLinearLayout setPadding(int left, int top, int right, int bottom) {\n super.setPadding(left, top, right, bottom);\n return this;\n }\n\n @Override\n public PDFLinearLayout setBorder(Action<Border, Border> action) {\n super.setBorder(action);\n return this;\n }\n\n @Override\n public PDFLinearLayout setAnchor(Integer horizontal, Integer vertical) {\n super.setAnchor(horizontal, vertical);\n return this;\n }\n @Override\n protected PDFLinearLayout setParent(PDFComponent parent) {\n super.setParent(parent);\n return this;\n }\n\n public static PDFLinearLayout build(){return new PDFLinearLayout();}\n}" }, { "identifier": "Orientation", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Orientation.java", "snippet": "public class Orientation {\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({Row, Column})\n public @interface OrientationInt {}\n /**\n * 가로\n */\n public static final int Row = 0;\n /**\n * 세로\n */\n public static final int Column = 1;\n}" }, { "identifier": "Paper", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Paper.java", "snippet": "public enum Paper{\n // 840 x1188mm\n A0(2381.103648f,3367.5608736f),\n // 594 x840mm\n A1(1683.7804368f,2381.103648f),\n // 420 x594mm\n A2(1190.551824f,1683.7804368f),\n // 297 x420mm\n A3(841.8902184f,1190.551824f),\n // 210 x297mm\n A4(595.275912f, 841.8902184f),\n // 148.5x210mm\n A5(595.275912f, 841.8902184f),\n // 1028 1456\n B0(2914.0173216f, 4127.2463232f),\n // 728 1028\n B1(2063.6231616f, 2914.0173216f),\n // 514 728\n B2(1457.0086608f, 2063.6231616f),\n // 364 514\n B3(1031.8115808f, 1457.0086608f),\n // 257 364\n B4(728.5043304f, 1031.8115808f),\n // 182 x257mm\n B5(515.9057904f, 728.5043304f),\n // 8.5 X11inch\n Letter(612f, 792f),\n // 8.5 X14inch\n Legal(612f, 1008f);\n //*2.8346472\n\n private float width;\n private float height;\n\n Paper(float width, float height){\n this.width = width;\n this.height = height;\n }\n\n public void setCustom(float width, float height){\n this.width = width;\n this.height = height;\n }\n\n public float getHeight() {\n return height;\n }\n\n public float getWidth() {\n return width;\n }\n\n public Paper Landscape(){\n float w = getWidth();\n width = getHeight();\n height = w;\n return this;\n }\n}" }, { "identifier": "StandardDirectory", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/StandardDirectory.java", "snippet": "public class StandardDirectory {\n @Retention(RetentionPolicy.SOURCE)\n @StringDef({\n DIRECTORY_MUSIC,\n DIRECTORY_PODCASTS,\n DIRECTORY_RINGTONES,\n DIRECTORY_ALARMS,\n DIRECTORY_NOTIFICATIONS,\n DIRECTORY_PICTURES,\n DIRECTORY_MOVIES,\n DIRECTORY_DOWNLOADS,\n DIRECTORY_DCIM,\n DIRECTORY_DOCUMENTS,\n DIRECTORY_AUDIOBOOKS,\n })\n public @interface DirectoryString {}\n\n public static final String DIRECTORY_MUSIC = \"Music\";\n public static final String DIRECTORY_PODCASTS = \"Podcasts\";\n public static final String DIRECTORY_RINGTONES = \"Ringtones\";\n public static final String DIRECTORY_ALARMS = \"Alarms\";\n public static final String DIRECTORY_NOTIFICATIONS = \"Notifications\";\n public static final String DIRECTORY_PICTURES = \"Pictures\";\n public static final String DIRECTORY_MOVIES = \"Movies\";\n public static final String DIRECTORY_DOWNLOADS = \"Download\";\n public static final String DIRECTORY_DCIM = \"DCIM\";\n @RequiresApi(api = Build.VERSION_CODES.KITKAT)\n public static final String DIRECTORY_DOCUMENTS = \"Documents\";\n @RequiresApi(api = Build.VERSION_CODES.Q)\n public static final String DIRECTORY_AUDIOBOOKS = \"Audiobooks\";\n\n public static final String[] STANDARD_DIRECTORIES = {\n DIRECTORY_MUSIC,\n DIRECTORY_PODCASTS,\n DIRECTORY_RINGTONES,\n DIRECTORY_ALARMS,\n DIRECTORY_NOTIFICATIONS,\n DIRECTORY_PICTURES,\n DIRECTORY_MOVIES,\n DIRECTORY_DOWNLOADS,\n DIRECTORY_DCIM,\n DIRECTORY_DOCUMENTS,\n DIRECTORY_AUDIOBOOKS,\n };\n\n public static boolean isStandardDirectory(String dir) {\n for (String valid : STANDARD_DIRECTORIES) {\n if (valid.equals(dir)) {\n return true;\n }\n }\n return false;\n }\n}" }, { "identifier": "TextAlign", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/TextAlign.java", "snippet": "public class TextAlign {\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({Start, Center, End})\n public @interface TextAlignInt {}\n public static final int Start = 0;\n public static final int Center = 1;\n public static final int End = 2;\n}" } ]
import android.content.Context; import android.graphics.Color; import android.os.Environment; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
3,450
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFBuilderTest { Context context; PDFBuilder<PDFLinearLayout> builder; @Before public void setUp(){ context = InstrumentationRegistry.getInstrumentation().getTargetContext(); builder = new PDFBuilder<>(Paper.A4); builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setPadding(10,10,10,10) .setBackgroundColor(Color.BLUE) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.WHITE)
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFBuilderTest { Context context; PDFBuilder<PDFLinearLayout> builder; @Before public void setUp(){ context = InstrumentationRegistry.getInstrumentation().getTargetContext(); builder = new PDFBuilder<>(Paper.A4); builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setPadding(10,10,10,10) .setBackgroundColor(Color.BLUE) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.WHITE)
.setTextAlign(TextAlign.Center))
6
2023-11-15 08:05:28+00:00
4k
frc-7419/SwerveBase
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "SwerveDriveFieldCentric", "path": "src/main/java/frc/robot/commands/SwerveDriveFieldCentric.java", "snippet": "public class SwerveDriveFieldCentric extends CommandBase {\n private XboxController joystick;\n private DriveBaseSubsystem driveBaseSubsystem;\n\n public SwerveDriveFieldCentric(XboxController joystick, DriveBaseSubsystem driveBaseSubsystem) {\n this.joystick = joystick;\n this.driveBaseSubsystem = driveBaseSubsystem;\n addRequirements(driveBaseSubsystem);\n }\n\n @Override\n public void initialize() {\n driveBaseSubsystem.coast();\n driveBaseSubsystem.zeroYaw();\n }\n\n @Override\n public void execute() {\n driveBaseSubsystem.setModuleStates(driveBaseSubsystem.getChassisSpeedsFromJoystick(joystick.getLeftY(), joystick.getLeftX(), joystick.getRightX(), joystick.getLeftBumper()));\n }\n\n @Override\n public void end(boolean interrupted) {\n driveBaseSubsystem.brake();\n }\n\n @Override\n public boolean isFinished() {\n return false;\n }\n}" }, { "identifier": "TranslateDistance", "path": "src/main/java/frc/robot/commands/TranslateDistance.java", "snippet": "public class TranslateDistance extends CommandBase {\n private final DriveBaseSubsystem driveBaseSubsystem;\n private final double xVelocity;\n private final double yVelocity;\n private final double totalDistance;\n private final ChassisSpeeds chassisSpeeds;\n\n public TranslateDistance(DriveBaseSubsystem driveBaseSubsystem, double xDistance, double yDistance) {\n this.driveBaseSubsystem = driveBaseSubsystem;\n this.xVelocity = xDistance==0?0:0.2*(xDistance/Math.abs(xDistance));\n this.yVelocity = yDistance==0?0:0.2*(yDistance/Math.abs(yDistance));\n this.totalDistance = Math.sqrt((xDistance*xDistance)+(yDistance*yDistance));\n this.chassisSpeeds = new ChassisSpeeds(xVelocity, yVelocity,0);\n addRequirements(driveBaseSubsystem);\n }\n\n \n @Override\n public void initialize() {\n driveBaseSubsystem.resetDriveEnc();\n \n }\n\n @Override\n public void execute() {\n driveBaseSubsystem.setModuleStates(chassisSpeeds);\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n driveBaseSubsystem.setModuleStates(new ChassisSpeeds(0,0,0));\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return driveBaseSubsystem.reachedDist(totalDistance);\n }\n}" }, { "identifier": "DriveBaseSubsystem", "path": "src/main/java/frc/robot/subsystems/drive/DriveBaseSubsystem.java", "snippet": "public class DriveBaseSubsystem extends SubsystemBase {\n private final SwerveDriveOdometry m_odometry;\n private final SwerveModule frontLeftModule;\n private final SwerveModule frontRightModule;\n private final SwerveModule backLeftModule;\n private final SwerveModule backRightModule;\n private final AHRS ahrs;\n\n public DriveBaseSubsystem() {\n frontLeftModule = new SwerveModule(SwerveConstants.frontLeft.turnMotorID, SwerveConstants.frontLeft.driveMotorID, SwerveConstants.frontLeft.turnEncoderID, SwerveConstants.frontLeft.offset, \"FrontLeftModule\");\n frontRightModule = new SwerveModule(SwerveConstants.frontRight.turnMotorID, SwerveConstants.frontRight.driveMotorID, SwerveConstants.frontRight.turnEncoderID, SwerveConstants.frontRight.offset, \"FrontRightModule\");\n backLeftModule = new SwerveModule(SwerveConstants.backLeft.turnMotorID, SwerveConstants.backLeft.driveMotorID, SwerveConstants.backLeft.turnEncoderID, SwerveConstants.backLeft.offset, \"BackLeftModule\");\n backRightModule = new SwerveModule(SwerveConstants.backRight.turnMotorID, SwerveConstants.backRight.driveMotorID, SwerveConstants.backRight.turnEncoderID, SwerveConstants.backRight.offset, \"BackRightModule\");\n ahrs = new AHRS(SerialPort.Port.kMXP);\n ahrs.zeroYaw(); // field centric, we need yaw to be zero\n m_odometry = new SwerveDriveOdometry(Constants.SwerveConstants.m_SwerveDriveKinematics, ahrs.getRotation2d(), getPositions());\n coast();\n }\n\n\n\n public void zeroYaw() {\n ahrs.zeroYaw();\n }\n\n public double getYaw() { // CW IS POSITIVE BY DEFAULT\n return -ahrs.getYaw();\n }\n\n public double getPitch() {\n return ahrs.getPitch();\n }\n\n public double getRoll() {\n return ahrs.getRoll();\n }\n\n public boolean reachedDist(double meters) {\n return \n (frontLeftModule.reachedDist(meters))&&\n (frontRightModule.reachedDist(meters))&&\n (backLeftModule.reachedDist(meters))&&\n (backRightModule.reachedDist(meters));\n }\n\n public void resetDriveEnc() {\n frontLeftModule.resetDriveEncoder();\n frontRightModule.resetDriveEncoder();\n backLeftModule.resetDriveEncoder();\n backRightModule.resetDriveEncoder();\n }\n\n public Rotation2d getRotation2d() {\n return ahrs.getRotation2d();\n /*\n * the thing is .getYaw is -180 to 180 so it not being 0 to 360\n * may cause the internal conversion that Rotation2d does to be wrong\n */\n }\n\n public void brake() {\n frontLeftModule.brake();\n frontRightModule.brake();\n backLeftModule.brake();\n backRightModule.brake();\n }\n\n public void coast() {\n frontLeftModule.coast();\n frontRightModule.coast();\n backLeftModule.coast();\n backRightModule.coast();\n }\n\n public SwerveModulePosition[] getPositions() {\n return new SwerveModulePosition[]{frontLeftModule.getPose(), frontRightModule.getPose(), backLeftModule.getPose(), backRightModule.getPose()};\n }\n\n public void stop() {\n frontLeftModule.stop();\n frontRightModule.stop();\n backLeftModule.stop();\n backRightModule.stop();\n }\n\n /**\n * Returns the currently-estimated pose of the robot.\n *\n * @return The pose.\n */\n public Pose2d getPose() {\n return m_odometry.getPoseMeters();\n }\n\n /**\n * Resets the odometry to the specified pose.\n *\n * @param pose The pose to which to set the odometry.\n */\n public void resetOdometry(Pose2d pose) {\n m_odometry.resetPosition(ahrs.getRotation2d(), getPositions(), pose);\n }\n\n /**\n * Returns chassis speeds from field-centric joystick controls. This is what determines the translational speed of the robot in proportion to joystick values.\n * @param joystick\n * @return\n */\n public ChassisSpeeds getChassisSpeedsFromJoystick(double vx, double vy, double rx, boolean slowMode) {\n vx = Math.abs(vx)>0.05?-vx*SwerveConstants.kMaxTranslationalSpeed:0;\n vy = Math.abs(vy)>0.05?vy*SwerveConstants.kMaxTranslationalSpeed:0;\n rx = Math.abs(rx)>0.05?-0.7*rx*SwerveConstants.kMaxRotationalSpeed:0;\n if(slowMode) {\n vx *= 0.2;\n vy *= 0.2;\n rx *= 0.2;\n }\n return ChassisSpeeds.fromFieldRelativeSpeeds(vx, vy, rx, getRotation2d());\n }\n\n /**\n * Sets the individual swerve module states\n * @param moduleStates\n */\n public void setModuleStates(SwerveModuleState[] moduleStates) {\n frontLeftModule.setSwerveModuleState(moduleStates[0]);\n frontRightModule.setSwerveModuleState(moduleStates[1]);\n backLeftModule.setSwerveModuleState(moduleStates[2]);\n backRightModule.setSwerveModuleState(moduleStates[3]);\n }\n\n /**\n * Sets the individual swerve module states from chassis speed\n * @param moduleStates\n */\n public void setModuleStates(ChassisSpeeds chassisSpeeds) {\n setModuleStates(Constants.SwerveConstants.m_SwerveDriveKinematics.toSwerveModuleStates(chassisSpeeds));\n }\n\n @Override\n public void periodic() {\n SmartDashboard.putNumber( \"Yaw\", getYaw());\n frontLeftModule.outputDashboard();\n frontRightModule.outputDashboard();\n backLeftModule.outputDashboard();\n backRightModule.outputDashboard();\n m_odometry.update(getRotation2d(), getPositions());\n }\n}" } ]
import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import frc.robot.commands.SwerveDriveFieldCentric; import frc.robot.commands.TranslateDistance; import frc.robot.subsystems.drive.DriveBaseSubsystem;
2,240
package frc.robot; public class RobotContainer { // Joysticks, subsystems, and commands must all be private and final // Joysticks private final XboxController driver = new XboxController(0); //driver //Subsystems
package frc.robot; public class RobotContainer { // Joysticks, subsystems, and commands must all be private and final // Joysticks private final XboxController driver = new XboxController(0); //driver //Subsystems
private final DriveBaseSubsystem driveBase = new DriveBaseSubsystem();
2
2023-11-17 04:37:58+00:00
4k
SoBadFish/Report
src/main/java/org/sobadfish/report/form/DisplayManageForm.java
[ { "identifier": "ReportMainClass", "path": "src/main/java/org/sobadfish/report/ReportMainClass.java", "snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n\n private Config messageConfig;\n\n private Config adminPlayerConfig;\n\n private PlayerInfoManager playerInfoManager;\n\n private List<String> adminPlayers = new ArrayList<>();\n\n\n @Override\n public void onEnable() {\n mainClass = this;\n saveDefaultConfig();\n reloadConfig();\n sendMessageToConsole(\"&e举报系统正在加载\");\n if(!initSql()){\n sendMessageToConsole(\"&c无法接入数据库!\");\n dataManager = new ReportYamlManager(this);\n }\n this.getServer().getPluginManager().registerEvents(new ReportListener(),this);\n reportConfig = new ReportConfig(getConfig());\n saveResource(\"message.yml\",false);\n saveResource(\"players.yml\",false);\n messageConfig = new Config(this.getDataFolder()+\"/message.yml\",Config.YAML);\n adminPlayerConfig = new Config(this.getDataFolder()+\"/players.yml\",Config.YAML);\n adminPlayers = adminPlayerConfig.getStringList(\"admin-players\");\n playerInfoManager = new PlayerInfoManager();\n this.getServer().getCommandMap().register(\"report\",new ReportCommand(\"rp\"));\n this.getServer().getScheduler().scheduleRepeatingTask(this,playerInfoManager,20);\n sendMessageToConsole(\"举报系统加载完成\");\n }\n\n public List<String> getAdminPlayers() {\n return adminPlayers;\n }\n\n public Config getAdminPlayerConfig() {\n return adminPlayerConfig;\n }\n\n public void saveAdminPlayers(){\n adminPlayerConfig.set(\"admin-players\",adminPlayers);\n adminPlayerConfig.save();\n }\n\n public PlayerInfoManager getPlayerInfoManager() {\n return playerInfoManager;\n }\n\n public ReportConfig getReportConfig() {\n return reportConfig;\n }\n\n public Config getMessageConfig() {\n return messageConfig;\n }\n\n public static ReportMainClass getMainClass() {\n return mainClass;\n }\n\n private boolean initSql(){\n sendMessageToConsole(\"初始化数据库\");\n try {\n\n Class.forName(\"com.smallaswater.easysql.EasySql\");\n String user = getConfig().getString(\"mysql.username\");\n int port = getConfig().getInt(\"mysql.port\");\n String url = getConfig().getString(\"mysql.host\");\n String passWorld = getConfig().getString(\"mysql.password\");\n String table = getConfig().getString(\"mysql.database\");\n UserData data = new UserData(user, passWorld, url, port, table);\n SqlManager sql = new SqlManager(this, data);\n dataManager = new ReportSqlManager(sql);\n if (!((ReportSqlManager) dataManager).createTable()) {\n sendMessageToConsole(\"&c创建表单 \" + ReportSqlManager.SQL_TABLE + \" 失败!\");\n }\n sendMessageToConsole(\"&a数据库初始化完成\");\n return true;\n\n }catch (Exception e) {\n sendMessageToConsole(\"&c数据库初始化失败\");\n return false;\n }\n\n }\n\n public static IDataManager getDataManager() {\n return dataManager;\n }\n\n private static void sendMessageToConsole(String msg){\n sendMessageToObject(msg,null);\n }\n\n public static void sendMessageToAdmin(String msg){\n for(Player player: Server.getInstance().getOnlinePlayers().values()){\n if(player.isOp() || getMainClass().adminPlayers.contains(player.getName())){\n sendMessageToObject(msg,player);\n }\n }\n }\n\n public static void sendMessageToObject(String msg, CommandSender target){\n if(target == null){\n mainClass.getLogger().info(formatString(msg));\n }else{\n target.sendMessage(formatString(msg));\n }\n }\n\n public static void sendMessageToAll(String msg){\n Server.getInstance().broadcastMessage(formatString(msg));\n }\n\n\n private static String formatString(String str){\n return TextFormat.colorize('&',\"&7[&e举报系统&7] &r>&r \"+str);\n }\n}" }, { "identifier": "Report", "path": "src/main/java/org/sobadfish/report/config/Report.java", "snippet": "public class Report {\n\n private final int id;\n\n /**\n * 被举报玩家\n * */\n private final String player;\n\n private final String reportMessage;\n\n private final String time;\n\n /**\n * 举报玩家\n * */\n private final String target;\n\n private String manager;\n\n public int delete = 0;\n\n private String managerMsg;\n\n private String managerTime = \"\";\n\n public Report(int id,\n String player,\n String time,\n String reportMessage,\n String target,\n String manager,\n String managerMsg){\n this.id = id;\n this.player = player;\n this.reportMessage = reportMessage;\n this.time = time;\n this.target = target;\n this.manager = manager;\n this.managerMsg = managerMsg;\n }\n\n public int getId() {\n return id;\n }\n\n public String getManager() {\n return manager;\n }\n\n public void setManagerTime(String managerTime) {\n this.managerTime = managerTime;\n }\n\n public String getManagerTime() {\n return managerTime;\n }\n\n public String getManagerMsg() {\n return managerMsg;\n }\n\n public void setManagerMsg(String managerMsg) {\n this.managerMsg = managerMsg;\n }\n\n public void setManager(String manager) {\n this.manager = manager;\n }\n\n\n public String getTime() {\n return time;\n }\n\n public String getPlayer() {\n return player;\n }\n\n public String getReportMessage() {\n return reportMessage;\n }\n\n public String getTarget() {\n return target;\n }\n\n\n}" }, { "identifier": "ReportConfig", "path": "src/main/java/org/sobadfish/report/config/ReportConfig.java", "snippet": "public class ReportConfig {\n\n private final int dayMax;\n\n private final int cold;\n\n private final List<ReportBtn> reportBtns = new ArrayList<>();\n\n\n public ReportConfig(Config config){\n this.dayMax = config.getInt(\"day-max\",20);\n this.cold = config.getInt(\"cold\",2);\n List<Map> c = config.getMapList(\"report-btn\");\n for(Map<?,?> e: c){\n reportBtns.add(new ReportBtn(e.get(\"name\").toString(),e.get(\"cmd\").toString()));\n }\n }\n\n public List<ReportBtn> getReportBtns() {\n return reportBtns;\n }\n\n public int getCold() {\n return cold;\n }\n\n public int getDayMax() {\n return dayMax;\n }\n\n public static class ReportBtn{\n public String name;\n\n public String cmd;\n\n public ReportBtn(String name,String cmd){\n this.name = name;\n this.cmd = cmd;\n }\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/org/sobadfish/report/tools/Utils.java", "snippet": "public class Utils {\n\n private static final SplittableRandom RANDOM = new SplittableRandom(System.currentTimeMillis());\n\n public static int rand(int min, int max) {\n return min == max ? max : RANDOM.nextInt(max + 1 - min) + min;\n }\n\n public static double rand(double min, double max) {\n return min == max ? max : min + Math.random() * (max - min);\n }\n\n public static float rand(float min, float max) {\n return min == max ? max : min + (float)Math.random() * (max - min);\n }\n\n /**\n * 计算两个时间相差天数\n *\n * @param oldDate 终点时间\n *\n * @return 时差\n * */\n public static int getDifferDay(Date oldDate){\n if(oldDate == null) {\n return 0;\n }\n Calendar cal = Calendar.getInstance();\n cal.setTime(oldDate);\n long time1 = cal.getTimeInMillis();\n cal.setTime(Objects.requireNonNull(getDate(getDateToString(new Date()))));\n long time2 = cal.getTimeInMillis();\n long betweenDays = (time1-time2)/(1000*3600*24);\n return Integer.parseInt(String.valueOf(betweenDays));\n }\n\n public static String getDateToString(Date date){\n SimpleDateFormat lsdStrFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n return lsdStrFormat.format(date);\n }\n\n\n\n //转换String为Date\n\n public static Date getDate(String format){\n SimpleDateFormat lsdStrFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n return lsdStrFormat.parse(format);\n }catch (ParseException e){\n return null;\n }\n }\n\n public static String[] splitMsg(String msg){\n String[] rel = msg.split(\"&\");\n if(rel.length <= 1){\n String rr = rel[0].trim();\n if(\"\".equalsIgnoreCase(rr)){\n rr = \"-\";\n }\n rel = new String[]{rr,\"-\"};\n }\n return rel;\n }\n}" } ]
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.ConsoleCommandSender; import cn.nukkit.form.element.ElementDropdown; import cn.nukkit.form.element.ElementInput; import cn.nukkit.form.element.ElementLabel; import cn.nukkit.form.response.FormResponseCustom; import cn.nukkit.form.window.FormWindowCustom; import cn.nukkit.utils.TextFormat; import org.sobadfish.report.ReportMainClass; import org.sobadfish.report.config.Report; import org.sobadfish.report.config.ReportConfig; import org.sobadfish.report.tools.Utils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List;
2,486
package org.sobadfish.report.form; /** * @author Sobadfish * @date 2023/11/14 */ public class DisplayManageForm { public static LinkedHashMap<Player, DisplayManageForm> DISPLAY_FROM = new LinkedHashMap<>(); private final int id; private int reportId; public static int getRid(){
package org.sobadfish.report.form; /** * @author Sobadfish * @date 2023/11/14 */ public class DisplayManageForm { public static LinkedHashMap<Player, DisplayManageForm> DISPLAY_FROM = new LinkedHashMap<>(); private final int id; private int reportId; public static int getRid(){
return Utils.rand(31000,41000);
3
2023-11-15 03:08:23+00:00
4k
daobab-projects/orm-performance-comparator
src/main/java/io/daobab/performance/invoker/InvokerService.java
[ { "identifier": "SakilaDataBase", "path": "src/main/java/io/daobab/performance/daobab/SakilaDataBase.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class SakilaDataBase extends DataBaseTarget implements SakilaTables, SqlProducer {\n\n private final RentalGenerator rentalGenerator;\n boolean recreate_database_on_start = false;\n @Value(\"${spring.datasource.url}\")\n private String url;\n @Value(\"${spring.datasource.username}\")\n private String user;\n @Value(\"${spring.datasource.password}\")\n private String pass;\n @Value(\"${spring.datasource.driverClassName}\")\n private String driverClassName;\n\n @Override\n protected DataSource initDataSource() {\n\n var config = new HikariConfig();\n config.setJdbcUrl(url);\n config.setUsername(user);\n config.setPassword(pass);\n config.setDriverClassName(driverClassName);\n config.setSchema(\"PUBLIC\");\n var db = new HikariDataSource(config);\n\n if (recreate_database_on_start) {\n createDatabaseContent(db);\n }\n\n return db;\n }\n\n @PostConstruct\n public void init() {\n getAccessProtector().setColumnAccess(tabActor.colLastName(), Access.NO_INSERT, Access.NO_UPDATE);\n setShowSql(false);\n }\n\n\n @Override\n public List<Entity> initTables() {\n return Arrays.asList(\n tabActor,\n tabAddress,\n tabCategory,\n tabCity,\n tabCountry,\n tabCustomer,\n tabFilm,\n tabFilmActor,\n tabFilmCategory,\n tabFilmText,\n tabInventory,\n tabLanguage,\n tabPayment,\n tabRental,\n tabStaff,\n tabStore\n );\n }\n\n\n private void createDatabaseContent(DataSource ds) {\n\n try {\n var con = ds.getConnection();\n\n RunScript.execute(con, new BufferedReader(\n new InputStreamReader(new ClassPathResource(\"schema.sql\").getInputStream())));\n\n RunScript.execute(con, new BufferedReader(\n new InputStreamReader(new ClassPathResource(\"data.sql\").getInputStream())));\n\n } catch (Exception e) {\n e.printStackTrace();\n throw new RuntimeException(\"Database initialize script error\");\n }\n\n }\n\n @Override\n public <E extends Entity> DataBaseIdGeneratorSupplier<?> getPrimaryKeyGenerator(E entity) {\n\n if (entity.getClass().equals(Rental.class)) {\n return rentalGenerator;\n }\n return null;\n }\n\n}" }, { "identifier": "SakilaTables", "path": "src/main/java/io/daobab/performance/daobab/SakilaTables.java", "snippet": "package io.daobab.performance.daobab;\r\rimport io.daobab.parser.ParserGeneral;\rimport io.daobab.performance.daobab.table.*;\rimport io.daobab.performance.daobab.table.enhanced.CountryCity;\rimport io.daobab.performance.daobab.table.enhanced.EnglishFilm;\rimport io.daobab.target.database.query.base.QueryDataBaseWhisperer;\r\r\rpublic interface SakilaTables extends ParserGeneral, QueryDataBaseWhisperer {\r\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * ActorId(PK) Integer 5 ACTOR_ID SMALLINT\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r Actor tabActor = new Actor();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Address String 50 ADDRESS VARCHAR\r * Address2 String 50 ADDRESS2 VARCHAR\r * AddressId(PK) Integer 5 ADDRESS_ID SMALLINT\r * CityId Integer 5 CITY_ID SMALLINT\r * District String 20 DISTRICT VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Phone String 20 PHONE VARCHAR\r * PostalCode String 10 POSTAL_CODE VARCHAR\r * </pre>\r */\r Address tabAddress = new Address();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CategoryId(PK) Integer 3 CATEGORY_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Name String 25 NAME VARCHAR\r * </pre>\r */\r Category tabCategory = new Category();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * City String 50 CITY VARCHAR\r * CityId(PK) Integer 5 CITY_ID SMALLINT\r * CountryId Integer 5 COUNTRY_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r City tabCity = new City();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Country String 50 COUNTRY VARCHAR\r * CountryId(PK) Integer 5 COUNTRY_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r Country tabCountry = new Country();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Active Boolean 1 ACTIVE BOOLEAN\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * CreateDate Timestamp 26 CREATE_DATE TIMESTAMP\r * CustomerId(PK) Integer 5 CUSTOMER_ID SMALLINT\r * Email String 50 EMAIL VARCHAR\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * StoreId Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Customer tabCustomer = new Customer();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Description String 2147483647 DESCRIPTION VARCHAR\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LanguageId Integer 3 LANGUAGE_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Length Integer 5 LENGTH SMALLINT\r * OriginalLanguageId Integer 3 ORIGINAL_LANGUAGE_ID TINYINT\r * Rating String 5 RATING VARCHAR\r * ReleaseYear Date 10 RELEASE_YEAR DATE\r * RentalDuration Integer 3 RENTAL_DURATION TINYINT\r * RentalRate BigDecimal 4 RENTAL_RATE DECIMAL\r * ReplacementCost BigDecimal 5 REPLACEMENT_COST DECIMAL\r * SpecialFeatures String 54 SPECIAL_FEATURES VARCHAR\r * Title String 255 TITLE VARCHAR\r * </pre>\r */\r Film tabFilm = new Film();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * ActorId(PK) Integer 5 ACTOR_ID SMALLINT\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r FilmActor tabFilmActor = new FilmActor();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CategoryId(PK) Integer 3 CATEGORY_ID TINYINT\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r FilmCategory tabFilmCategory = new FilmCategory();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Description String 2147483647 DESCRIPTION VARCHAR\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * Title String 255 TITLE VARCHAR\r * </pre>\r */\r FilmText tabFilmText = new FilmText();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * FilmId Integer 5 FILM_ID SMALLINT\r * InventoryId(PK) BigDecimal 10 INVENTORY_ID INTEGER\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * StoreId Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Inventory tabInventory = new Inventory();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * LanguageId(PK) Integer 3 LANGUAGE_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Name String 20 NAME VARCHAR\r * </pre>\r */\r Language tabLanguage = new Language();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Amount BigDecimal 5 AMOUNT DECIMAL\r * CustomerId Integer 5 CUSTOMER_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * PaymentDate Timestamp 26 PAYMENT_DATE TIMESTAMP\r * PaymentId(PK) Integer 5 PAYMENT_ID SMALLINT\r * RentalId BigDecimal 10 RENTAL_ID INTEGER\r * StaffId Integer 3 STAFF_ID TINYINT\r * </pre>\r */\r Payment tabPayment = new Payment();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CustomerId Integer 5 CUSTOMER_ID SMALLINT\r * InventoryId BigDecimal 10 INVENTORY_ID INTEGER\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * RentalDate Timestamp 26 RENTAL_DATE TIMESTAMP\r * RentalId(PK) BigDecimal 10 RENTAL_ID INTEGER\r * ReturnDate Timestamp 26 RETURN_DATE TIMESTAMP\r * StaffId Integer 3 STAFF_ID TINYINT\r * </pre>\r */\r Rental tabRental = new Rental();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Active Boolean 1 ACTIVE BOOLEAN\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * Email String 50 EMAIL VARCHAR\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Password String 40 PASSWORD VARCHAR\r * Picture byte[] 2147483647 PICTURE VARBINARY\r * StaffId(PK) Integer 3 STAFF_ID TINYINT\r * StoreId Integer 3 STORE_ID TINYINT\r * Username String 16 USERNAME VARCHAR\r * </pre>\r */\r Staff tabStaff = new Staff();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * ManagerStaffId Integer 3 MANAGER_STAFF_ID TINYINT\r * StoreId(PK) Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Store tabStore = new Store();\r\r //===================================\r\r /**\r * Enhanced Entity\r */\r EnglishFilm tabEnglishFilm = new EnglishFilm();\r\r\r /**\r * Enhanced Entity\r */\r CountryCity tabCountryCity = new CountryCity();\r}\r" } ]
import io.daobab.performance.daobab.SakilaDataBase; import io.daobab.performance.daobab.SakilaTables; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import static java.lang.String.format;
3,457
package io.daobab.performance.invoker; @Component @Slf4j @RequiredArgsConstructor public class InvokerService implements SakilaTables {
package io.daobab.performance.invoker; @Component @Slf4j @RequiredArgsConstructor public class InvokerService implements SakilaTables {
private final SakilaDataBase db;
0
2023-11-12 21:43:51+00:00
4k
lastnightinparis/tinkoff-investement-bot
bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/update/impl/CallbackUpdateHandler.java
[ { "identifier": "BotUserDeniedException", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/chat/BotUserDeniedException.java", "snippet": "public class BotUserDeniedException extends ChatException {\n\n public BotUserDeniedException(Long chatId) {\n super(chatId);\n }\n\n}" }, { "identifier": "ProcessingException", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/chat/ProcessingException.java", "snippet": "public class ProcessingException extends ChatException {\n\n public ProcessingException(Long chatId, String message) {\n super(chatId, message);\n }\n\n public ProcessingException(Long chatId, String message, Throwable cause) {\n super(chatId, message, cause);\n }\n\n public String getMasterMessage() {\n return String.format(\"#processing_error\\nChat ID: %d, Message: %s\", getChatId(), getMessage());\n }\n}" }, { "identifier": "UnknownUserException", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/chat/UnknownUserException.java", "snippet": "public class UnknownUserException extends ChatException {\n\n public UnknownUserException(Long chatId) {\n super(chatId);\n }\n}" }, { "identifier": "IllegalTradingBotException", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/system/IllegalTradingBotException.java", "snippet": "public class IllegalTradingBotException extends TradingBotException {\n\n public IllegalTradingBotException(String message) {\n super(message);\n }\n\n public IllegalTradingBotException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "UpdateHandlersRegistry", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/registry/UpdateHandlersRegistry.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class UpdateHandlersRegistry {\n\n @Qualifier(\"textHandlers\")\n private final Map<BotState, TextUpdate> textHandlers;\n @Qualifier(\"callbackHandlers\")\n private final Map<BotState, CallbackUpdate> callbackHandlers;\n\n public TextUpdate getTextHandlerFor(BotState botState) {\n if (textHandlers.containsKey(botState)) {\n return textHandlers.get(botState);\n }\n throw new IllegalTradingBotException(\"Unknown text handler botState: \" + botState.toString());\n }\n\n public CallbackUpdate getCallbackHandlerFor(BotState botState) {\n if (callbackHandlers.containsKey(botState)) {\n return callbackHandlers.get(botState);\n }\n throw new IllegalTradingBotException(\n \"Unknown callback handler botState: \" + botState.toString());\n }\n}" }, { "identifier": "BotUpdateHandler", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/update/BotUpdateHandler.java", "snippet": "public interface BotUpdateHandler {\n\n void handelUpdates(Update update);\n\n UpdateType supportedUpdateType();\n}" }, { "identifier": "User", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/domain/User.java", "snippet": "@Data\n@Entity\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = \"users\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"chat_id\")\n private Long chatId;\n\n @Column(name = \"username\")\n private String username;\n\n @Column(name = \"tg_username\")\n private String tgUsername;\n\n @Column(name = \"is_active\")\n private boolean active;\n\n @Column(name = \"is_blocked\")\n private boolean blocked;\n\n @Column(name = \"is_connected_account\")\n private boolean connectedInvestAccount;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"bot_state\")\n private BotState botState;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"prev_bot_state\")\n private BotState previousBotState;\n\n @Column(name = \"registered_at\")\n private Instant registeredAt;\n\n @Column(name = \"last_activity_at\")\n private Instant lastActivityAt;\n}" }, { "identifier": "CallbackType", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/bot/CallbackType.java", "snippet": "@Getter\npublic enum CallbackType {\n\n STRATEGY(\"strategy\", BotState.CHOOSE_STRATEGY_ACTION),\n CHOOSE_PARAM(\"chooseStrategyParam\", BotState.CHOOSE_STRATEGY_PARAM),\n EDIT_NOTIFICATION_EVENT(\"editNotificationEvent\", BotState.START),\n CANCEL_NOTIFICATION_EVENT(\"cancelNotificationEvent\", BotState.START),\n INVEST_ACCOUNT_ACTION(\"InvestAccount\", BotState.INVEST_ACCOUNT_ACTION),\n CHOOSE_TYPE_OF_CHANGING(\"chooseTypeOfChange\", BotState.START);\n\n private final String message;\n private final BotState botState;\n\n CallbackType(String message, BotState botState) {\n this.message = message;\n this.botState = botState;\n }\n\n public String getFullMessage(String prefix) {\n return message + \"_\" + prefix;\n }\n\n public static Optional<CallbackType> findByMessage(String message) {\n return Stream.of(CallbackType.values())\n .filter(button -> message.startsWith(button.message))\n .findFirst();\n }\n}" }, { "identifier": "UpdateType", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/handler/UpdateType.java", "snippet": "public enum UpdateType {\n TEXT,\n CALLBACK\n}" }, { "identifier": "BotSenderService", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/bot/BotSenderService.java", "snippet": "public interface BotSenderService {\n\n Message sendMessage(SendMessage message);\n\n CompletableFuture<Message> sendDocumentAsync(SendDocument message);\n\n Boolean sendAnswerCallbackQuery(AnswerCallbackQuery answerCallbackQuery);\n\n CompletableFuture<Serializable> sendEditMessageTextAsync(EditMessageText editMessageText);\n\n CompletableFuture<Message> sendMessageAsync(SendMessage message, long sleepTime);\n\n void notifyMasters(String message);\n\n Future<Boolean> sendNewsLetter(List<Long> chatIds, String message,\n InlineKeyboardMarkup keyboardMarkup);\n}" }, { "identifier": "UserService", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/users/UserService.java", "snippet": "public interface UserService {\n\n List<User> findAll();\n\n Optional<User> findUserByChatId(long chatId);\n\n Optional<User> findUserByTgUsername(String tgUsername);\n\n List<Long> getAdminChatIds();\n\n User getUserById(Long id);\n\n User getUserByChatId(Long chatId);\n\n User save(User user);\n\n User setCurrentBotState(Long chatId, BotState botState);\n\n boolean isNew(Long chatId);\n}" } ]
import com.itmo.tinkoffinvestementbot.exception.chat.BotUserDeniedException; import com.itmo.tinkoffinvestementbot.exception.chat.ProcessingException; import com.itmo.tinkoffinvestementbot.exception.chat.UnknownUserException; import com.itmo.tinkoffinvestementbot.exception.system.IllegalTradingBotException; import com.itmo.tinkoffinvestementbot.handler.registry.UpdateHandlersRegistry; import com.itmo.tinkoffinvestementbot.handler.update.BotUpdateHandler; import com.itmo.tinkoffinvestementbot.model.domain.User; import com.itmo.tinkoffinvestementbot.model.enums.bot.CallbackType; import com.itmo.tinkoffinvestementbot.model.enums.handler.UpdateType; import com.itmo.tinkoffinvestementbot.service.bot.BotSenderService; import com.itmo.tinkoffinvestementbot.service.users.UserService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; import org.telegram.telegrambots.meta.api.objects.CallbackQuery; import org.telegram.telegrambots.meta.api.objects.Update; import java.util.Optional;
2,014
package com.itmo.tinkoffinvestementbot.handler.update.impl; @Slf4j @Component @RequiredArgsConstructor public class CallbackUpdateHandler implements BotUpdateHandler { private final UserService userService; private final BotSenderService senderService; private final UpdateHandlersRegistry updateHandlersRegistry; @Override public void handelUpdates(Update update) { CallbackQuery callbackQuery = update.getCallbackQuery(); Long userChatId = callbackQuery.getFrom().getId(); senderService.sendAnswerCallbackQuery( AnswerCallbackQuery.builder() .callbackQueryId(callbackQuery.getId()) .build() ); User user; if (userService.isNew(userChatId)) { // Если пользователь новый if (callbackQuery.getFrom().getIsBot()) { // Если пользователь является ботом throw new BotUserDeniedException(userChatId); } else { // Если новый пользователь не является ботом
package com.itmo.tinkoffinvestementbot.handler.update.impl; @Slf4j @Component @RequiredArgsConstructor public class CallbackUpdateHandler implements BotUpdateHandler { private final UserService userService; private final BotSenderService senderService; private final UpdateHandlersRegistry updateHandlersRegistry; @Override public void handelUpdates(Update update) { CallbackQuery callbackQuery = update.getCallbackQuery(); Long userChatId = callbackQuery.getFrom().getId(); senderService.sendAnswerCallbackQuery( AnswerCallbackQuery.builder() .callbackQueryId(callbackQuery.getId()) .build() ); User user; if (userService.isNew(userChatId)) { // Если пользователь новый if (callbackQuery.getFrom().getIsBot()) { // Если пользователь является ботом throw new BotUserDeniedException(userChatId); } else { // Если новый пользователь не является ботом
throw new UnknownUserException(userChatId);
2
2023-11-13 09:28:00+00:00
4k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/manager/ResourcePackManagerImpl.java
[ { "identifier": "InventoryAPI", "path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java", "snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontManager fontManager;\n private ResourcePackManager resourcePackManager;\n\n @Override\n public final void onLoad() {\n if (api != null) throw new SecurityException();\n api = this;\n }\n\n public static @NotNull InventoryAPI getInstance() {\n return Objects.requireNonNull(api);\n }\n\n public final void setFontManager(@NotNull FontManager fontManager) {\n this.fontManager = Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull FontManager getFontManager() {\n return Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull ImageManager getImageManager() {\n return Objects.requireNonNull(imageManager);\n }\n\n public final void setImageManager(@NotNull ImageManager imageManager) {\n this.imageManager = Objects.requireNonNull(imageManager);\n }\n\n public final void setResourcePackManager(@NotNull ResourcePackManager resourcePackManager) {\n this.resourcePackManager = Objects.requireNonNull(resourcePackManager);\n }\n\n public @NotNull ResourcePackManager getResourcePackManager() {\n return Objects.requireNonNull(resourcePackManager);\n }\n public final void reload() {\n reload(true);\n }\n\n public abstract void reload(boolean callEvent);\n public void reload(@NotNull Consumer<Long> longConsumer) {\n var pluginManager = Bukkit.getPluginManager();\n pluginManager.callEvent(new PluginReloadStartEvent());\n Bukkit.getScheduler().runTaskAsynchronously(this, () -> {\n var time = System.currentTimeMillis();\n reload(false);\n var time2 = System.currentTimeMillis() - time;\n Bukkit.getScheduler().runTask(this, () -> {\n pluginManager.callEvent(new PluginReloadEndEvent());\n longConsumer.accept(time2);\n });\n });\n }\n\n public @NotNull ItemStack getEmptyItem(@NotNull Consumer<ItemMeta> metaConsumer) {\n var stack = new ItemStack(getResourcePackManager().getEmptyMaterial());\n var meta = stack.getItemMeta();\n assert meta != null;\n metaConsumer.accept(meta);\n meta.setCustomModelData(1);\n stack.setItemMeta(meta);\n return stack;\n }\n public abstract @NotNull MiniMessage miniMessage();\n public abstract @NotNull GuiFont defaultFont();\n public abstract void openGui(@NotNull Player player, @NotNull Gui gui, @NotNull GuiType type, long delay, @NotNull GuiExecutor executor);\n}" }, { "identifier": "GuiFont", "path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiFont.java", "snippet": "@Getter\npublic final class GuiFont implements GuiResource {\n\n public static final FontRenderContext CONTEXT = new FontRenderContext(null, true, true);\n public static final double VERTICAL_SIZE = 1.4;\n\n private final @NotNull String name;\n private final @NotNull Font font;\n private final int size;\n private final @NotNull Map<Character, Function<Integer, Integer>> fontWidth;\n private final @NotNull List<Character> availableChar;\n private final @NotNull FontMetrics metrics;\n\n public GuiFont(@NotNull Font font, @NotNull String name) {\n this(font, name, 16);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size) {\n this(font, name, size, 0);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size, double width) {\n this(font, name, size, width, 1);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size, double width, double widthMultiplier) {\n this.font = font.deriveFont((float) size);\n this.name = name;\n this.size = size;\n var widthMap = new TreeMap<@NotNull Character, @NotNull Function<Integer, Integer>>();\n IntStream.rangeClosed(Character.MIN_VALUE, Character.MAX_VALUE).mapToObj(i -> (char) i).filter(font::canDisplay).forEach(c -> {\n var str = this.font.getStringBounds(Character.toString(c), CONTEXT);\n widthMap.put(c, i -> (int) Math.round((str.getWidth() * i / VERTICAL_SIZE / str.getHeight() + width) * widthMultiplier));\n });\n fontWidth = ImmutableMap.copyOf(widthMap);\n var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).createGraphics();\n metrics = graphics.getFontMetrics(this.font);\n graphics.dispose();\n var c = new ArrayList<>(widthMap.keySet());\n availableChar = ImmutableList.copyOf(c.subList(0, c.size() - c.size() % 16));\n }\n}" }, { "identifier": "GuiObjectGenerator", "path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiObjectGenerator.java", "snippet": "public interface GuiObjectGenerator {\n int getAscent();\n int getHeight();\n @NotNull GuiObjectBuilder builder();\n @NotNull Key getFontKey();\n}" }, { "identifier": "GuiResource", "path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiResource.java", "snippet": "public interface GuiResource {\n default @NotNull GuiObjectGenerator generator(int height, int ascent) {\n return InventoryAPI.getInstance().getResourcePackManager().registerTask(this, height, ascent);\n }\n}" }, { "identifier": "ResourcePackManager", "path": "api/src/main/java/kor/toxicity/inventory/api/manager/ResourcePackManager.java", "snippet": "public interface ResourcePackManager extends InventoryManager {\n @NotNull GuiObjectGenerator registerTask(@NotNull GuiResource resource, int height, int ascent);\n @NotNull Material getEmptyMaterial();\n}" }, { "identifier": "JsonArrayBuilder", "path": "plugin/src/main/java/kor/toxicity/inventory/builder/JsonArrayBuilder.java", "snippet": "public class JsonArrayBuilder {\n private final JsonArray array = new JsonArray();\n\n\n public JsonArrayBuilder add(Number value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(Character value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(String value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(Boolean value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(JsonElement value) {\n array.add(value);\n return this;\n }\n\n public JsonArray build() {\n return array;\n }\n}" }, { "identifier": "JsonObjectBuilder", "path": "plugin/src/main/java/kor/toxicity/inventory/builder/JsonObjectBuilder.java", "snippet": "public class JsonObjectBuilder {\n private final JsonObject object = new JsonObject();\n\n\n public JsonObjectBuilder add(String key, Number value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, Character value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, String value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, Boolean value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, JsonElement value) {\n object.add(key, value);\n return this;\n }\n\n public JsonObject build() {\n return object;\n }\n}" }, { "identifier": "FontObjectGeneratorImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/generator/FontObjectGeneratorImpl.java", "snippet": "public class FontObjectGeneratorImpl implements FontObjectGenerator {\n\n private final GuiFont font;\n private final int height;\n private final int ascent;\n @Getter\n private final String fontTitle;\n private final Key key;\n\n public FontObjectGeneratorImpl(GuiFont font, int height, int ascent) {\n this.font = font;\n this.height = height;\n this.ascent = ascent;\n fontTitle = font.getName() + \"_\" + height + \"_\" + ascent;\n key = Key.key(\"inventory:font/\" + fontTitle);\n }\n\n @Override\n public @NotNull GuiFont getFont() {\n return font;\n }\n\n @Override\n public int getAscent() {\n return ascent;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n\n @Override\n public @NotNull GuiObjectBuilder builder() {\n return new FontObjectBuilder() {\n private int space = 6;\n private String text = \"none\";\n private int xOffset = 0;\n private Style style = Style.empty();\n\n @Override\n public @NotNull FontObjectBuilder setSpace(int space) {\n this.space = space;\n return this;\n }\n\n @Override\n public @NotNull FontObjectBuilder setText(@NotNull String text) {\n this.text = Objects.requireNonNull(text);\n return this;\n }\n\n @Override\n public @NotNull GuiObjectBuilder setXOffset(int xOffset) {\n this.xOffset = xOffset;\n return this;\n }\n\n @Override\n public @NotNull FontObjectBuilder setStyle(@NotNull Style style) {\n this.style = Objects.requireNonNull(style);\n return this;\n }\n\n @Override\n public @NotNull GuiObject build() {\n return new FontObjectImpl(FontObjectGeneratorImpl.this, text, style, space, xOffset);\n }\n };\n }\n\n @Override\n public @NotNull Key getFontKey() {\n return key;\n }\n}" }, { "identifier": "ImageObjectGeneratorImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/generator/ImageObjectGeneratorImpl.java", "snippet": "public class ImageObjectGeneratorImpl implements ImageObjectGenerator, Comparable<ImageObjectGeneratorImpl> {\n\n private static final Key GUI_KEY = Key.key(\"inventory:gui\");\n private static int serialNumber = 0xD0000;\n\n public static void initialize() {\n serialNumber = 0xD0000;\n }\n\n private final GuiImage image;\n private final int height;\n private final int ascent;\n @Getter\n private final String serialChar;\n private final int compareNumber;\n\n public ImageObjectGeneratorImpl(GuiImage image, int height, int ascent) {\n this.image = image;\n this.height = height;\n this.ascent = ascent;\n compareNumber = ++serialNumber;\n serialChar = AdventureUtil.parseChar(compareNumber);\n }\n @Override\n public int getAscent() {\n return ascent;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n @Override\n public @NotNull GuiObjectBuilder builder() {\n return new ImageObjectBuilder() {\n private int xOffset;\n @Override\n public @NotNull GuiObjectBuilder setXOffset(int xOffset) {\n this.xOffset = xOffset;\n return this;\n }\n\n @Override\n public @NotNull GuiObject build() {\n return new ImageObjectImpl(ImageObjectGeneratorImpl.this, xOffset);\n }\n };\n }\n\n @Override\n public @NotNull Key getFontKey() {\n return GUI_KEY;\n }\n\n @Override\n public @NotNull GuiImage getImage() {\n return image;\n }\n\n @Override\n public int compareTo(@NotNull ImageObjectGeneratorImpl o) {\n return Integer.compare(compareNumber, o.compareNumber);\n }\n}" }, { "identifier": "PluginUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/PluginUtil.java", "snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\npublic class PluginUtil {\n private PluginUtil() {\n throw new SecurityException();\n }\n\n public static void loadFolder(String dir, Consumer<File> fileConsumer) {\n var dataFolder = InventoryAPI.getInstance().getDataFolder();\n if (!dataFolder.exists()) dataFolder.mkdir();\n var folder = new File(dataFolder, dir);\n if (!folder.exists()) folder.mkdir();\n var listFiles = folder.listFiles();\n if (listFiles != null) for (File listFile : listFiles) {\n fileConsumer.accept(listFile);\n }\n }\n\n public static FileName getFileName(File file) {\n var name = file.getName().split(\"\\\\.\");\n return new FileName(name[0], name.length > 1 ? name[1] : \"\");\n }\n\n public static void warn(String message) {\n InventoryAPI.getInstance().getLogger().warning(message);\n }\n\n public record FileName(String name, String extension) {\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.stream.JsonWriter; import kor.toxicity.inventory.api.InventoryAPI; import kor.toxicity.inventory.api.gui.GuiFont; import kor.toxicity.inventory.api.gui.GuiImage; import kor.toxicity.inventory.api.gui.GuiObjectGenerator; import kor.toxicity.inventory.api.gui.GuiResource; import kor.toxicity.inventory.api.manager.ResourcePackManager; import kor.toxicity.inventory.builder.JsonArrayBuilder; import kor.toxicity.inventory.builder.JsonObjectBuilder; import kor.toxicity.inventory.generator.FontObjectGeneratorImpl; import kor.toxicity.inventory.generator.ImageObjectGeneratorImpl; import kor.toxicity.inventory.util.PluginUtil; import lombok.Getter; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List;
3,210
package kor.toxicity.inventory.manager; public class ResourcePackManagerImpl implements ResourcePackManager { private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();
package kor.toxicity.inventory.manager; public class ResourcePackManagerImpl implements ResourcePackManager { private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();
private final List<ImageObjectGeneratorImpl> images = new ArrayList<>();
8
2023-11-13 00:19:46+00:00
4k
Hikaito/Fox-Engine
src/system/project/treeElements/ProjectTypeAdapter.java
[ { "identifier": "ProjectFile", "path": "src/system/project/treeElements/ProjectFile.java", "snippet": "public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> {\n\n // constructor\n public ProjectFile(String title, long id){\n super(\"file\", id); //super\n this.title = title;\n }\n\n // longer constructor\n public ProjectFile(String path, String title, long id){\n super(\"file\", id); //super\n this.path = path;\n this.title = title;\n }\n\n //path for file\n @Expose\n @SerializedName(value = \"filepath\")\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n public void setNewPath(String directory, String path){\n // reject if directory doesn't match\n if(!(directory.equals(path.substring(0, directory.length())))){\n WarningWindow.warningWindow(\"File rejected; must be in root folder.\");\n return;\n }\n\n this.path = FileOperations.trimDirectory(directory, path).toString(); // get relative path\n fileValid = true;\n }\n\n //file validation function\n protected boolean fileValid = false;\n public boolean isValid(){return fileValid;}\n public void setValid(boolean state){fileValid = state;}\n\n //boolean for use color\n @Expose\n @SerializedName(value = \"use_color\")\n protected boolean use_color = true;\n public void setUseColor(boolean set){use_color = set;}\n public boolean getUseColor(){return use_color;}\n\n //Color to use\n @Expose\n @SerializedName(value = \"color\")\n public Color color = Color.lightGray;\n public void setColor(Color color){this.color = color;}\n public Color getColor(){return color;}\n\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n }\n\n // used for sorting during save and load\n @Override\n public int compareTo(ProjectFile o) {\n return path.compareTo(o.getPath());\n }\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // only add to tree if valid file\n if(fileValid){\n // add self to menu\n JMenuItem menu = new JMenuItem(this.getTitle());\n root.add(menu);\n\n // when clicked, generate new layer with file\n menu.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n BufferedImage image = Program.getImage(getID());\n //if image loaded properly, initalize a node\n if (image != null){\n Program.addLayer(id, use_color, color);\n }\n else{\n Program.log(\"File missing for element \" + title + \" at \" + path);\n }\n }\n });\n }\n }\n}" }, { "identifier": "ProjectFolder", "path": "src/system/project/treeElements/ProjectFolder.java", "snippet": "public class ProjectFolder extends ProjectCore implements ProjectFolderInterface {\n\n //constructor\n public ProjectFolder(String title, long id){\n super(\"folder\", id);\n this.title = title;\n }\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n }\n //endregion\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // add self to menu\n JMenu menu = new JMenu(this.getTitle());\n root.add(menu);\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n }\n\n}" }, { "identifier": "ProjectRoot", "path": "src/system/project/treeElements/ProjectRoot.java", "snippet": "public class ProjectRoot extends ProjectUnitCore implements ProjectFolderInterface {\n\n // constructor\n public ProjectRoot(){\n super(\"root\"); //set type to root\n this.title = \"Project\";\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // longer constructor\n public ProjectRoot(String title){\n super(\"root\"); //set type to root\n this.title = title; //set title\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // unique project identifier\n @Expose\n @SerializedName(value = \"UUID\")\n protected final String uuid;\n public String getUUID(){return uuid;}\n\n // count for layer ID [saves space as it is smaller]\n @Expose\n @SerializedName(value = \"current_layer_id\")\n protected long layerIDIterate = 0;\n public long getNextID(){\n return layerIDIterate++;\n }\n public long checkID(){return layerIDIterate;}\n\n //directory of project (set at load)\n //path for file\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n\n // program path\n @Expose\n @SerializedName(value=\"program_version\")\n protected VersionNumber programVersion;\n public VersionNumber getProgramVersion(){return programVersion;}\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public DefaultMutableTreeNode getTree(){\n // create tree root\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n\n return cat;\n }\n //endregion\n\n JMenu menu = null;\n\n //build menu for menubar\n public JMenu generateMenu(){\n //create menu element for self; initalize when necessary\n if(menu == null){\n menu = new JMenu(getTitle());\n }\n else{\n menu.removeAll();\n menu.setText(getTitle());\n }\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n\n menu.revalidate();\n return menu;\n }\n}" } ]
import com.google.gson.*; import system.project.treeElements.ProjectFile; import system.project.treeElements.ProjectFolder; import system.project.treeElements.ProjectRoot; import java.lang.reflect.Type;
2,094
package system.project.treeElements; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectTypeAdapter implements JsonDeserializer { @Override public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // retrieve json JsonObject json = jsonElement.getAsJsonObject(); // case switching for type if (json.get("type").getAsString().equals("file")) return jsonDeserializationContext.deserialize(jsonElement, ProjectFile.class); if (json.get("type").getAsString().equals("folder")) return jsonDeserializationContext.deserialize(jsonElement, ProjectFolder.class); if (json.get("type").getAsString().equals("root"))
package system.project.treeElements; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectTypeAdapter implements JsonDeserializer { @Override public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // retrieve json JsonObject json = jsonElement.getAsJsonObject(); // case switching for type if (json.get("type").getAsString().equals("file")) return jsonDeserializationContext.deserialize(jsonElement, ProjectFile.class); if (json.get("type").getAsString().equals("folder")) return jsonDeserializationContext.deserialize(jsonElement, ProjectFolder.class); if (json.get("type").getAsString().equals("root"))
return jsonDeserializationContext.deserialize(jsonElement, ProjectRoot.class);
2
2023-11-12 21:12:21+00:00
4k
shizotoaster/thaumon
fabric/src/main/java/jdlenl/thaumon/fabric/ThaumonFabric.java
[ { "identifier": "Thaumon", "path": "common/src/main/java/jdlenl/thaumon/Thaumon.java", "snippet": "public class Thaumon {\n public static final String MOD_ID = \"thaumon\";\n public static Logger logger = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n ThaumonItems.init();\n ThaumonBlocks.init();\n }\n}" }, { "identifier": "ThaumonItemGroupFabric", "path": "fabric/src/main/java/jdlenl/thaumon/itemgroup/fabric/ThaumonItemGroupFabric.java", "snippet": "public class ThaumonItemGroupFabric {\n public static final ItemGroup THAUMON_GROUP = Registry.register(Registries.ITEM_GROUP, new Identifier(Thaumon.MOD_ID, \"thaumon_item_group\"),\n FabricItemGroup.builder().displayName(Text.translatable(\"itemgroup.thaumon.thaumon_item_group\")).icon(() -> new ItemStack(ThaumonBlocks.ELDRITCH_LANTERN.get().asItem()))\n .entries(((displayContext, entries) -> {\n entries.add(ThaumonBlocks.AMBER.get());\n entries.add(ThaumonBlocks.AMBER_STAIRS.get());\n entries.add(ThaumonBlocks.AMBER_SLAB.get());\n entries.add(ThaumonBlocks.AMBER_BRICKS.get());\n entries.add(ThaumonBlocks.AMBER_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.AMBER_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.AMBERGLASS.get());\n entries.add(ThaumonBlocks.AMBERGLASS_PANE.get());\n\n entries.add(ThaumonBlocks.GREATWOOD_LOG.get());\n entries.add(ThaumonBlocks.GREATWOOD_WOOD.get());\n entries.add(ThaumonBlocks.GREATWOOD_LOG_WALL.get());\n entries.add(ThaumonBlocks.GREATWOOD_LOG_POST.get());\n entries.add(ThaumonBlocks.GREATWOOD_PLANKS.get());\n entries.add(ThaumonBlocks.GREATWOOD_STAIRS.get());\n entries.add(ThaumonBlocks.GREATWOOD_SLAB.get());\n entries.add(ThaumonBlocks.GREATWOOD_DOOR.get());\n entries.add(ThaumonBlocks.GREATWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.GILDED_GREATWOOD_DOOR.get());\n entries.add(ThaumonBlocks.GILDED_GREATWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.GREATWOOD_FENCE.get());\n entries.add(ThaumonBlocks.GREATWOOD_FENCE_GATE.get());\n entries.add(ThaumonBlocks.GREATWOOD_WINDOW.get());\n entries.add(ThaumonBlocks.GREATWOOD_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.EMPTY_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.CLASSIC_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.DUSTY_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.ALCHEMISTS_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.GREATWOOD_GRIMOIRE_BOOKSHELF.get());\n entries.add(ThaumonBlocks.GREATWOOD_BUTTON.get());\n entries.add(ThaumonBlocks.GREATWOOD_PRESSURE_PLATE.get());\n\n entries.add(ThaumonBlocks.SILVERWOOD_LOG.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WOOD.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LOG_WALL.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LOG_POST.get());\n entries.add(ThaumonBlocks.SILVERWOOD_PLANKS.get());\n entries.add(ThaumonBlocks.SILVERWOOD_STAIRS.get());\n entries.add(ThaumonBlocks.SILVERWOOD_SLAB.get());\n entries.add(ThaumonBlocks.SILVERWOOD_DOOR.get());\n entries.add(ThaumonBlocks.SILVERWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.SILVERWOOD_FENCE.get());\n entries.add(ThaumonBlocks.SILVERWOOD_FENCE_GATE.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WINDOW.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.EMPTY_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.CLASSIC_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.DUSTY_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.ALCHEMISTS_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.SILVERWOOD_GRIMOIRE_BOOKSHELF.get());\n entries.add(ThaumonBlocks.SILVERWOOD_BUTTON.get());\n entries.add(ThaumonBlocks.SILVERWOOD_PRESSURE_PLATE.get());\n\n entries.add(ThaumonBlocks.ARCANE_STONE.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_SlAB.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WALL.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_TILES.get());\n entries.add(ThaumonBlocks.ARCANE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.RUNIC_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.TILED_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.ARCANE_LANTERN.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_BUTTON.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_PRESSURE_PLATE.get());\n\n entries.add(ThaumonBlocks.ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WALL.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILES.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_CAPSTONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_FACADE.get());\n entries.add(ThaumonBlocks.CHISELED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.CARVED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ENGRAVED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_LANTERN.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW_PANE.get());\n\n entries.add(ThaumonBlocks.ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WALL.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILES.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_DOOR.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.ENGRAVED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.CHISELED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.RUNIC_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.TILED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.ANCIENT_LANTERN.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BUTTON.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_PRESSURE_PLATE.get());\n\n entries.add(ThaumonBlocks.GREATWOOD_LEAVES.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAVES.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAF_POST.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAF_WALL.get());\n\n entries.add(ThaumonBlocks.GRIMOIRE.get());\n entries.add(ThaumonBlocks.GRIMOIRE_STACK.get());\n entries.add(ThaumonBlocks.RESEARCH_NOTES.get());\n entries.add(ThaumonBlocks.CRYSTAL_LAMP.get());\n entries.add(ThaumonBlocks.RETORT.get());\n entries.add(ThaumonBlocks.VIAL_RACK.get());\n entries.add(ThaumonBlocks.CRYSTAL_STAND.get());\n\n entries.add(ThaumonItems.MUTAGEN.get());\n })).build()\n );\n\n public static void init() {}\n}" } ]
import jdlenl.thaumon.Thaumon; import jdlenl.thaumon.itemgroup.fabric.ThaumonItemGroupFabric; import net.fabricmc.api.ModInitializer;
2,964
package jdlenl.thaumon.fabric; public class ThaumonFabric implements ModInitializer { @Override public void onInitialize() { Thaumon.init();
package jdlenl.thaumon.fabric; public class ThaumonFabric implements ModInitializer { @Override public void onInitialize() { Thaumon.init();
ThaumonItemGroupFabric.init();
1
2023-11-16 06:03:29+00:00
4k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/dashboard/DashboardFragment.java
[ { "identifier": "Repository", "path": "app/src/main/java/gr/ihu/geoapp/managers/Repository.java", "snippet": "public class Repository {\n private FirebaseAuth auth;\n\n\n public Repository() {\n auth = FirebaseAuth.getInstance();\n }\n\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> createUser(String email, String password){\n\n return auth.createUserWithEmailAndPassword(email,password);\n }\n\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> checkUser(String email, String password){\n\n return auth.signInWithEmailAndPassword(email,password);\n }\n\n public void uploadUserData(EditText fullNameEditText,EditText emailEditText,EditText birthDateEditText,EditText professionEditText,EditText diplomaEditText){\n String fullName = fullNameEditText.getText().toString().trim();\n String email = emailEditText.getText().toString().trim();\n String birthDate = birthDateEditText.getText().toString().trim();\n String profession = professionEditText.getText().toString().trim();\n String diploma = diplomaEditText.getText().toString().trim();\n\n RegularUser user = RegularUser.getInstance();\n user.setFullName(fullName);\n user.setEmail(email);\n user.setDateOfBirth(birthDate);\n user.setProfession(profession);\n user.setDiploma(diploma);\n\n FirebaseDatabase.getInstance().getReference(\"users\").child(auth.getUid()).setValue(user);\n }\n\n public String getID(){\n return auth.getUid();\n }\n}" }, { "identifier": "PhotoBinActivity", "path": "app/src/main/java/gr/ihu/geoapp/ui/dashboard/PhotoBinActivity/PhotoBinActivity.java", "snippet": "public class PhotoBinActivity extends AppCompatActivity {\n private GridView gridView;\n private ArrayList<String> imagePaths;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.photo_bin_fragment_layout);\n\n gridView = findViewById(R.id.gridView);\n imagePaths = getTodayImages();\n\n ImageAdapter imageAdapter = new ImageAdapter();\n gridView.setAdapter(imageAdapter);\n }\n\n private ArrayList<String> getTodayImages() {\n ArrayList<String> paths = new ArrayList<>();\n Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;\n String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN};\n Cursor cursor = getContentResolver().query(uri, projection, null, null, MediaStore.Images.Media.DATE_TAKEN + \" DESC\");\n\n if (cursor != null) {\n while (cursor.moveToNext()) {\n String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));\n long dateTaken = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN));\n\n if (isToday(dateTaken)) {\n paths.add(imagePath);\n }\n }\n cursor.close();\n }\n\n return paths;\n }\n\n private boolean isToday(long dateTaken) {\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMdd\", Locale.getDefault());\n String todayDate = sdf.format(new Date());\n String imageDate = sdf.format(new Date(dateTaken));\n\n return todayDate.equals(imageDate);\n }\n\n private class ImageAdapter extends BaseAdapter {\n\n @Override\n public int getCount() {\n return imagePaths.size();\n }\n\n @Override\n public Object getItem(int position) {\n return imagePaths.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ImageView imageView;\n if (convertView == null) {\n imageView = new ImageView(PhotoBinActivity.this);\n imageView.setLayoutParams(new GridView.LayoutParams(300, 300));\n imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);\n imageView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClick(position);\n }\n });\n } else {\n imageView = (ImageView) convertView;\n }\n\n Glide.with(PhotoBinActivity.this)\n .load(imagePaths.get(position))\n .into(imageView);\n\n return imageView;\n }\n\n private void onItemClick(int position) {\n String selectedImagePath = imagePaths.get(position);\n\n Intent resultIntent = new Intent();\n resultIntent.setData(Uri.parse(selectedImagePath));\n setResult(Activity.RESULT_OK, resultIntent);\n\n finish();\n\n }\n\n\n\n\n\n }\n}" } ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import com.bumptech.glide.Glide; import com.google.android.material.chip.Chip; import com.google.android.material.chip.ChipGroup; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.io.ByteArrayOutputStream; import gr.ihu.geoapp.R; import gr.ihu.geoapp.databinding.FragmentDashboardBinding; import gr.ihu.geoapp.databinding.DataLayoutBinding; import gr.ihu.geoapp.managers.Repository; import gr.ihu.geoapp.ui.dashboard.PhotoBinActivity.PhotoBinActivity;
1,743
package gr.ihu.geoapp.ui.dashboard; public class DashboardFragment extends Fragment { private FragmentDashboardBinding binding; private DataLayoutBinding dataLayoutBinding; public static final int GALLERY_REQUEST_CODE = 1000; public static final int CAMERA_REQUEST_CODE = 2000; private DashboardViewModel dashboardViewModel; private ChipGroup chipGroup; private String currentDescription = ""; private String currentTitle = ""; private FloatingActionButton fab; private static final int PICK_PHOTO_REQUEST = 1; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class); binding = FragmentDashboardBinding.inflate(inflater,container, false); dataLayoutBinding = binding.include; View root = binding.getRoot(); final ImageView imageView = binding.image; chipGroup = binding.chipGroup; // // chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(ChipGroup group, int checkedId) { // // Chip selectedChip = findViewById(checkedId); // if (selectedChip != null) { // String category = selectedChip.getText().toString(); // // } // } // }); Button addButton= binding.addButton; EditText tagEditText= binding.tagEditText; EditText descrEditText = dataLayoutBinding.descrEditText; EditText titleEditText = dataLayoutBinding.titleEditText; Button addDescrBtn = dataLayoutBinding.addDescrBtn; Button saveDescrBtn = dataLayoutBinding.saveDescrBtn; Button editDescrBtn = dataLayoutBinding.editDescrBtn; Button addTitleBtn = dataLayoutBinding.addTitleBtn; Button saveTitleBtn = dataLayoutBinding.saveTitleBtn; Button editTitleBtn = dataLayoutBinding.editTitleBtn; Button sendPhotoBtn = binding.sendPhotoBtn; fab = binding.fab; addTitleBtn.setVisibility(View.GONE); addDescrBtn.setVisibility(View.GONE); saveDescrBtn.setVisibility(View.GONE); editDescrBtn.setVisibility(View.GONE); saveTitleBtn.setVisibility(View.GONE); editTitleBtn.setVisibility(View.GONE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
package gr.ihu.geoapp.ui.dashboard; public class DashboardFragment extends Fragment { private FragmentDashboardBinding binding; private DataLayoutBinding dataLayoutBinding; public static final int GALLERY_REQUEST_CODE = 1000; public static final int CAMERA_REQUEST_CODE = 2000; private DashboardViewModel dashboardViewModel; private ChipGroup chipGroup; private String currentDescription = ""; private String currentTitle = ""; private FloatingActionButton fab; private static final int PICK_PHOTO_REQUEST = 1; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class); binding = FragmentDashboardBinding.inflate(inflater,container, false); dataLayoutBinding = binding.include; View root = binding.getRoot(); final ImageView imageView = binding.image; chipGroup = binding.chipGroup; // // chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(ChipGroup group, int checkedId) { // // Chip selectedChip = findViewById(checkedId); // if (selectedChip != null) { // String category = selectedChip.getText().toString(); // // } // } // }); Button addButton= binding.addButton; EditText tagEditText= binding.tagEditText; EditText descrEditText = dataLayoutBinding.descrEditText; EditText titleEditText = dataLayoutBinding.titleEditText; Button addDescrBtn = dataLayoutBinding.addDescrBtn; Button saveDescrBtn = dataLayoutBinding.saveDescrBtn; Button editDescrBtn = dataLayoutBinding.editDescrBtn; Button addTitleBtn = dataLayoutBinding.addTitleBtn; Button saveTitleBtn = dataLayoutBinding.saveTitleBtn; Button editTitleBtn = dataLayoutBinding.editTitleBtn; Button sendPhotoBtn = binding.sendPhotoBtn; fab = binding.fab; addTitleBtn.setVisibility(View.GONE); addDescrBtn.setVisibility(View.GONE); saveDescrBtn.setVisibility(View.GONE); editDescrBtn.setVisibility(View.GONE); saveTitleBtn.setVisibility(View.GONE); editTitleBtn.setVisibility(View.GONE); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Intent intent = new Intent(getActivity(), PhotoBinActivity.class);
1
2023-11-10 17:43:18+00:00
4k
ImShyMike/QuestCompassPlus
src/main/java/shymike/questcompassplus/commands/CommandRegister.java
[ { "identifier": "Config", "path": "src/main/java/shymike/questcompassplus/config/Config.java", "snippet": "public class Config {\n\tpublic static boolean isModEnabled = true;\n public static double x = 0, y = 0, z = 0;\n\tpublic static boolean chatFeedback = false;\n\tpublic static int color = 0;\n\tpublic static boolean waypointCopy = false;\n\tpublic static boolean requireCompass = true;\n\t\n\tstatic public void toggleIsModEnabled() { isModEnabled = !isModEnabled; onUpdate(); }\n\tstatic public void toggleChatFeedback() { chatFeedback = !chatFeedback; onUpdate(); }\n\tstatic public void toggleWaypointCopy() { waypointCopy = !waypointCopy; onUpdate(); }\n\tstatic public void toggleRequireCompass() { requireCompass = !requireCompass; onUpdate(); }\n\tstatic public void setCoordinates(double X, double Y, double Z) { x = X; y = Y; z = Z; onUpdate(); }\n\tstatic public void setColor(int value) { color = value; onUpdate(); }\n\t\n\tstatic private void onUpdate() {\n\t\t// TODO: save configs to file\n\t}\n}" }, { "identifier": "DistanceCalculator", "path": "src/main/java/shymike/questcompassplus/utils/DistanceCalculator.java", "snippet": "public class DistanceCalculator {\n public static double getDistance2D(double X, double Z, double x, double z) {\n return Math.sqrt(Math.pow(x - X, 2) + Math.pow(z - Z, 2));\n }\n \n public static double getDistance3D(double X, double Y, double Z, double x, double y, double z) {\n return Math.sqrt(Math.pow(x - X, 2) + Math.pow(y - Y, 2) + Math.pow(z - Z, 2));\n }\n}" }, { "identifier": "RenderUtils", "path": "src/main/java/shymike/questcompassplus/utils/RenderUtils.java", "snippet": "public class RenderUtils implements HudRenderCallback {\n\tMinecraftClient mc = MinecraftClient.getInstance();\n\tpublic static String line1 = \"Compass Position: 0 0 0\";\n\tpublic static String line2 = \"\";\n\tpublic static double x = 0, y = 0, z = 0;\n\tpublic static String mainHandItem = null;\n\tpublic static boolean isDebugHudEnabled = false;\n\n public static void setCoordinates(double x, double y, double z) {\n \tRenderUtils.x = x;\n \tRenderUtils.y = y;\n \tRenderUtils.z = z;\n }\n \n @Override\n public void onHudRender(MatrixStack matrixStack, float tickDelta) {\n \tif (Config.requireCompass == true) {\n\t\t\tmainHandItem = mc.player.getInventory().getMainHandStack().getItem().toString();\n \t} else { mainHandItem = \"compass\"; }\n \ttry {\n \t\tGameOptions gameOptions = mc.options;\n \t\tRenderUtils.isDebugHudEnabled = gameOptions.debugEnabled;\n \t} catch(Exception e) {\n \t\tRenderUtils.isDebugHudEnabled = false;\n \t}\n \tif (Config.isModEnabled && ServerUtils.isOnMonumenta() && !isDebugHudEnabled && mainHandItem == \"compass\") {\n\t int x = 10, y = 10;\n\t int color = Config.color;\n\t Vec3d playerPos = mc.player.getPos();\n\t \tdouble distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, RenderUtils.x, RenderUtils.z));\n\t \tline2 = \"Distance: \" + (int)distance;\n\t \tString[] lines = {line1, line2};\n\t \tfor (String line : lines) {\n\t\t\t\tTextRenderer textRenderer = mc.textRenderer;\n\t \tText formattedText = Text.literal(line).formatted(Formatting.WHITE);;\n\t DrawableHelper.drawTextWithShadow(matrixStack, textRenderer, formattedText, x, y, color);\n\t y += textRenderer.fontHeight;\n\t \t}\n }\n }\n}" }, { "identifier": "ServerUtils", "path": "src/main/java/shymike/questcompassplus/utils/ServerUtils.java", "snippet": "public class ServerUtils {\n\tpublic static boolean bypass = false;\n\tprivate static MinecraftClient mc = MinecraftClient.getInstance();\n\t\n\tpublic static boolean isOnMonumenta() {\n\t if (bypass != true) {\n\t\t if (mc.getNetworkHandler() != null && mc.player != null) {\n\t\t ServerInfo serverInfo = mc.getCurrentServerEntry();\n\t\n\t\t String ServerAddress = \"server.playmonumenta.com\";\n\t\t return serverInfo != null && serverInfo.address.equals(ServerAddress) && !mc.isInSingleplayer();\n\t\t }\n\t } else { return true; }\n\t \n\t return false;\n\t}\n}" } ]
import shymike.questcompassplus.config.Config; import shymike.questcompassplus.utils.DistanceCalculator; import shymike.questcompassplus.utils.RenderUtils; import shymike.questcompassplus.utils.ServerUtils; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.tree.LiteralCommandNode; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.minecraft.client.MinecraftClient; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.Text; import net.minecraft.util.math.Vec3d;
2,077
package shymike.questcompassplus.commands; //import net.minecraft.command.argument.NumberRangeArgumentType; //import net.minecraft.command.argument.NumberRangeArgumentType.IntRangeArgumentType; public class CommandRegister { static public void run() { MinecraftClient mc = MinecraftClient.getInstance(); ClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { LiteralCommandNode<FabricClientCommandSource> mainNode = ClientCommandManager .literal("qcp") .executes(context -> { throw new SimpleCommandExceptionType(Text.literal("Invalid usage. Use \"/qcp help\" for more information.")).create(); }) .build(); LiteralCommandNode<FabricClientCommandSource> helpNode = ClientCommandManager .literal("help") .executes(context -> { context.getSource().sendFeedback(Text.literal("Quest Compass Plus commands:")); context.getSource().sendFeedback(Text.literal("/qcp help - Display this help message")); context.getSource().sendFeedback(Text.literal("/qcp toggle - Toggle the mod on/off")); context.getSource().sendFeedback(Text.literal("/qcp get - Get current quest location")); context.getSource().sendFeedback(Text.literal("/qcp settings - Change settings")); context.getSource().sendFeedback(Text.literal("/qcp debug - For debugging")); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> toggleNode = ClientCommandManager .literal("toggle") .executes(context -> { Config.toggleIsModEnabled(); if (!Config.isModEnabled) { RenderUtils.line1 = ""; RenderUtils.line2 = ""; } else { RenderUtils.line1 = "Compass Position: " + (int)RenderUtils.x + " " + (int)RenderUtils.y + " " + (int)RenderUtils.z; } context.getSource().sendFeedback(Text.literal("Quest Compass Plus is now " + (Config.isModEnabled ? "enabled" : "disabled"))); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> getterNode = ClientCommandManager .literal("get") .executes(context -> { Vec3d playerPos = mc.player.getPos(); double distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, Config.x, Config.z)); if (Config.waypointCopy) { context.getSource().sendFeedback(Text.literal("Compass Position: x=" + (int)Config.x + ", y=" + (int)Config.y + ", z=" + (int)Config.z + ", distance=" + (int)distance).styled(style -> style .withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/jm wpedit [name:\"Quest Location\", x:"+(int)Config.x+", y:"+(int)Config.y+", z:"+(int)Config.z+", dim:minecraft:overworld]")) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Click to make waypoint!"))))); } else if (Config.chatFeedback) { context.getSource().sendFeedback(Text.literal("Compass Position: x=" + (int)Config.x + ", y=" + (int)Config.y + ", z=" + (int)Config.z + ", distance=" + (int)distance).styled(style -> style .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, (int)Config.x+" "+(int)Config.y+" "+(int)Config.z)) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Click to copy coordinates to clipboard!"))))); } return 1;}) .build(); LiteralCommandNode<FabricClientCommandSource> debugNode = ClientCommandManager .literal("debug") .executes(context -> {
package shymike.questcompassplus.commands; //import net.minecraft.command.argument.NumberRangeArgumentType; //import net.minecraft.command.argument.NumberRangeArgumentType.IntRangeArgumentType; public class CommandRegister { static public void run() { MinecraftClient mc = MinecraftClient.getInstance(); ClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { LiteralCommandNode<FabricClientCommandSource> mainNode = ClientCommandManager .literal("qcp") .executes(context -> { throw new SimpleCommandExceptionType(Text.literal("Invalid usage. Use \"/qcp help\" for more information.")).create(); }) .build(); LiteralCommandNode<FabricClientCommandSource> helpNode = ClientCommandManager .literal("help") .executes(context -> { context.getSource().sendFeedback(Text.literal("Quest Compass Plus commands:")); context.getSource().sendFeedback(Text.literal("/qcp help - Display this help message")); context.getSource().sendFeedback(Text.literal("/qcp toggle - Toggle the mod on/off")); context.getSource().sendFeedback(Text.literal("/qcp get - Get current quest location")); context.getSource().sendFeedback(Text.literal("/qcp settings - Change settings")); context.getSource().sendFeedback(Text.literal("/qcp debug - For debugging")); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> toggleNode = ClientCommandManager .literal("toggle") .executes(context -> { Config.toggleIsModEnabled(); if (!Config.isModEnabled) { RenderUtils.line1 = ""; RenderUtils.line2 = ""; } else { RenderUtils.line1 = "Compass Position: " + (int)RenderUtils.x + " " + (int)RenderUtils.y + " " + (int)RenderUtils.z; } context.getSource().sendFeedback(Text.literal("Quest Compass Plus is now " + (Config.isModEnabled ? "enabled" : "disabled"))); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> getterNode = ClientCommandManager .literal("get") .executes(context -> { Vec3d playerPos = mc.player.getPos(); double distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, Config.x, Config.z)); if (Config.waypointCopy) { context.getSource().sendFeedback(Text.literal("Compass Position: x=" + (int)Config.x + ", y=" + (int)Config.y + ", z=" + (int)Config.z + ", distance=" + (int)distance).styled(style -> style .withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/jm wpedit [name:\"Quest Location\", x:"+(int)Config.x+", y:"+(int)Config.y+", z:"+(int)Config.z+", dim:minecraft:overworld]")) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Click to make waypoint!"))))); } else if (Config.chatFeedback) { context.getSource().sendFeedback(Text.literal("Compass Position: x=" + (int)Config.x + ", y=" + (int)Config.y + ", z=" + (int)Config.z + ", distance=" + (int)distance).styled(style -> style .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, (int)Config.x+" "+(int)Config.y+" "+(int)Config.z)) .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Click to copy coordinates to clipboard!"))))); } return 1;}) .build(); LiteralCommandNode<FabricClientCommandSource> debugNode = ClientCommandManager .literal("debug") .executes(context -> {
context.getSource().sendFeedback(Text.literal("Is On Monumenta: " + ServerUtils.isOnMonumenta()));
3
2023-11-14 15:56:39+00:00
4k
kawainime/IOT-Smart_Farming
IOT_Farm_V.2/src/com/deshans/chart/LineChart.java
[ { "identifier": "BlankPlotChart", "path": "IOT_Farm_V.2/src/com/deshan/chart/blankchart/BlankPlotChart.java", "snippet": "public class BlankPlotChart extends JComponent {\n\n public BlankPlotChatRender getBlankPlotChatRender() {\n return blankPlotChatRender;\n }\n\n public void setBlankPlotChatRender(BlankPlotChatRender blankPlotChatRender) {\n this.blankPlotChatRender = blankPlotChatRender;\n }\n\n public double getMaxValues() {\n return maxValues;\n }\n\n public void setMaxValues(double maxValues) {\n this.maxValues = maxValues;\n niceScale.setMax(maxValues);\n repaint();\n }\n\n public double getMinValues() {\n return minValues;\n }\n\n public int getLabelCount() {\n return labelCount;\n }\n\n public void setLabelCount(int labelCount) {\n this.labelCount = labelCount;\n }\n\n public String getValuesFormat() {\n return valuesFormat;\n }\n\n public void setValuesFormat(String valuesFormat) {\n this.valuesFormat = valuesFormat;\n format.applyPattern(valuesFormat);\n }\n\n private final DecimalFormat format = new DecimalFormat(\"#,##0.##\");\n private NiceScale niceScale;\n private double maxValues;\n private double minValues;\n private int labelCount;\n private String valuesFormat = \"#,##0.##\";\n private BlankPlotChatRender blankPlotChatRender;\n\n public BlankPlotChart() {\n setBackground(Color.WHITE);\n setOpaque(false);\n setForeground(new Color(180, 180, 180));\n setBorder(new EmptyBorder(35, 10, 10, 10));\n init();\n }\n\n private void init() {\n initValues(0, 10);\n addMouseMotionListener(new MouseMotionAdapter() {\n @Override\n public void mouseMoved(MouseEvent me) {\n mouseMove((Graphics2D) getGraphics(), me);\n }\n });\n }\n\n public void initValues(double minValues, double maxValues) {\n this.minValues = minValues;\n this.maxValues = maxValues;\n niceScale = new NiceScale(minValues, maxValues);\n repaint();\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n super.paintComponent(grphcs);\n if (niceScale != null) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);\n createLine(g2);\n createValues(g2);\n createLabelText(g2);\n renderSeries(g2);\n }\n }\n\n private void createLine(Graphics2D g2) {\n g2.setColor(new Color(150, 150, 150, 20));\n Insets insets = getInsets();\n double textHeight = getLabelTextHeight(g2);\n double height = getHeight() - (insets.top + insets.bottom) - textHeight;\n double space = height / niceScale.getMaxTicks();\n double locationY = insets.bottom + textHeight;\n double textWidth = getMaxValuesTextWidth(g2);\n double spaceText = 5;\n for (int i = 0; i <= niceScale.getMaxTicks(); i++) {\n int y = (int) (getHeight() - locationY);\n g2.drawLine((int) (insets.left + textWidth + spaceText), y, (int) getWidth() - insets.right, y);\n locationY += space;\n }\n\n }\n\n private void createValues(Graphics2D g2) {\n g2.setColor(getForeground());\n Insets insets = getInsets();\n double textHeight = getLabelTextHeight(g2);\n double height = getHeight() - (insets.top + insets.bottom) - textHeight;\n double space = height / niceScale.getMaxTicks();\n double valuesCount = niceScale.getNiceMin();\n double locationY = insets.bottom + textHeight;\n FontMetrics ft = g2.getFontMetrics();\n for (int i = 0; i <= niceScale.getMaxTicks(); i++) {\n String text = format.format(valuesCount);\n Rectangle2D r2 = ft.getStringBounds(text, g2);\n double stringY = r2.getCenterY() * -1;\n double y = getHeight() - locationY + stringY;\n g2.drawString(text, insets.left, (int) y);\n locationY += space;\n valuesCount += niceScale.getTickSpacing();\n }\n }\n\n private void createLabelText(Graphics2D g2) {\n if (labelCount > 0) {\n Insets insets = getInsets();\n double textWidth = getMaxValuesTextWidth(g2);\n double spaceText = 5;\n double width = getWidth() - insets.left - insets.right - textWidth - spaceText;\n double space = width / labelCount;\n double locationX = insets.left + textWidth + spaceText;\n double locationText = getHeight() - insets.bottom + 5;\n FontMetrics ft = g2.getFontMetrics();\n for (int i = 0; i < labelCount; i++) {\n double centerX = ((locationX + space / 2));\n g2.setColor(getForeground());\n String text = getChartText(i);\n Rectangle2D r2 = ft.getStringBounds(text, g2);\n double textX = centerX - r2.getWidth() / 2;\n g2.drawString(text, (int) textX, (int) locationText);\n locationX += space;\n }\n }\n }\n\n private void renderSeries(Graphics2D g2) {\n if (blankPlotChatRender != null) {\n Insets insets = getInsets();\n double textWidth = getMaxValuesTextWidth(g2);\n double textHeight = getLabelTextHeight(g2);\n double spaceText = 5;\n double width = getWidth() - insets.left - insets.right - textWidth - spaceText;\n double height = getHeight() - insets.top - insets.bottom - textHeight;\n double space = width / labelCount;\n double locationX = insets.left + textWidth + spaceText;\n for (int i = 0; i < labelCount; i++) {\n blankPlotChatRender.renderSeries(this, g2, getRectangle(i, height, space, locationX, insets.top), i);\n }\n List<Path2D.Double> gra = initGra(blankPlotChatRender.getMaxLegend());\n for (int i = 0; i < labelCount; i++) {\n blankPlotChatRender.renderSeries(this, g2, getRectangle(i, height, space, locationX, insets.top), i, gra);\n }\n blankPlotChatRender.renderGraphics(g2, gra);\n }\n }\n\n private List initGra(int size) {\n List<Path2D.Double> list = new ArrayList<>();\n for (int i = 0; i < size; i++) {\n list.add(new Path2D.Double());\n }\n return list;\n }\n\n private void mouseMove(Graphics2D g2, MouseEvent evt) {\n if (blankPlotChatRender != null) {\n Insets insets = getInsets();\n double textWidth = getMaxValuesTextWidth(g2);\n double textHeight = getLabelTextHeight(g2);\n double spaceText = 5;\n double width = getWidth() - insets.left - insets.right - textWidth - spaceText;\n double height = getHeight() - insets.top - insets.bottom - textHeight;\n double space = width / labelCount;\n double locationX = insets.left + textWidth + spaceText;\n for (int i = 0; i < labelCount; i++) {\n boolean stop = blankPlotChatRender.mouseMoving(this, evt, g2, getRectangle(i, height, space, locationX, insets.top), i);\n if (stop) {\n break;\n }\n }\n }\n }\n\n private double getMaxValuesTextWidth(Graphics2D g2) {\n double width = 0;\n FontMetrics ft = g2.getFontMetrics();\n double valuesCount = niceScale.getNiceMin();\n for (int i = 0; i <= niceScale.getMaxTicks(); i++) {\n String text = format.format(valuesCount);\n Rectangle2D r2 = ft.getStringBounds(text, g2);\n double w = r2.getWidth();\n if (w > width) {\n width = w;\n }\n valuesCount += niceScale.getTickSpacing();\n }\n return width;\n }\n\n private int getLabelTextHeight(Graphics2D g2) {\n FontMetrics ft = g2.getFontMetrics();\n return ft.getHeight();\n }\n\n private String getChartText(int index) {\n if (blankPlotChatRender != null) {\n return blankPlotChatRender.getLabelText(index);\n } else {\n return \"Label\";\n }\n }\n\n public SeriesSize getRectangle(int index, double height, double space, double startX, double startY) {\n double x = startX + space * index;\n SeriesSize size = new SeriesSize(x, startY + 1, space, height);\n return size;\n }\n\n public double getSeriesValuesOf(double values, double height) {\n double max = niceScale.getTickSpacing() * niceScale.getMaxTicks();\n double percentValues = values * 100d / max;\n return height * percentValues / 100d;\n }\n\n public NiceScale getNiceScale() {\n return niceScale;\n }\n\n public void setNiceScale(NiceScale niceScale) {\n this.niceScale = niceScale;\n }\n}" }, { "identifier": "BlankPlotChatRender", "path": "IOT_Farm_V.2/src/com/deshan/chart/blankchart/BlankPlotChatRender.java", "snippet": "public abstract class BlankPlotChatRender {\n\n public abstract String getLabelText(int index);\n\n public abstract void renderSeries(BlankPlotChart chart, Graphics2D g2, SeriesSize size, int index);\n\n public abstract void renderSeries(BlankPlotChart chart, Graphics2D g2, SeriesSize size, int index, List<Path2D.Double> gra);\n\n public abstract boolean mouseMoving(BlankPlotChart chart, MouseEvent evt, Graphics2D g2, SeriesSize size, int index);\n\n public abstract void renderGraphics(Graphics2D g2, List<Path2D.Double> gra);\n\n public abstract int getMaxLegend();\n}" }, { "identifier": "SeriesSize", "path": "IOT_Farm_V.2/src/com/deshan/chart/blankchart/SeriesSize.java", "snippet": "public class SeriesSize {\n\n public double getX() {\n return x;\n }\n\n public void setX(double x) {\n this.x = x;\n }\n\n public double getY() {\n return y;\n }\n\n public void setY(double y) {\n this.y = y;\n }\n\n public double getWidth() {\n return width;\n }\n\n public void setWidth(double width) {\n this.width = width;\n }\n\n public double getHeight() {\n return height;\n }\n\n public void setHeight(double height) {\n this.height = height;\n }\n\n public SeriesSize(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n public SeriesSize() {\n }\n\n private double x;\n private double y;\n private double width;\n private double height;\n}" } ]
import com.deshan.chart.blankchart.BlankPlotChart; import com.deshan.chart.blankchart.BlankPlotChatRender; import com.deshan.chart.blankchart.SeriesSize; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.event.MouseEvent; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.jdesktop.animation.timing.Animator; import org.jdesktop.animation.timing.TimingTarget; import org.jdesktop.animation.timing.TimingTargetAdapter;
3,196
package com.deshans.chart; public class LineChart extends javax.swing.JPanel { DecimalFormat df = new DecimalFormat("#,##0.##"); private List<ModelLegend> legends = new ArrayList<>(); private List<ModelChart> model = new ArrayList<>(); private final int seriesSize = 18; private final int seriesSpace = 0; private final Animator animator; private float animate; private String showLabel; private Point labelLocation = new Point(); public LineChart() { initComponents(); setOpaque(false); TimingTarget target = new TimingTargetAdapter() { @Override public void timingEvent(float fraction) { animate = fraction; repaint(); } }; animator = new Animator(800, target); animator.setResolution(0); animator.setAcceleration(0.5f); animator.setDeceleration(0.5f); blankPlotChart.getNiceScale().setMaxTicks(5); blankPlotChart.setBlankPlotChatRender(new BlankPlotChatRender() { @Override public int getMaxLegend() { return legends.size(); } @Override public String getLabelText(int index) { return model.get(index).getLabel(); } @Override
package com.deshans.chart; public class LineChart extends javax.swing.JPanel { DecimalFormat df = new DecimalFormat("#,##0.##"); private List<ModelLegend> legends = new ArrayList<>(); private List<ModelChart> model = new ArrayList<>(); private final int seriesSize = 18; private final int seriesSpace = 0; private final Animator animator; private float animate; private String showLabel; private Point labelLocation = new Point(); public LineChart() { initComponents(); setOpaque(false); TimingTarget target = new TimingTargetAdapter() { @Override public void timingEvent(float fraction) { animate = fraction; repaint(); } }; animator = new Animator(800, target); animator.setResolution(0); animator.setAcceleration(0.5f); animator.setDeceleration(0.5f); blankPlotChart.getNiceScale().setMaxTicks(5); blankPlotChart.setBlankPlotChatRender(new BlankPlotChatRender() { @Override public int getMaxLegend() { return legends.size(); } @Override public String getLabelText(int index) { return model.get(index).getLabel(); } @Override
public void renderSeries(BlankPlotChart chart, Graphics2D g2, SeriesSize size, int index) {
0
2023-11-11 08:23:10+00:00
4k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/api/Internal.java
[ { "identifier": "Settings", "path": "src/main/java/io/mindspice/itemserver/Settings.java", "snippet": "public class Settings {\n static Settings INSTANCE;\n\n /* Monitor */\n public volatile int startHeight;\n public volatile int chainScanInterval;\n public volatile int heightBuffer;\n public volatile boolean isPaused;\n\n /* Database Config */\n public String okraDBUri;\n public String okraDBUser;\n public String okraDBPass;\n public String chiaDBUri;\n public String chiaDBUser;\n public String chiaDBPass;\n\n /* Internal Services */\n public String authServiceUri;\n public int authServicePort;\n public String authServiceUser;\n public String authServicePass;\n\n /* Card Rarity */\n public int holoPct = 3;\n public int goldPct = 20;\n public int highLvl = 40;\n public String currCollection;\n\n /* Config Paths */\n public String mainNodeConfig;\n public String mintWalletConfig;\n public String transactionWalletConfig;\n public String mintJobConfig;\n public String okraJobConfig;\n public String outrJobConfig;\n\n /* S3 */\n public String s3AccessKey;\n public String s3SecretKey;\n\n\n /* Assets */\n public String boosterAddress;\n public String boosterTail;\n public String starterAddress;\n public String starterTail;\n\n\n /* DID Mint */\n public String didMintToAddr;\n public List<String> didUris;\n public List<String> didMetaUris;\n public List<String> didLicenseUris;\n public String didHash;\n public String didMetaHash;\n public String didLicenseHash;\n\n /* Dispersal Limits */\n public int nftFlagAmount;\n public int okraFlagAmount;\n public int outrFlagAmount;\n\n\n\n static {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n\n File file = new File(\"config.yaml\");\n\n try {\n INSTANCE = mapper.readValue(file, Settings.class);\n } catch (IOException e) {\n try {\n writeBlank();\n } catch (IOException ex) { throw new RuntimeException(ex); }\n throw new RuntimeException(\"Failed to read config file.\", e);\n }\n }\n\n public static Settings get() {\n return INSTANCE;\n }\n\n public static MetaData getAccountMintMetaData() {\n return null;\n }\n\n public static void writeBlank() throws IOException {\n var mapper = new ObjectMapper(new YAMLFactory());\n mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);\n File yamlFile = new File(\"defaults.yaml\");\n mapper.writeValue(yamlFile, new Settings());\n }\n\n\n}" }, { "identifier": "AvatarService", "path": "src/main/java/io/mindspice/itemserver/services/AvatarService.java", "snippet": "public class AvatarService {\n private final WalletAPI walletAPI;\n private final OkraGameAPI gameApi;\n private final CustomLogger logger;\n private final S3Service s3Service;\n UnsafeHttpClient client = new UnsafeHttpClient(10_000, 10_000, 10_000);\n String uuid = UUID.randomUUID().toString();\n\n public AvatarService(WalletAPI monWalletApi, OkraGameAPI gameApi, S3Service s3Service, CustomLogger logger) {\n this.walletAPI = monWalletApi;\n this.gameApi = gameApi;\n this.s3Service = s3Service;\n this.logger = logger;\n }\n\n public void submit(Pair<Integer, String> updateInfo) {\n logger.logApp(this.getClass(), TLogLevel.DEBUG, \"Received avatar update playerId: \" + updateInfo.first()\n + \" | NFT: \" + updateInfo.second());\n Thread.ofVirtual().start(updateTask(updateInfo.first(), updateInfo.second()));\n }\n\n public Runnable updateTask(int playerId, String nftLauncher) {\n\n return new Runnable() {\n @Override\n public void run() {\n try {\n\n long lastUpdate = gameApi.getLastAvatarUpdate(playerId).data().orElseThrow();\n if (Instant.now().getEpochSecond() - lastUpdate < 86400) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Ignored avatar update: Too soon\");\n return;\n }\n\n NftInfo nftInfo = Utils.nftGetInfoWrapper(walletAPI, nftLauncher);\n List<String> uris = nftInfo.dataUris();\n byte[] imgBytes = getConvertedImage(uris);\n if (imgBytes == null || imgBytes.length > 1024 * 66) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Ignored avatar update: Too large of file\");\n return;\n }\n s3Service.uploadBytes(playerId + \".png\", imgBytes);\n gameApi.updatePlayerAvatar(playerId, playerId + \".png\");\n\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Updated player avatar with: \" + nftLauncher);\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \" | PlayerId: \" + playerId +\n \" | Failed updating avatar with: \" + nftLauncher +\n \" | Message: \" + e.getMessage(), e);\n }\n }\n };\n }\n\n public byte[] getConvertedImage(List<String> uris) throws IOException {\n\n byte[] imgBytes = null;\n for (var uri : uris) {\n try {\n imgBytes = client.requestBuilder()\n .address(uri)\n .asGet()\n .maxResponseSize(10 * 1024 * 1024)\n .makeAndGetBytes();\n if (imgBytes != null) { break; }\n } catch (Exception ignored) {\n }\n }\n\n if (imgBytes == null) { return null; }\n ByteArrayInputStream imageByteStream = new ByteArrayInputStream(imgBytes);\n if (!checkSafeImage(new ByteArrayInputStream(imgBytes))) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Abuse attempted in ConversionJob: \"\n + uuid + \" with: \" + uris);\n throw new IllegalStateException(\"Validation Fail\");\n }\n\n BufferedImage ogImage = ImageIO.read(imageByteStream);\n\n BufferedImage resizedImage = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(ogImage, 0, 0, 128, 128, null);\n g.dispose();\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n ImageIO.write(resizedImage, \"png\", outputStream);\n return outputStream.toByteArray();\n }\n\n private boolean checkSafeImage(InputStream input) throws IOException {\n ImageInputStream imageInputStream = ImageIO.createImageInputStream(input);\n Iterator<ImageReader> iter = ImageIO.getImageReaders(imageInputStream);\n long maxSize = 2048L * 2048L;\n\n if (!iter.hasNext()) {\n imageInputStream.close();\n return false;\n }\n\n boolean safe = false;\n try {\n ImageReader reader = iter.next();\n reader.setInput(imageInputStream, true, true);\n\n long width = reader.getWidth(0);\n long height = reader.getHeight(0);\n\n safe = (height * width) <= maxSize;\n } finally {\n imageInputStream.close();\n }\n return safe;\n }\n\n}" }, { "identifier": "LeaderBoardService", "path": "src/main/java/io/mindspice/itemserver/services/LeaderBoardService.java", "snippet": "public class LeaderBoardService {\n private final OkraGameAPI gameAPI;\n public final CustomLogger logger;\n\n private volatile List<PlayerScore> dailyScores;\n private volatile List<PlayerScore> weeklyScores;\n private volatile List<PlayerScore> monthlyScores;\n\n public LeaderBoardService(OkraGameAPI gameAPI, CustomLogger logger) {\n this.gameAPI = gameAPI;\n this.logger = logger;\n }\n\n public Runnable updateScores() {\n return () -> {\n java.time.LocalDate day = java.time.LocalDate.now();\n List<MatchResult> dailyResults = gameAPI.getMatchResults(\n day.atStartOfDay(ZoneId.systemDefault()).minusDays(1).toInstant().toEpochMilli(), //this is right, but workish\n day.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n dailyScores = calcAndSortResults(dailyResults);\n\n java.time.LocalDate week = java.time.LocalDate.now().with(DayOfWeek.MONDAY);\n List<MatchResult> weeklyResults = gameAPI.getMatchResults(\n week.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),\n week.plusWeeks(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n weeklyScores = calcAndSortResults(weeklyResults);\n\n java.time.LocalDate month = LocalDate.now().withDayOfMonth(1);\n List<MatchResult> monthlyResult = gameAPI.getMatchResults(\n month.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),\n month.plusMonths(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n monthlyScores = calcAndSortResults(monthlyResult);\n };\n }\n\n private List<PlayerScore> calcAndSortResults(List<MatchResult> results) {\n HashMap<String, PlayerScore> interimMap = new HashMap<>();\n results.forEach(result -> {\n interimMap.computeIfAbsent(result.player1Name(),\n k -> new PlayerScore(result.player1Name())).addResult(result.player1Won()\n );\n interimMap.computeIfAbsent(result.player2Name(),\n k -> new PlayerScore(result.player2Name())).addResult(result.player2Won()\n );\n }\n );\n interimMap.remove(\"BramBot\");\n return interimMap.values().stream()\n .sorted(Comparator.comparing(PlayerScore::getSortMetric).reversed())\n .limit(35)\n .toList();\n }\n\n public List<PlayerScore> getDailyScores() { return dailyScores; }\n\n public List<PlayerScore> getWeeklyScores() { return weeklyScores; }\n\n public List<PlayerScore> getMonthlyScores() { return monthlyScores; }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import io.mindspice.databaseservice.client.api.OkraNFTAPI; import io.mindspice.databaseservice.client.schema.Card; import io.mindspice.itemserver.schema.ApiMint; import io.mindspice.itemserver.Settings; import io.mindspice.itemserver.schema.ApiMintReq; import io.mindspice.itemserver.services.AvatarService; import io.mindspice.itemserver.services.LeaderBoardService; import io.mindspice.jxch.rpc.schemas.wallet.nft.MetaData; import io.mindspice.jxch.transact.logging.TLogLevel; import io.mindspice.jxch.transact.logging.TLogger; import io.mindspice.jxch.transact.service.mint.MintItem; import io.mindspice.jxch.transact.service.mint.MintService; import io.mindspice.mindlib.data.tuples.Pair; import io.mindspice.mindlib.util.JsonUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.net.http.HttpResponse; import java.util.*; import java.util.stream.IntStream;
2,816
package io.mindspice.itemserver.api; @CrossOrigin @RestController @RequestMapping("/internal") public class Internal { private final MintService mintService; private final AvatarService avatarService;
package io.mindspice.itemserver.api; @CrossOrigin @RestController @RequestMapping("/internal") public class Internal { private final MintService mintService; private final AvatarService avatarService;
private final LeaderBoardService leaderBoardService;
2
2023-11-14 14:56:37+00:00
4k
KvRae/Mobile-Exemple-Java-Android
Project/app/src/main/java/com/example/pharmacie2/Data/Database/PharmacyDB.java
[ { "identifier": "MedecinDao", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Dao/MedecinDao.java", "snippet": "@Dao\npublic interface MedecinDao {\n\n @Insert\n long insertMedecin(Medecin medecin);\n\n @Update\n void updateMedecin(Medecin medecin);\n\n @Delete\n void deleteMedecin(Medecin medecin);\n\n @Query(\"SELECT * FROM medecins\")\n List<Medecin> getAllMedecins();\n\n @Query(\"SELECT * FROM medecins WHERE id = :id\")\n Medecin getMedecinById(int id);\n\n}" }, { "identifier": "MedicamentDao", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Dao/MedicamentDao.java", "snippet": "@Dao\npublic interface MedicamentDao {\n @Query(\"SELECT * FROM medicaments\")\n List<Medicament> getAllMedicaments();\n\n @Query(\"SELECT * FROM medicaments WHERE id = :medicamentId\")\n Medicament getMedicamentById(long medicamentId);\n\n\n @Insert\n void insertMedicament(Medicament medicament);\n\n @Delete\n void deleteMedicament(Medicament medicament);\n}" }, { "identifier": "UserDao", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Dao/UserDao.java", "snippet": "@Dao\npublic interface UserDao {\n @Insert\n void insert(User user);\n @Delete\n void delete(User user);\n\n @Query(\"SELECT * FROM users WHERE email = :email\")\n User getUserByEmail(String email);\n\n @Query(\"SELECT * FROM users WHERE email = :email AND password = :password\")\n User getUserByEmailAndPassword(String email, String password);\n @Query(\"SELECT * FROM users\")\n List<User> getAllUsers();\n\n @Query(\"SELECT * FROM users WHERE id = :id\")\n User getUserById(int id);\n\n @Update\n void updateUser(User user);\n\n\n}" }, { "identifier": "Medecin", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Entities/Medecin.java", "snippet": "@Entity(tableName = \"medecins\")\npublic class Medecin {\n @PrimaryKey(autoGenerate = true)\n private int id;\n\n private String nom;\n private String prenom;\n private String specialite;\n private String email;\n private int numero;\n\n private String localisation;\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 getNom() {\n return nom;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\n }\n\n public String getPrenom() {\n return prenom;\n }\n\n public void setPrenom(String prenom) {\n this.prenom = prenom;\n }\n\n public String getSpecialite() {\n return specialite;\n }\n\n public void setSpecialite(String specialite) {\n this.specialite = specialite;\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 int getNumero() {\n return numero;\n }\n\n public void setNumero(int numero) {\n this.numero = numero;\n }\n\n public String getLocalisation() {\n return localisation;\n }\n\n public void setLocalisation(String localisation) {\n this.localisation = localisation;\n }\n\n public Medecin() {\n }\n\n public Medecin(int id) {\n this.id = id;\n }\n\n public Medecin(String nom, String prenom, String specialite, String email, int numero, String localisation) {\n this.nom = nom;\n this.prenom = prenom;\n this.specialite = specialite;\n this.email = email;\n this.numero = numero;\n this.localisation = localisation;\n }\n}" }, { "identifier": "Medicament", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Entities/Medicament.java", "snippet": "@Entity(tableName = \"medicaments\")\npublic class Medicament {\n @PrimaryKey(autoGenerate = true)\n private int id;\n\n private String nom;\n private String description;\n private String fabricant;\n private double prix;\n private int quantiteEnStock;\n\n public Medicament() {\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 String getNom() {\n return nom;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\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 getFabricant() {\n return fabricant;\n }\n\n public void setFabricant(String fabricant) {\n this.fabricant = fabricant;\n }\n\n public double getPrix() {\n return prix;\n }\n\n public void setPrix(double prix) {\n this.prix = prix;\n }\n\n public int getQuantiteEnStock() {\n return quantiteEnStock;\n }\n\n public void setQuantiteEnStock(int quantiteEnStock) {\n this.quantiteEnStock = quantiteEnStock;\n }\n\n\n public Medicament(String nom, String description, String fabricant, double prix, int quantiteEnStock) {\n this.nom = nom;\n this.description = description;\n this.fabricant = fabricant;\n this.prix = prix;\n this.quantiteEnStock = quantiteEnStock;\n }\n}" }, { "identifier": "User", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Entities/User.java", "snippet": "@Entity(tableName = \"users\")\npublic class User {\n public String getEmail;\n @PrimaryKey(autoGenerate = true)\n private int id;\n\n private String name;\n private String email;\n\n private String password;\n\n\n\n public User(String email) {\n this.email = email;\n }\n public User(String email, String password) {\n this.name = email;\n this.email = password;\n }\n\n public User(String name, String email, String password) {\n this.name = name;\n this.email = email;\n this.password = password;\n }\n\n public User() {\n }\n\n\n\n // Getters and setters\n public int getId() {\n return id;\n }\n\n public void setId(int 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 getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\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 User user = (User) o;\n return id == user.id && Objects.equals(getEmail, user.getEmail) && Objects.equals(name, user.name) && Objects.equals(email, user.email) && Objects.equals(password, user.password);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getEmail, id, name, email, password);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"getEmail='\" + getEmail + '\\'' +\n \", id=\" + id +\n \", name='\" + name + '\\'' +\n \", email='\" + email + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n}" } ]
import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import com.example.pharmacie2.Data.Dao.MedecinDao; import com.example.pharmacie2.Data.Dao.MedicamentDao; import com.example.pharmacie2.Data.Dao.UserDao; import com.example.pharmacie2.Data.Entities.Medecin; import com.example.pharmacie2.Data.Entities.Medicament; import com.example.pharmacie2.Data.Entities.User;
2,162
package com.example.pharmacie2.Data.Database; @Database(entities = {User.class, Medicament.class, Medecin.class}, version = 1, exportSchema = false) public abstract class PharmacyDB extends RoomDatabase { private static PharmacyDB instance; public abstract UserDao userDao();
package com.example.pharmacie2.Data.Database; @Database(entities = {User.class, Medicament.class, Medecin.class}, version = 1, exportSchema = false) public abstract class PharmacyDB extends RoomDatabase { private static PharmacyDB instance; public abstract UserDao userDao();
public abstract MedicamentDao medicamentDao();
1
2023-11-14 22:07:33+00:00
4k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java
[ { "identifier": "Client", "path": "src/main/java/com/github/codecnomad/codecclient/Client.java", "snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft();\n public static Rotation rotation = new Rotation();\n public static Config guiConfig;\n\n static {\n modules.put(\"FishingMacro\", new FishingMacro());\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n guiConfig = new Config();\n\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(rotation);\n\n MinecraftForge.EVENT_BUS.register(MainCommand.pathfinding);\n\n CommandManager.register(new MainCommand());\n }\n\n @SubscribeEvent\n public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {\n for (Map.Entry<String, Module> moduleMap : modules.entrySet()) {\n moduleMap.getValue().unregister();\n }\n }\n}" }, { "identifier": "PacketEvent", "path": "src/main/java/com/github/codecnomad/codecclient/events/PacketEvent.java", "snippet": "public class PacketEvent extends Event {\n public enum Phase {\n pre,\n post\n }\n\n public final Packet<?> packet;\n public final Phase phase;\n\n\n public PacketEvent(final Packet<?> packet, Phase phase) {\n this.packet = packet;\n this.phase = phase;\n }\n\n public static class ReceiveEvent extends PacketEvent {\n public ReceiveEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n\n public static class SendEvent extends PacketEvent {\n public SendEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n}" }, { "identifier": "S19PacketAccessor", "path": "src/main/java/com/github/codecnomad/codecclient/mixins/S19PacketAccessor.java", "snippet": "@Mixin(S19PacketEntityHeadLook.class)\npublic interface S19PacketAccessor {\n @Accessor(\"entityId\")\n int getEntityId();\n}" }, { "identifier": "Config", "path": "src/main/java/com/github/codecnomad/codecclient/ui/Config.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Config extends cc.polyfrost.oneconfig.config.Config {\n @Color(\n name = \"Color\",\n category = \"Visuals\"\n )\n public static OneColor VisualColor = new OneColor(100, 60, 160, 200);\n @KeyBind(\n name = \"Fishing key-bind\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);\n @Number(\n name = \"Catch delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 20\n )\n public static int FishingDelay = 10;\n @Number(\n name = \"Kill delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 40\n )\n public static int KillDelay = 20;\n @Number(\n name = \"Attack c/s\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 20\n )\n public static int AttackCps = 10;\n\n @Number(\n name = \"Smoothing\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 2,\n max = 10\n )\n public static int RotationSmoothing = 4;\n\n @Number(\n name = \"Random movement frequency\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 50\n )\n public static int MovementFrequency = 15;\n\n @Switch(\n name = \"Auto kill\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean AutoKill = true;\n\n @Switch(\n name = \"Only sound failsafe\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean OnlySound = false;\n\n @Number(\n name = \"Weapon slot\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 9\n )\n public static int WeaponSlot = 9;\n\n @Switch(\n name = \"Right click attack\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean RightClick = false;\n\n @HUD(\n name = \"Fishing HUD\",\n category = \"Visuals\"\n )\n public FishingHud hudFishing = new FishingHud();\n\n public Config() {\n super(new Mod(\"CodecClient\", ModType.UTIL_QOL), \"config.json\");\n initialize();\n\n registerKeyBind(FishingKeybinding, () -> toggle(\"FishingMacro\"));\n save();\n }\n\n private static void toggle(String name) {\n Module helperClassModule = Client.modules.get(name);\n if (helperClassModule.state) {\n helperClassModule.unregister();\n } else {\n helperClassModule.register();\n }\n }\n}" }, { "identifier": "Math", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Math.java", "snippet": "public class Math {\n\n public static float easeInOut(float t) {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n }\n\n public static float interpolate(float goal, float current, float time) {\n while (goal - current > 180) {\n current += 360;\n }\n while (goal - current < -180) {\n current -= 360;\n }\n\n float t = easeInOut(time);\n return current + (goal - current) * t;\n }\n\n public static String toClock(int seconds) {\n int hours = seconds / 3600;\n int minutes = (seconds % 3600) / 60;\n int remainingSeconds = seconds % 60;\n\n return String.format(\"%dh, %dm, %ds\", hours, minutes, remainingSeconds);\n }\n\n public static String toFancyNumber(int number) {\n int k = number / 1000;\n int m = number / 1000000;\n int remaining = number % 1000000;\n\n if (m > 0) {\n return String.format(\"%dM\", m);\n } else if (k > 0) {\n return String.format(\"%dk\", k);\n } else {\n return String.format(\"%d\", remaining);\n }\n }\n\n public static float getYaw(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double yawToBlock = java.lang.Math.atan2(-deltaX, deltaZ);\n double yaw = java.lang.Math.toDegrees(yawToBlock);\n\n yaw = (yaw + 360) % 360;\n if (yaw > 180) {\n yaw -= 360;\n }\n\n return (float) yaw;\n }\n\n public static Vec3 fromBlockPos(BlockPos pos) {\n return new Vec3(pos.getX(), pos.getY(), pos.getZ());\n }\n\n public static float getPitch(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaY = blockPos.getY() + 0.5 - Client.mc.thePlayer.posY - Client.mc.thePlayer.getEyeHeight();\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double distanceXZ = java.lang.Math.sqrt(deltaX * deltaX + deltaZ * deltaZ);\n double pitchToBlock = -java.lang.Math.atan2(deltaY, distanceXZ);\n double pitch = java.lang.Math.toDegrees(pitchToBlock);\n pitch = java.lang.Math.max(-90, java.lang.Math.min(90, pitch));\n return (float) pitch;\n }\n\n public static double getXZDistance(BlockPos pos1, BlockPos pos2) {\n double xDiff = pos1.getX() - pos2.getX();\n double zDiff = pos1.getZ() - pos2.getZ();\n return java.lang.Math.sqrt(xDiff * xDiff + zDiff * zDiff);\n }\n\n}" } ]
import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.events.PacketEvent; import com.github.codecnomad.codecclient.mixins.S19PacketAccessor; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Math; import com.github.codecnomad.codecclient.utils.*; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.item.*; import net.minecraft.network.play.server.*; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.List; import java.util.regex.Matcher;
2,596
package com.github.codecnomad.codecclient.modules; @SuppressWarnings("DuplicatedCode") public class FishingMacro extends Module { public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",}; public static int startTime = 0; public static int catches = 0; public static float xpGain = 0; public static FishingSteps currentStep = FishingSteps.FIND_ROD; public static Counter MainCounter = new Counter(); public static Counter AlternativeCounter = new Counter(); public static Counter FailsafeCounter = new Counter(); public static boolean failSafe = false; Entity fishingHook = null; Entity fishingMarker = null; Entity fishingMonster = null; public static float lastYaw = 0; public static float lastPitch = 0; public static AxisAlignedBB lastAABB = null; public BlockPos startPos = null; public static Pathfinding pathfinding = new Pathfinding(); @Override public void register() { MinecraftForge.EVENT_BUS.register(this); this.state = true; lastYaw = Client.mc.thePlayer.rotationYaw; lastPitch = Client.mc.thePlayer.rotationPitch; Sound.disableSounds();
package com.github.codecnomad.codecclient.modules; @SuppressWarnings("DuplicatedCode") public class FishingMacro extends Module { public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",}; public static int startTime = 0; public static int catches = 0; public static float xpGain = 0; public static FishingSteps currentStep = FishingSteps.FIND_ROD; public static Counter MainCounter = new Counter(); public static Counter AlternativeCounter = new Counter(); public static Counter FailsafeCounter = new Counter(); public static boolean failSafe = false; Entity fishingHook = null; Entity fishingMarker = null; Entity fishingMonster = null; public static float lastYaw = 0; public static float lastPitch = 0; public static AxisAlignedBB lastAABB = null; public BlockPos startPos = null; public static Pathfinding pathfinding = new Pathfinding(); @Override public void register() { MinecraftForge.EVENT_BUS.register(this); this.state = true; lastYaw = Client.mc.thePlayer.rotationYaw; lastPitch = Client.mc.thePlayer.rotationPitch; Sound.disableSounds();
startTime = (int) java.lang.Math.floor((double) System.currentTimeMillis() / 1000);
4
2023-11-16 10:12:20+00:00
4k
maarlakes/common
src/main/java/cn/maarlakes/common/factory/datetime/DateTimeFactories.java
[ { "identifier": "SpiServiceLoader", "path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java", "snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader, ConcurrentMap<Class<?>, SpiServiceLoader<?>>> SERVICE_LOADER_CACHE = new ConcurrentHashMap<>();\n\n private final Class<T> service;\n\n private final ClassLoader loader;\n private final boolean isShared;\n\n private final Supplier<List<Holder>> holders = Lazy.of(this::loadServiceHolder);\n private final ConcurrentMap<Class<?>, T> serviceCache = new ConcurrentHashMap<>();\n\n private SpiServiceLoader(@Nonnull Class<T> service, ClassLoader loader, boolean isShared) {\n this.service = Objects.requireNonNull(service, \"Service interface cannot be null\");\n this.loader = (loader == null) ? ClassLoader.getSystemClassLoader() : loader;\n this.isShared = isShared;\n }\n\n public boolean isEmpty() {\n return this.holders.get().isEmpty();\n }\n\n @Nonnull\n public T first() {\n return this.firstOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public T first(@Nonnull Class<? extends T> serviceType) {\n return this.firstOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> firstOptional() {\n return this.firstOptional(this.service);\n }\n\n @Nonnull\n public Optional<T> firstOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream().filter(item -> serviceType.isAssignableFrom(item.serviceType)).map(this::loadService).findFirst();\n }\n\n @Nonnull\n public T last() {\n return this.lastOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional() {\n return this.lastOptional(this.service);\n }\n\n @Nonnull\n public T last(@Nonnull Class<? extends T> serviceType) {\n return this.lastOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream()\n .filter(item -> serviceType.isAssignableFrom(item.serviceType))\n .sorted((left, right) -> Holder.compare(right, left))\n .map(this::loadService)\n .findFirst();\n }\n\n @Nonnull\n @Override\n public Iterator<T> iterator() {\n return this.holders.get().stream().map(this::loadService).iterator();\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service) {\n return load(service, Thread.currentThread().getContextClassLoader());\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return new SpiServiceLoader<>(service, loader, false);\n }\n\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service) {\n return loadShared(service, Thread.currentThread().getContextClassLoader());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return (SpiServiceLoader<S>) SERVICE_LOADER_CACHE.computeIfAbsent(loader, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(service, k -> new SpiServiceLoader<>(service, loader, true));\n }\n\n private T loadService(@Nonnull Holder holder) {\n if (holder.spiService != null && holder.spiService.lifecycle() == SpiService.Lifecycle.SINGLETON) {\n return this.serviceCache.computeIfAbsent(holder.serviceType, k -> this.createService(holder));\n }\n return this.createService(holder);\n }\n\n private T createService(@Nonnull Holder holder) {\n try {\n return this.service.cast(holder.serviceType.getConstructor().newInstance());\n } catch (Exception e) {\n throw new SpiServiceException(e.getMessage(), e);\n }\n }\n\n\n private List<Holder> loadServiceHolder() {\n final Enumeration<URL>[] configArray = this.loadConfigs();\n try {\n final Map<String, Holder> map = new HashMap<>();\n for (Enumeration<URL> configs : configArray) {\n while (configs.hasMoreElements()) {\n final URL url = configs.nextElement();\n try (InputStream in = url.openStream()) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {\n String ln;\n int lineNumber = 0;\n while ((ln = reader.readLine()) != null) {\n lineNumber++;\n final int ci = ln.indexOf('#');\n if (ci >= 0) {\n ln = ln.substring(0, ci);\n }\n ln = ln.trim();\n if (!ln.isEmpty()) {\n this.check(url, ln, lineNumber);\n if (!map.containsKey(ln)) {\n final Class<?> type = Class.forName(ln, false, loader);\n if (!this.service.isAssignableFrom(type)) {\n throw new SpiServiceException(this.service.getName() + \": Provider\" + ln + \" not a subtype\");\n }\n map.put(ln, new Holder(type, type.getAnnotation(SpiService.class)));\n }\n }\n }\n }\n }\n }\n }\n if (map.isEmpty() && this.isShared) {\n // 移除\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n\n return map.values().stream().sorted().collect(Collectors.toList());\n } catch (IOException | ClassNotFoundException e) {\n if (this.isShared) {\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n throw new SpiServiceException(e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private Enumeration<URL>[] loadConfigs() {\n final String fullName = PREFIX + service.getName();\n try {\n return new Enumeration[]{this.loader.getResources(fullName), ClassLoader.getSystemResources(fullName)};\n } catch (IOException e) {\n throw new SpiServiceException(service.getName() + \": Error locating configuration files\", e);\n }\n }\n\n private void check(@Nonnull URL url, @Nonnull String className, int lineNumber) {\n if ((className.indexOf(' ') >= 0) || (className.indexOf('\\t') >= 0)) {\n throw new SpiServiceException(this.service.getName() + \": \" + className + \":\" + lineNumber + \":Illegal configuration-file syntax\");\n }\n int cp = className.codePointAt(0);\n if (!Character.isJavaIdentifierStart(cp)) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n final int length = className.length();\n for (int i = Character.charCount(cp); i < length; i += Character.charCount(cp)) {\n cp = className.codePointAt(i);\n if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n }\n }\n\n private static final class Holder implements Comparable<Holder> {\n\n private final Class<?> serviceType;\n\n private final SpiService spiService;\n\n private Holder(@Nonnull Class<?> serviceType, SpiService spiService) {\n this.serviceType = serviceType;\n this.spiService = spiService;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof Holder) {\n return this.serviceType == ((Holder) obj).serviceType;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(serviceType);\n }\n\n @Override\n public int compareTo(@Nullable Holder o) {\n if (o == null) {\n return 1;\n }\n return Integer.compare(this.spiService == null ? Integer.MAX_VALUE : this.spiService.order(), o.spiService == null ? Integer.MAX_VALUE : o.spiService.order());\n }\n\n public static int compare(Holder left, Holder right) {\n if (left == right) {\n return 0;\n }\n if (left == null) {\n return -1;\n }\n return left.compareTo(right);\n }\n }\n}" }, { "identifier": "CompareUtils", "path": "src/main/java/cn/maarlakes/common/utils/CompareUtils.java", "snippet": "public final class CompareUtils {\n private CompareUtils() {\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> T min(@Nonnull T first, @Nonnull T... others) {\n for (T other : others) {\n if (first.compareTo(other) > 0) {\n first = other;\n }\n }\n return first;\n }\n\n @Nonnull\n public static <T extends Comparable<? super T>> T max(@Nonnull T first, @Nonnull T... others) {\n for (T other : others) {\n if (first.compareTo(other) < 0) {\n first = other;\n }\n }\n return first;\n }\n}" }, { "identifier": "Lazy", "path": "src/main/java/cn/maarlakes/common/utils/Lazy.java", "snippet": "public final class Lazy {\n private Lazy() {\n }\n\n @Nonnull\n public static <T> Supplier<T> of(@Nonnull Supplier<T> action) {\n return new Supplier<T>() {\n\n private volatile T value = null;\n private final Object sync = new Object();\n\n @Override\n public T get() {\n if (this.value == null) {\n synchronized (this.sync) {\n if (this.value == null) {\n this.value = action.get();\n }\n }\n }\n return this.value;\n }\n };\n }\n}" } ]
import cn.maarlakes.common.spi.SpiServiceLoader; import cn.maarlakes.common.utils.CompareUtils; import cn.maarlakes.common.utils.Lazy; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import java.time.*; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.SignStyle; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.time.temporal.ChronoField.*;
3,357
package cn.maarlakes.common.factory.datetime; /** * @author linjpxc */ public final class DateTimeFactories { private DateTimeFactories() { } private static final Supplier<List<ParserWrapper>> PARSER = Lazy.of(() -> StreamSupport.stream(SpiServiceLoader.loadShared(DateTimeParser.class).spliterator(), false) .map(ParserWrapper::new) .collect(Collectors.toList()) ); public static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendValue(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .appendValue(MINUTE_OF_HOUR, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .optionalStart() .appendValue(SECOND_OF_MINUTE, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, true) .optionalEnd() .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, false) .optionalEnd() .optionalStart() .appendOffsetId() .toFormatter(); public static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .optionalStart() .appendValueReduced(YEAR_OF_ERA, 2, 4, LocalDate.of(2000, 1, 1)) .optionalEnd() .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('年') .optionalEnd() .appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('月') .optionalEnd() .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('日') .optionalEnd() .toFormatter(); public static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DATE_FORMATTER) .optionalStart() .appendLiteral(' ') .optionalEnd() .optionalStart() .appendLiteral('T') .optionalEnd() .optionalStart() .append(TIME_FORMATTER) .optionalEnd() .toFormatter(); @Nonnull public static LocalDateTime parse(@Nonnull String datetime) { return parse(datetime, Locale.getDefault(Locale.Category.FORMAT)); } @Nonnull public static LocalDateTime parse(@Nonnull String datetime, @Nonnull Locale locale) { final String newDatetime = datetime.trim(); return PARSER.get().stream().sorted() .filter(item -> item.parser.supported(newDatetime, LocalDateTime.class, locale)) .findFirst() .map(item -> { final LocalDateTime time = toLocalDateTime(item.parser.parse(newDatetime, locale)); item.counter.incrementAndGet(); return time; }).orElseGet(() -> LocalDateTime.parse(newDatetime, DATE_TIME_FORMATTER.withLocale(locale))); } @Nonnull public static <T extends ChronoLocalDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) {
package cn.maarlakes.common.factory.datetime; /** * @author linjpxc */ public final class DateTimeFactories { private DateTimeFactories() { } private static final Supplier<List<ParserWrapper>> PARSER = Lazy.of(() -> StreamSupport.stream(SpiServiceLoader.loadShared(DateTimeParser.class).spliterator(), false) .map(ParserWrapper::new) .collect(Collectors.toList()) ); public static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendValue(HOUR_OF_DAY, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .appendValue(MINUTE_OF_HOUR, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendLiteral(':') .optionalEnd() .optionalStart() .appendValue(SECOND_OF_MINUTE, 1, 2, SignStyle.NOT_NEGATIVE) .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, true) .optionalEnd() .optionalStart() .appendFraction(NANO_OF_SECOND, 0, 9, false) .optionalEnd() .optionalStart() .appendOffsetId() .toFormatter(); public static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .optionalStart() .appendValueReduced(YEAR_OF_ERA, 2, 4, LocalDate.of(2000, 1, 1)) .optionalEnd() .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('年') .optionalEnd() .appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('-') .optionalEnd() .optionalStart() .appendLiteral('/') .optionalEnd() .optionalStart() .appendLiteral('月') .optionalEnd() .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NORMAL) .optionalStart() .appendLiteral('日') .optionalEnd() .toFormatter(); public static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DATE_FORMATTER) .optionalStart() .appendLiteral(' ') .optionalEnd() .optionalStart() .appendLiteral('T') .optionalEnd() .optionalStart() .append(TIME_FORMATTER) .optionalEnd() .toFormatter(); @Nonnull public static LocalDateTime parse(@Nonnull String datetime) { return parse(datetime, Locale.getDefault(Locale.Category.FORMAT)); } @Nonnull public static LocalDateTime parse(@Nonnull String datetime, @Nonnull Locale locale) { final String newDatetime = datetime.trim(); return PARSER.get().stream().sorted() .filter(item -> item.parser.supported(newDatetime, LocalDateTime.class, locale)) .findFirst() .map(item -> { final LocalDateTime time = toLocalDateTime(item.parser.parse(newDatetime, locale)); item.counter.incrementAndGet(); return time; }).orElseGet(() -> LocalDateTime.parse(newDatetime, DATE_TIME_FORMATTER.withLocale(locale))); } @Nonnull public static <T extends ChronoLocalDateTime<?>> T min(@Nonnull T first, @Nonnull T... others) {
return CompareUtils.min(first, others);
1
2023-11-18 07:49:00+00:00
4k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/productController.java
[ { "identifier": "App", "path": "src/main/java/com/systeminventory/App.java", "snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException{\n primaryStage = stage;\n loadLoginScene();\n\n }\n\n public static Stage getPrimaryStage(){\n return primaryStage;\n }\n\n public static void loadLoginScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setResizable(false);\n primaryStage.initStyle(StageStyle.UNDECORATED);\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadLogoutScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"dashboardLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadProductScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"productLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Product - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"cashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Cashier - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n\n }\n public static void loadEmployeeDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeProductLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadEmployeeCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeCashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n}" }, { "identifier": "DeleteProductListener", "path": "src/main/java/com/systeminventory/interfaces/DeleteProductListener.java", "snippet": "public interface DeleteProductListener {\n public void clickDeleteProductListener(Product product);\n}" }, { "identifier": "DetailsProductListener", "path": "src/main/java/com/systeminventory/interfaces/DetailsProductListener.java", "snippet": "public interface DetailsProductListener {\n public void clickDetailsProductListener(Product product);\n}" }, { "identifier": "EditProductListener", "path": "src/main/java/com/systeminventory/interfaces/EditProductListener.java", "snippet": "public interface EditProductListener {\n public void clickEditProductListener(Product product);\n}" }, { "identifier": "Product", "path": "src/main/java/com/systeminventory/model/Product.java", "snippet": "public class Product {\n private String productName;\n private String imageSource;\n private String productOriginalPrice;\n private String productSellingPrice;\n private String productStock;\n private String keyProduct;\n private String idProduct;\n\n\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getImageSource() {\n return imageSource;\n }\n\n public void setImageSource(String imageSource) {\n this.imageSource = imageSource;\n }\n\n public String getProductSellingPrice() {\n return productSellingPrice;\n }\n\n public void setProductSellingPrice(String productSellingPrice) {\n this.productSellingPrice = productSellingPrice;\n }\n\n public String getProductStock() {\n return productStock;\n }\n\n public void setProductStock(String productStock) {\n this.productStock = productStock;\n }\n\n public String getKeyProduct() {\n return keyProduct;\n }\n\n public void setKeyProduct(String keyProduct) {\n this.keyProduct = keyProduct;\n }\n\n public String getProductOriginalPrice() {\n return productOriginalPrice;\n }\n\n public void setProductOriginalPrice(String productOriginalPrice) {\n this.productOriginalPrice = productOriginalPrice;\n }\n\n public String getIdProduct() {\n return idProduct;\n }\n\n public void setIdProduct(String idProduct) {\n this.idProduct = idProduct;\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.systeminventory.App; import com.systeminventory.interfaces.DeleteProductListener; import com.systeminventory.interfaces.DetailsProductListener; import com.systeminventory.interfaces.EditProductListener; import com.systeminventory.model.Product; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; 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.util.*; import java.text.NumberFormat;
1,874
package com.systeminventory.controller; public class productController { @FXML public Pane filterDropdown; @FXML public Button filterButton; public ImageView imageFIlter; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Button buttonCashier; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Button buttonDashboard; @FXML private ScrollPane scrollPane; @FXML private Button buttonAddProduct; @FXML public Pane backgroundPopup; @FXML private Pane addProductPopup; @FXML private Button addProductApplyButton; @FXML private Button addProductCancelButton; @FXML private TextField addProductProductNameField; @FXML private TextField addProductOriginalPriceField; @FXML private TextField addProductSellingPriceField; @FXML private TextField addProductProductStockField; @FXML private Label addProductProductImagePathLabel; @FXML private Pane addProductChooseFilePane; @FXML private Label addProductProductImageLabel; @FXML private Label addProductSellingPriceLabel; @FXML private Label addProductOriginalPriceLabel; @FXML private Label addProductProductNameLabel; @FXML private Label addProductProductStockLabel; @FXML private GridPane productCardContainer; @FXML private Label addProductProductImageGetFullPathLabel; @FXML private TextField searchProductNameField; @FXML private Label confirmDeleteVariableProductName; @FXML private Button confirmDeleteDeleteButton; @FXML private Button confirmDeleteCancelButton; @FXML private Label confirmDeleteKeyProduct; @FXML public Pane confirmDeletePane; @FXML private Label addProductLabel; @FXML private Label keyProductOnPopUp; @FXML private Pane detailsProductPopup; @FXML private Label varProductNameDetailsProduct; @FXML private Label varOriginalPriceDetailsProduct; @FXML private Label varSellingPriceDetailsProduct; @FXML private Label varProductStockDetailsProduct; @FXML private ImageView barcodeImageDetailsProduct; private DeleteProductListener deleteProductListener;
package com.systeminventory.controller; public class productController { @FXML public Pane filterDropdown; @FXML public Button filterButton; public ImageView imageFIlter; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Button buttonCashier; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Button buttonDashboard; @FXML private ScrollPane scrollPane; @FXML private Button buttonAddProduct; @FXML public Pane backgroundPopup; @FXML private Pane addProductPopup; @FXML private Button addProductApplyButton; @FXML private Button addProductCancelButton; @FXML private TextField addProductProductNameField; @FXML private TextField addProductOriginalPriceField; @FXML private TextField addProductSellingPriceField; @FXML private TextField addProductProductStockField; @FXML private Label addProductProductImagePathLabel; @FXML private Pane addProductChooseFilePane; @FXML private Label addProductProductImageLabel; @FXML private Label addProductSellingPriceLabel; @FXML private Label addProductOriginalPriceLabel; @FXML private Label addProductProductNameLabel; @FXML private Label addProductProductStockLabel; @FXML private GridPane productCardContainer; @FXML private Label addProductProductImageGetFullPathLabel; @FXML private TextField searchProductNameField; @FXML private Label confirmDeleteVariableProductName; @FXML private Button confirmDeleteDeleteButton; @FXML private Button confirmDeleteCancelButton; @FXML private Label confirmDeleteKeyProduct; @FXML public Pane confirmDeletePane; @FXML private Label addProductLabel; @FXML private Label keyProductOnPopUp; @FXML private Pane detailsProductPopup; @FXML private Label varProductNameDetailsProduct; @FXML private Label varOriginalPriceDetailsProduct; @FXML private Label varSellingPriceDetailsProduct; @FXML private Label varProductStockDetailsProduct; @FXML private ImageView barcodeImageDetailsProduct; private DeleteProductListener deleteProductListener;
private EditProductListener editProductListener;
3
2023-11-18 02:53:02+00:00
4k
CivilisationPlot/CivilisationPlot_Papermc
src/main/java/fr/laptoff/civilisationplot/plots/Plot.java
[ { "identifier": "CivilisationPlot", "path": "src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java", "snippet": "public final class CivilisationPlot extends JavaPlugin {\n\n public static final Logger LOGGER = Logger.getLogger(\"CivilisationPlot\");\n private static CivilisationPlot instance;\n private DatabaseManager database;\n private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml)\n\n @Override\n public void onEnable() {\n instance = this;\n saveDefaultConfig();\n ConfigManager configManagerMessages = new ConfigManager(getConfig().getString(\"Language.language\"));\n configMessages = configManagerMessages.getFileConfiguration();\n\n if (getConfig().getBoolean(\"Database.enable\")){\n database = new DatabaseManager();\n database.connection();\n\n database.setup();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_connection\"));\n }\n\n Civil.load();\n Nation.load();\n\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n getServer().getPluginManager().registerEvents(new joinListener(), this);\n }\n\n @Override\n public void onDisable() {\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n if (DatabaseManager.isOnline()){\n database.disconnection();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_disconnection\"));\n }\n }\n\n public static CivilisationPlot getInstance(){\n return instance;\n }\n\n public DatabaseManager getDatabase(){\n return database;\n }\n\n}" }, { "identifier": "DatabaseManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/DatabaseManager.java", "snippet": "public class DatabaseManager {\n\n private static Connection co;\n private static final CivilisationPlot plugin = CivilisationPlot.getInstance();\n\n public Connection getConnection()\n {\n return co;\n }\n\n public void connection()\n {\n if(!isConnected())\n {\n try\n {\n String motorDriver = \"org.mariadb\";\n\n if (Objects.requireNonNull(plugin.getConfig().getString(\"Database.motor\")).equalsIgnoreCase(\"mysql\"))\n motorDriver = \"com.mysql.cj\";\n\n Class.forName(motorDriver + \".jdbc.Driver\"); //loading of the driver.\n co = DriverManager.getConnection(\"jdbc:\" + plugin.getConfig().getString(\"Database.motor\") + \"://\" + plugin.getConfig().getString(\"Database.host\") + \":\" + plugin.getConfig().getString(\"Database.port\") + \"/\" + plugin.getConfig().getString(\"Database.database_name\"), plugin.getConfig().getString(\"Database.user\"), plugin.getConfig().getString(\"Database.password\"));\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public void disconnection()\n {\n if (isConnected())\n {\n try\n {\n co.close();\n }\n catch(SQLException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n\n\n public static boolean isConnected()\n {\n try {\n return co != null && !co.isClosed() && plugin.getConfig().getBoolean(\"Database.enable\");\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n }\n return false;\n }\n\n public static boolean isOnline() {\n try {\n return !(co == null) || !co.isClosed();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public boolean doesTableExist(String tableName) {\n try {\n DatabaseMetaData metaData = co.getMetaData();\n ResultSet resultSet = metaData.getTables(null, null, tableName, null);\n\n return resultSet.next();\n } catch (SQLException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n\n public void setup(){\n try {\n\n //create the civils table\n if (!doesTableExist(\"civils\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE civils (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), name VARCHAR(50), money INT, nation VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the nations table\n if (!doesTableExist(\"nations\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE nations (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), uuid VARCHAR(50), leader_uuid VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the plots table\n if (!doesTableExist(\"plots\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE plots (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), wordlName VARCHAR(50), xCoordinates DOUBLE, yCoordinates DOUBLE, level TINYINT, propertyType VARCHAR(50), uuidProprietary VARCHAR(50));\");\n pstmt.execute();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "FileManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/FileManager.java", "snippet": "public class FileManager {\n\n public static void createResourceFile(File file){\n File file_ = new File(CivilisationPlot.getInstance().getDataFolder() + \"/\" + file.getPath());\n if (file_.exists())\n return;\n\n file.getParentFile().mkdirs();\n\n CivilisationPlot.getInstance().saveResource(file.getPath(), false);\n }\n\n public static void createFile(File file){\n if (file.exists())\n return;\n\n file.getParentFile().mkdirs();\n try {\n file.createNewFile();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void rewrite(File file, String text){\n //This method erase the text into the file and write the new text\n if (!file.exists())\n return;\n\n try {\n FileWriter writer = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(writer);\n bw.write(text);\n bw.flush();\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fr.laptoff.civilisationplot.CivilisationPlot; import fr.laptoff.civilisationplot.Managers.DatabaseManager; import fr.laptoff.civilisationplot.Managers.FileManager; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID;
3,069
package fr.laptoff.civilisationplot.plots; public class Plot { private String WorldName; private double XCoordinate; private double YCoordinates; private String PropertyType; private UUID Proprietary; private byte Level; private UUID Uuid; private File file; private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json"); private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection(); private static List<UUID> plotsList = new ArrayList<UUID>(); public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){ this.WorldName = worldName; this.XCoordinate = xCoordinates; this.YCoordinates = yCoordinates; this.PropertyType = propertyType; this.Proprietary = proprietary; this.Level = level; this.Uuid = uuid; this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json"); plotsList.add(this.Uuid); } public Chunk getChunk(){ return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk(); } public World getWorld(){ return Bukkit.getWorld(this.WorldName); } public String getPropertyType(){ return this.PropertyType; } public UUID getProprietary(){ return this.Proprietary; } public byte getLevel(){ return this.Level; } public UUID getUuid(){ return this.Uuid; } public void setWorld(World world){ this.WorldName = world.getName(); } public void setPropertyType(String s){ this.PropertyType = s; } public void setProprietary(UUID uuid){ this.Proprietary = uuid; } public void setLevel(byte lvl){ this.Level = lvl; } public static List<UUID> getPlotsList(){ return plotsList; } //Database public void updateObjectFromDatabase(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("SELECT * FROM plots WHERE uuid = '" + this.Uuid.toString() + "'"); ResultSet result = pstmt.executeQuery(); if (!result.next()) return; while (result.next()){ this.WorldName = result.getString("worldName"); this.YCoordinates = result.getDouble("yCoordinates"); this.XCoordinate = result.getDouble("xCoordinates"); this.Level = result.getByte("level"); this.PropertyType = result.getString("propertyType"); this.Proprietary = UUID.fromString(result.getString("uuidProprietary")); } } catch (SQLException e) { throw new RuntimeException(e); } } public void updateDatabaseFromObject(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("UPDATE plots SET worldName = '" + this.WorldName + "', yCoordinates = " + this.YCoordinates + ", xCoordinates = " + this.XCoordinate + ", level = " + this.Level + ", propertyType = '" + this.PropertyType + "', uuidProprietary = '" + this.Proprietary.toString() + "' WHERE uuid = '" + this.Uuid.toString() + "'"); pstmt.execute(); } catch (SQLException e) { throw new RuntimeException(e); } } public void deleteFromDatabase(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("DELETE FROM plots WHERE uuid = '" + this.Uuid + "';"); } catch (SQLException e) { throw new RuntimeException(e); } } //Local (/CivilisationPlot/Data/Plots/) public static Plot getPlotLocal(double x, double z){ for (UUID plotUuid : plotsList){ Plot plot = getPlotLocal(plotUuid); if (plot == null) return null; if (plot.getChunk().getX() == x && plot.getChunk().getZ() == z) return plot; } return null; } public static Plot getPlotLocal(UUID uuid){ File file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + uuid.toString() + ".json"); Gson gson = new GsonBuilder().create(); if (!file.exists()) return null; try { return gson.fromJson(Files.readString(Path.of(file.getPath())), Plot.class); } catch (IOException e) { throw new RuntimeException(e); } } public void updateListFromLocal(){ try {
package fr.laptoff.civilisationplot.plots; public class Plot { private String WorldName; private double XCoordinate; private double YCoordinates; private String PropertyType; private UUID Proprietary; private byte Level; private UUID Uuid; private File file; private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json"); private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection(); private static List<UUID> plotsList = new ArrayList<UUID>(); public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){ this.WorldName = worldName; this.XCoordinate = xCoordinates; this.YCoordinates = yCoordinates; this.PropertyType = propertyType; this.Proprietary = proprietary; this.Level = level; this.Uuid = uuid; this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json"); plotsList.add(this.Uuid); } public Chunk getChunk(){ return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk(); } public World getWorld(){ return Bukkit.getWorld(this.WorldName); } public String getPropertyType(){ return this.PropertyType; } public UUID getProprietary(){ return this.Proprietary; } public byte getLevel(){ return this.Level; } public UUID getUuid(){ return this.Uuid; } public void setWorld(World world){ this.WorldName = world.getName(); } public void setPropertyType(String s){ this.PropertyType = s; } public void setProprietary(UUID uuid){ this.Proprietary = uuid; } public void setLevel(byte lvl){ this.Level = lvl; } public static List<UUID> getPlotsList(){ return plotsList; } //Database public void updateObjectFromDatabase(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("SELECT * FROM plots WHERE uuid = '" + this.Uuid.toString() + "'"); ResultSet result = pstmt.executeQuery(); if (!result.next()) return; while (result.next()){ this.WorldName = result.getString("worldName"); this.YCoordinates = result.getDouble("yCoordinates"); this.XCoordinate = result.getDouble("xCoordinates"); this.Level = result.getByte("level"); this.PropertyType = result.getString("propertyType"); this.Proprietary = UUID.fromString(result.getString("uuidProprietary")); } } catch (SQLException e) { throw new RuntimeException(e); } } public void updateDatabaseFromObject(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("UPDATE plots SET worldName = '" + this.WorldName + "', yCoordinates = " + this.YCoordinates + ", xCoordinates = " + this.XCoordinate + ", level = " + this.Level + ", propertyType = '" + this.PropertyType + "', uuidProprietary = '" + this.Proprietary.toString() + "' WHERE uuid = '" + this.Uuid.toString() + "'"); pstmt.execute(); } catch (SQLException e) { throw new RuntimeException(e); } } public void deleteFromDatabase(){ if (!DatabaseManager.isOnline()) return; try { PreparedStatement pstmt = co.prepareStatement("DELETE FROM plots WHERE uuid = '" + this.Uuid + "';"); } catch (SQLException e) { throw new RuntimeException(e); } } //Local (/CivilisationPlot/Data/Plots/) public static Plot getPlotLocal(double x, double z){ for (UUID plotUuid : plotsList){ Plot plot = getPlotLocal(plotUuid); if (plot == null) return null; if (plot.getChunk().getX() == x && plot.getChunk().getZ() == z) return plot; } return null; } public static Plot getPlotLocal(UUID uuid){ File file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + uuid.toString() + ".json"); Gson gson = new GsonBuilder().create(); if (!file.exists()) return null; try { return gson.fromJson(Files.readString(Path.of(file.getPath())), Plot.class); } catch (IOException e) { throw new RuntimeException(e); } } public void updateListFromLocal(){ try {
FileManager.createFile(fileList);
2
2023-11-11 18:26:55+00:00
4k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/mixin/meteor/modules/KillAuraMixin.java
[ { "identifier": "ShieldBypass", "path": "src/main/java/anticope/rejects/modules/ShieldBypass.java", "snippet": "public class ShieldBypass extends Module {\n private final SettingGroup sgGeneral = settings.getDefaultGroup();\n\n private final Setting<Boolean> ignoreAxe = sgGeneral.add(new BoolSetting.Builder()\n .name(\"ignore-axe\")\n .description(\"Ignore if you are holding an axe.\")\n .defaultValue(true)\n .build()\n );\n\n public ShieldBypass() {\n super(MeteorRejectsAddon.CATEGORY, \"shield-bypass\", \"Attempts to teleport you behind enemies to bypass shields.\");\n }\n\n @EventHandler\n private void onMouseButton(MouseButtonEvent event) {\n if (Modules.get().isActive(KillAura.class)) return;\n if (mc.currentScreen == null && !mc.player.isUsingItem() && event.action == KeyAction.Press && event.button == GLFW_MOUSE_BUTTON_LEFT) {\n if (mc.crosshairTarget instanceof EntityHitResult result) {\n bypass(result.getEntity(), event);\n }\n }\n }\n\n private boolean isBlocked(Vec3d pos, LivingEntity target) {\n Vec3d vec3d3 = pos.relativize(target.getPos()).normalize();\n return new Vec3d(vec3d3.x, 0.0d, vec3d3.z).dotProduct(target.getRotationVec(1.0f)) >= 0.0d;\n }\n\n public void bypass(Entity target, Cancellable event) {\n if (target instanceof LivingEntity e && e.isBlocking()) {\n if (ignoreAxe.get() && InvUtils.testInMainHand(i -> i.getItem() instanceof AxeItem)) return;\n\n // Shield check\n if (isBlocked(mc.player.getPos(), e)) return;\n\n Vec3d offset = Vec3d.fromPolar(0, mc.player.getYaw()).normalize().multiply(2);\n Vec3d newPos = e.getPos().add(offset);\n\n // Move up to prevent tping into blocks\n boolean inside = false;\n for (float i = 0; i < 4; i += 0.25) {\n Vec3d targetPos = newPos.add(0, i, 0);\n\n boolean collides = !mc.world.isSpaceEmpty(null, e.getBoundingBox().offset(offset).offset(targetPos.subtract(newPos)));\n\n if (!inside && collides) {\n inside = true;\n } else if (inside && !collides) {\n newPos = targetPos;\n break;\n }\n }\n\n if (!isBlocked(newPos, e)) return;\n\n event.cancel();\n\n mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(newPos.getX(), newPos.getY(), newPos.getZ(), true));\n\n mc.getNetworkHandler().sendPacket(PlayerInteractEntityC2SPacket.attack(e, mc.player.isSneaking()));\n mc.getNetworkHandler().sendPacket(new HandSwingC2SPacket(mc.player.getActiveHand()));\n mc.player.resetLastAttackedTicks();\n\n mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), true));\n }\n }\n}" }, { "identifier": "RejectsUtils", "path": "src/main/java/anticope/rejects/utils/RejectsUtils.java", "snippet": "public class RejectsUtils {\n @PostInit\n public static void init() {\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n System.out.println(\"saving seeds...\");\n RejectsConfig.get().save(MeteorClient.FOLDER);\n Seeds.get().save(MeteorClient.FOLDER);\n }));\n }\n\n public static String getModuleName(String name) {\n int dupe = 0;\n Modules modules = Modules.get();\n if (modules == null) {\n MeteorRejectsAddon.LOG.warn(\"Module instantiation before Modules initialized.\");\n return name;\n }\n for (Module module : modules.getAll()) {\n if (module.name.equals(name)) {\n dupe++;\n break;\n }\n }\n return dupe == 0 ? name : getModuleName(name + \"*\".repeat(dupe));\n }\n\n public static String getRandomPassword(int num) {\n String str = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";\n Random random = new Random();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < num; i++) {\n int number = random.nextInt(63);\n sb.append(str.charAt(number));\n }\n return sb.toString();\n }\n\n public static boolean inFov(Entity entity, double fov) {\n if (fov >= 360) return true;\n float[] angle = PlayerUtils.calculateAngle(entity.getBoundingBox().getCenter());\n double xDist = MathHelper.angleBetween(angle[0], mc.player.getYaw());\n double yDist = MathHelper.angleBetween(angle[1], mc.player.getPitch());\n double angleDistance = Math.hypot(xDist, yDist);\n return angleDistance <= fov;\n }\n\n public static float fullFlightMove(PlayerMoveEvent event, double speed, boolean verticalSpeedMatch) {\n if (PlayerUtils.isMoving()) {\n double dir = getDir();\n\n double xDir = Math.cos(Math.toRadians(dir + 90));\n double zDir = Math.sin(Math.toRadians(dir + 90));\n\n ((IVec3d) event.movement).setXZ(xDir * speed, zDir * speed);\n } else {\n ((IVec3d) event.movement).setXZ(0, 0);\n }\n\n float ySpeed = 0;\n\n if (mc.options.jumpKey.isPressed())\n ySpeed += speed;\n if (mc.options.sneakKey.isPressed())\n ySpeed -= speed;\n ((IVec3d) event.movement).setY(verticalSpeedMatch ? ySpeed : ySpeed / 2);\n\n return ySpeed;\n }\n\n private static double getDir() {\n double dir = 0;\n\n if (Utils.canUpdate()) {\n dir = mc.player.getYaw() + ((mc.player.forwardSpeed < 0) ? 180 : 0);\n\n if (mc.player.sidewaysSpeed > 0) {\n dir += -90F * ((mc.player.forwardSpeed < 0) ? -0.5F : ((mc.player.forwardSpeed > 0) ? 0.5F : 1F));\n } else if (mc.player.sidewaysSpeed < 0) {\n dir += 90F * ((mc.player.forwardSpeed < 0) ? -0.5F : ((mc.player.forwardSpeed > 0) ? 0.5F : 1F));\n }\n }\n return dir;\n }\n}" } ]
import anticope.rejects.modules.ShieldBypass; import anticope.rejects.utils.RejectsUtils; import meteordevelopment.meteorclient.events.Cancellable; import meteordevelopment.meteorclient.events.world.TickEvent; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.modules.Category; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.meteorclient.systems.modules.Modules; import meteordevelopment.meteorclient.systems.modules.combat.KillAura; import net.minecraft.entity.Entity; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Random;
2,673
package anticope.rejects.mixin.meteor.modules; @Mixin(value = KillAura.class, remap = false) public class KillAuraMixin extends Module { @Shadow @Final private SettingGroup sgGeneral; @Shadow @Final private SettingGroup sgTargeting; @Shadow @Final private Setting<Boolean> onlyOnLook; @Shadow private int hitTimer; @Shadow @Final private SettingGroup sgTiming; @Shadow @Final private Setting<Boolean> customDelay; private final Random random = new Random(); private Setting<Double> fov; private Setting<Boolean> ignoreInvisible; private Setting<Boolean> randomTeleport; private Setting<Double> hitChance; private Setting<Integer> randomDelayMax; public KillAuraMixin(Category category, String name, String description) { super(category, name, description); } @Inject(method = "<init>", at = @At("TAIL")) private void onInit(CallbackInfo info) { fov = sgGeneral.add(new DoubleSetting.Builder() .name("fov") .description("Will only aim entities in the fov.") .defaultValue(360) .min(0) .max(360) .build() ); ignoreInvisible = sgTargeting.add(new BoolSetting.Builder() .name("ignore-invisible") .description("Whether or not to attack invisible entities.") .defaultValue(false) .build() ); randomTeleport = sgGeneral.add(new BoolSetting.Builder() .name("random-teleport") .description("Randomly teleport around the target.") .defaultValue(false) .visible(() -> !onlyOnLook.get()) .build() ); hitChance = sgGeneral.add(new DoubleSetting.Builder() .name("hit-chance") .description("The probability of your hits landing.") .defaultValue(100) .range(1, 100) .sliderRange(1, 100) .build() ); randomDelayMax = sgTiming.add(new IntSetting.Builder() .name("random-delay-max") .description("The maximum value for random delay.") .defaultValue(4) .min(0) .sliderMax(20) .visible(customDelay::get) .build() ); } @Inject(method = "entityCheck", at = @At(value = "RETURN", ordinal = 14), cancellable = true) private void onReturn(Entity entity, CallbackInfoReturnable<Boolean> info) { if (ignoreInvisible.get() && entity.isInvisible()) info.setReturnValue(false); if (!RejectsUtils.inFov(entity, fov.get())) info.setReturnValue(false); info.setReturnValue(info.getReturnValueZ()); } @Inject(method = "attack", at = @At("HEAD"), cancellable = true) private void onAttack(Entity entity, CallbackInfo info) { if (hitChance.get() < 100 && Math.random() > hitChance.get() / 100) info.cancel(); } @Inject(method = "onTick", at = @At("TAIL"), locals = LocalCapture.CAPTURE_FAILSOFT) private void onTick(TickEvent.Pre event, CallbackInfo ci, Entity primary) { if (randomTeleport.get() && !onlyOnLook.get()) { mc.player.setPosition(primary.getX() + randomOffset(), primary.getY(), primary.getZ() + randomOffset()); } } @Inject(method = "attack", at = @At(value = "TAIL")) private void modifyHitDelay(CallbackInfo info) { if (randomDelayMax.get() == 0) return; hitTimer -= random.nextInt(randomDelayMax.get()); } @Inject(method = "attack", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;attackEntity(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/entity/Entity;)V"), cancellable = true) private void onHit(Entity target, CallbackInfo info) {
package anticope.rejects.mixin.meteor.modules; @Mixin(value = KillAura.class, remap = false) public class KillAuraMixin extends Module { @Shadow @Final private SettingGroup sgGeneral; @Shadow @Final private SettingGroup sgTargeting; @Shadow @Final private Setting<Boolean> onlyOnLook; @Shadow private int hitTimer; @Shadow @Final private SettingGroup sgTiming; @Shadow @Final private Setting<Boolean> customDelay; private final Random random = new Random(); private Setting<Double> fov; private Setting<Boolean> ignoreInvisible; private Setting<Boolean> randomTeleport; private Setting<Double> hitChance; private Setting<Integer> randomDelayMax; public KillAuraMixin(Category category, String name, String description) { super(category, name, description); } @Inject(method = "<init>", at = @At("TAIL")) private void onInit(CallbackInfo info) { fov = sgGeneral.add(new DoubleSetting.Builder() .name("fov") .description("Will only aim entities in the fov.") .defaultValue(360) .min(0) .max(360) .build() ); ignoreInvisible = sgTargeting.add(new BoolSetting.Builder() .name("ignore-invisible") .description("Whether or not to attack invisible entities.") .defaultValue(false) .build() ); randomTeleport = sgGeneral.add(new BoolSetting.Builder() .name("random-teleport") .description("Randomly teleport around the target.") .defaultValue(false) .visible(() -> !onlyOnLook.get()) .build() ); hitChance = sgGeneral.add(new DoubleSetting.Builder() .name("hit-chance") .description("The probability of your hits landing.") .defaultValue(100) .range(1, 100) .sliderRange(1, 100) .build() ); randomDelayMax = sgTiming.add(new IntSetting.Builder() .name("random-delay-max") .description("The maximum value for random delay.") .defaultValue(4) .min(0) .sliderMax(20) .visible(customDelay::get) .build() ); } @Inject(method = "entityCheck", at = @At(value = "RETURN", ordinal = 14), cancellable = true) private void onReturn(Entity entity, CallbackInfoReturnable<Boolean> info) { if (ignoreInvisible.get() && entity.isInvisible()) info.setReturnValue(false); if (!RejectsUtils.inFov(entity, fov.get())) info.setReturnValue(false); info.setReturnValue(info.getReturnValueZ()); } @Inject(method = "attack", at = @At("HEAD"), cancellable = true) private void onAttack(Entity entity, CallbackInfo info) { if (hitChance.get() < 100 && Math.random() > hitChance.get() / 100) info.cancel(); } @Inject(method = "onTick", at = @At("TAIL"), locals = LocalCapture.CAPTURE_FAILSOFT) private void onTick(TickEvent.Pre event, CallbackInfo ci, Entity primary) { if (randomTeleport.get() && !onlyOnLook.get()) { mc.player.setPosition(primary.getX() + randomOffset(), primary.getY(), primary.getZ() + randomOffset()); } } @Inject(method = "attack", at = @At(value = "TAIL")) private void modifyHitDelay(CallbackInfo info) { if (randomDelayMax.get() == 0) return; hitTimer -= random.nextInt(randomDelayMax.get()); } @Inject(method = "attack", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;attackEntity(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/entity/Entity;)V"), cancellable = true) private void onHit(Entity target, CallbackInfo info) {
ShieldBypass shieldBypass = Modules.get().get(ShieldBypass.class);
0
2023-11-13 08:11:28+00:00
4k
stiemannkj1/java-utilities
src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java
[ { "identifier": "binarySearchArrayPrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(prefixes);\n}" }, { "identifier": "binarySearchArraySuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> binarySearchArraySuffixMapping(\n final Map<String, T> suffixes) {\n return new BinarySearchArraySuffixMapping<>(suffixes);\n}" }, { "identifier": "limitedCharArrayTriePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> limitedCharArrayTriePrefixMapping(\n final char min, final char max, final Map<String, T> prefixes) {\n return new LimitedCharArrayTriePrefixMapping<>(min, max, prefixes);\n}" }, { "identifier": "limitedCharArrayTrieSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> limitedCharArrayTrieSuffixMapping(\n final char min, final char max, final Map<String, T> suffixes) {\n return new LimitedCharArrayTrieSuffixMapping<>(min, max, suffixes);\n}" }, { "identifier": "ImmutablePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutablePrefixMapping<T> extends ImmutablePrefixMatcher {\n\n @Override\n default boolean matchesAnyPrefix(final String string) {\n return keyAndValueForPrefix(string) != null;\n }\n\n default T valueForPrefix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForPrefix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForPrefix(final String string);\n}" }, { "identifier": "ImmutableSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutableSuffixMapping<T> extends ImmutableSuffixMatcher {\n\n @Override\n default boolean matchesAnySuffix(final String string) {\n return keyAndValueForSuffix(string) != null;\n }\n\n default T valueForSuffix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForSuffix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForSuffix(final String string);\n}" }, { "identifier": "Pair", "path": "src/main/java/dev/stiemannkj1/util/Pair.java", "snippet": "public class Pair<T1, T2> implements Map.Entry<T1, T2> {\n public final T1 first;\n public final T2 second;\n\n private Pair(final T1 first, final T2 second) {\n this.first = first;\n this.second = second;\n }\n\n public T1 first() {\n return first;\n }\n\n public T2 second() {\n return second;\n }\n\n public T1 left() {\n return first;\n }\n\n public T2 right() {\n return second;\n }\n\n public T1 key() {\n return first;\n }\n\n public T2 value() {\n return second;\n }\n\n @Override\n public T1 getKey() {\n return first;\n }\n\n @Override\n public T2 getValue() {\n return second;\n }\n\n @Override\n public T2 setValue(final T2 value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(final Object o) {\n\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Pair<?, ?> pair = (Pair<?, ?>) o;\n\n return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(first, second);\n }\n\n @Override\n public String toString() {\n return \"{\" + first + ',' + second + '}';\n }\n\n public static <T1, T2> Pair<T1, T2> of(final T1 first, final T2 second) {\n return new Pair<>(first, second);\n }\n\n public static <K, V> Pair<K, V> fromEntry(final Map.Entry<K, V> entry) {\n return new Pair<>(entry.getKey(), entry.getValue());\n }\n\n public static final class NameValue<V> extends Pair<String, V> {\n private NameValue(final String name, final V value) {\n super(name, value);\n }\n\n public String name() {\n return first;\n }\n }\n\n public static <V> NameValue<V> nameValuePair(final String name, final V value) {\n return new NameValue<>(name, value);\n }\n}" } ]
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping; import dev.stiemannkj1.util.Pair; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource;
2,323
/* Copyright 2023 Kyle J. Stiemann 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 dev.stiemannkj1.collection.fixmapping; final class FixMappingsTests { // TODO test unicode interface PrefixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "abe,true,1", "abd,true,2", "aba,false,null", "abd,true,2", "abdi,true,2", "abdic,true,2", "abdica,true,2", "abdicat,true,2", "abdicat,true,2", "abdicate,true,3", "abdicated,true,3", "x,false,null", "xy,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_prefixes( final String string, final boolean expectPrefixed, final Integer expectedValue) { // Test odd number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); // Test odd number of prefixes. prefixes.put("xyz", 4); prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); } @SuppressWarnings("unchecked") default void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals(
/* Copyright 2023 Kyle J. Stiemann 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 dev.stiemannkj1.collection.fixmapping; final class FixMappingsTests { // TODO test unicode interface PrefixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "abe,true,1", "abd,true,2", "aba,false,null", "abd,true,2", "abdi,true,2", "abdic,true,2", "abdica,true,2", "abdicat,true,2", "abdicat,true,2", "abdicate,true,3", "abdicated,true,3", "x,false,null", "xy,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_prefixes( final String string, final boolean expectPrefixed, final Integer expectedValue) { // Test odd number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); // Test odd number of prefixes. prefixes.put("xyz", 4); prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); } @SuppressWarnings("unchecked") default void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals(
Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)),
6
2023-11-12 05:05:22+00:00
4k
intrepidLi/BUAA_Food
library/base/src/main/java/com/hjq/base/BasePopupWindow.java
[ { "identifier": "ActivityAction", "path": "library/base/src/main/java/com/hjq/base/action/ActivityAction.java", "snippet": "public interface ActivityAction {\n\n /**\n * 获取 Context 对象\n */\n Context getContext();\n\n /**\n * 获取 Activity 对象\n */\n default Activity getActivity() {\n Context context = getContext();\n do {\n if (context instanceof Activity) {\n return (Activity) context;\n } else if (context instanceof ContextWrapper) {\n context = ((ContextWrapper) context).getBaseContext();\n } else {\n return null;\n }\n } while (context != null);\n return null;\n }\n\n /**\n * 跳转 Activity 简化版\n */\n default void startActivity(Class<? extends Activity> clazz) {\n startActivity(new Intent(getContext(), clazz));\n }\n\n /**\n * 跳转 Activity\n */\n default void startActivity(Intent intent) {\n if (!(getContext() instanceof Activity)) {\n // 如果当前的上下文不是 Activity,调用 startActivity 必须加入新任务栈的标记,否则会报错:android.util.AndroidRuntimeException\n // Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n getContext().startActivity(intent);\n }\n}" }, { "identifier": "AnimAction", "path": "library/base/src/main/java/com/hjq/base/action/AnimAction.java", "snippet": "public interface AnimAction {\n\n /** 默认动画效果 */\n int ANIM_DEFAULT = -1;\n\n /** 没有动画效果 */\n int ANIM_EMPTY = 0;\n\n /** 缩放动画 */\n int ANIM_SCALE = R.style.ScaleAnimStyle;\n\n /** IOS 动画 */\n int ANIM_IOS = R.style.IOSAnimStyle;\n\n /** 吐司动画 */\n int ANIM_TOAST = android.R.style.Animation_Toast;\n\n /** 顶部弹出动画 */\n int ANIM_TOP = R.style.TopAnimStyle;\n\n /** 底部弹出动画 */\n int ANIM_BOTTOM = R.style.BottomAnimStyle;\n\n /** 左边弹出动画 */\n int ANIM_LEFT = R.style.LeftAnimStyle;\n\n /** 右边弹出动画 */\n int ANIM_RIGHT = R.style.RightAnimStyle;\n}" }, { "identifier": "ClickAction", "path": "library/base/src/main/java/com/hjq/base/action/ClickAction.java", "snippet": "public interface ClickAction extends View.OnClickListener {\n\n <V extends View> V findViewById(@IdRes int id);\n\n default void setOnClickListener(@IdRes int... ids) {\n setOnClickListener(this, ids);\n }\n\n default void setOnClickListener(@Nullable View.OnClickListener listener, @IdRes int... ids) {\n for (int id : ids) {\n findViewById(id).setOnClickListener(listener);\n }\n }\n\n default void setOnClickListener(View... views) {\n setOnClickListener(this, views);\n }\n\n default void setOnClickListener(@Nullable View.OnClickListener listener, View... views) {\n for (View view : views) {\n view.setOnClickListener(listener);\n }\n }\n\n @Override\n default void onClick(View view) {\n // 默认不实现,让子类实现\n }\n}" }, { "identifier": "HandlerAction", "path": "library/base/src/main/java/com/hjq/base/action/HandlerAction.java", "snippet": "public interface HandlerAction {\n\n Handler HANDLER = new Handler(Looper.getMainLooper());\n\n /**\n * 获取 Handler\n */\n default Handler getHandler() {\n return HANDLER;\n }\n\n /**\n * 延迟执行\n */\n default boolean post(Runnable runnable) {\n return postDelayed(runnable, 0);\n }\n\n /**\n * 延迟一段时间执行\n */\n default boolean postDelayed(Runnable runnable, long delayMillis) {\n if (delayMillis < 0) {\n delayMillis = 0;\n }\n return postAtTime(runnable, SystemClock.uptimeMillis() + delayMillis);\n }\n\n /**\n * 在指定的时间执行\n */\n default boolean postAtTime(Runnable runnable, long uptimeMillis) {\n // 发送和当前对象相关的消息回调\n return HANDLER.postAtTime(runnable, this, uptimeMillis);\n }\n\n /**\n * 移除单个消息回调\n */\n default void removeCallbacks(Runnable runnable) {\n HANDLER.removeCallbacks(runnable);\n }\n\n /**\n * 移除全部消息回调\n */\n default void removeCallbacks() {\n // 移除和当前对象相关的消息回调\n HANDLER.removeCallbacksAndMessages(this);\n }\n}" }, { "identifier": "KeyboardAction", "path": "library/base/src/main/java/com/hjq/base/action/KeyboardAction.java", "snippet": "public interface KeyboardAction {\n\n /**\n * 显示软键盘,需要先 requestFocus 获取焦点,如果是在 Activity Create,那么需要延迟一段时间\n */\n default void showKeyboard(View view) {\n if (view == null) {\n return;\n }\n InputMethodManager manager = (InputMethodManager) view.getContext()\n .getSystemService(Context.INPUT_METHOD_SERVICE);\n if (manager == null) {\n return;\n }\n manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);\n }\n\n /**\n * 隐藏软键盘\n */\n default void hideKeyboard(View view) {\n if (view == null) {\n return;\n }\n InputMethodManager manager = (InputMethodManager) view.getContext()\n .getSystemService(Context.INPUT_METHOD_SERVICE);\n if (manager == null) {\n return;\n }\n manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);\n }\n\n /**\n * 切换软键盘\n */\n default void toggleSoftInput(View view) {\n if (view == null) {\n return;\n }\n InputMethodManager manager = (InputMethodManager) view.getContext()\n .getSystemService(Context.INPUT_METHOD_SERVICE);\n if (manager == null) {\n return;\n }\n manager.toggleSoftInput(0, 0);\n }\n}" }, { "identifier": "ResourcesAction", "path": "library/base/src/main/java/com/hjq/base/action/ResourcesAction.java", "snippet": "public interface ResourcesAction {\n\n Context getContext();\n\n default Resources getResources() {\n return getContext().getResources();\n }\n\n default String getString(@StringRes int id) {\n return getContext().getString(id);\n }\n\n default String getString(@StringRes int id, Object... formatArgs) {\n return getResources().getString(id, formatArgs);\n }\n\n default Drawable getDrawable(@DrawableRes int id) {\n return ContextCompat.getDrawable(getContext(), id);\n }\n\n @ColorInt\n default int getColor(@ColorRes int id) {\n return ContextCompat.getColor(getContext(), id);\n }\n\n default <S> S getSystemService(@NonNull Class<S> serviceClass) {\n return ContextCompat.getSystemService(getContext(), serviceClass);\n }\n}" } ]
import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.util.SparseArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.DrawableRes; import androidx.annotation.FloatRange; import androidx.annotation.IdRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.annotation.StyleRes; import androidx.core.content.ContextCompat; import androidx.core.widget.PopupWindowCompat; import com.hjq.base.action.ActivityAction; import com.hjq.base.action.AnimAction; import com.hjq.base.action.ClickAction; import com.hjq.base.action.HandlerAction; import com.hjq.base.action.KeyboardAction; import com.hjq.base.action.ResourcesAction; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.List;
3,372
@Override public void onDismiss() { if (mDismissListeners == null) { return; } for (BasePopupWindow.OnDismissListener listener : mDismissListeners) { listener.onDismiss(this); } } @Override public void showAsDropDown(View anchor, int xOff, int yOff, int gravity) { if (isShowing() || getContentView() == null) { return; } if (mShowListeners != null) { for (BasePopupWindow.OnShowListener listener : mShowListeners) { listener.onShow(this); } } super.showAsDropDown(anchor, xOff, yOff, gravity); } @Override public void showAtLocation(View parent, int gravity, int x, int y) { if (isShowing() || getContentView() == null) { return; } if (mShowListeners != null) { for (BasePopupWindow.OnShowListener listener : mShowListeners) { listener.onShow(this); } } super.showAtLocation(parent, gravity, x, y); } @Override public void dismiss() { super.dismiss(); removeCallbacks(); } @Override public <V extends View> V findViewById(@IdRes int id) { return getContentView().findViewById(id); } @Override public void setWindowLayoutType(int type) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { super.setWindowLayoutType(type); } else { PopupWindowCompat.setWindowLayoutType(this, type); } } @Override public int getWindowLayoutType() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return super.getWindowLayoutType(); } else { return PopupWindowCompat.getWindowLayoutType(this); } } @Override public void setOverlapAnchor(boolean overlapAnchor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { super.setOverlapAnchor(overlapAnchor); } else { PopupWindowCompat.setOverlapAnchor(this, overlapAnchor); } } /** * 设置背景遮盖层的透明度 */ public void setBackgroundDimAmount(@FloatRange(from = 0.0, to = 1.0) float dimAmount) { float alpha = 1 - dimAmount; if (isShowing()) { setActivityAlpha(alpha); } if (mPopupBackground == null && alpha != 1) { mPopupBackground = new PopupBackground(); addOnShowListener(mPopupBackground); addOnDismissListener(mPopupBackground); } if (mPopupBackground != null) { mPopupBackground.setAlpha(alpha); } } /** * 设置 Activity 窗口透明度 */ private void setActivityAlpha(float alpha) { Activity activity = getActivity(); if (activity == null) { return; } WindowManager.LayoutParams params = activity.getWindow().getAttributes(); final ValueAnimator animator = ValueAnimator.ofFloat(params.alpha, alpha); animator.setDuration(300); animator.addUpdateListener(animation -> { float value = (float) animation.getAnimatedValue(); if (value != params.alpha) { params.alpha = value; activity.getWindow().setAttributes(params); } }); animator.start(); } @SuppressWarnings("unchecked") public static class Builder<B extends BasePopupWindow.Builder<?>> implements
package com.hjq.base; public class BasePopupWindow extends PopupWindow implements ActivityAction, HandlerAction, ClickAction, AnimAction, KeyboardAction, PopupWindow.OnDismissListener { private final Context mContext; private PopupBackground mPopupBackground; private List<BasePopupWindow.OnShowListener> mShowListeners; private List<BasePopupWindow.OnDismissListener> mDismissListeners; public BasePopupWindow(@NonNull Context context) { super(context); mContext = context; } @Override public Context getContext() { return mContext; } /** * 设置一个销毁监听器 * * @param listener 销毁监听器对象 * @deprecated 请使用 {@link #addOnDismissListener(BasePopupWindow.OnDismissListener)} */ @Deprecated @Override public void setOnDismissListener(@Nullable PopupWindow.OnDismissListener listener) { if (listener == null) { return; } addOnDismissListener(new DismissListenerWrapper(listener)); } /** * 添加一个显示监听器 * * @param listener 监听器对象 */ public void addOnShowListener(@Nullable BasePopupWindow.OnShowListener listener) { if (mShowListeners == null) { mShowListeners = new ArrayList<>(); } mShowListeners.add(listener); } /** * 添加一个销毁监听器 * * @param listener 监听器对象 */ public void addOnDismissListener(@Nullable BasePopupWindow.OnDismissListener listener) { if (mDismissListeners == null) { mDismissListeners = new ArrayList<>(); super.setOnDismissListener(this); } mDismissListeners.add(listener); } /** * 移除一个显示监听器 * * @param listener 监听器对象 */ public void removeOnShowListener(@Nullable BasePopupWindow.OnShowListener listener) { if (mShowListeners == null) { return; } mShowListeners.remove(listener); } /** * 移除一个销毁监听器 * * @param listener 监听器对象 */ public void removeOnDismissListener(@Nullable BasePopupWindow.OnDismissListener listener) { if (mDismissListeners == null) { return; } mDismissListeners.remove(listener); } /** * 设置显示监听器集合 */ private void setOnShowListeners(@Nullable List<BasePopupWindow.OnShowListener> listeners) { mShowListeners = listeners; } /** * 设置销毁监听器集合 */ private void setOnDismissListeners(@Nullable List<BasePopupWindow.OnDismissListener> listeners) { super.setOnDismissListener(this); mDismissListeners = listeners; } /** * {@link PopupWindow.OnDismissListener} */ @Override public void onDismiss() { if (mDismissListeners == null) { return; } for (BasePopupWindow.OnDismissListener listener : mDismissListeners) { listener.onDismiss(this); } } @Override public void showAsDropDown(View anchor, int xOff, int yOff, int gravity) { if (isShowing() || getContentView() == null) { return; } if (mShowListeners != null) { for (BasePopupWindow.OnShowListener listener : mShowListeners) { listener.onShow(this); } } super.showAsDropDown(anchor, xOff, yOff, gravity); } @Override public void showAtLocation(View parent, int gravity, int x, int y) { if (isShowing() || getContentView() == null) { return; } if (mShowListeners != null) { for (BasePopupWindow.OnShowListener listener : mShowListeners) { listener.onShow(this); } } super.showAtLocation(parent, gravity, x, y); } @Override public void dismiss() { super.dismiss(); removeCallbacks(); } @Override public <V extends View> V findViewById(@IdRes int id) { return getContentView().findViewById(id); } @Override public void setWindowLayoutType(int type) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { super.setWindowLayoutType(type); } else { PopupWindowCompat.setWindowLayoutType(this, type); } } @Override public int getWindowLayoutType() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return super.getWindowLayoutType(); } else { return PopupWindowCompat.getWindowLayoutType(this); } } @Override public void setOverlapAnchor(boolean overlapAnchor) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { super.setOverlapAnchor(overlapAnchor); } else { PopupWindowCompat.setOverlapAnchor(this, overlapAnchor); } } /** * 设置背景遮盖层的透明度 */ public void setBackgroundDimAmount(@FloatRange(from = 0.0, to = 1.0) float dimAmount) { float alpha = 1 - dimAmount; if (isShowing()) { setActivityAlpha(alpha); } if (mPopupBackground == null && alpha != 1) { mPopupBackground = new PopupBackground(); addOnShowListener(mPopupBackground); addOnDismissListener(mPopupBackground); } if (mPopupBackground != null) { mPopupBackground.setAlpha(alpha); } } /** * 设置 Activity 窗口透明度 */ private void setActivityAlpha(float alpha) { Activity activity = getActivity(); if (activity == null) { return; } WindowManager.LayoutParams params = activity.getWindow().getAttributes(); final ValueAnimator animator = ValueAnimator.ofFloat(params.alpha, alpha); animator.setDuration(300); animator.addUpdateListener(animation -> { float value = (float) animation.getAnimatedValue(); if (value != params.alpha) { params.alpha = value; activity.getWindow().setAttributes(params); } }); animator.start(); } @SuppressWarnings("unchecked") public static class Builder<B extends BasePopupWindow.Builder<?>> implements
ActivityAction, ResourcesAction, ClickAction, KeyboardAction {
5
2023-11-14 10:04:26+00:00
4k
WallasAR/GUITest
src/main/java/com/session/employee/medOrderController.java
[ { "identifier": "Main", "path": "src/main/java/com/example/guitest/Main.java", "snippet": "public class Main extends Application {\n\n private static Stage stage; // Variavel estaticas para fazer a mudança de tela\n\n private static Scene mainScene, homeScene, funcScene, medScene, clientScene, recordScene, funcServiceScene, medOrderScene, funcClientScene; // variavel do tipo Scene\n\n @Override\n public void start(Stage primaryStage) throws Exception { // Metodo padrão do JavaFX\n stage = primaryStage; // inicializando a variavel stage\n\n primaryStage.setTitle(\"UmbrellaCorp. System\");\n stage.getIcons().add(new Image(\"icon.png\"));\n primaryStage.initStyle(StageStyle.UNDECORATED);\n\n Parent fxmlLogin = FXMLLoader.load(getClass().getResource(\"TelaLogin.fxml\"));\n mainScene = new Scene(fxmlLogin, 700, 500); // Cache tela 1\n\n Parent fxmlHome = FXMLLoader.load(getClass().getResource(\"homePage.fxml\"));\n homeScene = new Scene(fxmlHome, 1920, 1080); // Cache tela 2\n\n Parent fxmlFunc = FXMLLoader.load(getClass().getResource(\"funcPage.fxml\"));\n funcScene = new Scene(fxmlFunc, 1920, 1080); // Cache tela 3\n\n Parent fxmlMed = FXMLLoader.load(getClass().getResource(\"medPage.fxml\"));\n medScene = new Scene(fxmlMed, 1920, 1080); // Cache tela 4\n\n Parent fxmlClient = FXMLLoader.load(getClass().getResource(\"clientPage.fxml\"));\n clientScene = new Scene(fxmlClient, 1920, 1080); // Cache tela\n\n Parent fxmlRecord = FXMLLoader.load(getClass().getResource(\"RecordPage.fxml\"));\n recordScene = new Scene(fxmlRecord, 1920, 1080); // Cache tela\n\n Parent fxmlfuncService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/PurchasePage.fxml\"));\n funcServiceScene = new Scene(fxmlfuncService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncMedOrderService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/medicineOrderPage.fxml\"));\n medOrderScene = new Scene(fxmlfuncMedOrderService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncClientService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/employeeClientPage.fxml\"));\n funcClientScene = new Scene(fxmlfuncClientService, 1920, 1080);\n\n primaryStage.setScene(mainScene); // Definindo tela principal/inicial\n primaryStage.show(); // mostrando a cena\n Banco banco = new Banco();\n banco.registro();\n banco.carrinho();\n banco.tablecliete();\n banco.encomendas();\n }\n\n public static void changedScene(String scr){ // metodo que muda a tela\n switch (scr){\n case \"main\":\n stage.setScene(mainScene);\n stage.centerOnScreen();\n break;\n case \"home\":\n stage.setScene(homeScene);\n stage.centerOnScreen();\n break;\n case \"func\":\n stage.setScene(funcScene);\n stage.centerOnScreen();\n break;\n case \"med\":\n stage.setScene(medScene);\n stage.centerOnScreen();\n break;\n case \"client\":\n stage.setScene(clientScene);\n stage.centerOnScreen();\n break;\n case \"sale\":\n stage.setScene(funcServiceScene);\n stage.centerOnScreen();\n break;\n case \"medOrder\":\n stage.setScene(medOrderScene);\n stage.centerOnScreen();\n break;\n case \"ClientAdmFunc\":\n stage.setScene(funcClientScene);\n stage.centerOnScreen();\n break;\n case \"record\":\n stage.setScene(recordScene);\n stage.centerOnScreen();\n break;\n }\n }\n\n public static void main(String[] args) {\n launch();\n }\n}" }, { "identifier": "EncomendasTable", "path": "src/main/java/com/table/view/EncomendasTable.java", "snippet": "public class EncomendasTable {\n private int id;\n private String user;\n private String medicine;\n private int amount;\n private float price;\n private String date;\n private String phone;\n private String status;\n\n public EncomendasTable(int id, String user, String medicine, int amount, float price, String date, String phone, String status) {\n this.id = id;\n this.user = user;\n this.medicine = medicine;\n this.amount = amount;\n this.price = price;\n this.date = date;\n this.phone = phone;\n this.status = status;\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 String getUser() {\n return user;\n }\n\n public void setUser(String user) {\n this.user = user;\n }\n\n public String getMedicine() {\n return medicine;\n }\n\n public void setMedicine(String medicine) {\n this.medicine = medicine;\n }\n\n public int getAmount() {\n return amount;\n }\n\n public void setAmount(int amount) {\n this.amount = amount;\n }\n\n public float getPrice() {\n return price;\n }\n\n public void setPrice(float price) {\n this.price = price;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n}" }, { "identifier": "AlertMsg", "path": "src/main/java/com/warning/alert/AlertMsg.java", "snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}" }, { "identifier": "connection", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public static Connection connection = conexao();" } ]
import com.example.guitest.Main; import com.table.view.EncomendasTable; import com.warning.alert.AlertMsg; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import static com.db.bank.Banco.connection; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle;
1,869
package com.session.employee; public class medOrderController implements Initializable { @FXML protected void MainAction(MouseEvent e) {
package com.session.employee; public class medOrderController implements Initializable { @FXML protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
2
2023-11-16 14:55:08+00:00
4k
wzh933/Buffer-Manager
src/main/java/cs/adb/wzh/bufferManager/BMgr.java
[ { "identifier": "Disk", "path": "src/main/java/cs/adb/wzh/Storage/Disk.java", "snippet": "public class Disk {\n private final int diskSize;\n private final Page[] disk;\n\n public int getDiskSize() {\n return diskSize;\n }\n\n public Page[] getDisk() {\n return disk;\n }\n\n\n public Disk() {\n final int DEF_BUF_SIZE = 65536;//256MB的磁盘\n this.diskSize = DEF_BUF_SIZE;\n this.disk = new Page[DEF_BUF_SIZE];\n //初始化磁盘空间\n for (int pageId = 0; pageId < this.diskSize; pageId++) {\n this.disk[pageId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "Bucket", "path": "src/main/java/cs/adb/wzh/bucket/Bucket.java", "snippet": "public class Bucket {\n private final int bucketSize = 4;\n private final ArrayList<BCB> bcbList;\n private Bucket next;\n\n public Bucket() {\n bcbList = new ArrayList<>();\n }\n\n public boolean isFull() {\n return bcbList.size() == bucketSize;\n }\n\n /**\n * 挺好用的\n *\n * @param bcb:将要加入桶的BCB块\n */\n public void appendBCB(BCB bcb) {\n Bucket curBucket = this;//从当前第一个桶开始遍历\n while (curBucket.isFull()) {//当前桶非空时退出循环\n if (curBucket.getNext() == null) {//当前桶刚满,还没创建溢出块时\n curBucket.setNext(new Bucket());//创建溢出块\n }\n curBucket = curBucket.getNext();//遍历下个桶\n }\n curBucket.getBcbList().add(bcb);//将BCB控制块放入当前桶中\n }\n\n\n/*\n /**\n * 虽然这段代码被我注释掉了,但是最开始我确实是用Bucket里自定义的remove方法删除BCB的,我想把它留着作纪念\n *\n * @param bcb:将要被删除的BCB\n * @throws Exception:如果找不到要删除的BCB那就是代码出问题了\n * /\n public void removeBCB(BCB bcb) throws Exception {\n if (this.searchPage(bcb.getPageId()) == null) {\n throw new Exception(\"找不到要删除的页,代码出错啦!\");\n }\n\n for (Bucket curBucket = this; curBucket != null; curBucket = curBucket.getNext()) {\n for (int i = 0; i < curBucket.getBcbNum(); i++) {\n if (curBucket.getBcbList().get(i) == bcb) {\n curBucket.getBcbList().remove(i);\n// System.out.println(curBucket);\n for (Bucket curBucket1 = curBucket; curBucket1 != null; curBucket1 = curBucket1.getNext()) {\n if (curBucket1.getNext() != null) {\n //将下个桶中的首元素加入当前桶\n curBucket1.getBcbList().add(curBucket1.getNext().getBcbList().get(0));\n //删除下个桶的首元素\n curBucket1.getNext().getBcbList().remove(0);\n //如果下个桶空则删除桶\n if (curBucket1.getNext().getBcbNum() == 0) {\n curBucket1.setNext(null);\n }\n }\n }\n break;\n }\n }\n }\n }\n*/\n\n\n /**\n * @param pageId:要查找的pageId\n * @return pageId所在的BCB块\n */\n public BCB searchPage(int pageId) {\n for (BCB bcb : this.bcbList) {\n if (bcb.getPageId() == pageId) {\n return bcb;\n }\n }\n if (this.next != null) {//溢出块非空则继续搜索溢出块\n return this.next.searchPage(pageId);\n } else {//否则返回空\n return null;\n }\n }\n\n public int getBucketSize() {\n return bucketSize;\n }\n\n public int getBcbNum() {\n return bcbList.size();\n }\n\n\n public ArrayList<BCB> getBcbList() {\n return bcbList;\n }\n\n public Bucket getNext() {\n return next;\n }\n\n public void setNext(Bucket next) {\n this.next = next;\n }\n\n public void printBucket() {\n for (Bucket curBucket = this; curBucket != null; curBucket = curBucket.getNext()) {\n for (BCB bcb : curBucket.getBcbList()) {\n System.out.println(bcb.getPageId());\n }\n System.out.println();\n }\n }\n}" }, { "identifier": "Buffer", "path": "src/main/java/cs/adb/wzh/Storage/Buffer.java", "snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n }\n\n\n public Buffer() {\n final int DEF_BUF_SIZE = 1024;\n this.bufSize = DEF_BUF_SIZE;\n this.buf = new Frame[DEF_BUF_SIZE];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n /**\n * @param bufSize:用户自定义的缓存区大小\n */\n public Buffer(int bufSize) throws Exception {\n if (bufSize <= 0) {\n throw new Exception(\"缓存区大小不可以为非正数!\");\n }\n this.bufSize = bufSize;\n this.buf = new Frame[bufSize];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n public Frame readFrame(int frameId) {\n return buf[frameId];\n }\n\n public void writeFrame(Page page, int frameId) {\n //先不进行任何操作\n }\n\n}" }, { "identifier": "BCB", "path": "src/main/java/cs/adb/wzh/bufferControlBlocks/BCB.java", "snippet": "public class BCB {\n private int pageId;\n private final int frameId;\n private int latch;\n private int count;\n private int dirty = 0;\n private int referenced = 1;\n private BCB next;\n private BCB pre;\n\n /**\n * BCB块的id对应其在缓存区中的frameId\n *\n * @param frameId:缓存区页号\n */\n public BCB(int frameId) {\n this.frameId = frameId;\n }\n\n\n public void setPageId(int pageId) {\n this.pageId = pageId;\n }\n\n public void setNext(BCB next) {\n this.next = next;\n }\n\n public void setPre(BCB pre) {\n this.pre = pre;\n }\n\n public void setDirty(int dirty) {\n this.dirty = dirty;\n }\n\n public void setReferenced(int referenced) {\n this.referenced = referenced;\n }\n\n public BCB getNext() {\n return next;\n }\n\n\n public BCB getPre() {\n return pre;\n }\n\n public int getPageId() {\n return pageId;\n }\n\n public int getFrameId() {\n return frameId;\n }\n\n public int getDirty() {\n return dirty;\n }\n\n public int getReferenced() {\n return referenced;\n }\n}" }, { "identifier": "DSMgr", "path": "src/main/java/cs/adb/wzh/dataStorageManager/DSMgr.java", "snippet": "public class DSMgr {\n private final int maxPageNum;\n private int pageNum = 0;//开始时被固定的页面数位0\n private final int[] pages;\n private int curRecordId;\n private File curFile;\n private final Buffer bf;\n private final Disk disk;\n private int readDiskNum = 0;\n private int writeDiskNum = 0;\n\n public DSMgr(Buffer bf, Disk disk) {\n this.bf = bf;\n this.disk = disk;\n this.maxPageNum = disk.getDiskSize();\n /*\n pages是一个page与其useBit的索引表\n pages[pageId] = 0表示该页可用,1表示该页被固定\n 开辟新内存空间之后所有值默认为0\n */\n this.pages = new int[this.maxPageNum];\n }\n\n public void openFile(String fileName) {\n this.curFile = new File(fileName);\n }\n\n public void closeFile() {\n this.curFile = null;\n }\n\n public Page getPage(int pageId) {\n return this.disk.getDisk()[pageId];\n }\n\n public void readPage(int pageId) {\n this.readDiskNum++;\n }\n\n\n public void writePage(int frameId, int pageId) {\n this.writeDiskNum++;\n }\n\n /**\n * 将文件指针从位置pos移动offset个偏移量\n *\n * @param offset:偏移量\n * @param pos:文件位置\n */\n public void seek(int offset, int pos) throws Exception {\n if (pos + offset >= curFile.getFileSize() || pos + offset < 0) {\n throw new Exception(\"文件访问越界!\");\n }\n this.curRecordId = pos + offset;\n }\n\n public File getFile() {\n return curFile;\n }\n\n public void incNumPages() {\n pageNum += 1;\n }\n\n public void setUse(int pageId, int useBit) {\n /*\n useBit:\n 0:该页可用\n 1:该页被固定\n */\n this.pages[pageId] = useBit;\n }\n\n public int getUse(int pageId) {\n return this.pages[pageId];\n }\n\n public int getNumPages() {\n return pageNum;\n }\n\n public int getMaxPageNum() {\n return maxPageNum;\n }\n\n public int getReadDiskNum() {\n return readDiskNum;\n }\n\n public int getWriteDiskNum() {\n return writeDiskNum;\n }\n}" }, { "identifier": "SwapMethod", "path": "src/main/java/cs/adb/wzh/utils/SwapMethod.java", "snippet": "public enum SwapMethod {\n LRU, CLOCK;\n}" } ]
import cs.adb.wzh.Storage.Disk; import cs.adb.wzh.bucket.Bucket; import cs.adb.wzh.Storage.Buffer; import cs.adb.wzh.bufferControlBlocks.BCB; import cs.adb.wzh.dataStorageManager.DSMgr; import cs.adb.wzh.utils.SwapMethod; import java.io.IOException;
2,916
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class BMgr { private final DSMgr dsMgr; private final Bucket[] p2f; /* 有了BCB表之后就不需要f2p索引表了 其中bcbTable[frameId] = BCB(frameId) */
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class BMgr { private final DSMgr dsMgr; private final Bucket[] p2f; /* 有了BCB表之后就不需要f2p索引表了 其中bcbTable[frameId] = BCB(frameId) */
private final BCB[] bcbTable;
3
2023-11-15 16:30:06+00:00
4k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/utils/chat/ChatUtils.java
[ { "identifier": "ReturnCode", "path": "src/main/java/top/sharehome/springbootinittemplate/common/base/ReturnCode.java", "snippet": "@Getter\npublic enum ReturnCode {\n\n /**\n * 操作成功 200\n */\n SUCCESS(HttpStatus.SUCCESS, \"操作成功\"),\n\n /**\n * 操作失败 500\n */\n FAIL(HttpStatus.ERROR, \"操作失败\"),\n\n /**\n * 系统警告 600\n */\n WARN(HttpStatus.WARN, \"系统警告\"),\n\n /**\n * 账户名称校验失败 11000\n */\n USERNAME_VALIDATION_FAILED(11000, \"账户名称校验失败\"),\n\n /**\n * 账户名称已经存在 11001\n */\n USERNAME_ALREADY_EXISTS(11001, \"账户名称已经存在\"),\n\n /**\n * 账户名称包含特殊字符 11002\n */\n PASSWORD_AND_SECONDARY_PASSWORD_NOT_SAME(11002, \"密码和二次密码不相同\"),\n\n /**\n * 密码校验失败 11003\n */\n PASSWORD_VERIFICATION_FAILED(11003, \"密码校验失败\"),\n\n /**\n * 用户基本信息校验失败 11004\n */\n USER_BASIC_INFORMATION_VERIFICATION_FAILED(11004, \"用户基本信息校验失败\"),\n\n /**\n * 用户账户不存在 11005\n */\n USER_ACCOUNT_DOES_NOT_EXIST(11005, \"用户账户不存在\"),\n\n /**\n * 用户账户被封禁 11006\n */\n USER_ACCOUNT_BANNED(11006, \"用户账户被封禁\"),\n\n /**\n * 用户账号或密码错误 11007\n */\n WRONG_USER_ACCOUNT_OR_PASSWORD(11007, \"用户账号或密码错误\"),\n\n /**\n * 用户登录已过期 11008\n */\n USER_LOGIN_HAS_EXPIRED(11008, \"用户登录已过期\"),\n\n /**\n * 用户操作异常 11009\n */\n ABNORMAL_USER_OPERATION(11009, \"用户操作异常\"),\n\n /**\n * 用户设备异常 11010\n */\n ABNORMAL_USER_EQUIPMENT(11010, \"用户设备异常\"),\n\n /**\n * 用户登录验证码为空 11011\n */\n CAPTCHA_IS_EMPTY(11011, \"验证码为空\"),\n\n /**\n * 用户登录验证码已过期 11012\n */\n CAPTCHA_HAS_EXPIRED(11012, \"验证码已过期\"),\n\n /**\n * 用户登录验证码无效 11013\n */\n CAPTCHA_IS_INVALID(11013, \"验证码无效\"),\n\n /**\n * 用户登录验证码无效 11014\n */\n CAPTCHA_IS_INCORRECT(11014, \"验证码错误\"),\n\n /**\n * 用户发出无效请求 11015\n */\n USER_SENT_INVALID_REQUEST(11015, \"用户发出无效请求\"),\n\n /**\n * 手机格式校验失败 12000\n */\n PHONE_FORMAT_VERIFICATION_FAILED(12000, \"手机格式校验失败\"),\n\n /**\n * 邮箱格式校验失败 12001\n */\n EMAIL_FORMAT_VERIFICATION_FAILED(12001, \"邮箱格式校验失败\"),\n\n /**\n * 访问未授权 13000\n */\n ACCESS_UNAUTHORIZED(13000, \"访问未授权\"),\n\n /**\n * 请求必填参数为空 13001\n */\n REQUEST_REQUIRED_PARAMETER_IS_EMPTY(13001, \"请求必填参数为空\"),\n\n /**\n * 参数格式不匹配 13002\n */\n PARAMETER_FORMAT_MISMATCH(13002, \"参数格式不匹配\"),\n\n /**\n * 用户请求次数太多 13003\n */\n TOO_MANY_REQUESTS(13003, \"用户请求次数太多\"),\n\n /**\n * 用户上传文件异常 14000\n */\n FILE_UPLOAD_EXCEPTION(14000, \"用户上传文件异常\"),\n\n /**\n * 用户没有上传文件 14001\n */\n USER_DO_NOT_UPLOAD_FILE(14001, \"用户没有上传文件\"),\n\n /**\n * 用户上传文件类型不匹配 14002\n */\n USER_UPLOADED_FILE_TYPE_MISMATCH(14002, \"用户上传文件类型不匹配\"),\n\n /**\n * 用户上传文件太大 14003\n */\n USER_UPLOADED_FILE_IS_TOO_LARGE(14003, \"用户上传文件太大\"),\n\n /**\n * 用户上传图片太大 14004\n */\n USER_UPLOADED_IMAGE_IS_TOO_LARGE(14004, \"用户上传图片太大\"),\n\n /**\n * 用户上传视频太大 14005\n */\n USER_UPLOADED_VIDEO_IS_TOO_LARGE(14005, \"用户上传视频太大\"),\n\n /**\n * 用户上传压缩文件太大 14006\n */\n USER_UPLOADED_ZIP_IS_TOO_LARGE(14006, \"用户上传压缩文件太大\"),\n\n /**\n * 用户文件地址异常 14007\n */\n USER_FILE_ADDRESS_IS_ABNORMAL(14007, \"用户文件地址异常\"),\n\n /**\n * 用户文件删除异常 14008\n */\n USER_FILE_DELETION_IS_ABNORMAL(14008, \"用户文件删除异常\"),\n\n /**\n * 系统文件地址异常 14009\n */\n SYSTEM_FILE_ADDRESS_IS_ABNORMAL(14007, \"系统文件地址异常\"),\n\n /**\n * 邮件发送异常 15000\n */\n EMAIL_WAS_SENT_ABNORMALLY(15000, \"邮件发送异常\"),\n\n /**\n * 数据库服务出错 20000\n */\n ERRORS_OCCURRED_IN_THE_DATABASE_SERVICE(20000, \"数据库服务出错\"),\n\n /**\n * 消息中间件服务出错 30000\n */\n MQ_SERVICE_ERROR(30000, \"消息中间件服务出错\"),\n\n /**\n * 内存数据库服务出错 30001\n */\n MAIN_MEMORY_DATABASE_SERVICE_ERROR(30001, \"内存数据库服务出错\"),\n\n /**\n * 搜索引擎服务出错 30002\n */\n SEARCH_ENGINE_SERVICE_ERROR(30002, \"搜索引擎服务出错\"),\n\n /**\n * 网关服务出错 30003\n */\n GATEWAY_SERVICE_ERROR(30003, \"网关服务出错\"),\n\n /**\n * 分布式锁服务出错 30004\n */\n LOCK_SERVICE_ERROR(30004, \"分布式锁服务出错\"),\n\n /**\n * 分布式锁设计出错 30005\n */\n LOCK_DESIGN_ERROR(30005, \"分布式锁设计出错\");\n\n final private int code;\n\n final private String msg;\n\n ReturnCode(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}" }, { "identifier": "SpringContextHolder", "path": "src/main/java/top/sharehome/springbootinittemplate/config/bean/SpringContextHolder.java", "snippet": "@Component\n@Slf4j\npublic class SpringContextHolder implements ApplicationContextAware {\n\n /**\n * 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.\n */\n private static ApplicationContext context;\n\n /**\n * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.\n */\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n SpringContextHolder.context = applicationContext;\n }\n\n /**\n * 获取applicationContext\n *\n * @return 返回结果\n */\n public ApplicationContext getApplicationContext() {\n return context;\n }\n\n /**\n * 通过name获取 Bean.\n *\n * @param name Bean名称\n * @return 返回结果\n */\n public static Object getBean(String name) {\n return context.getBean(name);\n }\n\n /**\n * 通过class获取Bean.\n *\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> Map<String, T> getBeans(Class<T> clazz) {\n return context.getBeansOfType(clazz);\n }\n\n /**\n * 通过class获取Bean.\n *\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> T getBean(Class<T> clazz) {\n return context.getBean(clazz);\n }\n\n /**\n * 通过name,以及Clazz返回指定的Bean\n *\n * @param name Bean名称\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> T getBean(String name, Class<T> clazz) {\n return context.getBean(name, clazz);\n }\n\n /**\n * 依赖注入日志输出\n */\n @PostConstruct\n private void initDi() {\n log.info(\"############ {} Configuration DI.\", this.getClass().getSimpleName());\n }\n\n}" }, { "identifier": "CustomizeReturnException", "path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeReturnException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeReturnException extends RuntimeException {\n\n private ReturnCode returnCode;\n\n private String msg;\n\n public <T> CustomizeReturnException() {\n this.returnCode = ReturnCode.FAIL;\n this.msg = ReturnCode.FAIL.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode, String msg) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg() + \" ==> [\" + msg + \"]\";\n }\n\n @Override\n public String getMessage() {\n return this.msg;\n }\n\n}" } ]
import com.yupi.yucongming.dev.client.YuCongMingClient; import com.yupi.yucongming.dev.common.BaseResponse; import com.yupi.yucongming.dev.model.DevChatRequest; import com.yupi.yucongming.dev.model.DevChatResponse; import groovy.util.logging.Slf4j; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException;
2,865
package top.sharehome.springbootinittemplate.utils.chat; /** * AI对话工具类 * * @author AntonyCheng * @since 2023/10/8 19:06:36 */ @Slf4j public class ChatUtils { /** * 封装好的AI */ private static final YuCongMingClient AI_CLIENT = SpringContextHolder.getBean(YuCongMingClient.class); public static String doChat(long modelId, String message) { DevChatRequest devChatRequest = new DevChatRequest(); devChatRequest.setModelId(modelId); devChatRequest.setMessage(message); BaseResponse<DevChatResponse> response = AI_CLIENT.doChat(devChatRequest); if (response == null) {
package top.sharehome.springbootinittemplate.utils.chat; /** * AI对话工具类 * * @author AntonyCheng * @since 2023/10/8 19:06:36 */ @Slf4j public class ChatUtils { /** * 封装好的AI */ private static final YuCongMingClient AI_CLIENT = SpringContextHolder.getBean(YuCongMingClient.class); public static String doChat(long modelId, String message) { DevChatRequest devChatRequest = new DevChatRequest(); devChatRequest.setModelId(modelId); devChatRequest.setMessage(message); BaseResponse<DevChatResponse> response = AI_CLIENT.doChat(devChatRequest); if (response == null) {
throw new CustomizeReturnException(ReturnCode.FAIL, "AI 响应异常");
2
2023-11-12 07:49:59+00:00
4k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render/Window.java
[ { "identifier": "EventBus", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/event/EventBus.java", "snippet": "public final class EventBus {\n private static final class HandlerFn implements Comparable<HandlerFn> {\n private final Listener listener;\n private final Method method;\n private final EventPriority priority;\n\n public HandlerFn(Listener listener, Method method, EventPriority priority) {\n this.listener = listener;\n this.method = method;\n this.priority = priority;\n }\n\n public void invoke(Event event) {\n try {\n method.invoke(listener, event);\n } catch (ReflectiveOperationException e) {\n System.err.println(\"Failed to invoke event handler \" + method);\n e.printStackTrace();\n }\n }\n\n @Override\n public int compareTo(HandlerFn o) {\n // Comparison intentionally backwards, this makes higher priority\n // handlers happen earlier\n return Integer.compare(o.priority.getLevel(), this.priority.getLevel());\n }\n\n @Override\n public String toString() {\n return method.getDeclaringClass().getSimpleName() + \"#\" + method.getName();\n }\n }\n\n private static final class HandlerSet {\n private final List<HandlerFn> handlers;\n\n public HandlerSet() {\n handlers = new ArrayList<>();\n }\n\n public void add(HandlerFn handler) {\n handlers.add(handler);\n }\n\n public List<HandlerFn> getHandlers() {\n return handlers;\n }\n }\n\n private final Map<Class<? extends Event>, HandlerSet> handlerSets;\n\n public EventBus() {\n handlerSets = new HashMap<>();\n }\n\n private void dispatch(Class<?> type, Event event) {\n // Collect handlers for event and all supertypes of event\n List<HandlerFn> handlers = new ArrayList<>();\n while (Event.class.isAssignableFrom(type)) {\n // Put them at the beginning so superclasses get called first\n HandlerSet set = handlerSets.get(type);\n if (set != null)\n handlers.addAll(0, set.getHandlers());\n\n type = type.getSuperclass();\n }\n\n // Put in priority order\n handlers.sort(Comparator.naturalOrder());\n\n // Call them\n for (HandlerFn fn : handlers) {\n if (event.isCancelled())\n break;\n fn.invoke(event);\n }\n }\n\n /**\n * Call handlers for an event and its superclasses. Superclasses are called\n * first, then handlers are called going down the type hierarchy.\n *\n * @param event event to dispatch\n */\n public void dispatchEvent(Event event) {\n dispatch(event.getClass(), event);\n }\n\n /**\n * Registers a listener to receive events. All methods in the listener\n * annotated with {@link EventHandler} are registered to handle events.\n *\n * @param listener listener to register\n */\n public void registerListener(Listener listener) {\n for (Method method : listener.getClass().getMethods()) {\n EventHandler annotation = method.getAnnotation(EventHandler.class);\n if (annotation == null)\n continue;\n\n Class<?>[] params = method.getParameterTypes();\n if (params.length != 1 || !Event.class.isAssignableFrom(params[0])) {\n System.err.println(\"Invalid event listener: \" + method);\n continue;\n }\n\n handlerSets.computeIfAbsent(params[0].asSubclass(Event.class), (t) -> new HandlerSet())\n .add(new HandlerFn(listener, method, annotation.priority()));\n }\n }\n\n /**\n * Unregisters a listener from receiving events. After unregistering, it\n * will no longer receive events.\n *\n * @param listener listener to unregister\n */\n public void unregisterListener(Listener listener) {\n // TODO\n }\n}" }, { "identifier": "Keyboard", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/input/keyboard/Keyboard.java", "snippet": "public interface Keyboard {\n boolean isKeyPressed(Key key);\n}" }, { "identifier": "Mouse", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/input/mouse/Mouse.java", "snippet": "public interface Mouse {\n Vector2d getCursorPos();\n boolean isButtonPressed(MouseButton button);\n}" }, { "identifier": "OpenGLWindow", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/opengl/OpenGLWindow.java", "snippet": "public final class OpenGLWindow extends GlfwWindow {\n private OpenGLRenderer renderer;\n\n public OpenGLWindow(WindowSettings settings) {\n super(settings);\n }\n\n @Override\n protected void setContextWindowHints() {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);\n }\n\n @Override\n protected void initContext() {\n GL.createCapabilities(true);\n renderer = new OpenGLRenderer();\n }\n\n @Override\n public Renderer getRenderer() {\n return renderer;\n }\n}" }, { "identifier": "SafeCloseable", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/utils/SafeCloseable.java", "snippet": "public interface SafeCloseable extends AutoCloseable {\n @Override\n void close();\n}" } ]
import com.github.rmheuer.azalea.event.EventBus; import com.github.rmheuer.azalea.input.keyboard.Keyboard; import com.github.rmheuer.azalea.input.mouse.Mouse; import com.github.rmheuer.azalea.render.opengl.OpenGLWindow; import com.github.rmheuer.azalea.utils.SafeCloseable; import org.joml.Vector2i;
1,820
package com.github.rmheuer.azalea.render; /** * Represents the platform window graphics are rendered into. There can * currently only be one window at a time. */ public interface Window extends SafeCloseable { /** * Gets the renderer used to render into this window. * * @return renderer */ Renderer getRenderer(); /** * Gets whether the window should currently close. This will be true after * something has requested the window to close, such as pressing its close * button. * * @return whether the window should close */ boolean shouldClose(); /** * Updates the contents of the window. This will show the result of * rendering done using {@link #getRenderer()}. This may temporarily block * if VSync is enabled, in order to limit the frame rate. */ void update(); /** * Sets the window title. This is typically shown in the window's title * bar. * * @param title new window title */ void setTitle(String title); /** * Gets the size of the window's framebuffer. This is not necessarily the * same as the window's size, since the framebuffer may be larger on high * DPI displays. * * @return size of the framebuffer */ Vector2i getFramebufferSize(); /** * Gets the size of the window. * * @return window size */ Vector2i getSize(); /** * Gets the window's keyboard input. * * @return keyboard input */ Keyboard getKeyboard(); /** * Gets the window's mouse input. * * @return mouse input */ Mouse getMouse(); /** * Registers this window with the {@code EventBus} so it can send events. * * @param bus event bus to receive events */ void registerEvents(EventBus bus); /** * Creates a window compatible with the current platform. * * @param settings settings for the window to create * @return created window */ static Window create(WindowSettings settings) {
package com.github.rmheuer.azalea.render; /** * Represents the platform window graphics are rendered into. There can * currently only be one window at a time. */ public interface Window extends SafeCloseable { /** * Gets the renderer used to render into this window. * * @return renderer */ Renderer getRenderer(); /** * Gets whether the window should currently close. This will be true after * something has requested the window to close, such as pressing its close * button. * * @return whether the window should close */ boolean shouldClose(); /** * Updates the contents of the window. This will show the result of * rendering done using {@link #getRenderer()}. This may temporarily block * if VSync is enabled, in order to limit the frame rate. */ void update(); /** * Sets the window title. This is typically shown in the window's title * bar. * * @param title new window title */ void setTitle(String title); /** * Gets the size of the window's framebuffer. This is not necessarily the * same as the window's size, since the framebuffer may be larger on high * DPI displays. * * @return size of the framebuffer */ Vector2i getFramebufferSize(); /** * Gets the size of the window. * * @return window size */ Vector2i getSize(); /** * Gets the window's keyboard input. * * @return keyboard input */ Keyboard getKeyboard(); /** * Gets the window's mouse input. * * @return mouse input */ Mouse getMouse(); /** * Registers this window with the {@code EventBus} so it can send events. * * @param bus event bus to receive events */ void registerEvents(EventBus bus); /** * Creates a window compatible with the current platform. * * @param settings settings for the window to create * @return created window */ static Window create(WindowSettings settings) {
return new OpenGLWindow(settings);
3
2023-11-16 04:46:53+00:00
4k
orijer/IvritInterpreter
src/IvritInterpreterGUI.java
[ { "identifier": "TextAreaOutputStream", "path": "src/IvritStreams/TextAreaOutputStream.java", "snippet": "public class TextAreaOutputStream extends OutputStream {\r\n //The default amount of lines the console saves at the same time:\r\n public static final int defaultMaxConcurrentLines = 1000;\r\n\r\n //The object that control the text in the TextArea:\r\n private Appender appender;\r\n\r\n /**\r\n * Constructor.\r\n * @param textArea - the textArea object we want to write on.\r\n */\r\n public TextAreaOutputStream(JTextArea textArea) {\r\n this(textArea, defaultMaxConcurrentLines);\r\n }\r\n\r\n /**\r\n * Constructor.\r\n * @param textArea - the textArea object we want to write on.\r\n * @param maxConcurrentLines - the maximum amount of lines the console saves at the same time.\r\n */\r\n public TextAreaOutputStream(JTextArea textArea, int maxConcurrentLines) {\r\n if (maxConcurrentLines < 1) {\r\n throw new IllegalArgumentException(\r\n \"מספר השורות של הקונסול חייב להיות חיובי, אך התקבל \" + maxConcurrentLines);\r\n }\r\n\r\n this.appender = new Appender(textArea, maxConcurrentLines);\r\n }\r\n\r\n /** \r\n * Clear the current console text area.\r\n */\r\n public synchronized void clear() {\r\n if (this.appender != null) {\r\n this.appender.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Closes this stream.\r\n */\r\n public synchronized void close() {\r\n this.appender = null;\r\n }\r\n\r\n /**\r\n * Writes to the TextArea when the data is represented as an integer.\r\n */\r\n public synchronized void write(int val) {\r\n byte[] byteArr = { (byte) val };\r\n write(byteArr, 0, 1);\r\n }\r\n\r\n /**\r\n * Writes to the TextArea when the data is represented as a byte array.\r\n */\r\n public synchronized void write(byte[] byteArr) {\r\n write(byteArr, 0, byteArr.length);\r\n }\r\n\r\n /**\r\n * Writes to the TextArea when the data is represented as a byte array, \r\n * starting from a given offset for a given length.\r\n */\r\n public synchronized void write(byte[] byteArr, int offset, int len) {\r\n if (this.appender != null) {\r\n try { //We force the console to be slower so that it doesnt hurt the user's eyes (it was really annoying before...)\r\n Thread.sleep(100);\r\n } catch (InterruptedException e) {\r\n //Do nothing!\r\n }\r\n\r\n //Decodes the byte array to a string and adds it at the end of the console:\r\n this.appender.append(bytesToString(byteArr, offset, len)); \r\n }\r\n }\r\n\r\n /**\r\n * Decodes a byte array to a string (in UTF-8).\r\n * @param byteArr - the byte array which contains the data.\r\n * @param offset - the index of the first byte to decode.\r\n * @param len - the number of bytes to decode from the array\r\n * @return the string represented by the given parameters.\r\n */\r\n private static String bytesToString(byte[] byteArr, int offset, int len) {\r\n return new String(byteArr, offset, len, StandardCharsets.UTF_8);\r\n }\r\n\r\n //Inner class:\r\n /**\r\n * The thread that is responsible for the behaviour of the console (like adding and clearing it).\r\n */\r\n private class Appender implements Runnable {\r\n //A set that contains all the end of line strings we use:\r\n private static final Set<String> endOfLineSet = new HashSet<String>(\r\n Arrays.asList(\"\\n\", System.getProperty(\"line.separator\", \"\\n\")));\r\n\r\n //The TextArea we want to write on:\r\n private final JTextArea textArea;\r\n //The maximum amount of lines the console will remember at a time:\r\n private final int maxLines;\r\n //A linked list that keeps the length of each line of the text area:\r\n private final Queue<Integer> lineLengthsQueue;\r\n //A list that contains the next strings waiting to be processed:\r\n private final List<String> unprocessedList;\r\n //The length of the current line:\r\n private int curLineLength;\r\n //true IFF the console is empty = has no text in it:\r\n private boolean isClear;\r\n //true IFF this is waiting for CPU time.\r\n private boolean isInQueue;\r\n\r\n /**\r\n * Construtor.\r\n * @param textArea - the TextArea we want to write on.\r\n * @param maxLines - the maximum amount of lines the console will remember at a time.\r\n */\r\n private Appender(JTextArea textArea, int maxLines) {\r\n this.textArea = textArea;\r\n this.maxLines = maxLines;\r\n this.lineLengthsQueue = new LinkedList<Integer>();\r\n this.unprocessedList = new LinkedList<String>();\r\n this.curLineLength = 0;\r\n this.isClear = false;\r\n this.isInQueue = false;\r\n }\r\n\r\n /**\r\n * Saves the given string to be processed later, and tries to queue this thread for running.\r\n * @param str - the string to be processed.\r\n */\r\n synchronized void append(String str) {\r\n this.unprocessedList.add(str);\r\n\r\n if (!this.isInQueue) {\r\n this.isInQueue = true;\r\n EventQueue.invokeLater(this);\r\n }\r\n }\r\n\r\n /**\r\n * Clears the console, and tries to queue this thread for running.\r\n */\r\n synchronized void clear() {\r\n this.isClear = true;\r\n this.curLineLength = 0;\r\n this.lineLengthsQueue.clear();\r\n this.unprocessedList.clear();\r\n\r\n if (!this.isInQueue) {\r\n this.isInQueue = true;\r\n EventQueue.invokeLater(this);\r\n }\r\n }\r\n\r\n /**\r\n * Updates the console with the next values needed.\r\n */\r\n public synchronized void run() {\r\n if (this.isClear) {\r\n this.textArea.setText(\"\");\r\n }\r\n\r\n for (String str : this.unprocessedList) {\r\n this.curLineLength += str.length();\r\n if (hasReachedEndOfLine(str)) {\r\n handlePassingMaxLines();\r\n\r\n //Add the new line:\r\n this.lineLengthsQueue.add(this.curLineLength);\r\n this.curLineLength = 0;\r\n }\r\n this.textArea.append(str);\r\n\r\n }\r\n\r\n this.unprocessedList.clear();\r\n this.isClear = false;\r\n this.isInQueue = false;\r\n }\r\n\r\n /**\r\n * @param str - the string we want to check.\r\n * @return true IFF the given string ends with one of our EOL strings = the line ends with it.\r\n */\r\n private boolean hasReachedEndOfLine(String str) {\r\n for (String EOL : endOfLineSet) {\r\n if (str.endsWith(EOL)) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * The logic executed when we pass the maximum amount of lines the console holds at the same time.\r\n */\r\n private void handlePassingMaxLines() {\r\n if (this.lineLengthsQueue.size() >= this.maxLines) {\r\n int firstLineLength = this.lineLengthsQueue.remove();\r\n\r\n //Deletes the first line (since the given string is the empty string):\r\n this.textArea.replaceRange(\"\", 0, firstLineLength);\r\n }\r\n }\r\n }\r\n}\r" }, { "identifier": "UserInput", "path": "src/UserInput/UserInput.java", "snippet": "public class UserInput {\r\n //this is true IFF the user is currently allowed to send input:\r\n private volatile boolean isUserInputAllowed;\r\n //The last input from the user (if there wasn't any input yet, it is null):\r\n private String lastUserInput;\r\n\r\n public UserInput() {\r\n this.isUserInputAllowed = false;\r\n this.lastUserInput = null;\r\n }\r\n\r\n /**\r\n * @return the last input from the user.\r\n * If there wasn't any input yet- we return null\r\n */\r\n public String getLastUserInput() {\r\n return this.lastUserInput;\r\n }\r\n\r\n /**\r\n * Updates this object after receiving an input from the user\r\n * @param newInput - The new last input of the user.\r\n * @throws UnsupportedOperationException when a new input was received from the user while this object was not expecting it.\r\n */\r\n public void newInputReceived(String newInput) {\r\n if (this.isUserInputAllowed) {\r\n this.lastUserInput = newInput;\r\n this.isUserInputAllowed = false;\r\n } else {\r\n throw new UnsupportedOperationException(\"התקבל קלט משתמש ללא הכנה מוקדמת לכך\");\r\n }\r\n\r\n }\r\n\r\n /**\r\n * @return true IFF the user can currently send input.\r\n */\r\n public boolean getIsUserInputAllowed() {\r\n return this.isUserInputAllowed;\r\n }\r\n\r\n /**\r\n * Enables to user to send input.\r\n */\r\n public void allowUserInput() {\r\n this.isUserInputAllowed = true;\r\n }\r\n\r\n /**\r\n * Does nothing until a new input is received from the user.\r\n */\r\n public void waitForNewUserInput() {\r\n allowUserInput();\r\n\r\n CountDownLatch latch = new CountDownLatch(1);\r\n UserInputWorker worker = new UserInputWorker(this, latch);\r\n worker.execute();\r\n\r\n try {\r\n latch.await();\r\n } catch (InterruptedException exception) {\r\n exception.printStackTrace();\r\n }\r\n\r\n }\r\n}\r" } ]
import java.io.PrintStream; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import IvritStreams.TextAreaOutputStream; import UserInput.UserInput; import java.awt.BorderLayout; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent;
2,838
/** * The GUI of the console that the Interpreter uses. * We allow printing messages from the program, and receiving input from the user when we need it. */ public class IvritInterpreterGUI { //The fonts used for the GUI: public static final Font TITLE_FONT = new Font("Ariel", Font.PLAIN, 40); public static final Font TEXT_FONT = new Font("Ariel", Font.PLAIN, 20); //The class that handles inputs from the user: private UserInput userInput; /** * Constructor. */ public IvritInterpreterGUI(UserInput userInput) { this.userInput = userInput; initializeFrame(); } /** * @return the console frame after creating and adding to it all the elements needed. */ private void initializeFrame() { JFrame consoleFrame = new JFrame(); consoleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); consoleFrame.add(initializeNorthBorder(), BorderLayout.NORTH); consoleFrame.add(initializeCenterBorder(), BorderLayout.CENTER); consoleFrame.add(initializeSouthBorder(), BorderLayout.SOUTH); consoleFrame.pack(); consoleFrame.setVisible(true); Dimension max = Toolkit.getDefaultToolkit().getScreenSize(); consoleFrame.setMaximumSize(max); consoleFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); } /** * Initializes and returns the north part of the console frame. * @return - the north border of the console frame. */ private Component initializeNorthBorder() { JLabel outputLabel = new JLabel("פלט התכנית:", SwingConstants.RIGHT); outputLabel.setFont(TITLE_FONT); return outputLabel; } /** * Initializes and returns the center part of the console frame. * @return - the center border of the console frame. */ private Component initializeCenterBorder() { JTextArea consoleOutputText = new JTextArea("התחלה\n"); consoleOutputText.setFont(TEXT_FONT); consoleOutputText.setEditable(false); consoleOutputText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
/** * The GUI of the console that the Interpreter uses. * We allow printing messages from the program, and receiving input from the user when we need it. */ public class IvritInterpreterGUI { //The fonts used for the GUI: public static final Font TITLE_FONT = new Font("Ariel", Font.PLAIN, 40); public static final Font TEXT_FONT = new Font("Ariel", Font.PLAIN, 20); //The class that handles inputs from the user: private UserInput userInput; /** * Constructor. */ public IvritInterpreterGUI(UserInput userInput) { this.userInput = userInput; initializeFrame(); } /** * @return the console frame after creating and adding to it all the elements needed. */ private void initializeFrame() { JFrame consoleFrame = new JFrame(); consoleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); consoleFrame.add(initializeNorthBorder(), BorderLayout.NORTH); consoleFrame.add(initializeCenterBorder(), BorderLayout.CENTER); consoleFrame.add(initializeSouthBorder(), BorderLayout.SOUTH); consoleFrame.pack(); consoleFrame.setVisible(true); Dimension max = Toolkit.getDefaultToolkit().getScreenSize(); consoleFrame.setMaximumSize(max); consoleFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); } /** * Initializes and returns the north part of the console frame. * @return - the north border of the console frame. */ private Component initializeNorthBorder() { JLabel outputLabel = new JLabel("פלט התכנית:", SwingConstants.RIGHT); outputLabel.setFont(TITLE_FONT); return outputLabel; } /** * Initializes and returns the center part of the console frame. * @return - the center border of the console frame. */ private Component initializeCenterBorder() { JTextArea consoleOutputText = new JTextArea("התחלה\n"); consoleOutputText.setFont(TEXT_FONT); consoleOutputText.setEditable(false); consoleOutputText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
TextAreaOutputStream consoleOutputStream = new TextAreaOutputStream(consoleOutputText);
0
2023-11-17 09:15:07+00:00
4k
WuKongOpenSource/Wukong_HRM
common/common-file/src/main/java/com/kakarote/common/upload/service/impl/QncFileServiceImpl.java
[ { "identifier": "UploadEntity", "path": "common/common-file/src/main/java/com/kakarote/common/upload/entity/UploadEntity.java", "snippet": "@Data\npublic class UploadEntity {\n\n /**\n * 文件ID\n */\n private String fileId;\n /**\n * 文件名称\n */\n private String name;\n\n /**\n * 文件大小\n */\n private Long size;\n\n /**\n * 上传后的相对路径\n */\n private String path;\n\n /**\n * 公网直接可访问的url\n */\n private String url;\n\n public UploadEntity() {\n\n }\n\n public UploadEntity(String path) {\n this.path = path;\n }\n\n}" }, { "identifier": "UploadProperties", "path": "common/common-file/src/main/java/com/kakarote/common/upload/entity/UploadProperties.java", "snippet": "@Data\n@ConfigurationProperties(prefix = \"wukong.common.upload\")\npublic class UploadProperties {\n\n /**\n * 上传类型\n */\n private UploadType type;\n\n /**\n * 端点\n */\n private String endpoint;\n\n /**\n * 默认的域名\n */\n private String domain;\n\n /**\n * 桶名称\n */\n private String bucketName;\n\n /**\n * 区域\n */\n private String region;\n\n /**\n * 账号\n */\n private String accessKeyId;\n\n /**\n * 密码\n */\n private String accessKeySecret;\n\n /**\n * 额外数据\n */\n private Map<String, Object> extra;\n\n public Map<String, Object> getExtra() {\n if (extra == null) {\n return Collections.emptyMap();\n }\n return extra;\n }\n}" }, { "identifier": "UploadType", "path": "common/common-file/src/main/java/com/kakarote/common/upload/entity/UploadType.java", "snippet": "public enum UploadType {\n /**\n * 亚马逊\n */\n aws_s3(),\n\n /**\n * ftp\n */\n ftp(),\n\n /**\n * 本地\n */\n local(),\n\n /**\n * 阿里云OSS\n */\n oss(),\n\n /**\n * 七牛云\n */\n qnc(),\n\n /**\n * 腾讯云\n */\n cos();\n\n UploadType() {\n }\n\n}" }, { "identifier": "FileService", "path": "common/common-file/src/main/java/com/kakarote/common/upload/service/FileService.java", "snippet": "public interface FileService {\n\n /**\n * 文件ID和文件名的连接符\n */\n String JOIN_STR = \"-\";\n\n /**\n * 文件分隔符\n */\n String SLASH = \"/\";\n\n /**\n * 上传文件\n *\n * @param inputStream 文件流\n * @param entity 参数对象\n * @return result\n */\n public UploadEntity uploadFile(InputStream inputStream, UploadEntity entity);\n\n /**\n * 上传文件\n *\n * @param inputStream 文件流\n * @param entity 参数对象\n * @param bucketName 桶名称\n * @return result\n */\n public UploadEntity uploadFile(InputStream inputStream, UploadEntity entity, String bucketName);\n\n /**\n * 上传临时文件,和正式上传不同的是,此文件7天后会被删除\n *\n * @param inputStream 文件流\n * @param entity 参数对象\n * @return result\n */\n public UploadEntity uploadTempFile(InputStream inputStream, UploadEntity entity);\n\n /**\n * 上传临时文件,和正式上传不同的是,此文件7天后会被删除\n *\n * @param inputStream 文件流\n * @param entity 参数对象\n * @param bucketName 桶名称\n * @return result\n */\n public UploadEntity uploadTempFile(InputStream inputStream, UploadEntity entity, String bucketName);\n\n /**\n * 删除文件\n *\n * @param key 上传接口返回的path\n */\n public void deleteFile(String key);\n\n /**\n * 删除文件\n *\n * @param key 上传接口返回的path\n * @param bucketName 桶名称\n */\n public void deleteFile(String key, String bucketName);\n\n /**\n * 批量删除文件\n *\n * @param keys key列表\n */\n public void deleteFileBatch(List<String> keys);\n\n\n /**\n * 批量删除文件\n *\n * @param keys key列表\n * @param bucketName 桶名称\n */\n public void deleteFileBatch(List<String> keys, String bucketName);\n\n\n /**\n * 重命名文件\n *\n * @param entity 参数对象\n * @param fileName 文件名称\n */\n public void renameFile(UploadEntity entity, String fileName);\n\n /**\n * 重命名文件\n *\n * @param entity 参数对象\n * @param fileName 文件名称\n * @param bucketName 桶名称\n */\n public void renameFile(UploadEntity entity, String fileName, String bucketName);\n\n /**\n * 获取文件\n *\n * @param entity 参数对象\n * @return 文件流,可能为空\n */\n public InputStream downFile(UploadEntity entity);\n\n /**\n * 获取文件\n *\n * @param entity 参数对象\n * @return 文件流,可能为空\n * @param bucketName 桶名称\n */\n public InputStream downFile(UploadEntity entity,String bucketName);\n /**\n * 获取文件上传类型\n *\n * @return type\n */\n UploadType getType();\n\n /**\n * 生成service\n *\n * @param properties 参数\n * @return fileService\n */\n FileService build(UploadProperties properties);\n\n /**\n * 生成默认的文件名\n * 文件名默认为 fileId-fileName\n *\n * @param fileId 文件ID\n * @param fileName 文件名\n * @return 格式后的文件名\n */\n default String buildFileName(String fileId, String fileName) {\n if (fileId == null || fileName == null) {\n throw new IllegalArgumentException(\"fileId or fileName is null\");\n }\n return getDateStr() + SLASH + fileId + JOIN_STR + fileName;\n }\n\n /**\n * 获取日期类型的字符串,上传文件默认按照日期存放\n *\n * @return data\n */\n default String getDateStr() {\n return DateTimeFormatter.ofPattern(\"yyyyMMdd\").format(LocalDate.now());\n }\n\n /**\n * 获取配置信息\n *\n * @return properties\n */\n UploadProperties getProperties();\n}" } ]
import com.kakarote.common.upload.entity.UploadEntity; import com.kakarote.common.upload.entity.UploadProperties; import com.kakarote.common.upload.entity.UploadType; import com.kakarote.common.upload.service.FileService; import com.qiniu.common.QiniuException; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.DownloadUrl; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.InputStream; import java.util.List; import java.util.Objects;
2,029
package com.kakarote.common.upload.service.impl; /** * @author zhangzhiwei * 七牛上传文件 */ public class QncFileServiceImpl implements FileService { private Auth clint; private UploadProperties properties; /** * 上传文件 * * @param inputStream 文件流 * @param entity 参数对象 * @return result */ @Override
package com.kakarote.common.upload.service.impl; /** * @author zhangzhiwei * 七牛上传文件 */ public class QncFileServiceImpl implements FileService { private Auth clint; private UploadProperties properties; /** * 上传文件 * * @param inputStream 文件流 * @param entity 参数对象 * @return result */ @Override
public UploadEntity uploadFile(InputStream inputStream, UploadEntity entity) {
0
2023-10-17 05:49:52+00:00
4k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/actions/complete/CodeGenEscAction.java
[ { "identifier": "CodeGenHintRenderer", "path": "src/main/java/com/codeshell/intellij/utils/CodeGenHintRenderer.java", "snippet": "public class CodeGenHintRenderer implements EditorCustomElementRenderer {\n private final String myText;\n private Font myFont;\n\n public CodeGenHintRenderer(String text, Font font) {\n myText = text;\n myFont = font;\n }\n\n public CodeGenHintRenderer(String text) {\n myText = text;\n }\n\n @Override\n public int calcWidthInPixels(@NotNull Inlay inlay) {\n Editor editor = inlay.getEditor();\n Font font = editor.getColorsScheme().getFont(EditorFontType.PLAIN);\n myFont = new Font(font.getName(), Font.ITALIC, font.getSize());\n return editor.getContentComponent().getFontMetrics(font).stringWidth(myText);\n }\n\n @Override\n public void paint(@NotNull Inlay inlay, @NotNull Graphics g, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {\n g.setColor(JBColor.GRAY);\n g.setFont(myFont);\n g.drawString(myText, targetRegion.x, targetRegion.y + targetRegion.height - (int) Math.ceil((double) g.getFontMetrics().getFont().getSize() / 2) + 1);\n }\n\n}" }, { "identifier": "CodeShellWidget", "path": "src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java", "snippet": "public class CodeShellWidget extends EditorBasedWidget\n implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation,\n CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener {\n public static final String ID = \"CodeShellWidget\";\n\n public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>(\"CodeShell Code Suggestion\");\n public static final Key<Integer> SHELL_CODER_POSITION = new Key<>(\"CodeShell Position\");\n public static boolean enableSuggestion = false;\n protected CodeShellWidget(@NotNull Project project) {\n super(project);\n }\n\n @Override\n public @NonNls @NotNull String ID() {\n return ID;\n }\n\n @Override\n public StatusBarWidget copy() {\n return new CodeShellWidget(getProject());\n }\n\n @Override\n public @Nullable Icon getIcon() {\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus());\n if (status == CodeShellStatus.OK) {\n return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled;\n } else {\n return CodeShellIcons.WidgetError;\n }\n }\n\n @Override\n public WidgetPresentation getPresentation() {\n return this;\n }\n\n @Override\n public @Nullable @NlsContexts.Tooltip String getTooltipText() {\n StringBuilder toolTipText = new StringBuilder(\"CodeShell\");\n if (CodeShellSettings.getInstance().isSaytEnabled()) {\n toolTipText.append(\" enabled\");\n } else {\n toolTipText.append(\" disabled\");\n }\n\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n int statusCode = codeShell.getStatus();\n CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode);\n switch (status) {\n case OK:\n if (CodeShellSettings.getInstance().isSaytEnabled()) {\n toolTipText.append(\" (Click to disable)\");\n } else {\n toolTipText.append(\" (Click to enable)\");\n }\n break;\n case UNKNOWN:\n toolTipText.append(\" (http error \");\n toolTipText.append(statusCode);\n toolTipText.append(\")\");\n break;\n default:\n toolTipText.append(\" (\");\n toolTipText.append(status.getDisplayValue());\n toolTipText.append(\")\");\n }\n\n return toolTipText.toString();\n }\n\n @Override\n public @Nullable Consumer<MouseEvent> getClickConsumer() {\n return mouseEvent -> {\n CodeShellSettings.getInstance().toggleSaytEnabled();\n if (Objects.nonNull(myStatusBar)) {\n myStatusBar.updateWidget(ID);\n }\n };\n }\n\n @Override\n public void install(@NotNull StatusBar statusBar) {\n super.install(statusBar);\n EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster();\n multicaster.addCaretListener(this, this);\n multicaster.addSelectionListener(this, this);\n multicaster.addDocumentListener(this, this);\n KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(\"focusOwner\", this);\n Disposer.register(this,\n () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener(\"focusOwner\",\n this)\n );\n }\n\n private Editor getFocusOwnerEditor() {\n Component component = getFocusOwnerComponent();\n Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor();\n return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null;\n }\n\n private Component getFocusOwnerComponent() {\n Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();\n if (Objects.isNull(focusOwner)) {\n IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject());\n Window frame = focusManager.getLastFocusedIdeWindow();\n if (Objects.nonNull(frame)) {\n focusOwner = focusManager.getLastFocusedFor(frame);\n }\n }\n return focusOwner;\n }\n\n private boolean isFocusedEditor(Editor editor) {\n Component focusOwner = getFocusOwnerComponent();\n return focusOwner == editor.getContentComponent();\n }\n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n updateInlayHints(getFocusOwnerEditor());\n }\n\n @Override\n public void selectionChanged(SelectionEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretPositionChanged(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretAdded(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void caretRemoved(@NotNull CaretEvent event) {\n updateInlayHints(event.getEditor());\n }\n\n @Override\n public void afterDocumentChange(@NotNull Document document) {\n enableSuggestion = true;\n if (ApplicationManager.getApplication().isDispatchThread()) {\n EditorFactory.getInstance().editors(document)\n .filter(this::isFocusedEditor)\n .findFirst()\n .ifPresent(this::updateInlayHints);\n }\n }\n\n private void updateInlayHints(Editor focusedEditor) {\n if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) {\n return;\n }\n VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument());\n if (Objects.isNull(file)) {\n return;\n }\n\n String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText();\n if (Objects.nonNull(selection) && !selection.isEmpty()) {\n String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);\n if (Objects.nonNull(existingHints) && existingHints.length > 0) {\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);\n file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset());\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n }\n return;\n }\n\n Integer codeShellPos = file.getUserData(SHELL_CODER_POSITION);\n int lastPosition = (Objects.isNull(codeShellPos)) ? 0 : codeShellPos;\n int currentPosition = focusedEditor.getCaretModel().getOffset();\n\n if (lastPosition == currentPosition) return;\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n if (currentPosition > lastPosition) {\n String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);\n if (Objects.nonNull(existingHints) && existingHints.length > 0) {\n String inlineHint = existingHints[0];\n String modifiedText = focusedEditor.getDocument().getCharsSequence().subSequence(lastPosition, currentPosition).toString();\n if (modifiedText.startsWith(\"\\n\")) {\n modifiedText = modifiedText.replace(\" \", \"\");\n }\n if (inlineHint.startsWith(modifiedText)) {\n inlineHint = inlineHint.substring(modifiedText.length());\n enableSuggestion = false;\n if (inlineHint.length() > 0) {\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.addInlineElement(currentPosition, true, new CodeGenHintRenderer(inlineHint));\n existingHints[0] = inlineHint;\n\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, existingHints);\n file.putUserData(SHELL_CODER_POSITION, currentPosition);\n return;\n } else if (existingHints.length > 1) {\n existingHints = Arrays.copyOfRange(existingHints, 1, existingHints.length);\n CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, existingHints);\n return;\n } else {\n file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);\n }\n }\n }\n }\n\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n\n file.putUserData(SHELL_CODER_POSITION, currentPosition);\n if(!enableSuggestion || currentPosition < lastPosition){\n enableSuggestion = false;\n return;\n }\n CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);\n CharSequence editorContents = focusedEditor.getDocument().getCharsSequence();\n CompletableFuture<String[]> future = CompletableFuture.supplyAsync(() -> codeShell.getCodeCompletionHints(editorContents, currentPosition));\n future.thenAccept(hintList -> CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, hintList));\n }\n\n}" } ]
import com.codeshell.intellij.utils.CodeGenHintRenderer; import com.codeshell.intellij.widget.CodeShellWidget; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.Inlay; import com.intellij.openapi.editor.InlayModel; import com.intellij.openapi.editor.actionSystem.EditorActionHandler; import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects;
2,824
package com.codeshell.intellij.actions.complete; public class CodeGenEscAction extends EditorWriteActionHandler { protected final EditorActionHandler handler; public CodeGenEscAction(EditorActionHandler actionHandler) { handler = actionHandler; } @Override public void executeWriteAction(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) { cancelCodeCompletion(editor, caret, dataContext); } private void cancelCodeCompletion(Editor editor, Caret caret, DataContext dataContext) { VirtualFile file = dataContext.getData(CommonDataKeys.VIRTUAL_FILE); if (Objects.isNull(file)) { return; } InlayModel inlayModel = editor.getInlayModel(); inlayModel.getInlineElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints); inlayModel.getBlockElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints);
package com.codeshell.intellij.actions.complete; public class CodeGenEscAction extends EditorWriteActionHandler { protected final EditorActionHandler handler; public CodeGenEscAction(EditorActionHandler actionHandler) { handler = actionHandler; } @Override public void executeWriteAction(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) { cancelCodeCompletion(editor, caret, dataContext); } private void cancelCodeCompletion(Editor editor, Caret caret, DataContext dataContext) { VirtualFile file = dataContext.getData(CommonDataKeys.VIRTUAL_FILE); if (Objects.isNull(file)) { return; } InlayModel inlayModel = editor.getInlayModel(); inlayModel.getInlineElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints); inlayModel.getBlockElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints);
CodeShellWidget.enableSuggestion = false;
1
2023-10-18 06:29:13+00:00
4k
djkcyl/Shamrock
qqinterface/src/main/java/msf/msgsvc/msgtransmit/msg_transmit.java
[ { "identifier": "ByteStringMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java", "snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr, int i2, int i3) {\n return null;\n }\n\n public static ByteStringMicro copyFromUtf8(String str) {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public int size() {\n return 0;\n }\n\n public byte[] toByteArray() {\n return null;\n }\n\n public String toString(String str) {\n return \"\";\n }\n\n public String toStringUtf8() {\n return \"\";\n }\n}" }, { "identifier": "MessageMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/MessageMicro.java", "snippet": "public class MessageMicro<T extends MessageMicro<T>> {\n public final T mergeFrom(byte[] bArr) {\n return null;\n }\n\n public final byte[] toByteArray() {\n return null;\n }\n\n public T get() {\n return null;\n }\n\n public void set(T t) {\n }\n}" }, { "identifier": "PBBytesField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBytesField.java", "snippet": "public class PBBytesField extends PBPrimitiveField<ByteStringMicro> {\n public static PBField<ByteStringMicro> __repeatHelper__;\n\n public PBBytesField(ByteStringMicro byteStringMicro, boolean z) {\n }\n\n public ByteStringMicro get() {\n return null;\n }\n\n public void set(ByteStringMicro byteStringMicro) {\n }\n}" }, { "identifier": "PBField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBField.java", "snippet": "public abstract class PBField<T> {\n public static <T extends MessageMicro<T>> PBRepeatMessageField<T> initRepeatMessage(Class<T> cls) {\n return new PBRepeatMessageField<>(cls);\n }\n\n public static <T> PBRepeatField<T> initRepeat(PBField<T> pBField) {\n return new PBRepeatField<>(pBField);\n }\n\n public static PBUInt32Field initUInt32(int i2) {\n return new PBUInt32Field(i2, false);\n }\n\n public static PBStringField initString(String str) {\n return new PBStringField(str, false);\n }\n\n public static PBBytesField initBytes(ByteStringMicro byteStringMicro) {\n return new PBBytesField(byteStringMicro, false);\n }\n\n public static PBBoolField initBool(boolean z) {\n return new PBBoolField(z, false);\n }\n\n public static PBInt32Field initInt32(int i2) {\n return new PBInt32Field(i2, false);\n }\n\n public static PBUInt64Field initUInt64(long j2) {\n return new PBUInt64Field(j2, false);\n }\n\n public static PBInt64Field initInt64(long j2) {\n return new PBInt64Field(j2, false);\n }\n\n public static PBEnumField initEnum(int i2) {\n return new PBEnumField(i2, false);\n }\n}" }, { "identifier": "PBRepeatMessageField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBRepeatMessageField.java", "snippet": "public final class PBRepeatMessageField<T extends MessageMicro<T>> extends PBField<List<T>> {\n public PBRepeatMessageField(Class<T> cls) {\n\n }\n\n public void add(T t) {\n\n }\n\n public T get(int pos) {\n return null;\n }\n\n public List<T> get() {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public void set(int i2, T t) {\n }\n\n public void set(List<T> list) {\n }\n\n public int size() {\n return 0;\n }\n\n\n}" }, { "identifier": "PBStringField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBStringField.java", "snippet": "public class PBStringField extends PBPrimitiveField<String>{\n public PBStringField(String str, boolean z) {\n }\n\n public void set(String str, boolean z) {\n }\n\n public void set(String str) {\n }\n\n public String get() {\n return \"\";\n }\n}" }, { "identifier": "msg_comm", "path": "qqinterface/src/main/java/msf/msgcomm/msg_comm.java", "snippet": "public class msg_comm {\n public static class Msg extends MessageMicro<Msg> {\n public MsgHead msg_head = new MsgHead();\n public ContentHead content_head = new ContentHead();\n public im_msg_body.MsgBody msg_body = new im_msg_body.MsgBody();\n //public msg_comm$AppShareInfo appshare_info = new msg_comm$AppShareInfo();\n }\n\n public static class ContentHead extends MessageMicro<ContentHead> {\n public final PBUInt32Field pkg_num = PBField.initUInt32(0);\n public final PBUInt32Field pkg_index = PBField.initUInt32(0);\n public final PBUInt32Field div_seq = PBField.initUInt32(0);\n public final PBUInt32Field auto_reply = PBField.initUInt32(0);\n }\n\n public static class MutilTransHead extends MessageMicro<MutilTransHead> {\n public final PBUInt32Field status = PBField.initUInt32(0);\n public final PBUInt32Field msgId = PBField.initUInt32(0);\n public final PBUInt32Field friend_flag = PBField.initUInt32(0);\n public final PBStringField from_anno_id = PBField.initString(\"\");\n public final PBStringField from_face_url = PBField.initString(\"\");\n }\n\n\n public static class MsgHead extends MessageMicro<MsgHead> {\n public final PBUInt64Field from_uin = PBField.initUInt64(0);\n public final PBUInt64Field to_uin = PBField.initUInt64(0);\n public final PBUInt32Field msg_type = PBField.initUInt32(0);\n public final PBUInt32Field c2c_cmd = PBField.initUInt32(0);\n public final PBUInt32Field msg_seq = PBField.initUInt32(0);\n public final PBUInt32Field msg_time = PBField.initUInt32(0);\n public final PBUInt64Field msg_uid = PBField.initUInt64(0);\n //public msg_comm$C2CTmpMsgHead c2c_tmp_msg_head = new msg_comm$C2CTmpMsgHead();\n public GroupInfo group_info = new GroupInfo();\n public final PBUInt32Field from_appid = PBField.initUInt32(0);\n public final PBUInt32Field from_instid = PBField.initUInt32(0);\n public final PBUInt32Field user_active = PBField.initUInt32(0);\n //public msg_comm$DiscussInfo discuss_info = new msg_comm$DiscussInfo();\n public final PBStringField from_nick = PBField.initString(\"\");\n public final PBUInt64Field auth_uin = PBField.initUInt64(0);\n public final PBStringField auth_nick = PBField.initString(\"\");\n public final PBUInt32Field msg_flag = PBField.initUInt32(0);\n public final PBStringField auth_remark = PBField.initString(\"\");\n public final PBStringField group_name = PBField.initString(\"\");\n public MutilTransHead mutiltrans_head = new MutilTransHead();\n //public im_msg_head$InstCtrl msg_inst_ctrl = new im_msg_head$InstCtrl();\n public final PBUInt32Field public_account_group_send_flag = PBField.initUInt32(0);\n public final PBUInt32Field wseq_in_c2c_msghead = PBField.initUInt32(0);\n public final PBUInt64Field cpid = PBField.initUInt64(0);\n //public msg_comm$ExtGroupKeyInfo ext_group_key_info = new msg_comm$ExtGroupKeyInfo();\n public final PBStringField multi_compatible_text = PBField.initString(\"\");\n public final PBUInt32Field auth_sex = PBField.initUInt32(0);\n public final PBBoolField is_src_msg = PBField.initBool(false);\n }\n\n public static class GroupInfo extends MessageMicro<GroupInfo> {\n public final PBBytesField group_card;\n public final PBUInt32Field group_card_type;\n public final PBUInt32Field group_level;\n public final PBBytesField group_name;\n public final PBBytesField group_rank;\n public final PBUInt64Field group_code = PBField.initUInt64(0);\n public final PBUInt32Field group_type = PBField.initUInt32(0);\n public final PBUInt64Field group_info_seq = PBField.initUInt64(0);\n\n public GroupInfo() {\n ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY;\n this.group_card = PBField.initBytes(byteStringMicro);\n this.group_rank = PBField.initBytes(byteStringMicro);\n this.group_level = PBField.initUInt32(0);\n this.group_card_type = PBField.initUInt32(0);\n this.group_name = PBField.initBytes(byteStringMicro);\n }\n }\n}" } ]
import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBRepeatMessageField; import com.tencent.mobileqq.pb.PBStringField; import msf.msgcomm.msg_comm;
2,463
package msf.msgsvc.msgtransmit; public class msg_transmit { public static class PbMultiMsgTransmit extends MessageMicro<PbMultiMsgTransmit> { public final PBRepeatMessageField<msg_comm.Msg> msg = PBField.initRepeatMessage(msg_comm.Msg.class); public final PBRepeatMessageField<msg_transmit.PbMultiMsgItem> pbItemList = PBField.initRepeatMessage(msg_transmit.PbMultiMsgItem.class); } public static class PbMultiMsgItem extends MessageMicro<PbMultiMsgItem> { public final PBStringField fileName = PBField.initString("");
package msf.msgsvc.msgtransmit; public class msg_transmit { public static class PbMultiMsgTransmit extends MessageMicro<PbMultiMsgTransmit> { public final PBRepeatMessageField<msg_comm.Msg> msg = PBField.initRepeatMessage(msg_comm.Msg.class); public final PBRepeatMessageField<msg_transmit.PbMultiMsgItem> pbItemList = PBField.initRepeatMessage(msg_transmit.PbMultiMsgItem.class); } public static class PbMultiMsgItem extends MessageMicro<PbMultiMsgItem> { public final PBStringField fileName = PBField.initString("");
public final PBBytesField buffer = PBField.initBytes(ByteStringMicro.EMPTY);
0
2023-10-20 10:43:47+00:00
4k
ballerina-platform/module-ballerinax-copybook
native/src/main/java/io/ballerina/lib/copybook/runtime/convertor/Utils.java
[ { "identifier": "Copybook", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/Copybook.java", "snippet": "public class Copybook {\n\n private Copybook() {\n }\n\n public static Schema parse(String schemaPath) throws IOException {\n CopybookLexer lexer = new CopybookLexer(CharStreams.fromStream(new FileInputStream(schemaPath)));\n CommonTokenStream tokens = new CommonTokenStream(lexer);\n CopybookParser parser = new CopybookParser(tokens);\n\n parser.removeErrorListeners();\n CopybookErrorListener errorListener = new CopybookErrorListener();\n parser.addErrorListener(errorListener);\n\n CopybookParser.StartRuleContext startRule = parser.startRule();\n SchemaBuilder visitor = new SchemaBuilder();\n try {\n startRule.accept(visitor);\n } catch (Exception e) {\n // Intentionally kept empty, already handled by the error listener.\n }\n Schema schema = visitor.getSchema();\n schema.addErrors(errorListener.getErrors());\n return schema;\n }\n}" }, { "identifier": "CopybookNode", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/CopybookNode.java", "snippet": "public interface CopybookNode {\n int getLevel();\n String getName();\n int getOccurringCount();\n String getRedefinedItemName();\n}" }, { "identifier": "DataItem", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/DataItem.java", "snippet": "public class DataItem implements CopybookNode {\n private final int level;\n private final String name;\n private final String picture;\n private final boolean isNumeric;\n private final int occurs;\n private final int readLength;\n private final boolean isSinged;\n private final int floatingPointLength;\n private final String redefinedItemName;\n\n public DataItem(int level, String name, String picture, boolean isNumeric, int readLength, int occurs,\n int floatingPointLength, String redefinedItemName, GroupItem parent) {\n this.level = level;\n this.name = name;\n this.picture = picture;\n this.isNumeric = isNumeric;\n this.readLength = readLength;\n this.occurs = occurs;\n this.isSinged = Utils.isSigned(picture);\n this.floatingPointLength = floatingPointLength;\n this.redefinedItemName = redefinedItemName;\n if (parent != null) {\n parent.addChild(this);\n }\n }\n\n @Override\n public int getLevel() {\n return this.level;\n }\n\n public String getName() {\n return this.name;\n }\n\n public String getPicture() {\n return this.picture;\n }\n\n public boolean isNumeric() {\n return this.isNumeric;\n }\n\n public int getOccurringCount() {\n return this.occurs;\n }\n\n public int getReadLength() {\n return this.readLength;\n }\n\n public boolean isSinged() {\n return this.isSinged;\n }\n\n public int getFloatingPointLength() {\n return this.floatingPointLength;\n }\n\n public String getRedefinedItemName() {\n return redefinedItemName;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(\"\\\"level\\\":\").append(this.level).append(\", \\\"name\\\":\\\"\").append(this.name).append(\"\\\"\")\n .append(\", \\\"picture\\\":\\\"\").append(this.picture).append(\"\\\"\").append(\", \\\"readLength\\\":\")\n .append(this.readLength).append(\", \\\"numeric\\\":\").append(this.isNumeric);\n\n if (this.occurs > -1) {\n sb.append(\", \\\"occurs\\\":\").append(this.occurs);\n }\n if (this.isNumeric) {\n sb.append(\", \\\"isSigned\\\":\").append(this.isSinged);\n }\n if (this.floatingPointLength > 0) {\n sb.append(\", \\\"floatingPointLength\\\":\").append(this.floatingPointLength);\n }\n if (this.redefinedItemName != null) {\n sb.append(\", \\\"redefinedItemName\\\": \\\"\").append(this.redefinedItemName).append(\"\\\"\");\n }\n sb.append(\"}\");\n return sb.toString();\n }\n}" }, { "identifier": "GroupItem", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/GroupItem.java", "snippet": "public class GroupItem implements CopybookNode {\n private final int level;\n private final String name;\n private final int occurs;\n private final GroupItem parent;\n public List<CopybookNode> children;\n private final String redefinedItemName;\n\n public GroupItem(int level, String name, int occurs, String redefinedItemName,\n GroupItem parent) {\n this.level = level;\n this.name = name;\n this.occurs = occurs;\n this.parent = parent;\n this.children = new CopybookNodeList();\n this.redefinedItemName = redefinedItemName;\n if (parent != null) {\n this.parent.addChild(this);\n }\n }\n\n public void addChild(CopybookNode copybookNode) {\n this.children.add(copybookNode);\n }\n\n @Override\n public int getLevel() {\n return this.level;\n }\n\n public String getName() {\n return this.name;\n }\n\n public int getOccurringCount() {\n return this.occurs;\n }\n\n public GroupItem getParent() {\n return this.parent;\n }\n\n public List<CopybookNode> getChildren() {\n return this.children;\n }\n\n public String getRedefinedItemName() {\n return redefinedItemName;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(\"\\\"level\\\":\").append(this.level).append(\", \\\"name\\\":\\\"\").append(this.name).append(\"\\\"\")\n .append(\", \\\"children\\\":\").append(this.children);\n if (this.occurs > -1) {\n sb.append(\", \\\"occurs\\\":\").append(this.occurs);\n }\n if (this.redefinedItemName != null) {\n sb.append(\", \\\"redefinedItemName\\\": \\\"\").append(this.redefinedItemName).append(\"\\\"\");\n }\n sb.append(\"}\");\n return sb.toString();\n }\n}" }, { "identifier": "Schema", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/Schema.java", "snippet": "public class Schema {\n private final List<CopybookNode> typeDefinitions = new CopybookNodeList();\n private final Map<String, CopybookNode> redefinedItems = new HashMap<>();\n private final List<String> errors = new ArrayList<>();\n\n void addTypeDefinition(CopybookNode copybookNode) {\n this.typeDefinitions.add(copybookNode);\n }\n\n void addRedefinedItem(CopybookNode copybookNode) {\n this.redefinedItems.put(copybookNode.getName(), copybookNode);\n }\n\n public List<CopybookNode> getTypeDefinitions() {\n return typeDefinitions;\n }\n\n public Map<String, CopybookNode> getRedefinedItems() {\n return redefinedItems;\n }\n\n @Override\n public String toString() {\n return \"{\" + \"\\\"schema\\\"\" + \":\" + typeDefinitions + \"}\";\n }\n\n void addErrors(List<String> errors) {\n this.errors.addAll(errors);\n }\n\n public List<String> getErrors() {\n return errors;\n }\n}" }, { "identifier": "getModule", "path": "native/src/main/java/io/ballerina/lib/copybook/runtime/convertor/ModuleUtils.java", "snippet": "public static Module getModule() {\n return copybookModule;\n}" } ]
import io.ballerina.lib.copybook.commons.schema.Copybook; import io.ballerina.lib.copybook.commons.schema.CopybookNode; import io.ballerina.lib.copybook.commons.schema.DataItem; import io.ballerina.lib.copybook.commons.schema.GroupItem; import io.ballerina.lib.copybook.commons.schema.Schema; import io.ballerina.runtime.api.Environment; import io.ballerina.runtime.api.Future; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.creators.ErrorCreator; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.ObjectType; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BObject; import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BTypedesc; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static io.ballerina.lib.copybook.runtime.converter.ModuleUtils.getModule;
2,336
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.runtime.converter; public final class Utils { private static final String NATIVE_VALUE = "native-value"; private static final String TO_RECORD_METHOD_NAME = "toRecord"; private static final String NODE_TYPE_NAME = "Node"; private static final String SCHEMA_TYPE_NAME = "Schema"; private static final String GROUP_ITEM_TYPE_NAME = "GroupItem";
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.runtime.converter; public final class Utils { private static final String NATIVE_VALUE = "native-value"; private static final String TO_RECORD_METHOD_NAME = "toRecord"; private static final String NODE_TYPE_NAME = "Node"; private static final String SCHEMA_TYPE_NAME = "Schema"; private static final String GROUP_ITEM_TYPE_NAME = "GroupItem";
private static final String DATA_ITEM_TYPE_NAME = "DataItem";
2
2023-10-24 04:51:53+00:00
4k
ballerina-platform/copybook-tools
copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/CodeGeneratorUtils.java
[ { "identifier": "generateIntConstraint", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/AnnotationGenerator.java", "snippet": "public static AnnotationNode generateIntConstraint(DataItem node) {\n List<String> fields = getIntAnnotFields(node);\n if (fields.isEmpty()) {\n return null;\n }\n String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) +\n GeneratorConstants.CLOSE_BRACE;\n return createAnnotationNode(GeneratorConstants.CONSTRAINT_INT, annotBody);\n}" }, { "identifier": "generateNumberConstraint", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/AnnotationGenerator.java", "snippet": "public static AnnotationNode generateNumberConstraint(DataItem node) {\n List<String> fields = getNumberAnnotFields(node);\n if (fields.isEmpty()) {\n return null;\n }\n String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) +\n GeneratorConstants.CLOSE_BRACE;\n return createAnnotationNode(GeneratorConstants.CONSTRAINT_NUMBER, annotBody);\n}" }, { "identifier": "generateStringConstraint", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/AnnotationGenerator.java", "snippet": "public static AnnotationNode generateStringConstraint(DataItem node) {\n List<String> fields = getStringAnnotFields(node);\n if (fields.isEmpty()) {\n return null;\n }\n String annotBody = GeneratorConstants.OPEN_BRACE + String.join(GeneratorConstants.COMMA, fields) +\n GeneratorConstants.CLOSE_BRACE;\n return createAnnotationNode(GeneratorConstants.CONSTRAINT_STRING, annotBody);\n}" }, { "identifier": "ALPHA_NUMERIC_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String ALPHA_NUMERIC_TYPE = \"AlphaNumeric\";" }, { "identifier": "ARRAY_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String ARRAY_TYPE = \"Array\";" }, { "identifier": "BAL_EXTENSION", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String BAL_EXTENSION = \".bal\";" }, { "identifier": "BAL_KEYWORDS", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final List<String> BAL_KEYWORDS = SyntaxInfo.keywords();" }, { "identifier": "BYTE_ARRAY", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String BYTE_ARRAY = \"byte[]\";" }, { "identifier": "COMP_PIC", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String COMP_PIC = \"COMP\";" }, { "identifier": "DECIMAL", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String DECIMAL = \"decimal\";" }, { "identifier": "DECIMAL_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String DECIMAL_TYPE = \"Decimal\";" }, { "identifier": "ESCAPE_PATTERN", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String ESCAPE_PATTERN = \"([\\\\[\\\\]\\\\\\\\?!<>@#&~`*\\\\-=^+();:\\\\/\\\\_{}\\\\s|.$])\";" }, { "identifier": "DECIMAL_POINT", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String DECIMAL_POINT = \"V\";" }, { "identifier": "IMPORT", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String IMPORT = \"import\";" }, { "identifier": "INT", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String INT = \"int\";" }, { "identifier": "INTEGER_IN_BINARY_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String INTEGER_IN_BINARY_TYPE = \"IntegerInBinary\";" }, { "identifier": "UNSIGNED_INTEGER_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String UNSIGNED_INTEGER_TYPE = \"UnsignedInteger\";" }, { "identifier": "NEGATIVE_DECIMAL_PIC", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String NEGATIVE_DECIMAL_PIC = \"-9\";" }, { "identifier": "POSITIVE_DECIMAL_PIC", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String POSITIVE_DECIMAL_PIC = \"+9\";" }, { "identifier": "SEMICOLON", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String SEMICOLON = \";\";" }, { "identifier": "SIGNED_DECIMAL_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String SIGNED_DECIMAL_TYPE = \"SignedDecimal\";" }, { "identifier": "SIGNED_INTEGER_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String SIGNED_INTEGER_TYPE = \"SignedInteger\";" }, { "identifier": "SLASH", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String SLASH = \"/\";" }, { "identifier": "STRING", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String STRING = \"string\";" }, { "identifier": "UNSIGNED_DECIMAL_TYPE", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String UNSIGNED_DECIMAL_TYPE = \"UnsignedDecimal\";" } ]
import io.ballerina.compiler.syntax.tree.AbstractNodeFactory; import io.ballerina.compiler.syntax.tree.AnnotationNode; import io.ballerina.compiler.syntax.tree.IdentifierToken; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; import io.ballerina.compiler.syntax.tree.ImportOrgNameNode; import io.ballerina.compiler.syntax.tree.Minutiae; import io.ballerina.compiler.syntax.tree.MinutiaeList; import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.NodeList; import io.ballerina.compiler.syntax.tree.SeparatedNodeList; import io.ballerina.compiler.syntax.tree.Token; import io.ballerina.lib.copybook.commons.schema.CopybookNode; import io.ballerina.lib.copybook.commons.schema.DataItem; import io.ballerina.lib.copybook.commons.schema.GroupItem; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static io.ballerina.tools.copybook.generator.AnnotationGenerator.generateIntConstraint; import static io.ballerina.tools.copybook.generator.AnnotationGenerator.generateNumberConstraint; import static io.ballerina.tools.copybook.generator.AnnotationGenerator.generateStringConstraint; import static io.ballerina.tools.copybook.generator.GeneratorConstants.ALPHA_NUMERIC_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.ARRAY_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.BAL_EXTENSION; import static io.ballerina.tools.copybook.generator.GeneratorConstants.BAL_KEYWORDS; import static io.ballerina.tools.copybook.generator.GeneratorConstants.BYTE_ARRAY; import static io.ballerina.tools.copybook.generator.GeneratorConstants.COMP_PIC; import static io.ballerina.tools.copybook.generator.GeneratorConstants.DECIMAL; import static io.ballerina.tools.copybook.generator.GeneratorConstants.DECIMAL_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.ESCAPE_PATTERN; import static io.ballerina.tools.copybook.generator.GeneratorConstants.DECIMAL_POINT; import static io.ballerina.tools.copybook.generator.GeneratorConstants.IMPORT; import static io.ballerina.tools.copybook.generator.GeneratorConstants.INT; import static io.ballerina.tools.copybook.generator.GeneratorConstants.INTEGER_IN_BINARY_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.UNSIGNED_INTEGER_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.NEGATIVE_DECIMAL_PIC; import static io.ballerina.tools.copybook.generator.GeneratorConstants.POSITIVE_DECIMAL_PIC; import static io.ballerina.tools.copybook.generator.GeneratorConstants.SEMICOLON; import static io.ballerina.tools.copybook.generator.GeneratorConstants.SIGNED_DECIMAL_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.SIGNED_INTEGER_TYPE; import static io.ballerina.tools.copybook.generator.GeneratorConstants.SLASH; import static io.ballerina.tools.copybook.generator.GeneratorConstants.STRING; import static io.ballerina.tools.copybook.generator.GeneratorConstants.UNSIGNED_DECIMAL_TYPE;
2,231
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.tools.copybook.generator; public class CodeGeneratorUtils { public static final MinutiaeList SINGLE_WS_MINUTIAE = getSingleWSMinutiae(); private CodeGeneratorUtils() { } public static TypeGenerator getTypeGenerator(CopybookNode schemaValue) { if (schemaValue.getOccurringCount() > 0) { return new ArrayTypeGenerator(schemaValue); } else if (schemaValue instanceof DataItem dataItem) { return new ReferencedTypeGenerator(dataItem); } return new RecordTypeGenerator((GroupItem) schemaValue); } public static String getTypeReferenceName(CopybookNode copybookNode, boolean isRecordFieldReference) { if (copybookNode instanceof DataItem dataItem) { if (isRecordFieldReference) { return extractTypeReferenceName(dataItem); } if (dataItem.isNumeric()) { if (dataItem.getFloatingPointLength() > 0) { return DECIMAL; } return INT; } else if (dataItem.getPicture().contains(COMP_PIC)) {
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.tools.copybook.generator; public class CodeGeneratorUtils { public static final MinutiaeList SINGLE_WS_MINUTIAE = getSingleWSMinutiae(); private CodeGeneratorUtils() { } public static TypeGenerator getTypeGenerator(CopybookNode schemaValue) { if (schemaValue.getOccurringCount() > 0) { return new ArrayTypeGenerator(schemaValue); } else if (schemaValue instanceof DataItem dataItem) { return new ReferencedTypeGenerator(dataItem); } return new RecordTypeGenerator((GroupItem) schemaValue); } public static String getTypeReferenceName(CopybookNode copybookNode, boolean isRecordFieldReference) { if (copybookNode instanceof DataItem dataItem) { if (isRecordFieldReference) { return extractTypeReferenceName(dataItem); } if (dataItem.isNumeric()) { if (dataItem.getFloatingPointLength() > 0) { return DECIMAL; } return INT; } else if (dataItem.getPicture().contains(COMP_PIC)) {
return BYTE_ARRAY;
7
2023-10-24 05:00:08+00:00
4k
zhaoeryu/eu-backend
eu-generate/src/main/java/cn/eu/generate/utils/VelocityHelper.java
[ { "identifier": "Constants", "path": "eu-common-core/src/main/java/cn/eu/common/constants/Constants.java", "snippet": "public class Constants {\n\n /** 当前登录账号是否管理的字段KEY */\n public static final String IS_ADMIN_KEY = \"isAdmin\";\n /** 当前登录账号信息的字段KEY */\n public static final String USER_KEY = \"user\";\n /** 当前登录账号的角色列表字段KEY */\n public static final String ROLE_KEY = \"role\";\n /** 默认管理员角色字符串 */\n public static final String ADMIN_ROLE = \"*\";\n /** 默认管理员权限字符串 */\n public static final String ADMIN_PERMISSION = \"*\";\n\n\n /** 验证码RedisKey */\n public static final String CAPTCHA_REDIS_KEY = \"captcha:\";\n /** 验证码有效期, 单位:秒 */\n public static final int CAPTCHA_EXPIRATION = 60 * 5;\n\n /** 尝试登录的redisKey */\n public static final String TRY_LOGIN_COUNT_REDIS_KEY = \"login:try:\";\n /** 最大尝试登录的次数 */\n public static final int MAX_TRY_LOGIN_LIMIT = 5;\n /**\n * 10分钟内超过最大尝试登录次数则锁定账号, 单位:秒\n */\n public static final int TRY_LOGIN_CACHE_TIME = 60 * 10;\n /**\n * 超过最大尝试登录后的账号锁定RedisKey\n */\n public static final String LOCK_LOGIN_REDIS_KEY = \"login:lock:\";\n /**\n * 超过最大尝试登录后的账号锁定时间, 单位:秒\n */\n public static final int LOCK_TIME = 60 * 60 * 3;\n\n\n /** 用户默认密码 */\n public static final String DEFAULT_PASSWORD = \"123123\";\n\n /**\n * 逻辑删除标记 - 正常\n */\n public static final Integer DEL_FLAG_NORMAL = 0;\n /**\n * 逻辑删除标记 - 删除\n */\n public static final Integer DEL_FLAG_DELETE = 1;\n /**\n * 密码字段名\n */\n public static final String PASSWORD_FIELD_NAME = \"password\";\n /**\n * 逻辑删除字段\n */\n public static final String DEL_FLAG_FIELD_NAME = \"delFlag\";\n\n /**\n * 前端请求头 - 前端标识\n */\n public static final String REQUEST_HEADER_FRONT_KEY = \"X-Eu-Front\";\n /**\n * 前端请求头 - 版本标识\n */\n public static final String REQUEST_HEADER_FRONT_VERSION_KEY = \"X-Eu-Front-Version\";\n\n /**\n * 动态数据源配置前缀\n */\n public static final String DS_BASE_PREFIX = \"spring.datasource.dynamic\";\n public static final String DS_PREFIX = DS_BASE_PREFIX + \".datasource.\";\n}" }, { "identifier": "EuFrontHeader", "path": "eu-common-core/src/main/java/cn/eu/common/enums/EuFrontHeader.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum EuFrontHeader {\n\n VUE2(\"vue2\"),\n VUE3(\"vue3\");\n\n private final String desc;\n\n}" }, { "identifier": "GenConstant", "path": "eu-generate/src/main/java/cn/eu/generate/constants/GenConstant.java", "snippet": "public class GenConstant {\n\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * 主键列\n */\n public static final String PK_COLUMN_KEY = \"PRI\";\n\n /**\n * 自增长\n */\n public static final String PK_AUTO_INCREMENT = \"auto_increment\";\n\n /**\n * 默认包名\n */\n public static final String DEFAULT_PACKAGE_NAME = \"cn.eu.business\";\n\n /**\n * 默认模块名\n */\n public static final String DEFAULT_MODULE_NAME = \"eu-admin\";\n\n /**\n * 字段黑名单:默认表格不显示的字段\n */\n public static final String[] BLACK_LIST_FIELD_TABLE = { \"id\", \"create_by\", \"update_by\", \"del_flag\", \"remark\" };\n /**\n * 字段黑名单:默认表单不显示的字段\n */\n public static final String[] BLACK_LIST_FIELD_FORM = { \"id\", \"create_by\", \"update_by\", \"del_flag\", \"remark\", \"create_time\", \"update_time\" };\n /**\n * 字段黑名单:默认导出不显示的字段\n */\n public static final String[] BLACK_LIST_FIELD_EXPORT = { \"create_by\", \"update_by\", \"del_flag\" };\n /**\n * BaseEntity里的字段\n */\n public static final String[] BASE_ENTITY_FIELD_LIST = { \"create_by\", \"update_by\", \"del_flag\", \"remark\", \"create_time\", \"update_time\" };\n\n /**\n * 模版文件类型\n */\n public static final String TPL_FILE_TYPE_JAVA = \"java\";\n public static final String TPL_FILE_TYPE_XML = \"xml\";\n public static final String TPL_FILE_TYPE_VUE = \"vue\";\n public static final String TPL_FILE_TYPE_JS = \"js\";\n public static final String TPL_FILE_TYPE_SQL = \"sql\";\n}" }, { "identifier": "GenTable", "path": "eu-generate/src/main/java/cn/eu/generate/domain/GenTable.java", "snippet": "@Data\n@TableName(\"gen_table\")\npublic class GenTable implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId\n private String id;\n\n /**\n * 包路径\n */\n @NotBlank(message = \"包路径不能为空\")\n private String packageName;\n /**\n * 模块名\n */\n @NotBlank(message = \"模块名不能为空\")\n private String moduleName;\n /**\n * 功能分组\n */\n private String funcGroup;\n /**\n * 作者\n */\n private String author;\n /**\n * 表注释\n */\n private String tableComment;\n /**\n * 表名\n */\n @NotBlank(message = \"表名不能为空\")\n private String tableName;\n /**\n * 删除时,提示使用的字段\n */\n private String delShowField;\n /**\n * 生成模式\n * @see GenMode#ordinal()\n */\n private Integer genMode;\n\n @ExcelIgnore\n @TableField(fill = FieldFill.INSERT)\n private String createBy;\n @ExcelProperty(\"创建时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime createTime;\n @ExcelIgnore\n @TableField(fill = FieldFill.UPDATE)\n private String updateBy;\n @ExcelIgnore\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime updateTime;\n}" }, { "identifier": "GenTableColumn", "path": "eu-generate/src/main/java/cn/eu/generate/domain/GenTableColumn.java", "snippet": "@Data\n@TableName(\"gen_table_column\")\npublic class GenTableColumn implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId\n private String id;\n\n @NotBlank(message = \"表名不能为空\")\n private String tableName;\n\n /**\n * 字段名称\n */\n @NotBlank(message = \"字段名称不能为空\")\n private String columnName;\n /**\n * 字段描述\n */\n private String columnComment;\n /**\n * 字段键\n */\n private String columnKey;\n @NotBlank(message = \"字段类型不能为空\")\n private String columnType;\n private Boolean autoPk;\n private Integer columnSort;\n /**\n * 是否不为空\n */\n private Boolean notNull;\n /**\n * java字段类型\n */\n @NotBlank(message = \"java字段类型不能为空\")\n private String javaType;\n /**\n * java字段名称\n */\n @NotBlank(message = \"java字段名称不能为空\")\n private String javaField;\n /**\n * 字段长度\n */\n private Integer columnLength;\n /**\n * 是否导出\n */\n private Boolean excelExport;\n /**\n * 是否在列表显示\n */\n private Boolean tableShow;\n /**\n * 是否在表单显示\n */\n private Boolean formShow;\n\n /**\n * 表单类型\n */\n private String formType;\n /**\n * 查询方式\n */\n private String queryType;\n\n /**\n * 关联字典\n */\n private String dictKey;\n\n @ExcelIgnore\n @TableField(fill = FieldFill.INSERT)\n private String createBy;\n @ExcelProperty(\"创建时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime createTime;\n @ExcelIgnore\n @TableField(fill = FieldFill.UPDATE)\n private String updateBy;\n @ExcelIgnore\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime updateTime;\n}" }, { "identifier": "GenerateTemplateDto", "path": "eu-generate/src/main/java/cn/eu/generate/model/dto/GenerateTemplateDto.java", "snippet": "@Data\n@NoArgsConstructor\npublic class GenerateTemplateDto {\n\n private String path;\n private String name;\n private String type;\n private String code;\n\n public GenerateTemplateDto(String path, String name, String type) {\n this.path = path;\n this.name = name;\n this.type = type;\n }\n}" } ]
import cn.dev33.satoken.spring.SpringMVCUtil; import cn.eu.common.constants.Constants; import cn.eu.common.enums.EuFrontHeader; import cn.eu.generate.constants.GenConstant; import cn.eu.generate.domain.GenTable; import cn.eu.generate.domain.GenTableColumn; import cn.eu.generate.model.dto.GenerateTemplateDto; import cn.hutool.core.util.StrUtil; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import java.io.StringWriter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors;
3,361
package cn.eu.generate.utils; /** * @author zhaoeryu * @since 2023/6/27 */ public class VelocityHelper { public static void init() { Properties p = new Properties(); try { // 加载classpath目录下的vm文件 p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); p.setProperty(Velocity.INPUT_ENCODING, GenConstant.UTF8); // 初始化Velocity引擎,指定配置Properties Velocity.init(p); } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取vm模版列表 */ public static List<GenerateTemplateDto> getTemplates() { String requestHeaderFront = SpringMVCUtil.getRequest().getHeader(Constants.REQUEST_HEADER_FRONT_KEY); List<GenerateTemplateDto> list = new ArrayList<>(); // java list.add(new GenerateTemplateDto("vm/java/Controller.vm", "Controller.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/ServiceImpl.vm", "ServiceImpl.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/IService.vm", "Service.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/Mapper.vm", "Mapper.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/Entity.vm", "Entity.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/QueryCriteria.vm", "QueryCriteria.java", GenConstant.TPL_FILE_TYPE_JAVA)); // xml list.add(new GenerateTemplateDto("vm/xml/Mapper.vm", "Mapper.xml", GenConstant.TPL_FILE_TYPE_XML)); // sql list.add(new GenerateTemplateDto("vm/sql/sql.vm", "sql", GenConstant.TPL_FILE_TYPE_SQL)); if (EuFrontHeader.VUE2.getDesc().equals(requestHeaderFront)) { // vue list.add(new GenerateTemplateDto("vm/vue/vue.vm", "index.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue/editDialog.vm", "editDialog.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue/api.vm", "api.js", GenConstant.TPL_FILE_TYPE_JS)); } else if (EuFrontHeader.VUE3.getDesc().equals(requestHeaderFront)) { // vue3 list.add(new GenerateTemplateDto("vm/vue3/vue.vm", "index.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue3/editDialog.vm", "editDialog.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue3/api.vm", "api.js", GenConstant.TPL_FILE_TYPE_JS)); } return list; } /** * 渲染vm模版 */ public static List<GenerateTemplateDto> render(VelocityContext velocityContext) { return render(getTemplates(), velocityContext); } public static List<GenerateTemplateDto> render(List<GenerateTemplateDto> templates, VelocityContext velocityContext) { // 加载宏 getMarcoTemplate().forEach(item -> { StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(item, GenConstant.UTF8); tpl.merge(velocityContext, sw); }); // 渲染模版 templates.forEach(item -> { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(item.getPath(), GenConstant.UTF8); tpl.merge(velocityContext, sw); item.setCode(sw.toString()); }); return templates; } public static List<String> getMarcoTemplate() { List<String> list = new ArrayList<>(); list.add("vm/macro/elFormItem.vm"); list.add("vm/macro/vue3_elFormItem.vm"); return list; }
package cn.eu.generate.utils; /** * @author zhaoeryu * @since 2023/6/27 */ public class VelocityHelper { public static void init() { Properties p = new Properties(); try { // 加载classpath目录下的vm文件 p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); p.setProperty(Velocity.INPUT_ENCODING, GenConstant.UTF8); // 初始化Velocity引擎,指定配置Properties Velocity.init(p); } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取vm模版列表 */ public static List<GenerateTemplateDto> getTemplates() { String requestHeaderFront = SpringMVCUtil.getRequest().getHeader(Constants.REQUEST_HEADER_FRONT_KEY); List<GenerateTemplateDto> list = new ArrayList<>(); // java list.add(new GenerateTemplateDto("vm/java/Controller.vm", "Controller.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/ServiceImpl.vm", "ServiceImpl.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/IService.vm", "Service.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/Mapper.vm", "Mapper.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/Entity.vm", "Entity.java", GenConstant.TPL_FILE_TYPE_JAVA)); list.add(new GenerateTemplateDto("vm/java/QueryCriteria.vm", "QueryCriteria.java", GenConstant.TPL_FILE_TYPE_JAVA)); // xml list.add(new GenerateTemplateDto("vm/xml/Mapper.vm", "Mapper.xml", GenConstant.TPL_FILE_TYPE_XML)); // sql list.add(new GenerateTemplateDto("vm/sql/sql.vm", "sql", GenConstant.TPL_FILE_TYPE_SQL)); if (EuFrontHeader.VUE2.getDesc().equals(requestHeaderFront)) { // vue list.add(new GenerateTemplateDto("vm/vue/vue.vm", "index.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue/editDialog.vm", "editDialog.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue/api.vm", "api.js", GenConstant.TPL_FILE_TYPE_JS)); } else if (EuFrontHeader.VUE3.getDesc().equals(requestHeaderFront)) { // vue3 list.add(new GenerateTemplateDto("vm/vue3/vue.vm", "index.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue3/editDialog.vm", "editDialog.vue", GenConstant.TPL_FILE_TYPE_VUE)); list.add(new GenerateTemplateDto("vm/vue3/api.vm", "api.js", GenConstant.TPL_FILE_TYPE_JS)); } return list; } /** * 渲染vm模版 */ public static List<GenerateTemplateDto> render(VelocityContext velocityContext) { return render(getTemplates(), velocityContext); } public static List<GenerateTemplateDto> render(List<GenerateTemplateDto> templates, VelocityContext velocityContext) { // 加载宏 getMarcoTemplate().forEach(item -> { StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(item, GenConstant.UTF8); tpl.merge(velocityContext, sw); }); // 渲染模版 templates.forEach(item -> { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(item.getPath(), GenConstant.UTF8); tpl.merge(velocityContext, sw); item.setCode(sw.toString()); }); return templates; } public static List<String> getMarcoTemplate() { List<String> list = new ArrayList<>(); list.add("vm/macro/elFormItem.vm"); list.add("vm/macro/vue3_elFormItem.vm"); return list; }
public static VelocityContext fillContext(GenTable genTable, List<GenTableColumn> genTableColumns) {
4
2023-10-20 07:08:37+00:00
4k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/spaceStation/SpaceStationAntiGravityCasing.java
[ { "identifier": "SpaceStationAntiGravityBlock", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java", "snippet": "public static final Block SpaceStationAntiGravityBlock = new SpaceStationAntiGravityCasing(\n \"SpaceStationAntiGravityBlock\",\n \"Space Station Anti Gravity Block\");" }, { "identifier": "iconsSpaceStationAntiGravityCasingMap", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockStaticDataClientOnly.java", "snippet": "@SideOnly(Side.CLIENT)\npublic static Map<Integer, IIcon> iconsSpaceStationAntiGravityCasingMap = new HashMap<>();" }, { "identifier": "initMetaItemStack", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/MetaItemStackUtils.java", "snippet": "public static ItemStack initMetaItemStack(String i18nName, int Meta, Item basicItem, Set<Integer> aContainerSet) {\n\n // Handle the Name\n texter(i18nName, basicItem.getUnlocalizedName() + \".\" + Meta + \".name\");\n // Hold the list of Meta-generated Items\n aContainerSet.add(Meta);\n\n return new ItemStack(basicItem, 1, Meta);\n}" }, { "identifier": "texter", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextHandler.java", "snippet": "public static String texter(String aTextLine, String aKey) {\n\n /**\n * If not in Dev mode , return vanilla forge method directly.\n */\n if (TwistSpaceTechnology.isInDevMode) {\n if (LangMap.get(aKey) == null) {\n TwistSpaceTechnology.LOG.info(\"Texter get a new key - TextLine: \" + aKey + \" - \" + aTextLine);\n LangMapNeedToWrite.put(aKey, aTextLine);\n return aTextLine;\n } else {\n return translateToLocalFormatted(aKey);\n }\n } else if (null != translateToLocalFormatted(aKey)) {\n return translateToLocalFormatted(aKey);\n }\n return \"texterError: \" + aTextLine;\n}" }, { "identifier": "GTCMCreativeTabs", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/client/GTCMCreativeTabs.java", "snippet": "public class GTCMCreativeTabs {\n\n /**\n * Creative Tab for MetaItem01\n */\n public static final CreativeTabs tabMetaItem01 = new CreativeTabs(\n texter(\"TST Meta Items 1\", \"itemGroup.TST Meta Items 1\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n public static final CreativeTabs tabGears = new CreativeTabs(texter(\"TSTGears\", \"itemGroup.TSTGears\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n /**\n * Creative Tab for MetaBlock01\n */\n public static final CreativeTabs tabMetaBlock01 = new CreativeTabs(\n texter(\"TST Meta Blocks 1\", \"itemGroup.TST Meta Blocks 1\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n /**\n * Creative Tab for MetaBlock01\n */\n public static final CreativeTabs tabGTCMGeneralTab = new CreativeTabs(texter(\"TST\", \"itemGroup.TST\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n public static final CreativeTabs tabMultiStructures = new CreativeTabs(\n texter(\"MultiStructures\", \"itemGroup.MultiStructures\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n}" }, { "identifier": "BlockBase01", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockBase01.java", "snippet": "public class BlockBase01 extends Block {\n\n // region Constructors\n protected BlockBase01(Material materialIn) {\n super(materialIn);\n }\n\n public BlockBase01() {\n this(Material.iron);\n this.setCreativeTab(GTCMCreativeTabs.tabMetaBlock01);\n }\n\n public BlockBase01(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, \"blockBase01.\" + unlocalizedName + \".name\");\n }\n\n // endregion\n // -----------------------\n // region member variables\n\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region getters\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region setters\n\n public void setUnlocalizedName(String aUnlocalizedName) {\n this.unlocalizedName = aUnlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region Overrides\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < BlockStaticDataClientOnly.iconsBlockMap01.size()\n ? BlockStaticDataClientOnly.iconsBlockMap01.get(meta)\n : BlockStaticDataClientOnly.iconsBlockMap01.get(0);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/0\");\n for (int Meta : MetaBlockSet01) {\n BlockStaticDataClientOnly.iconsBlockMap01\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/\" + Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : MetaBlockSet01) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n public int damageDropped(int meta) {\n return meta;\n }\n\n @Override\n public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n @Override\n public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) {\n return false;\n }\n\n @Override\n public boolean canCreatureSpawn(EnumCreatureType type, IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n // endregion\n}" } ]
import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.SpaceStationAntiGravityBlock; import static com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStaticDataClientOnly.iconsSpaceStationAntiGravityCasingMap; import static com.Nxer.TwistSpaceTechnology.util.MetaItemStackUtils.initMetaItemStack; import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter; import java.util.HashSet; import java.util.List; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import com.Nxer.TwistSpaceTechnology.client.GTCMCreativeTabs; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockBase01; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import gregtech.api.GregTech_API;
2,132
package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation; public class SpaceStationAntiGravityCasing extends BlockBase01 { public SpaceStationAntiGravityCasing() { this.setHardness(9.0F); this.setResistance(5.0F); this.setHarvestLevel("wrench", 1); this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab); SpaceStationAntiGravityCasingCasingSet.add(0); GregTech_API.registerMachineBlock(this, -1); } public SpaceStationAntiGravityCasing(String unlocalizedName, String localName) { this(); this.unlocalizedName = unlocalizedName; texter(localName, unlocalizedName + ".name"); } public static Set<Integer> SpaceStationAntiGravityCasingCasingSet = new HashSet<>(); /** * Tooltips of these blocks' ItemBlock. */ public static String[][] SpaceStationAntiGravityCasingTooltipsArray = new String[14][]; private String unlocalizedName; // endregion // ----------------------- // region Meta Generator public static ItemStack SpaceStationAntiGravityCasingMeta(String i18nName, int meta) {
package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation; public class SpaceStationAntiGravityCasing extends BlockBase01 { public SpaceStationAntiGravityCasing() { this.setHardness(9.0F); this.setResistance(5.0F); this.setHarvestLevel("wrench", 1); this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab); SpaceStationAntiGravityCasingCasingSet.add(0); GregTech_API.registerMachineBlock(this, -1); } public SpaceStationAntiGravityCasing(String unlocalizedName, String localName) { this(); this.unlocalizedName = unlocalizedName; texter(localName, unlocalizedName + ".name"); } public static Set<Integer> SpaceStationAntiGravityCasingCasingSet = new HashSet<>(); /** * Tooltips of these blocks' ItemBlock. */ public static String[][] SpaceStationAntiGravityCasingTooltipsArray = new String[14][]; private String unlocalizedName; // endregion // ----------------------- // region Meta Generator public static ItemStack SpaceStationAntiGravityCasingMeta(String i18nName, int meta) {
return initMetaItemStack(i18nName, meta, SpaceStationAntiGravityBlock, SpaceStationAntiGravityCasingCasingSet);
0
2023-10-16 09:57:15+00:00
4k
wyjsonGo/GoRouter
module_main/src/main/java/com/wyjson/module_main/activity/SplashActivity.java
[ { "identifier": "GoCallbackImpl", "path": "GoRouter-Api/src/main/java/com/wyjson/router/callback/impl/GoCallbackImpl.java", "snippet": "public abstract class GoCallbackImpl implements GoCallback {\n @Override\n public void onFound(Card card) {\n\n }\n\n @Override\n public void onLost(Card card) {\n\n }\n\n @Override\n public abstract void onArrival(Card card);\n\n @Override\n public void onInterrupt(Card card, @NonNull Throwable exception) {\n\n }\n}" }, { "identifier": "MainActivityGoRouter", "path": "module_common/src/main/java/com/wyjson/router/helper/module_main/group_main/MainActivityGoRouter.java", "snippet": "public class MainActivityGoRouter {\n public static String getPath() {\n return \"/main/activity\";\n }\n\n public static CardMeta getCardMeta() {\n return GoRouter.getInstance().build(getPath()).getCardMeta();\n }\n\n public static <T> void postEvent(T value) {\n GoRouter.getInstance().postEvent(getPath(), value);\n }\n\n public static Card build() {\n return GoRouter.getInstance().build(getPath());\n }\n\n public static void go() {\n build().go();\n }\n}" }, { "identifier": "Card", "path": "GoRouter-Api/src/main/java/com/wyjson/router/model/Card.java", "snippet": "public final class Card extends CardMeta {\n\n private Uri uri;\n private Bundle mBundle;\n private int flags = 0;\n private boolean greenChannel;// 绿色通道(跳过所有的拦截器)\n private String action;\n private Context context;\n private IJsonService jsonService;\n\n private int enterAnim = -1;// 转场动画\n private int exitAnim = -1;\n private ActivityOptionsCompat activityOptionsCompat;// 转场动画(API16+)\n\n private Throwable interceptorException;// 拦截执行中断异常信息\n private int timeout = 300;// go() timeout, TimeUnit.Second\n\n public void setUri(Uri uri) {\n if (uri == null || TextUtils.isEmpty(uri.toString()) || TextUtils.isEmpty(uri.getPath())) {\n throw new RouterException(\"uri Parameter is invalid!\");\n }\n this.uri = uri;\n setPath(uri.getPath());\n }\n\n public Uri getUri() {\n return uri;\n }\n\n public ActivityOptionsCompat getActivityOptionsCompat() {\n return activityOptionsCompat;\n }\n\n public int getEnterAnim() {\n return enterAnim;\n }\n\n public int getExitAnim() {\n return exitAnim;\n }\n\n public Card(Uri uri) {\n setUri(uri);\n this.mBundle = new Bundle();\n }\n\n public Card(String path, Bundle bundle) {\n setPath(path);\n this.mBundle = (null == bundle ? new Bundle() : bundle);\n }\n\n @Nullable\n public Object go() {\n return go(null, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context) {\n return go(context, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context, GoCallback callback) {\n return go(context, this, -1, null, callback);\n }\n\n @Nullable\n public Object go(Context context, int requestCode) {\n return go(context, this, requestCode, null, null);\n }\n\n @Nullable\n public Object go(Context context, int requestCode, GoCallback callback) {\n return go(context, this, requestCode, null, callback);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher) {\n return go(context, this, -1, activityResultLauncher, null);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return go(context, this, -1, activityResultLauncher, callback);\n }\n\n @Nullable\n private Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return GoRouter.getInstance().go(context, card, requestCode, activityResultLauncher, callback);\n }\n\n @Nullable\n public CardMeta getCardMeta() {\n try {\n return RouteCenter.getCardMeta(this);\n } catch (NoFoundRouteException e) {\n GoRouter.logger.warning(null, e.getMessage());\n }\n return null;\n }\n\n public void setCardMeta(RouteType type, Class<?> pathClass, int tag, boolean deprecated) {\n setType(type);\n setPathClass(pathClass);\n setTag(tag);\n setDeprecated(deprecated);\n }\n\n public Bundle getExtras() {\n return mBundle;\n }\n\n public Card with(Bundle bundle) {\n if (null != bundle) {\n mBundle = bundle;\n }\n return this;\n }\n\n public Card withFlags(int flag) {\n this.flags = flag;\n return this;\n }\n\n public Card addFlags(int flags) {\n this.flags |= flags;\n return this;\n }\n\n public int getFlags() {\n return flags;\n }\n\n /**\n * 使用 withObject 传递 List 和 Map 的实现了 Serializable 接口的实现类(ArrayList/HashMap)的时候,\n * 接收该对象的地方不能标注具体的实现类类型应仅标注为 List 或 Map,\n * 否则会影响序列化中类型的判断, 其他类似情况需要同样处理\n *\n * @param key\n * @param value\n * @return\n */\n public Card withObject(@Nullable String key, @Nullable Object value) {\n jsonService = GoRouter.getInstance().getService(IJsonService.class);\n if (jsonService == null) {\n throw new RouterException(\"To use withObject() method, you need to implement IJsonService\");\n }\n mBundle.putString(key, jsonService.toJson(value));\n return this;\n }\n\n public Card withString(@Nullable String key, @Nullable String value) {\n mBundle.putString(key, value);\n return this;\n }\n\n public Card withBoolean(@Nullable String key, boolean value) {\n mBundle.putBoolean(key, value);\n return this;\n }\n\n public Card withShort(@Nullable String key, short value) {\n mBundle.putShort(key, value);\n return this;\n }\n\n public Card withInt(@Nullable String key, int value) {\n mBundle.putInt(key, value);\n return this;\n }\n\n public Card withLong(@Nullable String key, long value) {\n mBundle.putLong(key, value);\n return this;\n }\n\n public Card withDouble(@Nullable String key, double value) {\n mBundle.putDouble(key, value);\n return this;\n }\n\n public Card withByte(@Nullable String key, byte value) {\n mBundle.putByte(key, value);\n return this;\n }\n\n public Card withChar(@Nullable String key, char value) {\n mBundle.putChar(key, value);\n return this;\n }\n\n public Card withFloat(@Nullable String key, float value) {\n mBundle.putFloat(key, value);\n return this;\n }\n\n public Card withCharSequence(@Nullable String key, @Nullable CharSequence value) {\n mBundle.putCharSequence(key, value);\n return this;\n }\n\n public Card withParcelable(@Nullable String key, @Nullable Parcelable value) {\n mBundle.putParcelable(key, value);\n return this;\n }\n\n public Card withParcelableArray(@Nullable String key, @Nullable Parcelable[] value) {\n mBundle.putParcelableArray(key, value);\n return this;\n }\n\n public Card withParcelableArrayList(@Nullable String key, @Nullable ArrayList<? extends Parcelable> value) {\n mBundle.putParcelableArrayList(key, value);\n return this;\n }\n\n public Card withSparseParcelableArray(@Nullable String key, @Nullable SparseArray<? extends Parcelable> value) {\n mBundle.putSparseParcelableArray(key, value);\n return this;\n }\n\n public Card withIntegerArrayList(@Nullable String key, @Nullable ArrayList<Integer> value) {\n mBundle.putIntegerArrayList(key, value);\n return this;\n }\n\n public Card withStringArrayList(@Nullable String key, @Nullable ArrayList<String> value) {\n mBundle.putStringArrayList(key, value);\n return this;\n }\n\n public Card withCharSequenceArrayList(@Nullable String key, @Nullable ArrayList<CharSequence> value) {\n mBundle.putCharSequenceArrayList(key, value);\n return this;\n }\n\n public Card withSerializable(@Nullable String key, @Nullable Serializable value) {\n mBundle.putSerializable(key, value);\n return this;\n }\n\n public Card withByteArray(@Nullable String key, @Nullable byte[] value) {\n mBundle.putByteArray(key, value);\n return this;\n }\n\n public Card withShortArray(@Nullable String key, @Nullable short[] value) {\n mBundle.putShortArray(key, value);\n return this;\n }\n\n public Card withCharArray(@Nullable String key, @Nullable char[] value) {\n mBundle.putCharArray(key, value);\n return this;\n }\n\n public Card withLongArray(@Nullable String key, @Nullable long[] value) {\n mBundle.putLongArray(key, value);\n return this;\n }\n\n public Card withIntArray(@Nullable String key, @Nullable int[] value) {\n mBundle.putIntArray(key, value);\n return this;\n }\n\n public Card withDoubleArray(@Nullable String key, @Nullable double[] value) {\n mBundle.putDoubleArray(key, value);\n return this;\n }\n\n public Card withBooleanArray(@Nullable String key, @Nullable boolean[] value) {\n mBundle.putBooleanArray(key, value);\n return this;\n }\n\n public Card withStringArray(@Nullable String key, @Nullable String[] value) {\n mBundle.putStringArray(key, value);\n return this;\n }\n\n public Card withFloatArray(@Nullable String key, @Nullable float[] value) {\n mBundle.putFloatArray(key, value);\n return this;\n }\n\n public Card withCharSequenceArray(@Nullable String key, @Nullable CharSequence[] value) {\n mBundle.putCharSequenceArray(key, value);\n return this;\n }\n\n public Card withBundle(@Nullable String key, @Nullable Bundle value) {\n mBundle.putBundle(key, value);\n return this;\n }\n\n public Card withTransition(int enterAnim, int exitAnim) {\n this.enterAnim = enterAnim;\n this.exitAnim = exitAnim;\n return this;\n }\n\n @RequiresApi(16)\n public Card withActivityOptionsCompat(ActivityOptionsCompat compat) {\n this.activityOptionsCompat = compat;\n return this;\n }\n\n public String getAction() {\n return action;\n }\n\n public Card withAction(String action) {\n this.action = action;\n return this;\n }\n\n public Context getContext() {\n return context;\n }\n\n public void setContext(Context context) {\n if (context == null) {\n throw new RouterException(\"Context cannot be empty, Call 'GoRouter.setApplication(...)' in application.\");\n }\n this.context = context;\n }\n\n public boolean isGreenChannel() {\n return greenChannel;\n }\n\n public Card greenChannel() {\n this.greenChannel = true;\n return this;\n }\n\n public Throwable getInterceptorException() {\n return interceptorException;\n }\n\n public void setInterceptorException(Throwable interceptorException) {\n this.interceptorException = interceptorException;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n /**\n * @param timeout Second\n */\n public Card setTimeout(int timeout) {\n this.timeout = timeout;\n return this;\n }\n\n @NonNull\n @Override\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n return \"Card{\" +\n \"path='\" + getPath() + '\\'' +\n \", uri=\" + uri +\n \", mBundle=\" + mBundle +\n \", flags=\" + flags +\n \", greenChannel=\" + greenChannel +\n \", action='\" + action + '\\'' +\n \", context=\" + (context != null ? context.getClass().getSimpleName() : null) +\n \", optionsCompat=\" + activityOptionsCompat +\n \", enterAnim=\" + enterAnim +\n \", exitAnim=\" + exitAnim +\n \", interceptorException=\" + interceptorException +\n \", timeout=\" + timeout +\n '}';\n }\n}" } ]
import androidx.fragment.app.FragmentActivity; import com.wyjson.router.annotation.Route; import com.wyjson.router.callback.impl.GoCallbackImpl; import com.wyjson.router.helper.module_main.group_main.MainActivityGoRouter; import com.wyjson.router.model.Card;
3,269
package com.wyjson.module_main.activity; @Route(path = "/main/splash/activity", remark = "欢迎页") public class SplashActivity extends FragmentActivity { @Override protected void onStart() { super.onStart(); goMainActivity(); } private void goMainActivity() { MainActivityGoRouter.build().go(this, new GoCallbackImpl() { @Override
package com.wyjson.module_main.activity; @Route(path = "/main/splash/activity", remark = "欢迎页") public class SplashActivity extends FragmentActivity { @Override protected void onStart() { super.onStart(); goMainActivity(); } private void goMainActivity() { MainActivityGoRouter.build().go(this, new GoCallbackImpl() { @Override
public void onArrival(Card card) {
2
2023-10-18 13:52:07+00:00
4k
trpc-group/trpc-java
trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/support/jetty/JettyHttpServerFactory.java
[ { "identifier": "HTTP2C_SCHEME", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/common/Constants.java", "snippet": "public static final String HTTP2C_SCHEME = \"http2c\";" }, { "identifier": "HTTP2_SCHEME", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/common/Constants.java", "snippet": "public static final String HTTP2_SCHEME = \"h2\";" }, { "identifier": "HTTPS_SCHEME", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/common/Constants.java", "snippet": "public static final String HTTPS_SCHEME = \"https\";" }, { "identifier": "ProtocolConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/ProtocolConfig.java", "snippet": "public class ProtocolConfig extends BaseProtocolConfig implements Cloneable {\n\n protected String name;\n protected String ip;\n protected int port;\n protected String nic;\n protected InetSocketAddress address;\n /**\n * Protocol type [stream, standard].\n */\n protected String protocolType;\n protected volatile boolean setDefault = false;\n protected volatile boolean inited = false;\n\n public static ProtocolConfig newInstance() {\n return new ProtocolConfig();\n }\n\n public static String toUniqId(String host, int port, String networkType) {\n return host + Constants.COLON + port + Constants.COLON + networkType;\n }\n\n public String toUniqId() {\n return toUniqId(ip, port, network);\n }\n\n /**\n * Set default values.\n */\n public synchronized void setDefault() {\n if (!setDefault) {\n setFieldDefault();\n setDefault = true;\n }\n }\n\n /**\n * Initialize client service\n */\n public synchronized void init() {\n if (!inited) {\n setDefault();\n inited = true;\n }\n }\n\n /**\n * Set protocol default values.\n */\n protected void setFieldDefault() {\n BinderUtils.bind(this);\n BinderUtils.lazyBind(this, ConfigConstants.IP, nic, obj -> NetUtils.resolveMultiNicAddr((String) obj));\n BinderUtils.bind(this, ConfigConstants.IO_THREADS, Constants.DEFAULT_IO_THREADS);\n PreconditionUtils.checkArgument(StringUtils.isNotBlank(ip), \"Protocol(%s), ip is null\", toSimpleString());\n BinderUtils.bind(this, \"address\", new InetSocketAddress(this.getIp(), this.getPort()));\n }\n\n public RpcClient createClient() {\n setDefault();\n RpcClientFactory extension = ExtensionLoader.getExtensionLoader(RpcClientFactory.class)\n .getExtension(getProtocol());\n PreconditionUtils.checkArgument(extension != null, \"rpc client extension %s not exist\",\n getProtocol());\n return extension.createRpcClient(this);\n }\n\n public RpcServer createServer() {\n setDefault();\n return RpcServerManager.getOrCreateRpcServer(this);\n }\n\n @Override\n public String toString() {\n return \"ProtocolConfig [name=\" + name + \", ip=\" + ip + \", port=\" + port + \", nic=\" + nic\n + \", address=\" + address + \", protocol=\" + protocol + \", serializationType=\"\n + serialization\n + \", compressorType=\" + compressor + \", keepAlive=\" + keepAlive + \", charset=\"\n + charset\n + \", transporter=\" + transporter + \", maxConns=\" + maxConns + \", backlog=\" + backlog\n + \", network=\" + network + \", receiveBuffer=\" + receiveBuffer + \", sendBuffer=\"\n + sendBuffer\n + \", payload=\" + payload + \", idleTimeout=\" + idleTimeout + \", lazyinit=\" + lazyinit\n + \", connsPerAddr=\" + connsPerAddr + \", connTimeout=\" + connTimeout + \", ioMode=\"\n + ioMode\n + \", ioThreadGroupShare=\" + ioThreadGroupShare + \", ioThreads=\" + ioThreads\n + \", extMap=\"\n + extMap + \", setDefault=\" + setDefault + \"]\";\n }\n\n public ProtocolConfig clone() {\n ProtocolConfig newConfig = null;\n try {\n newConfig = (ProtocolConfig) super.clone();\n } catch (CloneNotSupportedException ex) {\n throw new RuntimeException(\"\", ex);\n }\n newConfig.inited = false;\n newConfig.setDefault = false;\n newConfig.setExtMap(new HashMap<>(this.getExtMap()));\n return newConfig;\n }\n\n /**\n * Convert to InetSocketAddress.\n *\n * @return InetSocketAddress\n */\n public InetSocketAddress toInetSocketAddress() {\n if (address == null) {\n if (StringUtils.isNotBlank(ip)) {\n return new InetSocketAddress(ip, port);\n }\n }\n return address;\n }\n\n /**\n * Registration information: Polaris name + protocol + ip + port + network.\n *\n * @return Polaris name + protocol + ip + port + network\n */\n public String toSimpleString() {\n return (name == null ? \"<null>\" : name) + \":\" + protocol + \":\" + ip + \":\" + port + \":\" + network;\n }\n\n public boolean useEpoll() {\n return StringUtils.equalsIgnoreCase(ioMode, Constants.IO_MODE_EPOLL);\n }\n\n @Override\n protected void checkFiledModifyPrivilege() {\n super.checkFiledModifyPrivilege();\n Preconditions.checkArgument(!isInited(), \"Not allow to modify field,state is(init)\");\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n checkFiledModifyPrivilege();\n this.name = name;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(String ip) {\n checkFiledModifyPrivilege();\n this.ip = ip;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n checkFiledModifyPrivilege();\n this.port = port;\n }\n\n public Boolean isKeepAlive() {\n return keepAlive;\n }\n\n public Boolean isLazyinit() {\n return lazyinit;\n }\n\n public Boolean isIoThreadGroupShare() {\n return ioThreadGroupShare;\n }\n\n @Override\n public void setBossThreads(int bossThreads) {\n checkFiledModifyPrivilege();\n Preconditions.checkArgument(bossThreads < Runtime.getRuntime().availableProcessors() * 4,\n \"boss threads Cannot be greater than CPU * 4:\" + Runtime.getRuntime().availableProcessors() * 4);\n Preconditions.checkArgument(bossThreads < ioThreads,\n \"boss threads Cannot be greater than io Threads:\" + this.ioThreads);\n this.bossThreads = bossThreads;\n }\n\n public String getNic() {\n return nic;\n }\n\n public void setNic(String nic) {\n checkFiledModifyPrivilege();\n this.nic = nic;\n }\n\n public String getProtocolType() {\n return protocolType;\n }\n\n public void setProtocolType(String protocolType) {\n checkFiledModifyPrivilege();\n this.protocolType = protocolType;\n }\n\n public boolean isSetDefault() {\n return setDefault;\n }\n\n public boolean isInited() {\n return inited;\n }\n\n}" }, { "identifier": "HttpExecutor", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/HttpExecutor.java", "snippet": "public interface HttpExecutor {\n\n /**\n * Execute a http request and write response through the response param.\n *\n * @param request the {@link HttpServletRequest}\n * @param response the {@link HttpServletResponse}\n * @throws IOException in case of I/O error\n * @throws ServletException in case of Servlet handler error\n */\n void execute(HttpServletRequest request, HttpServletResponse response)\n throws IOException, ServletException;\n\n /**\n * Destroy this class\n */\n default void destroy() {\n }\n\n}" }, { "identifier": "HttpServer", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/HttpServer.java", "snippet": "public interface HttpServer {\n\n /**\n * Start server\n */\n void open() throws TransportException;\n\n /**\n * Get the http executor\n */\n HttpExecutor getExecutor();\n\n /**\n * Get protocol config\n */\n ProtocolConfig getConfig();\n\n /**\n * Get locol ip address\n */\n InetSocketAddress getLocalAddress();\n\n /**\n * Whether has bound\n */\n boolean isBound();\n\n /**\n * Whether has closed\n */\n boolean isClosed();\n\n /**\n * Close server\n */\n void close();\n\n /**\n * Get the server connector\n */\n ServerConnector getServerConnector(Server server);\n\n}" }, { "identifier": "HttpServerFactory", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/spi/HttpServerFactory.java", "snippet": "@Extensible(\"jetty\")\npublic interface HttpServerFactory {\n\n /**\n * Create a HTTPServer.\n *\n * @param config protocol config\n * @param executor http request executor\n * @return A tRPC HTTPServer\n */\n HttpServer create(ProtocolConfig config, HttpExecutor executor);\n\n}" }, { "identifier": "HttpUtils", "path": "trpc-transport/trpc-transport-http/src/main/java/com/tencent/trpc/transport/http/util/HttpUtils.java", "snippet": "public class HttpUtils {\n\n /**\n * Get the protocol of the server. If a keystore is configured, HTTPS or h2 is enabled;\n * otherwise, HTTP or http2c is used.\n *\n * @param config protocol config\n * @return the protocol scheme\n */\n public static String getScheme(ProtocolConfig config) {\n String protocol = config.getProtocol();\n Map<String, Object> extMap = config.getExtMap();\n boolean useHttps = extMap.containsKey(KEYSTORE_PATH) && extMap.containsKey(KEYSTORE_PASS);\n if (HTTP_SCHEME.equals(protocol)) {\n return useHttps ? HTTPS_SCHEME : HTTP_SCHEME;\n } else if (HTTP2_SCHEME.equals(protocol)) {\n return useHttps ? HTTP2_SCHEME : HTTP2C_SCHEME;\n } else {\n return HTTP_SCHEME;\n }\n }\n\n}" } ]
import static com.tencent.trpc.transport.http.common.Constants.HTTP2C_SCHEME; import static com.tencent.trpc.transport.http.common.Constants.HTTP2_SCHEME; import static com.tencent.trpc.transport.http.common.Constants.HTTPS_SCHEME; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.extension.Extension; import com.tencent.trpc.transport.http.HttpExecutor; import com.tencent.trpc.transport.http.HttpServer; import com.tencent.trpc.transport.http.spi.HttpServerFactory; import com.tencent.trpc.transport.http.util.HttpUtils;
2,764
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.transport.http.support.jetty; @Extension(JettyHttpServer.NAME) public class JettyHttpServerFactory implements HttpServerFactory { @Override public HttpServer create(ProtocolConfig config, HttpExecutor executor) { switch (HttpUtils.getScheme(config)) { case HTTP2C_SCHEME: return new JettyHttp2cServer(config, executor);
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.transport.http.support.jetty; @Extension(JettyHttpServer.NAME) public class JettyHttpServerFactory implements HttpServerFactory { @Override public HttpServer create(ProtocolConfig config, HttpExecutor executor) { switch (HttpUtils.getScheme(config)) { case HTTP2C_SCHEME: return new JettyHttp2cServer(config, executor);
case HTTP2_SCHEME:
1
2023-10-19 10:54:11+00:00
4k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/VideoHistoryCommentsActivity.java
[ { "identifier": "Comment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/Comment.java", "snippet": "public class Comment {\r\n public String commentText;\r\n public String commentId;\r\n\r\n public Comment() {\r\n }\r\n\r\n\r\n public Comment(String commentText, String commentId) {\r\n this.commentText = commentText;\r\n this.commentId = commentId;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"Comment{\" +\r\n \"commentText='\" + commentText + '\\'' +\r\n \", commentId='\" + commentId + '\\'' +\r\n '}';\r\n }\r\n}\r" }, { "identifier": "HistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/HistoryComment.java", "snippet": "public abstract class HistoryComment extends Comment{\r\n public static final String STATE_NORMAL = \"NORMAL\";\r\n public static final String STATE_SHADOW_BAN = \"SHADOW_BAN\";\r\n public static final String STATE_DELETED = \"DELETED\";\r\n\r\n public String state;\r\n public Date sendDate;\r\n @Nullable\r\n public Comment anchorComment;\r\n @Nullable\r\n public Comment repliedComment;\r\n\r\n public HistoryComment(){}\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment) {\r\n this(commentText,commentId,state,sendDate);\r\n this.anchorComment = anchorComment;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n this.anchorComment = anchorComment;\r\n this.repliedComment = repliedComment;\r\n }\r\n\r\n public abstract String getCommentSectionSourceId();\r\n\r\n public String getFormatDateFor_yMd(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n}\r" }, { "identifier": "VideoHistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoHistoryComment.java", "snippet": "public class VideoHistoryComment extends HistoryComment{\r\n\r\n public String videoId;\r\n\r\n public VideoHistoryComment(String commentId, String commentText, String anchorCommentId, String anchorCommentText, String videoId, String state, long sendDate, String repliedCommentId, String repliedCommentText) {\r\n this.commentId = commentId;\r\n this.commentText = commentText;\r\n if (!TextUtils.isEmpty(anchorCommentId) && anchorCommentText != null) {\r\n this.anchorComment = new Comment(anchorCommentText,anchorCommentId);\r\n }\r\n this.videoId = videoId;\r\n this.state = state;\r\n this.sendDate = new Date(sendDate);\r\n if (!TextUtils.isEmpty(repliedCommentId) && repliedCommentText != null){\r\n this.repliedComment = new Comment(repliedCommentText,repliedCommentId);\r\n }\r\n }\r\n\r\n public VideoHistoryComment(String commentText, String commentId, String state, Date sendDate, String videoId) {\r\n super(commentText, commentId, state, sendDate);\r\n this.videoId = videoId;\r\n }\r\n\r\n public VideoHistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, String videoId) {\r\n super(commentText, commentId, state, sendDate, anchorComment);\r\n this.videoId = videoId;\r\n }\r\n\r\n public VideoHistoryComment(String commentId,String commentText, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment, String videoId) {\r\n super(commentText, commentId, state, sendDate, anchorComment, repliedComment);\r\n this.videoId = videoId;\r\n }\r\n\r\n @Override\r\n public String getCommentSectionSourceId() {\r\n return videoId;\r\n }\r\n\r\n @NonNull\r\n @Override\r\n public String toString() {\r\n return \"VideoHistoryComment{\" +\r\n \"videoId='\" + videoId + '\\'' +\r\n \", state='\" + state + '\\'' +\r\n \", sendDate=\" + sendDate +\r\n \", anchorComment=\" + anchorComment +\r\n \", commentText='\" + commentText + '\\'' +\r\n \", commentId='\" + commentId + '\\'' +\r\n '}';\r\n }\r\n}\r" }, { "identifier": "StatisticsDB", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/db/StatisticsDB.java", "snippet": "public class StatisticsDB extends SQLiteOpenHelper {\r\n public static final String TABLE_NAME_VIDEO_HISTORY_COMMENTS = \"history_comments_from_video\";\r\n private static final String TABLE_NAME_TO_BE_CHECKED_COMMENTS = \"to_be_checked_comments\";\r\n SQLiteDatabase db;\r\n\r\n public static final int DB_VERSION = 1;\r\n\r\n public StatisticsDB(@Nullable Context context) {\r\n super(context, \"statistics\", null, DB_VERSION);\r\n db = getWritableDatabase();\r\n }\r\n\r\n @Override\r\n public void onCreate(SQLiteDatabase db) {\r\n db.execSQL(\"CREATE TABLE history_comments_from_video ( comment_id TEXT PRIMARY KEY UNIQUE NOT NULL, comment_text TEXT NOT NULL,anchor_comment_id TEXT,anchor_comment_text TEXT, video_id TEXT NOT NULL, state TEXT NOT NULL,send_date INTEGER NOT NULL,replied_comment_id TEXT,replied_comment_text TEXT ); \");\r\n db.execSQL(\"CREATE TABLE to_be_checked_comments ( comment_id TEXT PRIMARY KEY NOT NULL UNIQUE, comment_text TEXT NOT NULL, source_id TEXT NOT NULL, comment_section_type INTEGER NOT NULL, replied_comment_id TEXT, replied_comment_text TEXT, context1 BLOB NOT NULL ,send_time INTEGER NOT NULL);\");\r\n }\r\n\r\n @Override\r\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n\r\n }\r\n\r\n public long insertVideoHistoryComment(VideoHistoryComment comment){\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n if (comment.anchorComment != null) {\r\n v.put(\"anchor_comment_id\", comment.anchorComment.commentId);\r\n v.put(\"anchor_comment_text\", comment.anchorComment.commentText);\r\n }\r\n v.put(\"video_id\", comment.videoId);\r\n v.put(\"state\", comment.state);\r\n v.put(\"send_date\", comment.sendDate.getTime());\r\n if (comment.repliedComment != null) {\r\n v.put(\"replied_comment_id\", comment.repliedComment.commentId);\r\n v.put(\"replied_comment_text\", comment.repliedComment.commentText);\r\n }\r\n return db.insert(TABLE_NAME_VIDEO_HISTORY_COMMENTS,null,v);\r\n }\r\n\r\n @SuppressLint(\"Range\")\r\n public List<VideoHistoryComment> queryAllVideoHistoryComments(){\r\n List<VideoHistoryComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"anchor_comment_id\", \"anchor_comment_text\", \"video_id\", \"state\", \"send_date\", \"replied_comment_id\", \"replied_comment_text\"};\r\n Cursor cursor = db.query(\"history_comments_from_video\", columns, null, null, null, null, null);\r\n\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String anchorCommentId = cursor.getString(cursor.getColumnIndex(\"anchor_comment_id\"));\r\n String anchorCommentText = cursor.getString(cursor.getColumnIndex(\"anchor_comment_text\"));\r\n String videoId = cursor.getString(cursor.getColumnIndex(\"video_id\"));\r\n String state = cursor.getString(cursor.getColumnIndex(\"state\"));\r\n long sendDate = cursor.getLong(cursor.getColumnIndex(\"send_date\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n VideoHistoryComment comment = new VideoHistoryComment(commentId, commentText, anchorCommentId, anchorCommentText, videoId, state, sendDate, repliedCommentId, repliedCommentText);\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteVideoHistoryComment(String commentId) {\r\n return db.delete(TABLE_NAME_VIDEO_HISTORY_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n public void insertToBeCheckedComment(ToBeCheckedComment comment) {\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n v.put(\"source_id\", comment.sourceId);\r\n v.put(\"comment_section_type\", comment.commentSectionType);\r\n v.put(\"replied_comment_id\", comment.repliedCommentId);\r\n v.put(\"replied_comment_text\", comment.repliedCommentText);\r\n v.put(\"context1\", comment.context1);\r\n v.put(\"send_time\",comment.sendTime.getTime());\r\n db.insert(TABLE_NAME_TO_BE_CHECKED_COMMENTS, null, v);\r\n }\r\n @SuppressLint(\"Range\")\r\n public List<ToBeCheckedComment> getAllToBeCheckedComments() {\r\n List<ToBeCheckedComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"source_id\", \"comment_section_type\", \"replied_comment_id\", \"replied_comment_text\", \"context1\",\"send_time\"};\r\n Cursor cursor = db.query(\"to_be_checked_comments\", columns, null, null, null, null, null);\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String sourceId = cursor.getString(cursor.getColumnIndex(\"source_id\"));\r\n int commentSectionType = cursor.getInt(cursor.getColumnIndex(\"comment_section_type\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n byte[] context1 = cursor.getBlob(cursor.getColumnIndex(\"context1\"));\r\n long sendTime = cursor.getLong(cursor.getColumnIndex(\"send_time\"));\r\n ToBeCheckedComment comment = new ToBeCheckedComment(commentId, commentText, sourceId, commentSectionType, repliedCommentId, repliedCommentText, context1,new Date(sendTime));\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteToBeCheckedComment(String commentId){\r\n return db.delete(TABLE_NAME_TO_BE_CHECKED_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n}\r" }, { "identifier": "ProgressBarDialog", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/ProgressBarDialog.java", "snippet": "public class ProgressBarDialog implements DialogInterface {\r\n public static final int DEFAULT_MAX_PROGRESS = 1000;\r\n public final AlertDialog alertDialog;\r\n final ProgressBar progressBar;\r\n\r\n ProgressBarDialog(AlertDialog alertDialog, ProgressBar progressBar) {\r\n this.alertDialog = alertDialog;\r\n this.progressBar = progressBar;\r\n }\r\n\r\n public void setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n }\r\n\r\n public void setMax(int max){\r\n progressBar.setMax(max);\r\n }\r\n\r\n public void setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n }\r\n\r\n public void setMessage(String message){\r\n alertDialog.setMessage(message);\r\n }\r\n\r\n public void setTitle(String title){\r\n alertDialog.setTitle(title);\r\n }\r\n\r\n public Button getButton(int whichButton){\r\n return alertDialog.getButton(whichButton);\r\n }\r\n\r\n @Override\r\n public void cancel() {\r\n alertDialog.cancel();\r\n }\r\n\r\n @Override\r\n public void dismiss() {\r\n alertDialog.dismiss();\r\n }\r\n\r\n public static class Builder {\r\n\r\n private final AlertDialog.Builder dialogBuilder;\r\n private final ProgressBar progressBar;\r\n\r\n\r\n public Builder(Context context) {\r\n dialogBuilder = new AlertDialog.Builder(context);\r\n View view = View.inflate(context, R.layout.dialog_wait_progress,null);\r\n progressBar = view.findViewById(R.id.wait_progress_bar);\r\n dialogBuilder.setView(view);\r\n progressBar.setMax(DEFAULT_MAX_PROGRESS);\r\n }\r\n\r\n public Builder setTitle(String title) {\r\n dialogBuilder.setTitle(title);\r\n return this;\r\n }\r\n\r\n public Builder setMessage(String message) {\r\n dialogBuilder.setMessage(message);\r\n return this;\r\n }\r\n\r\n public Builder setPositiveButton(String text, OnClickListener listener) {\r\n dialogBuilder.setPositiveButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNegativeButton(String text, OnClickListener listener) {\r\n dialogBuilder.setNegativeButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNeutralButton (String text, OnClickListener listener){\r\n dialogBuilder.setNeutralButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setCancelable(boolean cancelable) {\r\n dialogBuilder.setCancelable(cancelable);\r\n return this;\r\n }\r\n\r\n public Builder setOnCancelListener(OnCancelListener listener) {\r\n dialogBuilder.setOnCancelListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setOnDismissListener(OnDismissListener listener) {\r\n dialogBuilder.setOnDismissListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n return this;\r\n }\r\n\r\n public Builder setMax(int max){\r\n progressBar.setMax(max);\r\n return this;\r\n }\r\n\r\n public Builder setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n return this;\r\n }\r\n\r\n public ProgressBarDialog show() {\r\n return new ProgressBarDialog(dialogBuilder.show(),progressBar);\r\n }\r\n }\r\n\r\n\r\n}\r" } ]
import androidx.annotation.Nullable; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import com.opencsv.exceptions.CsvValidationException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoHistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB; import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog;
3,588
package icu.freedomintrovert.YTSendCommAntiFraud; public class VideoHistoryCommentsActivity extends HistoryCommentActivity { StatisticsDB statisticsDB; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected String getExportFileName() { return "视频历史评论记录"; } @Override protected List<? extends HistoryComment> getHistoryCommentList() { return getVideoHistoryCommentList(); }
package icu.freedomintrovert.YTSendCommAntiFraud; public class VideoHistoryCommentsActivity extends HistoryCommentActivity { StatisticsDB statisticsDB; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected String getExportFileName() { return "视频历史评论记录"; } @Override protected List<? extends HistoryComment> getHistoryCommentList() { return getVideoHistoryCommentList(); }
private List<VideoHistoryComment> getVideoHistoryCommentList() {
2
2023-10-15 01:18:28+00:00
4k
New-Barams/This-Year-Ajaja-BE
src/test/java/com/newbarams/ajaja/module/user/application/SendVerificationEmailServiceTest.java
[ { "identifier": "MonkeySupport", "path": "src/test/java/com/newbarams/ajaja/common/support/MonkeySupport.java", "snippet": "public abstract class MonkeySupport {\n\tprotected final FixtureMonkey sut = FixtureMonkey.builder()\n\t\t.objectIntrospector(new FailoverIntrospector(\n\t\t\tList.of(\n\t\t\t\tFieldReflectionArbitraryIntrospector.INSTANCE,\n\t\t\t\tConstructorPropertiesArbitraryIntrospector.INSTANCE\n\t\t\t)\n\t\t))\n\t\t.plugin(new JakartaValidationPlugin())\n\t\t.defaultNotNull(true)\n\t\t.build();\n}" }, { "identifier": "CacheUtil", "path": "src/main/java/com/newbarams/ajaja/global/cache/CacheUtil.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class CacheUtil {\n\tprivate static final long VERIFICATION_EMAIL_EXPIRE_IN = 10 * 60 * 1000L; // 10분\n\tprivate static final String DEFAULT_KEY = \"AJAJA \";\n\n\tprivate final RedisTemplate<String, Object> redisTemplate;\n\n\tpublic void saveEmailVerification(Long userId, String email, String certification) {\n\t\tredisTemplate.opsForValue().set(\n\t\t\tDEFAULT_KEY + userId,\n\t\t\tnew EmailVerification(email, certification),\n\t\t\tDuration.ofMillis(VERIFICATION_EMAIL_EXPIRE_IN)\n\t\t);\n\t}\n\n\tpublic Verification getEmailVerification(Long userId) {\n\t\tif (getSaveByDefaultKey(userId) instanceof EmailVerification verification) {\n\t\t\treturn verification;\n\t\t}\n\n\t\tthrow new AjajaException(CERTIFICATION_NOT_FOUND);\n\t}\n\n\tprivate Object getSaveByDefaultKey(Long userId) {\n\t\treturn redisTemplate.opsForValue().get(DEFAULT_KEY + userId);\n\t}\n\n\tpublic void saveRefreshToken(String key, String refreshToken, long expireIn) {\n\t\tredisTemplate.opsForValue().set(key, refreshToken, Duration.ofMillis(expireIn));\n\t}\n\n\tpublic Object getRefreshToken(String key) {\n\t\treturn redisTemplate.opsForValue().get(key);\n\t}\n\n\tpublic boolean deleteRefreshToken(String key) {\n\t\treturn Boolean.TRUE.equals(redisTemplate.delete(key));\n\t}\n}" }, { "identifier": "Verification", "path": "src/main/java/com/newbarams/ajaja/module/user/application/model/Verification.java", "snippet": "public interface Verification {\n\tString getTarget();\n\n\tString getCertification();\n}" }, { "identifier": "SendCertificationPort", "path": "src/main/java/com/newbarams/ajaja/module/user/application/port/out/SendCertificationPort.java", "snippet": "public interface SendCertificationPort {\n\t/**\n\t * Send certification to request email\n\t * @param email Where to send\n\t * @param certification Six random generated Numbers\n\t */\n\tvoid send(String email, String certification);\n}" }, { "identifier": "Email", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/Email.java", "snippet": "@Getter\npublic class Email extends SelfValidating<Email> {\n\tprivate static final String EMAIL_REGEXP = \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\";\n\n\t@Pattern(regexp = EMAIL_REGEXP)\n\tprivate final String signUpEmail;\n\n\t@Pattern(regexp = EMAIL_REGEXP)\n\tprivate final String remindEmail;\n\n\tprivate final boolean verified;\n\n\t@ConstructorProperties({\"signUpEmail\", \"remindEmail\", \"verified\"})\n\tpublic Email(String signUpEmail, String remindEmail, boolean verified) {\n\t\tthis.signUpEmail = signUpEmail;\n\t\tthis.remindEmail = remindEmail;\n\t\tthis.verified = verified;\n\t\tthis.validateSelf();\n\t}\n\n\tpublic Email(String email) {\n\t\tthis(email, email, false);\n\t}\n\n\tvoid validateVerifiable(String email) {\n\t\tif (this.verified && isSameRemindEmail(email)) {\n\t\t\tthrow new AjajaException(UNABLE_TO_VERIFY_EMAIL);\n\t\t}\n\t}\n\n\tEmail verified(String email) {\n\t\treturn isSameRemindEmail(email) ? Email.verify(signUpEmail, remindEmail) : Email.verify(signUpEmail, email);\n\t}\n\n\tprivate static Email verify(String signUpEmail, String remindEmail) {\n\t\treturn new Email(signUpEmail, remindEmail, true);\n\t}\n\n\tprivate boolean isSameRemindEmail(String email) {\n\t\treturn remindEmail.equals(email);\n\t}\n}" }, { "identifier": "User", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/User.java", "snippet": "@Getter\n@AllArgsConstructor\npublic class User {\n\tpublic enum ReceiveType {\n\t\tKAKAO, EMAIL, BOTH\n\t}\n\n\tprivate final UserId userId;\n\tprivate Nickname nickname;\n\tprivate Email email;\n\tprivate ReceiveType receiveType;\n\tprivate boolean deleted;\n\n\tpublic static User init(String email, Long oauthId) {\n\t\treturn new User(UserId.from(oauthId), Nickname.renew(), new Email(email), ReceiveType.KAKAO, false);\n\t}\n\n\tpublic void delete() {\n\t\tthis.deleted = true;\n\t}\n\n\tpublic void validateEmail(String requestEmail) {\n\t\temail.validateVerifiable(requestEmail);\n\t}\n\n\tpublic void verified(String validatedEmail) {\n\t\tthis.email = email.verified(validatedEmail);\n\t}\n\n\tpublic void updateNickname() {\n\t\tthis.nickname = Nickname.renew();\n\t}\n\n\tpublic void updateReceive(ReceiveType receiveType) {\n\t\tthis.receiveType = receiveType;\n\t}\n\n\tpublic Long getId() {\n\t\treturn userId.getId();\n\t}\n\n\tpublic Long getOauthId() {\n\t\treturn userId.getOauthId();\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email.getSignUpEmail();\n\t}\n\n\tpublic String getRemindEmail() {\n\t\treturn email.getRemindEmail();\n\t}\n\n\tpublic boolean isVerified() {\n\t\treturn email.isVerified();\n\t}\n}" } ]
import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import com.newbarams.ajaja.common.annotation.RedisBasedTest; import com.newbarams.ajaja.common.support.MonkeySupport; import com.newbarams.ajaja.global.cache.CacheUtil; import com.newbarams.ajaja.module.user.application.model.Verification; import com.newbarams.ajaja.module.user.application.port.out.SendCertificationPort; import com.newbarams.ajaja.module.user.domain.Email; import com.newbarams.ajaja.module.user.domain.User;
1,698
package com.newbarams.ajaja.module.user.application; @RedisBasedTest class SendVerificationEmailServiceTest extends MonkeySupport { @Autowired private SendVerificationEmailService sendVerificationEmailService; @Autowired private CacheUtil cacheUtil; @MockBean private SendCertificationPort sendCertificationPort; @MockBean private RetrieveUserService retrieveUserService; @Test @DisplayName("이메일 인증 메일을 전송하면 인증 전용 객체가 cache에 잘 저장되어야 한다.") void sendVerification_Success_SavedOnRedis() { // given Long userId = sut.giveMeOne(Long.class); String email = "[email protected]";
package com.newbarams.ajaja.module.user.application; @RedisBasedTest class SendVerificationEmailServiceTest extends MonkeySupport { @Autowired private SendVerificationEmailService sendVerificationEmailService; @Autowired private CacheUtil cacheUtil; @MockBean private SendCertificationPort sendCertificationPort; @MockBean private RetrieveUserService retrieveUserService; @Test @DisplayName("이메일 인증 메일을 전송하면 인증 전용 객체가 cache에 잘 저장되어야 한다.") void sendVerification_Success_SavedOnRedis() { // given Long userId = sut.giveMeOne(Long.class); String email = "[email protected]";
User user = sut.giveMeBuilder(User.class)
5
2023-10-23 07:24:17+00:00
4k
eclipse-jgit/jgit
org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/GitServlet.java
[ { "identifier": "MetaServlet", "path": "org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/glue/MetaServlet.java", "snippet": "public class MetaServlet extends HttpServlet {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate final MetaFilter filter;\n\n\t/**\n\t * Empty servlet with no bindings.\n\t */\n\tpublic MetaServlet() {\n\t\tthis(new MetaFilter());\n\t}\n\n\t/**\n\t * Initialize a servlet wrapping a filter.\n\t *\n\t * @param delegateFilter\n\t * the filter being wrapped by the servlet.\n\t */\n\tprotected MetaServlet(MetaFilter delegateFilter) {\n\t\tfilter = delegateFilter;\n\t}\n\n\t/**\n\t * Get delegate filter\n\t *\n\t * @return filter this servlet delegates all routing logic to.\n\t */\n\tprotected MetaFilter getDelegateFilter() {\n\t\treturn filter;\n\t}\n\n\t/**\n\t * Construct a binding for a specific path.\n\t *\n\t * @param path\n\t * pattern to match.\n\t * @return binder for the passed path.\n\t */\n\tpublic ServletBinder serve(String path) {\n\t\treturn filter.serve(path);\n\t}\n\n\t/**\n\t * Construct a binding for a regular expression.\n\t *\n\t * @param expression\n\t * the regular expression to pattern match the URL against.\n\t * @return binder for the passed expression.\n\t */\n\tpublic ServletBinder serveRegex(String expression) {\n\t\treturn filter.serveRegex(expression);\n\t}\n\n\t@Override\n\tpublic void init(ServletConfig config) throws ServletException {\n\t\tString name = filter.getClass().getName();\n\t\tServletContext ctx = config.getServletContext();\n\t\tfilter.init(new NoParameterFilterConfig(name, ctx));\n\t}\n\n\t@Override\n\tpublic void destroy() {\n\t\tfilter.destroy();\n\t}\n\n\t@Override\n\tprotected void service(HttpServletRequest req, HttpServletResponse res)\n\t\t\tthrows ServletException, IOException {\n\t\tfilter.doFilter(req, res,\n\t\t\t\t(ServletRequest request, ServletResponse response) -> {\n\t\t\t\t\t((HttpServletResponse) response).sendError(SC_NOT_FOUND);\n\t\t\t\t});\n\t}\n\n\t/**\n\t * Configure a newly created binder.\n\t *\n\t * @param b\n\t * the newly created binder.\n\t * @return binder for the caller, potentially after adding one or more\n\t * filters into the pipeline.\n\t */\n\tprotected ServletBinder register(ServletBinder b) {\n\t\treturn filter.register(b);\n\t}\n}" }, { "identifier": "AsIsFileService", "path": "org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/resolver/AsIsFileService.java", "snippet": "public class AsIsFileService {\n\t/** Always throws {@link ServiceNotEnabledException}. */\n\tpublic static final AsIsFileService DISABLED = new AsIsFileService() {\n\t\t@Override\n\t\tpublic void access(HttpServletRequest req, Repository db)\n\t\t\t\tthrows ServiceNotEnabledException {\n\t\t\tthrow new ServiceNotEnabledException();\n\t\t}\n\t};\n\n\tprivate static class ServiceConfig {\n\t\tfinal boolean enabled;\n\n\t\tServiceConfig(Config cfg) {\n\t\t\tenabled = cfg.getBoolean(\"http\", \"getanyfile\", true);\n\t\t}\n\t}\n\n\t/**\n\t * Determine if {@code http.getanyfile} is enabled in the configuration.\n\t *\n\t * @param db\n\t * the repository to check.\n\t * @return {@code false} if {@code http.getanyfile} was explicitly set to\n\t * {@code false} in the repository's configuration file; otherwise\n\t * {@code true}.\n\t */\n\tprotected static boolean isEnabled(Repository db) {\n\t\treturn db.getConfig().get(ServiceConfig::new).enabled;\n\t}\n\n\t/**\n\t * Determine if access to any bare file of the repository is allowed.\n\t * <p>\n\t * This method silently succeeds if the request is allowed, or fails by\n\t * throwing a checked exception if access should be denied.\n\t * <p>\n\t * The default implementation of this method checks {@code http.getanyfile},\n\t * throwing\n\t * {@link org.eclipse.jgit.transport.resolver.ServiceNotEnabledException} if\n\t * it was explicitly set to {@code false}, and otherwise succeeding\n\t * silently.\n\t *\n\t * @param req\n\t * current HTTP request, in case information from the request may\n\t * help determine the access request.\n\t * @param db\n\t * the repository the request would obtain a bare file from.\n\t * @throws ServiceNotEnabledException\n\t * bare file access is not allowed on the target repository, by\n\t * any user, for any reason.\n\t * @throws ServiceNotAuthorizedException\n\t * bare file access is not allowed for this HTTP request and\n\t * repository, such as due to a permission error.\n\t */\n\tpublic void access(HttpServletRequest req, Repository db)\n\t\t\tthrows ServiceNotEnabledException, ServiceNotAuthorizedException {\n\t\tif (!isEnabled(db))\n\t\t\tthrow new ServiceNotEnabledException();\n\t}\n}" }, { "identifier": "ReceivePackFactory", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/resolver/ReceivePackFactory.java", "snippet": "public interface ReceivePackFactory<C> {\n\t/**\n\t * A factory disabling the ReceivePack service for all repositories\n\t */\n\tReceivePackFactory<?> DISABLED = (Object req, Repository db) -> {\n\t\tthrow new ServiceNotEnabledException();\n\t};\n\n\t/**\n\t * Create and configure a new ReceivePack instance for a repository.\n\t *\n\t * @param req\n\t * current request, in case information from the request may help\n\t * configure the ReceivePack instance.\n\t * @param db\n\t * the repository the receive would write into.\n\t * @return the newly configured ReceivePack instance, must not be null.\n\t * @throws ServiceNotEnabledException\n\t * this factory refuses to create the instance because it is not\n\t * allowed on the target repository, by any user.\n\t * @throws ServiceNotAuthorizedException\n\t * this factory refuses to create the instance for this HTTP\n\t * request and repository, such as due to a permission error.\n\t */\n\tReceivePack create(C req, Repository db) throws ServiceNotEnabledException,\n\t\t\tServiceNotAuthorizedException;\n}" }, { "identifier": "RepositoryResolver", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/resolver/RepositoryResolver.java", "snippet": "public interface RepositoryResolver<C> {\n\t/**\n\t * Resolver configured to open nothing.\n\t */\n\tRepositoryResolver<?> NONE = (Object req, String name) -> {\n\t\tthrow new RepositoryNotFoundException(name);\n\t};\n\n\t/**\n\t * Locate and open a reference to a {@link Repository}.\n\t * <p>\n\t * The caller is responsible for closing the returned Repository.\n\t *\n\t * @param req\n\t * the current request, may be used to inspect session state\n\t * including cookies or user authentication.\n\t * @param name\n\t * name of the repository, as parsed out of the URL.\n\t * @return the opened repository instance, never null.\n\t * @throws RepositoryNotFoundException\n\t * the repository does not exist or the name is incorrectly\n\t * formatted as a repository name.\n\t * @throws ServiceNotAuthorizedException\n\t * the repository may exist, but HTTP access is not allowed\n\t * without authentication, i.e. this corresponds to an HTTP 401\n\t * Unauthorized.\n\t * @throws ServiceNotEnabledException\n\t * the repository may exist, but HTTP access is not allowed on the\n\t * target repository, for the current user.\n\t * @throws ServiceMayNotContinueException\n\t * the repository may exist, but HTTP access is not allowed for\n\t * the current request. The exception message contains a detailed\n\t * message that should be shown to the user.\n\t */\n\tRepository open(C req, String name) throws RepositoryNotFoundException,\n\t\t\tServiceNotAuthorizedException, ServiceNotEnabledException,\n\t\t\tServiceMayNotContinueException;\n}" }, { "identifier": "UploadPackFactory", "path": "org.eclipse.jgit/src/org/eclipse/jgit/transport/resolver/UploadPackFactory.java", "snippet": "public interface UploadPackFactory<C> {\n\t/**\n\t * A factory disabling the UploadPack service for all repositories.\n\t */\n\tUploadPackFactory<?> DISABLED = (Object req, Repository db) -> {\n\t\tthrow new ServiceNotEnabledException();\n\t};\n\n\t/**\n\t * Create and configure a new UploadPack instance for a repository.\n\t *\n\t * @param req\n\t * current request, in case information from the request may help\n\t * configure the UploadPack instance.\n\t * @param db\n\t * the repository the upload would read from.\n\t * @return the newly configured UploadPack instance, must not be null.\n\t * @throws ServiceNotEnabledException\n\t * this factory refuses to create the instance because it is not\n\t * allowed on the target repository, by any user.\n\t * @throws ServiceNotAuthorizedException\n\t * this factory refuses to create the instance for this HTTP\n\t * request and repository, such as due to a permission error.\n\t */\n\tUploadPack create(C req, Repository db) throws ServiceNotEnabledException,\n\t\t\tServiceNotAuthorizedException;\n}" } ]
import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.eclipse.jgit.http.server.glue.MetaServlet; import org.eclipse.jgit.http.server.resolver.AsIsFileService; import org.eclipse.jgit.transport.resolver.ReceivePackFactory; import org.eclipse.jgit.transport.resolver.RepositoryResolver; import org.eclipse.jgit.transport.resolver.UploadPackFactory;
3,101
/* * Copyright (C) 2009-2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.http.server; /** * Handles Git repository access over HTTP. * <p> * Applications embedding this servlet should map a directory path within the * application to this servlet, for example: * * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt;GitServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.eclipse.jgit.http.server.GitServlet&lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;base-path&lt;/param-name&gt; * &lt;param-value&gt;/var/srv/git&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;export-all&lt;/param-name&gt; * &lt;param-value&gt;0&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;GitServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/git/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * * <p> * Applications may wish to add additional repository action URLs to this * servlet by taking advantage of its extension from * {@link org.eclipse.jgit.http.server.glue.MetaServlet}. Callers may register * their own URL suffix translations through {@link #serve(String)}, or their * regex translations through {@link #serveRegex(String)}. Each translation * should contain a complete filter pipeline which ends with the HttpServlet * that should handle the requested action. */ public class GitServlet extends MetaServlet { private static final long serialVersionUID = 1L; private final GitFilter gitFilter; /** * New servlet that will load its base directory from {@code web.xml}. * <p> * The required parameter {@code base-path} must be configured to point to * the local filesystem directory where all served Git repositories reside. */ public GitServlet() { super(new GitFilter()); gitFilter = (GitFilter) getDelegateFilter(); } /** * New servlet configured with a specific resolver. * * @param resolver * the resolver to use when matching URL to Git repository. If * null the {@code base-path} parameter will be looked for in the * parameter table during init, which usually comes from the * {@code web.xml} file of the web application. */ public void setRepositoryResolver(RepositoryResolver<HttpServletRequest> resolver) { gitFilter.setRepositoryResolver(resolver); } /** * Set AsIsFileService * * @param f * the filter to validate direct access to repository files * through a dumb client. If {@code null} then dumb client * support is completely disabled. */ public void setAsIsFileService(AsIsFileService f) { gitFilter.setAsIsFileService(f); } /** * Set upload-pack factory * * @param f * the factory to construct and configure an * {@link org.eclipse.jgit.transport.UploadPack} session when a * fetch or clone is requested by a client. */
/* * Copyright (C) 2009-2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.http.server; /** * Handles Git repository access over HTTP. * <p> * Applications embedding this servlet should map a directory path within the * application to this servlet, for example: * * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt;GitServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.eclipse.jgit.http.server.GitServlet&lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;base-path&lt;/param-name&gt; * &lt;param-value&gt;/var/srv/git&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;export-all&lt;/param-name&gt; * &lt;param-value&gt;0&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;GitServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/git/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * * <p> * Applications may wish to add additional repository action URLs to this * servlet by taking advantage of its extension from * {@link org.eclipse.jgit.http.server.glue.MetaServlet}. Callers may register * their own URL suffix translations through {@link #serve(String)}, or their * regex translations through {@link #serveRegex(String)}. Each translation * should contain a complete filter pipeline which ends with the HttpServlet * that should handle the requested action. */ public class GitServlet extends MetaServlet { private static final long serialVersionUID = 1L; private final GitFilter gitFilter; /** * New servlet that will load its base directory from {@code web.xml}. * <p> * The required parameter {@code base-path} must be configured to point to * the local filesystem directory where all served Git repositories reside. */ public GitServlet() { super(new GitFilter()); gitFilter = (GitFilter) getDelegateFilter(); } /** * New servlet configured with a specific resolver. * * @param resolver * the resolver to use when matching URL to Git repository. If * null the {@code base-path} parameter will be looked for in the * parameter table during init, which usually comes from the * {@code web.xml} file of the web application. */ public void setRepositoryResolver(RepositoryResolver<HttpServletRequest> resolver) { gitFilter.setRepositoryResolver(resolver); } /** * Set AsIsFileService * * @param f * the filter to validate direct access to repository files * through a dumb client. If {@code null} then dumb client * support is completely disabled. */ public void setAsIsFileService(AsIsFileService f) { gitFilter.setAsIsFileService(f); } /** * Set upload-pack factory * * @param f * the factory to construct and configure an * {@link org.eclipse.jgit.transport.UploadPack} session when a * fetch or clone is requested by a client. */
public void setUploadPackFactory(UploadPackFactory<HttpServletRequest> f) {
4
2023-10-20 15:09:17+00:00
4k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/entity/Tortoise.java
[ { "identifier": "EggLayingAnimal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/EggLayingAnimal.java", "snippet": "public interface EggLayingAnimal {\n boolean hasEgg();\n void setHasEgg(boolean hasEgg);\n boolean isLayingEgg();\n void setLayingEgg(boolean isLayingEgg);\n int getLayEggCounter();\n void setLayEggCounter(int layEggCounter);\n Block getEggBlock();\n TagKey<Block> getEggLayableBlockTag();\n}" }, { "identifier": "HidingAnimal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/HidingAnimal.java", "snippet": "public interface HidingAnimal {\n boolean canHide();\n}" }, { "identifier": "EggLayingBreedGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/EggLayingBreedGoal.java", "snippet": "public class EggLayingBreedGoal<T extends Animal & EggLayingAnimal> extends BreedGoal {\n private final T animal;\n\n public EggLayingBreedGoal(T animal, double speedModifier) {\n super(animal, speedModifier);\n this.animal = animal;\n }\n\n @Override\n public boolean canUse() {\n return super.canUse() && !this.animal.hasEgg();\n }\n\n @Override\n protected void breed() {\n ServerPlayer serverPlayer = this.animal.getLoveCause();\n if (serverPlayer == null && this.partner.getLoveCause() != null) {\n serverPlayer = this.partner.getLoveCause();\n }\n if (serverPlayer != null) {\n serverPlayer.awardStat(Stats.ANIMALS_BRED);\n CriteriaTriggers.BRED_ANIMALS.trigger(serverPlayer, this.animal, this.partner, null);\n }\n this.animal.setHasEgg(true);\n this.animal.resetLove();\n this.partner.resetLove();\n RandomSource randomSource = this.animal.getRandom();\n if (this.level.getGameRules().getBoolean(GameRules.RULE_DOMOBLOOT)) {\n this.level.addFreshEntity(new ExperienceOrb(this.level, this.animal.getX(), this.animal.getY(), this.animal.getZ(), randomSource.nextInt(7) + 1));\n }\n }\n}" }, { "identifier": "HideGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/HideGoal.java", "snippet": "public class HideGoal<T extends Mob & HidingAnimal> extends Goal {\n private final T mob;\n\n public HideGoal(T mob) {\n this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK, Flag.JUMP));\n this.mob = mob;\n }\n\n @Override\n public boolean canUse() {\n return mob.canHide();\n }\n\n @Override\n public void start() {\n mob.setJumping(false);\n mob.getNavigation().stop();\n mob.getMoveControl().setWantedPosition(mob.getX(), mob.getY(), mob.getZ(), 0.0D);\n }\n}" }, { "identifier": "LayEggGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/LayEggGoal.java", "snippet": "public class LayEggGoal<T extends Animal & EggLayingAnimal> extends MoveToBlockGoal {\n private final T animal;\n\n public LayEggGoal(T animal, double speedModifier) {\n super(animal, speedModifier, 16);\n this.animal = animal;\n }\n\n @Override\n public boolean canUse() {\n if (this.animal.hasEgg()) {\n return super.canUse();\n }\n return false;\n }\n\n @Override\n public boolean canContinueToUse() {\n return super.canContinueToUse() && this.animal.hasEgg();\n }\n\n @Override\n public void tick() {\n super.tick();\n BlockPos blockPos = this.animal.blockPosition();\n if(this.animal instanceof TamableAnimal ta){\n if(ta.isInSittingPose()) {\n this.animal.setLayingEgg(false);\n return;\n }\n }\n if (!this.animal.isInWater() && this.isReachedTarget()) {\n if (this.animal.getLayEggCounter() < 1) {\n this.animal.setLayingEgg(true);\n } else if (this.animal.getLayEggCounter() > this.adjustedTickDelay(200)) {\n Level level = this.animal.level;\n level.playSound(null, blockPos, SoundEvents.TURTLE_LAY_EGG, SoundSource.BLOCKS, 0.3f, 0.9f + level.random.nextFloat() * 0.2f);\n level.setBlock(this.blockPos.above(), this.animal.getEggBlock().defaultBlockState().setValue(TurtleEggBlock.EGGS, this.animal.getRandom().nextInt(4) + 1), 3);\n this.animal.setHasEgg(false);\n this.animal.setLayingEgg(false);\n this.animal.setInLoveTime(600);\n }\n if (this.animal.isLayingEgg()) {\n this.animal.setLayEggCounter(this.animal.getLayEggCounter() + 1);\n }\n }\n }\n\n @Override\n protected boolean isValidTarget(LevelReader level, BlockPos pos) {\n return level.isEmptyBlock(pos.above()) && level.getBlockState(pos).is(this.animal.getEggLayableBlockTag());\n }\n}" } ]
import com.starfish_studios.naturalist.common.entity.core.EggLayingAnimal; import com.starfish_studios.naturalist.common.entity.core.HidingAnimal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.EggLayingBreedGoal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.HideGoal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.LayEggGoal; import com.starfish_studios.naturalist.core.registry.*; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.tags.BiomeTags; import net.minecraft.tags.TagKey; import net.minecraft.util.Mth; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShearsItem; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import software.bernie.geckolib3.util.GeckoLibUtil; import java.util.List;
2,560
package com.starfish_studios.naturalist.common.entity; public class Tortoise extends TamableAnimal implements IAnimatable, HidingAnimal, EggLayingAnimal { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); private static final Ingredient TEMPT_ITEMS = Ingredient.of(NaturalistTags.ItemTags.TORTOISE_TEMPT_ITEMS); private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> HAS_EGG = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Boolean> LAYING_EGG = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.BOOLEAN); int layEggCounter; boolean isDigging; public Tortoise(EntityType<? extends TamableAnimal> entityType, Level level) { super(entityType, level); } public static AttributeSupplier.Builder createAttributes() { return Mob.createMobAttributes().add(Attributes.MOVEMENT_SPEED, 0.17f).add(Attributes.MAX_HEALTH, 20.0).add(Attributes.ATTACK_DAMAGE, 2.0).add(Attributes.KNOCKBACK_RESISTANCE, 0.6); } @Nullable @Override protected SoundEvent getHurtSound(DamageSource pDamageSource) { return SoundEvents.SHIELD_BLOCK; } @Nullable @Override public AgeableMob getBreedOffspring(ServerLevel level, AgeableMob otherParent) { Tortoise tortoise = NaturalistEntityTypes.TORTOISE.get().create(level); if (otherParent instanceof Tortoise tortoiseParent) { if (this.getVariant() == tortoiseParent.getVariant()) { tortoise.setVariant(this.getVariant()); } else { tortoise.setVariant(this.random.nextBoolean() ? tortoiseParent.getVariant() : this.getVariant()); } tortoise.setOwnerUUID(this.random.nextBoolean() ? tortoiseParent.getOwnerUUID() : this.getOwnerUUID()); } return tortoise; } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor level, DifficultyInstance difficulty, MobSpawnType reason, @Nullable SpawnGroupData spawnData, @Nullable CompoundTag dataTag) { Holder<Biome> holder = level.getBiome(this.blockPosition()); if (holder.is(Biomes.SWAMP) || holder.is(Biomes.MANGROVE_SWAMP)) { this.setVariant(1); } else if (holder.is(BiomeTags.IS_JUNGLE) || holder.is(Biomes.DARK_FOREST)) { this.setVariant(2); } else { this.setVariant(0); } return super.finalizeSpawn(level, difficulty, reason, spawnData, dataTag); } @Override public void setTame(boolean tamed) { super.setTame(tamed); if (tamed) { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(30.0); this.setHealth(30.0f); } else { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(20.0); } this.getAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0); } @Override protected void registerGoals() { super.registerGoals(); this.goalSelector.addGoal(0, new FloatGoal(this));
package com.starfish_studios.naturalist.common.entity; public class Tortoise extends TamableAnimal implements IAnimatable, HidingAnimal, EggLayingAnimal { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); private static final Ingredient TEMPT_ITEMS = Ingredient.of(NaturalistTags.ItemTags.TORTOISE_TEMPT_ITEMS); private static final EntityDataAccessor<Integer> VARIANT_ID = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> HAS_EGG = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Boolean> LAYING_EGG = SynchedEntityData.defineId(Tortoise.class, EntityDataSerializers.BOOLEAN); int layEggCounter; boolean isDigging; public Tortoise(EntityType<? extends TamableAnimal> entityType, Level level) { super(entityType, level); } public static AttributeSupplier.Builder createAttributes() { return Mob.createMobAttributes().add(Attributes.MOVEMENT_SPEED, 0.17f).add(Attributes.MAX_HEALTH, 20.0).add(Attributes.ATTACK_DAMAGE, 2.0).add(Attributes.KNOCKBACK_RESISTANCE, 0.6); } @Nullable @Override protected SoundEvent getHurtSound(DamageSource pDamageSource) { return SoundEvents.SHIELD_BLOCK; } @Nullable @Override public AgeableMob getBreedOffspring(ServerLevel level, AgeableMob otherParent) { Tortoise tortoise = NaturalistEntityTypes.TORTOISE.get().create(level); if (otherParent instanceof Tortoise tortoiseParent) { if (this.getVariant() == tortoiseParent.getVariant()) { tortoise.setVariant(this.getVariant()); } else { tortoise.setVariant(this.random.nextBoolean() ? tortoiseParent.getVariant() : this.getVariant()); } tortoise.setOwnerUUID(this.random.nextBoolean() ? tortoiseParent.getOwnerUUID() : this.getOwnerUUID()); } return tortoise; } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor level, DifficultyInstance difficulty, MobSpawnType reason, @Nullable SpawnGroupData spawnData, @Nullable CompoundTag dataTag) { Holder<Biome> holder = level.getBiome(this.blockPosition()); if (holder.is(Biomes.SWAMP) || holder.is(Biomes.MANGROVE_SWAMP)) { this.setVariant(1); } else if (holder.is(BiomeTags.IS_JUNGLE) || holder.is(Biomes.DARK_FOREST)) { this.setVariant(2); } else { this.setVariant(0); } return super.finalizeSpawn(level, difficulty, reason, spawnData, dataTag); } @Override public void setTame(boolean tamed) { super.setTame(tamed); if (tamed) { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(30.0); this.setHealth(30.0f); } else { this.getAttribute(Attributes.MAX_HEALTH).setBaseValue(20.0); } this.getAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0); } @Override protected void registerGoals() { super.registerGoals(); this.goalSelector.addGoal(0, new FloatGoal(this));
this.goalSelector.addGoal(1, new EggLayingBreedGoal<>(this, 1.0));
2
2023-10-16 21:54:32+00:00
4k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/DataCollector.java
[ { "identifier": "IDc", "path": "internal/otel-dc/src/main/java/com/instana/dc/IDc.java", "snippet": "public interface IDc {\n void initOnce() throws Exception;\n Resource getResourceAttributes();\n void initDC() throws Exception;\n SdkMeterProvider getDefaultSdkMeterProvider(Resource resource, String otelBackendUrl, long callbackInterval, boolean usingHTTP, long timeout);\n\n void initMeters(OpenTelemetry openTelemetry);\n void registerMetrics();\n\n void collectData();\n void start();\n\n RawMetric getRawMetric(String name);\n Map<String, RawMetric> getRawMetricsMap();\n Map<String, Meter> getMeters();\n}" }, { "identifier": "DbDcRegistry", "path": "rdb/src/main/java/com/instana/dc/rdb/impl/DbDcRegistry.java", "snippet": "public class DbDcRegistry {\n /* Add all DataCollector implementations here:\n **/\n private final Map<String, Class<? extends AbstractDbDc>> map = new HashMap<String, Class<? extends AbstractDbDc>>() {{\n put(\"DAMENG\", DamengDc.class);\n put(\"OCEANBASE4\", Oceanbase4Dc.class);\n }};\n\n public Class<? extends AbstractDbDc> findDatabaseDc(String dbSystem) throws DcException {\n Class<? extends AbstractDbDc> cls = map.get(dbSystem.toUpperCase());\n if (cls != null) {\n return cls;\n } else {\n throw new DcException(\"Unsupported DB system: \" + dbSystem);\n }\n }\n}" }, { "identifier": "DcUtil", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet": "public class DcUtil {\n private static final Logger logger = Logger.getLogger(DcUtil.class.getName());\n\n /* Configurations for the Data Collector:\n */\n public final static String POLLING_INTERVAL = \"poll.interval\";\n public static final int DEFAULT_POLL_INTERVAL = 30; //unit is second, read database\n public final static String CALLBACK_INTERVAL = \"callback.interval\";\n public static final int DEFAULT_CALLBACK_INTERVAL = 60; //unit is second, send to backend\n public final static String OTEL_BACKEND_URL = \"otel.backend.url\";\n public final static String OTEL_BACKEND_USING_HTTP = \"otel.backend.using.http\";\n public final static String DEFAULT_OTEL_BACKEND_URL = \"http://127.0.0.1:4317\";\n public final static String OTEL_SERVICE_NAME = \"otel.service.name\";\n public final static String DEFAULT_OTEL_SERVICE_NAME = \"odcd.default.service\";\n public final static String OTEL_SERVICE_INSTANCE_ID = \"otel.service.instance.id\";\n public final static String DEFAULT_OTEL_SERVICE_INSTANCE_ID = \"odcd.default.id\";\n\n //Standard environment variables;\n public static final String OTEL_RESOURCE_ATTRIBUTES = \"OTEL_RESOURCE_ATTRIBUTES\";\n\n //Configuration files;\n public static final String LOGGING_PROP = \"config/logging.properties\";\n public static final String CONFIG_YAML = \"config/config.yaml\";\n public static final String CONFIG_ENV = \"DC_CONFIG\";\n public static final String INSTANA_PLUGIN = \"INSTANA_PLUGIN\";\n\n\n /* Data Collector Utilities:\n */\n public static Resource mergeResourceAttributesFromEnv(Resource resource) {\n String resAttrs = System.getenv(OTEL_RESOURCE_ATTRIBUTES);\n if (resAttrs != null) {\n for (String resAttr : resAttrs.split(\",\")) {\n String[] kv = resAttr.split(\"=\");\n if (kv.length != 2)\n continue;\n String key = kv[0].trim();\n String value = kv[1].trim();\n resource = resource.merge(Resource.create(Attributes.of(AttributeKey.stringKey(key), value)));\n }\n }\n return resource;\n }\n\n public static void _registerMeterWithLongMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicLong data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static void _registerMeterWithDoubleMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicDouble data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static Attributes convertMapToAttributes(Map<String, Object> map) {\n AttributesBuilder builder = Attributes.builder();\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n if (value instanceof Long) {\n builder.put(key, (Long) value);\n } else if (value instanceof Double) {\n builder.put(key, (Double) value);\n } else if (value instanceof Boolean) {\n builder.put(key, (Boolean) value);\n } else {\n builder.put(key, value.toString());\n }\n }\n return builder.build();\n }\n\n public static void registerMetric(Map<String, Meter> meters, RawMetric rawMetric) {\n Consumer<ObservableLongMeasurement> recordLongMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Long value = dp.getLongValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n Consumer<ObservableDoubleMeasurement> recordDoubleMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Double value = dp.getDoubleValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n\n Meter meter = meters.get(rawMetric.getMeterName());\n switch (rawMetric.getInstrumentType()) {\n case GAUGE:\n if (rawMetric.isInteger())\n meter.gaugeBuilder(rawMetric.getName()).ofLongs().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.gaugeBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case COUNTER:\n if (rawMetric.isInteger())\n meter.counterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.counterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case UPDOWN_COUNTER:\n if (rawMetric.isInteger())\n meter.upDownCounterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.upDownCounterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", rawMetric.getInstrumentType());\n }\n }\n\n public static long getPid() {\n // While this is not strictly defined, almost all commonly used JVMs format this as\n // pid@hostname.\n String runtimeName = ManagementFactory.getRuntimeMXBean().getName();\n int atIndex = runtimeName.indexOf('@');\n if (atIndex >= 0) {\n String pidString = runtimeName.substring(0, atIndex);\n try {\n return Long.parseLong(pidString);\n } catch (NumberFormatException ignored) {\n // Ignore parse failure.\n }\n }\n return -1;\n }\n\n public static String base64Decode(String encodedStr) {\n return new String(Base64.getDecoder().decode(encodedStr));\n }\n}" } ]
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.instana.dc.IDc; import com.instana.dc.rdb.impl.DbDcRegistry; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.dc.DcUtil.*;
2,574
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public class DataCollector { static { System.setProperty("java.util.logging.config.file", LOGGING_PROP); } private static final Logger logger = Logger.getLogger(DataCollector.class.getName()); private final DcConfig dcConfig; private final List<IDc> dcs; private DataCollector() throws Exception { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); String configFile = System.getenv(CONFIG_ENV); if (configFile == null) { configFile = CONFIG_YAML; } dcConfig = objectMapper.readValue(new File(configFile), DcConfig.class); int n = dcConfig.getInstances().size(); dcs = new ArrayList<>(n); for (Map<String, String> props : dcConfig.getInstances()) { dcs.add(newDc(props)); } if (!dcs.isEmpty()) { dcs.get(0).initOnce(); } } private IDc newDc(Map<String, String> props) throws Exception {
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public class DataCollector { static { System.setProperty("java.util.logging.config.file", LOGGING_PROP); } private static final Logger logger = Logger.getLogger(DataCollector.class.getName()); private final DcConfig dcConfig; private final List<IDc> dcs; private DataCollector() throws Exception { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); String configFile = System.getenv(CONFIG_ENV); if (configFile == null) { configFile = CONFIG_YAML; } dcConfig = objectMapper.readValue(new File(configFile), DcConfig.class); int n = dcConfig.getInstances().size(); dcs = new ArrayList<>(n); for (Map<String, String> props : dcConfig.getInstances()) { dcs.add(newDc(props)); } if (!dcs.isEmpty()) { dcs.get(0).initOnce(); } } private IDc newDc(Map<String, String> props) throws Exception {
return new DbDcRegistry().findDatabaseDc(dcConfig.getDbSystem()).getConstructor(Map.class, String.class, String.class)
1
2023-10-23 01:16:38+00:00
4k
quarkiverse/quarkus-antivirus
deployment/src/main/java/io/quarkiverse/antivirus/deployment/AntivirusProcessor.java
[ { "identifier": "Antivirus", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/Antivirus.java", "snippet": "@ApplicationScoped\n@JBossLog\npublic class Antivirus {\n\n @Inject\n private Instance<AntivirusEngine> engineInstances;\n\n /**\n * Perform virus scan and throw exception if a virus has been detected.\n *\n * @param filename the name of the file to scan\n * @param inputStream the inputStream containing the file contents\n * @return the List of all {@link AntivirusScanResult} from all engines\n */\n @SneakyThrows\n public List<AntivirusScanResult> scan(final String filename, final InputStream inputStream) {\n final List<AntivirusScanResult> results = new ArrayList<>();\n for (AntivirusEngine plugin : engineInstances) {\n if (plugin.isEnabled()) {\n final AntivirusScanResult result = plugin.scan(filename, inputStream);\n results.add(result);\n // reset the stream for the next scan\n inputStream.reset();\n }\n }\n\n // let user know nothing happened meaning they had all engines disabled\n if (results.isEmpty()) {\n log.warn(\"Antivirus extension found NO scanning engines to execute!\");\n }\n return results;\n }\n}" }, { "identifier": "ClamAVEngine", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/ClamAVEngine.java", "snippet": "@ApplicationScoped\n@JBossLog\npublic class ClamAVEngine implements AntivirusEngine {\n private ClamAVClient client;\n @Inject\n ClamAVRuntimeConfig config;\n\n @Override\n public boolean isEnabled() {\n return config.enabled();\n }\n\n /**\n * Scans an {@link InputStream} for any viruses. If any virus is detected an exception will be thrown.\n *\n * @param filename the name of the file to be scanned\n * @param inputStream the {@link InputStream} of the file to scan\n * @return the {@link AntivirusScanResult} containing the results\n */\n @Override\n public AntivirusScanResult scan(final String filename, final InputStream inputStream) {\n AntivirusScanResult.AntivirusScanResultBuilder result = AntivirusScanResult.builder().engine(\"ClamAV\")\n .fileName(filename);\n if (!config.enabled()) {\n return result.status(404).message(\"ClamAV scanner is currently disabled!\").build();\n }\n log.infof(\"Starting the virus scan for file: %s\", filename);\n\n try {\n final ClamAVClient client = getClamAVClient();\n final byte[] reply = client.scan(inputStream);\n final String message = new String(reply, StandardCharsets.US_ASCII).trim();\n log.infof(\"Scanner replied with message: %s\", message);\n if (!ClamAVClient.isCleanReply(reply)) {\n final String error = String.format(\"Scan detected viruses in file '%s'! Virus scanner message = %s\",\n filename, message);\n log.errorf(\"ClamAV %s\", error);\n return result.status(400).message(error).payload(message).build();\n }\n return result.status(200).message(message).payload(message).build();\n } catch (final RuntimeException | IOException ex) {\n final String error = String.format(\"Unexpected error scanning file '%s' - %s\",\n filename, ex.getMessage());\n return result.status(400).message(error).payload(ex.getMessage()).build();\n } finally {\n log.infof(\"Finished scanning file %s!\", filename);\n }\n }\n\n /**\n * Ping the clamd service to make sure it is available.\n *\n * @return true if clamd is available false if not.\n */\n public boolean ping() {\n if (!config.enabled()) {\n return false;\n }\n try {\n return getClamAVClient().ping();\n } catch (final RuntimeException | IOException ex) {\n return false;\n }\n }\n\n /**\n * Returns a new ClamAvClient which can be overridden in unit tests.\n *\n * @return the {@link ClamAVClient}\n */\n ClamAVClient getClamAVClient() {\n if (client != null) {\n return client;\n }\n client = new ClamAVClient(this.config);\n return client;\n }\n}" }, { "identifier": "ClamAVHealthCheck", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/ClamAVHealthCheck.java", "snippet": "@Readiness\n@ApplicationScoped\npublic class ClamAVHealthCheck implements HealthCheck {\n\n @Inject\n ClamAVEngine engine;\n @Inject\n ClamAVRuntimeConfig config;\n\n @Override\n public HealthCheckResponse call() {\n final String server = String.format(\"%s:%s\", config.host(), config.port());\n HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named(\"ClamAV Daemon\");\n responseBuilder = engine.ping() ? responseBuilder.up().withData(server, \"UP\")\n : responseBuilder.down().withData(server, \"DOWN\");\n return responseBuilder.build();\n }\n}" }, { "identifier": "VirusTotalEngine", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/VirusTotalEngine.java", "snippet": "@ApplicationScoped\n@JBossLog\npublic class VirusTotalEngine implements AntivirusEngine {\n\n @Inject\n VirusTotalRuntimeConfig config;\n\n @Override\n public boolean isEnabled() {\n return config.enabled() && config.key().isPresent();\n }\n\n @Override\n public AntivirusScanResult scan(String filename, InputStream inputStream) {\n AntivirusScanResult.AntivirusScanResultBuilder result = AntivirusScanResult.builder().engine(\"VirusTotal\")\n .fileName(filename);\n if (!config.enabled()) {\n return result.status(404).message(\"VirusTotal scanner is currently disabled!\").build();\n }\n log.infof(\"Starting the virus scan for file: %s\", filename);\n try {\n String message;\n HttpURLConnection connection = openConnection(filename, inputStream);\n int code = connection.getResponseCode();\n result.status(code);\n switch (code) {\n case 200:\n result.message(\"OK\");\n break;\n case 204:\n message = \"Virus Total Request rate limit exceeded. You are making more requests than allowed. \"\n + \"You have exceeded one of your quotas (minute, daily or monthly). Daily quotas are reset every day at 00:00 UTC.\";\n return result.message(message).build();\n case 400:\n message = \"Bad request. Your request was somehow incorrect. \"\n + \"This can be caused by missing arguments or arguments with wrong values.\";\n return result.message(message).build();\n case 403:\n message = \"Forbidden. You don't have enough privileges to make the request. \"\n + \"You may be doing a request without providing an API key or you may be making a request \"\n + \"to a Private API without having the appropriate privileges.\";\n return result.message(message).build();\n case 404:\n message = \"Not Found. This file has never been scanned by VirusTotal before.\";\n return result.message(message).build();\n default:\n message = \"Unexpected HTTP code \" + code + \" calling Virus Total web service.\";\n return result.message(message).build();\n }\n\n try (InputStream response = connection.getInputStream()) {\n final String payload = convertInputStreamToString(response);\n result.payload(payload);\n final JsonObject json = new JsonObject(payload);\n return handleBodyResponse(filename, json, result);\n }\n } catch (IOException ex) {\n log.warn(\"Cannot perform virus scan\");\n return result.status(400).message(\"Cannot perform virus scan\").payload(ex.getMessage()).build();\n }\n }\n\n private AntivirusScanResult handleBodyResponse(String filename, JsonObject json,\n AntivirusScanResult.AntivirusScanResultBuilder result) {\n JsonObject data = json.getJsonObject(\"data\");\n if (data == null) {\n return result.status(200).build();\n }\n JsonObject attributes = data.getJsonObject(\"attributes\");\n if (attributes == null) {\n return result.status(200).build();\n }\n JsonObject totalVotes = attributes.getJsonObject(\"total_votes\");\n if (totalVotes == null) {\n return result.status(200).build();\n }\n int votes = totalVotes.getInteger(\"malicious\", 0);\n if (votes >= config.minimumVotes()) {\n String name = attributes.getString(\"meaningful_name\");\n log.debugf(String.format(\"Retrieved %s meaningful name.\", name));\n if (name != null && !name.isEmpty()) {\n final String error = String.format(\"Scan detected virus '%s' in file '%s'!\", name, filename);\n return result.status(400).message(error).build();\n }\n }\n return result.status(200).build();\n }\n\n protected HttpURLConnection openConnection(String filename, InputStream inputStream) throws IOException {\n HttpURLConnection connection;\n try {\n String key = config.key().orElseThrow(RuntimeException::new);\n String hash = md5Hex(filename, convertInputStreamToByteArray(inputStream));\n log.debugf(\"File Hash = %s\", hash);\n URL url = new URL(String.format(config.url(), hash));\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestProperty(\"x-apikey\", key);\n connection.setRequestMethod(\"GET\");\n connection.connect();\n } catch (IOException e) {\n throw new AntivirusException(filename, e.getMessage(), e);\n }\n\n return connection;\n }\n\n protected String convertInputStreamToString(InputStream inputStream) throws IOException {\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder stringBuilder = new StringBuilder();\n String line;\n\n while ((line = reader.readLine()) != null) {\n stringBuilder.append(line);\n }\n\n return stringBuilder.toString();\n }\n\n protected byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int bytesRead;\n\n while ((bytesRead = inputStream.read(buffer)) != -1) {\n byteArrayOutputStream.write(buffer, 0, bytesRead);\n }\n\n return byteArrayOutputStream.toByteArray();\n }\n\n protected String md5Hex(String filename, byte[] bytes) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(bytes);\n return DatatypeConverter.printHexBinary(md.digest());\n } catch (NoSuchAlgorithmException e) {\n throw new AntivirusException(filename, e.getMessage());\n }\n }\n}" } ]
import io.quarkiverse.antivirus.runtime.Antivirus; import io.quarkiverse.antivirus.runtime.ClamAVEngine; import io.quarkiverse.antivirus.runtime.ClamAVHealthCheck; import io.quarkiverse.antivirus.runtime.VirusTotalEngine; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.FeatureBuildItem;
2,698
package io.quarkiverse.antivirus.deployment; /** * Main processor for the Antivirus extension. */ class AntivirusProcessor { private static final String FEATURE = "antivirus"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans, ClamAVBuildConfig buildConfig) { beans.produce(AdditionalBeanBuildItem.builder().setUnremovable() .addBeanClasses(ClamAVEngine.class) .addBeanClasses(VirusTotalEngine.class)
package io.quarkiverse.antivirus.deployment; /** * Main processor for the Antivirus extension. */ class AntivirusProcessor { private static final String FEATURE = "antivirus"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans, ClamAVBuildConfig buildConfig) { beans.produce(AdditionalBeanBuildItem.builder().setUnremovable() .addBeanClasses(ClamAVEngine.class) .addBeanClasses(VirusTotalEngine.class)
.addBeanClasses(Antivirus.class)
0
2023-10-22 22:33:05+00:00
4k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/ios/FixupChains.java
[ { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}" }, { "identifier": "Symbol", "path": "unidbg-api/src/main/java/com/github/unidbg/Symbol.java", "snippet": "public abstract class Symbol {\n\n private final String name;\n\n public Symbol(String name) {\n this.name = name;\n }\n\n public abstract Number call(Emulator<?> emulator, Object... args);\n\n public abstract long getAddress();\n\n public abstract long getValue();\n\n public abstract boolean isUndef();\n\n public final UnidbgPointer createNameMemory(SvcMemory svcMemory) {\n return svcMemory.allocateSymbolName(name);\n }\n\n public Pointer createPointer(Emulator<?> emulator) {\n return UnidbgPointer.pointer(emulator, getAddress());\n }\n\n public String getName() {\n return name;\n }\n\n public abstract String getModuleName();\n\n @Override\n public String toString() {\n return name;\n }\n}" }, { "identifier": "HookListener", "path": "unidbg-api/src/main/java/com/github/unidbg/hook/HookListener.java", "snippet": "public interface HookListener {\n\n int EACH_BIND = -1;\n int WEAK_BIND = -2;\n int FIXUP_BIND = -3;\n\n /**\n * 返回0表示没有hook,否则返回hook以后的调用地址\n */\n long hook(SvcMemory svcMemory, String libraryName, String symbolName, long old);\n\n}" } ]
import com.github.unidbg.Emulator; import com.github.unidbg.Symbol; import com.github.unidbg.hook.HookListener; import com.sun.jna.Pointer; import io.kaitai.struct.ByteBufferKaitaiStream; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.nio.charset.StandardCharsets; import java.util.List;
3,079
static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8; static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) { return (addLHS > b) || (addRHS > (b-addLHS)); } private static long signExtendedAddend(long addend) { long top8Bits = addend & 0x00007f80000L; long bottom19Bits = addend & 0x0000007ffffL; return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL); } static void handleChain(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, int pointer_format, Pointer chain, long raw64, List<BindTarget> bindTargets, ByteBufferKaitaiStream symbolsPool) { switch (pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: { long dyld_chained_ptr_arm64e_auth_bind = chain.getLong(8); long dyld_chained_ptr_arm64e_rebase = chain.getLong(16); long dyld_chained_ptr_arm64e_bind = chain.getLong(24); long dyld_chained_ptr_arm64e_bind24 = chain.getLong(32); long dyld_chained_ptr_arm64e_auth_bind24 = chain.getLong(40); boolean authRebase_auth = (raw64 >>> 63) != 0; long newValue = -1; if (authRebase_auth) { boolean authBind_bind = (dyld_chained_ptr_arm64e_auth_bind >>> 62) != 0; if (authBind_bind) { int authBind24_ordinal = (int) (dyld_chained_ptr_arm64e_auth_bind24 & 0xffffff); int authBind_ordinal = (int) (dyld_chained_ptr_arm64e_auth_bind & 0xffff); int bindOrdinal = (pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? authBind24_ordinal : authBind_ordinal; if ( bindOrdinal >= bindTargets.size() ) { log.warn(String.format("out of range bind ordinal %d (max %d): pointer_format=%d", bindOrdinal, bindTargets.size(), pointer_format)); break; } else { // authenticated bind /*BindTarget bindTarget = bindTargets.get(bindOrdinal); newValue = (void*)(bindTargets[bindOrdinal]); if (newValue != 0) // Don't sign missing weak imports newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue);*/ log.warn("Unsupported authenticated bind: bindOrdinal=" + bindOrdinal); break; } } else { log.warn("Unsupported authenticated rebase"); break; } } else { boolean bind_bind = (dyld_chained_ptr_arm64e_bind >>> 62) != 0; if (bind_bind) { int bind24_ordinal = (int) (dyld_chained_ptr_arm64e_bind24 & 0xffffff); int bind_ordinal = (int) (dyld_chained_ptr_arm64e_bind & 0xffff); int bindOrdinal = (pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? bind24_ordinal : bind_ordinal; if (bindOrdinal >= bindTargets.size()) { log.warn(String.format("out of range bind ordinal %d (max %d): pointer_format=%d", bindOrdinal, bindTargets.size(), pointer_format)); break; } else { BindTarget bindTarget = bindTargets.get(bindOrdinal); long addend19 = (dyld_chained_ptr_arm64e_bind >>> 32) & 0x7ffff; if ((addend19 & 0x40000) != 0) { addend19 |= 0xfffffffffffc0000L; } newValue = bindTarget.bind(emulator, mm, hookListeners, symbolsPool) + addend19; chain.setLong(0, newValue); break; } } else { if (pointer_format == DYLD_CHAINED_PTR_ARM64E) { long target = dyld_chained_ptr_arm64e_rebase & 0xfffffffffL; long high8 = (dyld_chained_ptr_arm64e_rebase >>> 36) & 0xff; // plain rebase (old format target is vmaddr, new format target is offset) long unpackedTarget = (high8 << 56) | target; chain.setLong(0, unpackedTarget); break; } else { log.warn("Unsupported DYLD_CHAINED_PTR_ARM64E"); } } } throw new UnsupportedOperationException("DYLD_CHAINED_PTR_ARM64E dyld_chained_ptr_arm64e_auth_rebase=0x" + Long.toHexString(raw64) + ", dyld_chained_ptr_arm64e_auth_bind=0x" + Long.toHexString(dyld_chained_ptr_arm64e_auth_bind) + ", newValue=0x" + Long.toHexString(newValue)); } case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: long newValue; boolean bind = (raw64 >>> 63) != 0; if (bind) { int ordinal = (int) (raw64 & 0xffffff); long addend = (raw64 >>> 24) & 0xff; if (ordinal >= bindTargets.size()) { throw new IllegalStateException(String.format("out of range bind ordinal %d (max %d)", ordinal, bindTargets.size())); } else { BindTarget bindTarget = bindTargets.get(ordinal); newValue = bindTarget.bind(emulator, mm, hookListeners, symbolsPool) + signExtendedAddend(addend); chain.setLong(0, newValue); } } else { long target = raw64 & 0xfffffffffL; long high8 = (raw64 >>> 36) & 0xff; // plain rebase (old format target is vmaddr, new format target is offset) long unpackedTarget = (high8 << 56) | target; if (pointer_format == DYLD_CHAINED_PTR_64) { chain.setLong(0, unpackedTarget); } else { throw new UnsupportedOperationException("DYLD_CHAINED_PTR_64_OFFSET"); } } break; default: throw new UnsupportedOperationException("pointer_format=" + pointer_format); } } static abstract class BindTarget implements MachO { protected abstract long bind(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, ByteBufferKaitaiStream symbolsPool);
package com.github.unidbg.ios; final class FixupChains { private static final Log log = LogFactory.getLog(FixupChains.class); // values for dyld_chained_fixups_header.imports_format static final int DYLD_CHAINED_IMPORT = 1; static final int DYLD_CHAINED_IMPORT_ADDEND = 2; static final int DYLD_CHAINED_IMPORT_ADDEND64 = 3; static final int DYLD_CHAINED_PTR_START_NONE = 0xffff; // used in page_start[] to denote a page with no fixups static final int DYLD_CHAINED_PTR_START_MULTI = 0x8000; // used in page_start[] to denote a page which has multiple starts static final int DYLD_CHAINED_PTR_START_LAST = 0x8000; // used in chain_starts[] to denote last start in list for page // values for dyld_chained_starts_in_segment.pointer_format static final int DYLD_CHAINED_PTR_ARM64E = 1; // stride 8, unauth target is vmaddr static final int DYLD_CHAINED_PTR_64 = 2; // target is vmaddr static final int DYLD_CHAINED_PTR_32 = 3; static final int DYLD_CHAINED_PTR_32_CACHE = 4; static final int DYLD_CHAINED_PTR_32_FIRMWARE = 5; static final int DYLD_CHAINED_PTR_64_OFFSET = 6; // target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_OFFSET = 7; // stride 4, unauth target is vm offset static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8; static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) { return (addLHS > b) || (addRHS > (b-addLHS)); } private static long signExtendedAddend(long addend) { long top8Bits = addend & 0x00007f80000L; long bottom19Bits = addend & 0x0000007ffffL; return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL); } static void handleChain(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, int pointer_format, Pointer chain, long raw64, List<BindTarget> bindTargets, ByteBufferKaitaiStream symbolsPool) { switch (pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: { long dyld_chained_ptr_arm64e_auth_bind = chain.getLong(8); long dyld_chained_ptr_arm64e_rebase = chain.getLong(16); long dyld_chained_ptr_arm64e_bind = chain.getLong(24); long dyld_chained_ptr_arm64e_bind24 = chain.getLong(32); long dyld_chained_ptr_arm64e_auth_bind24 = chain.getLong(40); boolean authRebase_auth = (raw64 >>> 63) != 0; long newValue = -1; if (authRebase_auth) { boolean authBind_bind = (dyld_chained_ptr_arm64e_auth_bind >>> 62) != 0; if (authBind_bind) { int authBind24_ordinal = (int) (dyld_chained_ptr_arm64e_auth_bind24 & 0xffffff); int authBind_ordinal = (int) (dyld_chained_ptr_arm64e_auth_bind & 0xffff); int bindOrdinal = (pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? authBind24_ordinal : authBind_ordinal; if ( bindOrdinal >= bindTargets.size() ) { log.warn(String.format("out of range bind ordinal %d (max %d): pointer_format=%d", bindOrdinal, bindTargets.size(), pointer_format)); break; } else { // authenticated bind /*BindTarget bindTarget = bindTargets.get(bindOrdinal); newValue = (void*)(bindTargets[bindOrdinal]); if (newValue != 0) // Don't sign missing weak imports newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue);*/ log.warn("Unsupported authenticated bind: bindOrdinal=" + bindOrdinal); break; } } else { log.warn("Unsupported authenticated rebase"); break; } } else { boolean bind_bind = (dyld_chained_ptr_arm64e_bind >>> 62) != 0; if (bind_bind) { int bind24_ordinal = (int) (dyld_chained_ptr_arm64e_bind24 & 0xffffff); int bind_ordinal = (int) (dyld_chained_ptr_arm64e_bind & 0xffff); int bindOrdinal = (pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? bind24_ordinal : bind_ordinal; if (bindOrdinal >= bindTargets.size()) { log.warn(String.format("out of range bind ordinal %d (max %d): pointer_format=%d", bindOrdinal, bindTargets.size(), pointer_format)); break; } else { BindTarget bindTarget = bindTargets.get(bindOrdinal); long addend19 = (dyld_chained_ptr_arm64e_bind >>> 32) & 0x7ffff; if ((addend19 & 0x40000) != 0) { addend19 |= 0xfffffffffffc0000L; } newValue = bindTarget.bind(emulator, mm, hookListeners, symbolsPool) + addend19; chain.setLong(0, newValue); break; } } else { if (pointer_format == DYLD_CHAINED_PTR_ARM64E) { long target = dyld_chained_ptr_arm64e_rebase & 0xfffffffffL; long high8 = (dyld_chained_ptr_arm64e_rebase >>> 36) & 0xff; // plain rebase (old format target is vmaddr, new format target is offset) long unpackedTarget = (high8 << 56) | target; chain.setLong(0, unpackedTarget); break; } else { log.warn("Unsupported DYLD_CHAINED_PTR_ARM64E"); } } } throw new UnsupportedOperationException("DYLD_CHAINED_PTR_ARM64E dyld_chained_ptr_arm64e_auth_rebase=0x" + Long.toHexString(raw64) + ", dyld_chained_ptr_arm64e_auth_bind=0x" + Long.toHexString(dyld_chained_ptr_arm64e_auth_bind) + ", newValue=0x" + Long.toHexString(newValue)); } case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: long newValue; boolean bind = (raw64 >>> 63) != 0; if (bind) { int ordinal = (int) (raw64 & 0xffffff); long addend = (raw64 >>> 24) & 0xff; if (ordinal >= bindTargets.size()) { throw new IllegalStateException(String.format("out of range bind ordinal %d (max %d)", ordinal, bindTargets.size())); } else { BindTarget bindTarget = bindTargets.get(ordinal); newValue = bindTarget.bind(emulator, mm, hookListeners, symbolsPool) + signExtendedAddend(addend); chain.setLong(0, newValue); } } else { long target = raw64 & 0xfffffffffL; long high8 = (raw64 >>> 36) & 0xff; // plain rebase (old format target is vmaddr, new format target is offset) long unpackedTarget = (high8 << 56) | target; if (pointer_format == DYLD_CHAINED_PTR_64) { chain.setLong(0, unpackedTarget); } else { throw new UnsupportedOperationException("DYLD_CHAINED_PTR_64_OFFSET"); } } break; default: throw new UnsupportedOperationException("pointer_format=" + pointer_format); } } static abstract class BindTarget implements MachO { protected abstract long bind(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, ByteBufferKaitaiStream symbolsPool);
final Symbol resolveSymbol(MachOLoader loader, MachOModule mm, int libraryOrdinal, String symbolName, boolean weak) {
1
2023-10-17 06:13:28+00:00
4k
robaho/httpserver
src/test/java/robaho/net/httpserver/websockets/WebSocketResponseHandlerTest.java
[ { "identifier": "Code", "path": "src/main/java/robaho/net/httpserver/Code.java", "snippet": "public class Code {\n\n public static final int HTTP_CONTINUE = 100;\n public static final int HTTP_OK = 200;\n public static final int HTTP_CREATED = 201;\n public static final int HTTP_ACCEPTED = 202;\n public static final int HTTP_NOT_AUTHORITATIVE = 203;\n public static final int HTTP_NO_CONTENT = 204;\n public static final int HTTP_RESET = 205;\n public static final int HTTP_PARTIAL = 206;\n public static final int HTTP_MULT_CHOICE = 300;\n public static final int HTTP_MOVED_PERM = 301;\n public static final int HTTP_MOVED_TEMP = 302;\n public static final int HTTP_SEE_OTHER = 303;\n public static final int HTTP_NOT_MODIFIED = 304;\n public static final int HTTP_USE_PROXY = 305;\n public static final int HTTP_BAD_REQUEST = 400;\n public static final int HTTP_UNAUTHORIZED = 401;\n public static final int HTTP_PAYMENT_REQUIRED = 402;\n public static final int HTTP_FORBIDDEN = 403;\n public static final int HTTP_NOT_FOUND = 404;\n public static final int HTTP_BAD_METHOD = 405;\n public static final int HTTP_NOT_ACCEPTABLE = 406;\n public static final int HTTP_PROXY_AUTH = 407;\n public static final int HTTP_CLIENT_TIMEOUT = 408;\n public static final int HTTP_CONFLICT = 409;\n public static final int HTTP_GONE = 410;\n public static final int HTTP_LENGTH_REQUIRED = 411;\n public static final int HTTP_PRECON_FAILED = 412;\n public static final int HTTP_ENTITY_TOO_LARGE = 413;\n public static final int HTTP_REQ_TOO_LONG = 414;\n public static final int HTTP_UNSUPPORTED_TYPE = 415;\n public static final int HTTP_INTERNAL_ERROR = 500;\n public static final int HTTP_NOT_IMPLEMENTED = 501;\n public static final int HTTP_BAD_GATEWAY = 502;\n public static final int HTTP_UNAVAILABLE = 503;\n public static final int HTTP_GATEWAY_TIMEOUT = 504;\n public static final int HTTP_VERSION = 505;\n\n static String msg(int code) {\n\n switch (code) {\n case HTTP_OK:\n return \" OK\";\n case HTTP_CONTINUE:\n return \" Continue\";\n case HTTP_CREATED:\n return \" Created\";\n case HTTP_ACCEPTED:\n return \" Accepted\";\n case HTTP_NOT_AUTHORITATIVE:\n return \" Non-Authoritative Information\";\n case HTTP_NO_CONTENT:\n return \" No Content\";\n case HTTP_RESET:\n return \" Reset Content\";\n case HTTP_PARTIAL:\n return \" Partial Content\";\n case HTTP_MULT_CHOICE:\n return \" Multiple Choices\";\n case HTTP_MOVED_PERM:\n return \" Moved Permanently\";\n case HTTP_MOVED_TEMP:\n return \" Temporary Redirect\";\n case HTTP_SEE_OTHER:\n return \" See Other\";\n case HTTP_NOT_MODIFIED:\n return \" Not Modified\";\n case HTTP_USE_PROXY:\n return \" Use Proxy\";\n case HTTP_BAD_REQUEST:\n return \" Bad Request\";\n case HTTP_UNAUTHORIZED:\n return \" Unauthorized\";\n case HTTP_PAYMENT_REQUIRED:\n return \" Payment Required\";\n case HTTP_FORBIDDEN:\n return \" Forbidden\";\n case HTTP_NOT_FOUND:\n return \" Not Found\";\n case HTTP_BAD_METHOD:\n return \" Method Not Allowed\";\n case HTTP_NOT_ACCEPTABLE:\n return \" Not Acceptable\";\n case HTTP_PROXY_AUTH:\n return \" Proxy Authentication Required\";\n case HTTP_CLIENT_TIMEOUT:\n return \" Request Time-Out\";\n case HTTP_CONFLICT:\n return \" Conflict\";\n case HTTP_GONE:\n return \" Gone\";\n case HTTP_LENGTH_REQUIRED:\n return \" Length Required\";\n case HTTP_PRECON_FAILED:\n return \" Precondition Failed\";\n case HTTP_ENTITY_TOO_LARGE:\n return \" Request Entity Too Large\";\n case HTTP_REQ_TOO_LONG:\n return \" Request-URI Too Large\";\n case HTTP_UNSUPPORTED_TYPE:\n return \" Unsupported Media Type\";\n case HTTP_INTERNAL_ERROR:\n return \" Internal Server Error\";\n case HTTP_NOT_IMPLEMENTED:\n return \" Not Implemented\";\n case HTTP_BAD_GATEWAY:\n return \" Bad Gateway\";\n case HTTP_UNAVAILABLE:\n return \" Service Unavailable\";\n case HTTP_GATEWAY_TIMEOUT:\n return \" Gateway Timeout\";\n case HTTP_VERSION:\n return \" HTTP Version Not Supported\";\n default:\n return \" \";\n }\n }\n}" }, { "identifier": "StubHttpExchange", "path": "src/test/java/robaho/net/httpserver/StubHttpExchange.java", "snippet": "public class StubHttpExchange extends HttpExchange {\n @Override\n public Headers getRequestHeaders() {\n return null;\n }\n\n @Override\n public Headers getResponseHeaders() {\n return null;\n }\n\n @Override\n public URI getRequestURI() {\n return null;\n }\n\n @Override\n public String getRequestMethod() {\n return null;\n }\n\n @Override\n public HttpContext getHttpContext() {\n return null;\n }\n\n @Override\n public void close() {\n }\n\n @Override\n public InputStream getRequestBody() {\n return null;\n }\n\n @Override\n public OutputStream getResponseBody() {\n return null;\n }\n\n @Override\n public void sendResponseHeaders(int rCode, long responseLength) {\n }\n\n @Override\n public InetSocketAddress getRemoteAddress() {\n return null;\n }\n\n @Override\n public int getResponseCode() {\n return 0;\n }\n\n @Override\n public InetSocketAddress getLocalAddress() {\n return null;\n }\n\n @Override\n public String getProtocol() {\n return null;\n }\n\n @Override\n public Object getAttribute(String name) {\n return null;\n }\n\n @Override\n public void setAttribute(String name, Object value) {\n }\n\n @Override\n public void setStreams(InputStream i, OutputStream o) {\n }\n\n @Override\n public HttpPrincipal getPrincipal() {\n return null;\n }\n}" } ]
import static org.testng.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import robaho.net.httpserver.Code; import robaho.net.httpserver.StubHttpExchange;
2,639
package robaho.net.httpserver.websockets; /* * #%L * NanoHttpd-Websocket * %% * Copyright (C) 2012 - 2015 nanohttpd * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the nanohttpd nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ public class WebSocketResponseHandlerTest { Headers headers; WebSocketHandler handler; HttpExchange exchange; @BeforeMethod public void setUp() { this.headers = new Headers(); this.headers.add("upgrade", "websocket"); this.headers.add("connection", "Upgrade"); this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw=="); this.headers.add("sec-websocket-protocol", "chat, superchat"); this.headers.add("sec-websocket-version", "13"); handler = new TestWebsocketHandler(); exchange = new TestHttpExchange(headers, new Headers()); } private static class TestWebsocketHandler extends WebSocketHandler { @Override protected WebSocket openWebSocket(HttpExchange exchange) { return new TestWebSocket(exchange); } private static class TestWebSocket extends WebSocket { TestWebSocket(HttpExchange exchange) { super(exchange); } protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) { } @Override protected void onMessage(WebSocketFrame message) throws WebSocketException { } @Override protected void onPong(WebSocketFrame pong) throws WebSocketException { } } } private static class TestHttpExchange extends StubHttpExchange { private final Headers request, response; private InputStream in = new ByteArrayInputStream(new byte[0]); private OutputStream out = new ByteArrayOutputStream(); private int responseCode; TestHttpExchange(Headers request, Headers response) { this.request = request; this.response = response; } @Override public Headers getRequestHeaders() { return request; } @Override public Headers getResponseHeaders() { return response; } @Override public InputStream getRequestBody() { return in; } @Override public OutputStream getResponseBody() { return out; } @Override public void sendResponseHeaders(int rCode, long responseLength) { responseCode = rCode; } @Override public int getResponseCode() { return responseCode; } } private void testResponseHeader(String key, String expected) { String value = exchange.getResponseHeaders().getFirst(key); if (expected == null && value == null) { return; } if (expected == null && value != null) { Assert.fail(key + " should not have a value " + value); } assertEquals(value, expected); } @Test public void testConnectionHeaderHandlesKeepAlive_FixingFirefoxConnectIssue() throws IOException { this.headers.set("connection", "keep-alive, Upgrade"); handler.handle(exchange); } @Test public void testHandshakeReturnsResponseWithExpectedHeaders() throws IOException { handler.handle(exchange); testResponseHeader(Util.HEADER_WEBSOCKET_ACCEPT, "HSmrc0sMlYUkAGmm5OPpG2HaGWk="); testResponseHeader(Util.HEADER_WEBSOCKET_PROTOCOL, "chat"); } @Test public void testMissingKeyReturnsErrorResponse() throws IOException { this.headers.remove("sec-websocket-key"); handler.handle(exchange);
package robaho.net.httpserver.websockets; /* * #%L * NanoHttpd-Websocket * %% * Copyright (C) 2012 - 2015 nanohttpd * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the nanohttpd nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ public class WebSocketResponseHandlerTest { Headers headers; WebSocketHandler handler; HttpExchange exchange; @BeforeMethod public void setUp() { this.headers = new Headers(); this.headers.add("upgrade", "websocket"); this.headers.add("connection", "Upgrade"); this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw=="); this.headers.add("sec-websocket-protocol", "chat, superchat"); this.headers.add("sec-websocket-version", "13"); handler = new TestWebsocketHandler(); exchange = new TestHttpExchange(headers, new Headers()); } private static class TestWebsocketHandler extends WebSocketHandler { @Override protected WebSocket openWebSocket(HttpExchange exchange) { return new TestWebSocket(exchange); } private static class TestWebSocket extends WebSocket { TestWebSocket(HttpExchange exchange) { super(exchange); } protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) { } @Override protected void onMessage(WebSocketFrame message) throws WebSocketException { } @Override protected void onPong(WebSocketFrame pong) throws WebSocketException { } } } private static class TestHttpExchange extends StubHttpExchange { private final Headers request, response; private InputStream in = new ByteArrayInputStream(new byte[0]); private OutputStream out = new ByteArrayOutputStream(); private int responseCode; TestHttpExchange(Headers request, Headers response) { this.request = request; this.response = response; } @Override public Headers getRequestHeaders() { return request; } @Override public Headers getResponseHeaders() { return response; } @Override public InputStream getRequestBody() { return in; } @Override public OutputStream getResponseBody() { return out; } @Override public void sendResponseHeaders(int rCode, long responseLength) { responseCode = rCode; } @Override public int getResponseCode() { return responseCode; } } private void testResponseHeader(String key, String expected) { String value = exchange.getResponseHeaders().getFirst(key); if (expected == null && value == null) { return; } if (expected == null && value != null) { Assert.fail(key + " should not have a value " + value); } assertEquals(value, expected); } @Test public void testConnectionHeaderHandlesKeepAlive_FixingFirefoxConnectIssue() throws IOException { this.headers.set("connection", "keep-alive, Upgrade"); handler.handle(exchange); } @Test public void testHandshakeReturnsResponseWithExpectedHeaders() throws IOException { handler.handle(exchange); testResponseHeader(Util.HEADER_WEBSOCKET_ACCEPT, "HSmrc0sMlYUkAGmm5OPpG2HaGWk="); testResponseHeader(Util.HEADER_WEBSOCKET_PROTOCOL, "chat"); } @Test public void testMissingKeyReturnsErrorResponse() throws IOException { this.headers.remove("sec-websocket-key"); handler.handle(exchange);
assertEquals(Code.HTTP_BAD_REQUEST, exchange.getResponseCode());
0
2023-10-15 15:56:58+00:00
4k
ImCodist/funny-bfdi
src/main/java/xyz/imcodist/funnybfdi/features/BFDIHeadFeature.java
[ { "identifier": "FunnyBFDI", "path": "src/main/java/xyz/imcodist/funnybfdi/FunnyBFDI.java", "snippet": "public class FunnyBFDI implements ModInitializer {\n public static final String MOD_ID = \"funnybfdi\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n @Override\n public void onInitialize() {\n MidnightConfig.init(MOD_ID, Config.class);\n }\n}" }, { "identifier": "Config", "path": "src/main/java/xyz/imcodist/funnybfdi/other/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Entry public static boolean enabled = true;\n\n @Comment(centered = true) public static Comment mouthCategory;\n @Entry(isSlider = true, min = 0.2f, max = 1.8f) public static float mouthSpeed = 1.0f;\n @Entry public static boolean mouthTransitions = true;\n\n @Comment(centered = true) public static Comment mouthTransformCategory;\n @Entry(isSlider = true, min = 0.0f, max = 2.0f) public static float mouthSize = 1.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetX = 0.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetY = 0.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetZ = 0.0f;\n}" }, { "identifier": "MouthManager", "path": "src/main/java/xyz/imcodist/funnybfdi/other/MouthManager.java", "snippet": "public class MouthManager {\n private static final ArrayList<MouthState> playerMouths = new ArrayList<>();\n\n public static void tick() {\n if (!Config.enabled) {\n if (playerMouths.size() > 0) {\n playerMouths.clear();\n }\n\n return;\n }\n\n playerMouths.forEach(MouthState::tick);\n playerMouths.removeIf(mouthState -> mouthState.queueForDeletion);\n }\n\n public static void onPlayerChatted(Text message, UUID senderUUID) {\n if (!Config.enabled) return;\n\n MouthState mouthState = getOrCreatePlayerMouthState(senderUUID);\n\n mouthState.talkCharacter = 0;\n mouthState.talkText = message.getString();\n mouthState.updateMouthShape();\n\n mouthState.talking = true;\n }\n\n public static MouthState getOrCreatePlayerMouthState(UUID playerUUID) {\n MouthState getState = getPlayerMouthState(playerUUID);\n if (getState != null) return getState;\n\n\n MouthState newPlayerState = new MouthState();\n newPlayerState.playerUUID = playerUUID;\n playerMouths.add(newPlayerState);\n\n return newPlayerState;\n }\n\n public static MouthState getPlayerMouthState(UUID playerUUID) {\n for (MouthState mouthState : playerMouths) {\n if (mouthState.playerUUID.equals(playerUUID)) {\n return mouthState;\n }\n }\n\n return null;\n }\n\n public static class MouthState {\n public UUID playerUUID;\n\n public boolean queueForDeletion = false;\n\n public boolean talking = false;\n\n public String talkText = \"\";\n public int talkCharacter = 0;\n\n public String currentMouthShape = \"0\";\n public String transitionMouthShape = currentMouthShape;\n\n private double talkTimer = 0.0;\n\n public void tick() {\n if (talking) {\n talkTimer += 0.75 * Config.mouthSpeed;\n\n if (talkTimer >= 1.0) {\n if (talkCharacter >= talkText.length() - 1) {\n talking = false;\n queueForDeletion = true;\n }\n\n if (talkCharacter < talkText.length()) {\n talkCharacter += 1;\n if (talkCharacter >= talkText.length()) talkCharacter = talkText.length() - 1;\n\n updateMouthShape();\n }\n\n talkTimer -= 1.0;\n }\n\n if (Config.mouthTransitions) {\n if (currentMouthShape.equals(\"8\")) {\n transitionMouthShape = switch (transitionMouthShape) {\n case \"9\" -> \"7\";\n case \"7\", \"8\" -> \"8\";\n default -> \"9\";\n };\n } else {\n if (transitionMouthShape.equals(\"8\") || transitionMouthShape.equals(\"7\")) {\n transitionMouthShape = \"9\";\n } else if (transitionMouthShape.equals(\"3\") && !currentMouthShape.equals(\"3\")) {\n transitionMouthShape = \"2\";\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n }\n\n public void updateMouthShape() {\n String character = String.valueOf(talkText.charAt(talkCharacter));\n\n transitionMouthShape = currentMouthShape;\n currentMouthShape = switch (character.toLowerCase()) {\n case \"a\", \"e\", \"u\" -> \"2\";\n case \"i\" -> \"3\";\n case \"o\", \"r\" -> \"8\";\n case \"m\", \"p\", \"b\" -> \"6\";\n case \"f\", \"v\" -> \"5\";\n case \"l\" -> \"4\";\n case \"t\", \"d\", \"k\", \"g\", \"n\", \"s\", \" \" -> \"0\";\n default -> \"1\";\n };\n }\n }\n}" } ]
import net.minecraft.client.model.*; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.feature.FeatureRenderer; import net.minecraft.client.render.entity.feature.FeatureRendererContext; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.render.entity.model.ModelWithHead; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.util.Identifier; import net.minecraft.util.math.RotationAxis; import xyz.imcodist.funnybfdi.FunnyBFDI; import xyz.imcodist.funnybfdi.other.Config; import xyz.imcodist.funnybfdi.other.MouthManager;
1,883
package xyz.imcodist.funnybfdi.features; public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> { private final ModelPart base; public BFDIHeadFeature(FeatureRendererContext<T, M> context) { super(context); ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16); this.base = texturedModelData.createModel().getChild("mouth"); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (!Config.enabled) return; if (Config.mouthSize <= 0.0f) return; ModelPart head = getContextModel().getHead(); if (entity.isInvisible()) return; if (!head.visible) return;
package xyz.imcodist.funnybfdi.features; public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> { private final ModelPart base; public BFDIHeadFeature(FeatureRendererContext<T, M> context) { super(context); ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16); this.base = texturedModelData.createModel().getChild("mouth"); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (!Config.enabled) return; if (Config.mouthSize <= 0.0f) return; ModelPart head = getContextModel().getHead(); if (entity.isInvisible()) return; if (!head.visible) return;
MouthManager.MouthState mouthState = MouthManager.getPlayerMouthState(entity.getUuid());
2
2023-10-18 00:31:52+00:00
4k
ItzGreenCat/SkyImprover
src/main/java/me/greencat/skyimprover/feature/kuudraHelper/KuudraHelper.java
[ { "identifier": "Config", "path": "src/main/java/me/greencat/skyimprover/config/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashEnable = true;\n @Entry(category = \"render\")\n public static boolean damageSplashCompact = true;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 5.0F)\n public static float damageSplashOffset = 2.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 10.0F)\n public static float damageSplashDuration = 3.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 2.0F)\n public static float damageSplashAnimationSpeed = 0.3F;\n\n @Comment(category = \"misc\")\n public static Comment rainTimer;\n @Entry(category = \"misc\")\n public static boolean rainTimerEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetY = 0.3F;\n @Comment(category = \"misc\")\n public static Comment ferocityCount;\n @Entry(category = \"misc\")\n public static boolean ferocityCountEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetY = 0.4F;\n\n @Comment(category = \"dungeon\")\n public static Comment m3FreezeHelper;\n @Entry(category = \"dungeon\")\n public static boolean m3FreezeHelperEnable = true;\n\n @Comment(category = \"dungeon\")\n public static Comment dungeonDeathMessage;\n @Entry(category = \"dungeon\")\n public static boolean dungeonDeathMessageEnable = true;\n @Entry(category = \"dungeon\")\n public static String dungeonDeathMessageContent = \"BOOM!\";\n @Comment(category = \"dungeon\")\n public static Comment kuudraHelper;\n @Entry(category = \"dungeon\")\n public static boolean kuudraHelperEnable = true;\n}" }, { "identifier": "RenderLivingEntityPreEvent", "path": "src/main/java/me/greencat/skyimprover/event/RenderLivingEntityPreEvent.java", "snippet": "public interface RenderLivingEntityPreEvent {\n Event<RenderLivingEntityPreEvent> EVENT = EventFactory.createArrayBacked(RenderLivingEntityPreEvent.class,(listeners) -> (entity) -> {\n for(RenderLivingEntityPreEvent event : listeners){\n boolean result = event.render(entity);\n if(!result){\n return false;\n }\n }\n return true;\n });\n boolean render(LivingEntity entity);\n}" }, { "identifier": "Module", "path": "src/main/java/me/greencat/skyimprover/feature/Module.java", "snippet": "public interface Module {\n void registerEvent();\n}" }, { "identifier": "BeaconBeamUtils", "path": "src/main/java/me/greencat/skyimprover/utils/BeaconBeamUtils.java", "snippet": "public class BeaconBeamUtils {\n public static void renderBeaconBeam(WorldRenderContext context, BlockPos pos, Color color) {\n float[] colorComponents = new float[]{color.getRed() / 255.0F,color.getGreen() / 255.0F,color.getBlue() / 255.0F};\n if (FrustumUtils.isVisible(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, 319, pos.getZ() + 1)) {\n MatrixStack matrices = context.matrixStack();\n Vec3d camera = context.camera().getPos();\n\n matrices.push();\n matrices.translate(pos.getX() - camera.getX(), pos.getY() - camera.getY(), pos.getZ() - camera.getZ());\n\n Tessellator tessellator = RenderSystem.renderThreadTesselator();\n BufferBuilder buffer = tessellator.getBuffer();\n VertexConsumerProvider.Immediate consumer = VertexConsumerProvider.immediate(buffer);\n\n BeaconBlockEntityRendererAccessor.renderBeam(matrices, consumer, context.tickDelta(), context.world().getTime(), 0,319, colorComponents);\n\n consumer.draw();\n matrices.pop();\n }\n }\n\n}" }, { "identifier": "LocationUtils", "path": "src/main/java/me/greencat/skyimprover/utils/LocationUtils.java", "snippet": "public class LocationUtils {\n public static boolean isOnSkyblock = false;\n public static boolean isInDungeons = false;\n public static boolean isInKuudra = false;\n public static final ObjectArrayList<String> STRING_SCOREBOARD = new ObjectArrayList<>();\n\n public static void update(){\n MinecraftClient minecraftClient = MinecraftClient.getInstance();\n updateScoreboard(minecraftClient);\n updatePlayerPresenceFromScoreboard(minecraftClient);\n }\n public static void updatePlayerPresenceFromScoreboard(MinecraftClient client) {\n List<String> sidebar = STRING_SCOREBOARD;\n\n FabricLoader fabricLoader = FabricLoader.getInstance();\n if (client.world == null || client.isInSingleplayer() || sidebar.isEmpty()) {\n isOnSkyblock = false;\n isInDungeons = false;\n isInKuudra = false;\n }\n\n if (sidebar.isEmpty() && !fabricLoader.isDevelopmentEnvironment()) return;\n String string = sidebar.toString();\n if(sidebar.isEmpty()){\n isInDungeons = false;\n isInKuudra = false;\n return;\n }\n if (sidebar.get(0).contains(\"SKYBLOCK\") || sidebar.get(0).contains(\"SKIBLOCK\")) {\n if (!isOnSkyblock) {\n isOnSkyblock = true;\n }\n } else {\n isOnSkyblock = false;\n }\n isInDungeons = isOnSkyblock && string.contains(\"The Catacombs\");\n isInKuudra = isOnSkyblock && string.contains(\"Kuudra\");\n }\n private static void updateScoreboard(MinecraftClient client) {\n try {\n STRING_SCOREBOARD.clear();\n\n ClientPlayerEntity player = client.player;\n if (player == null) return;\n\n Scoreboard scoreboard = player.getScoreboard();\n ScoreboardObjective objective = scoreboard.getObjectiveForSlot(1);\n ObjectArrayList<Text> textLines = new ObjectArrayList<>();\n ObjectArrayList<String> stringLines = new ObjectArrayList<>();\n\n for (ScoreboardPlayerScore score : scoreboard.getAllPlayerScores(objective)) {\n Team team = scoreboard.getPlayerTeam(score.getPlayerName());\n\n if (team != null) {\n Text textLine = Text.empty().append(team.getPrefix().copy()).append(team.getSuffix().copy());\n String strLine = team.getPrefix().getString() + team.getSuffix().getString();\n\n if (!strLine.trim().isEmpty()) {\n String formatted = Formatting.strip(strLine);\n\n textLines.add(textLine);\n stringLines.add(formatted);\n }\n }\n }\n\n if (objective != null) {\n stringLines.add(objective.getDisplayName().getString());\n textLines.add(Text.empty().append(objective.getDisplayName().copy()));\n\n Collections.reverse(stringLines);\n Collections.reverse(textLines);\n }\n STRING_SCOREBOARD.addAll(stringLines);\n } catch (NullPointerException ignored) {\n\n }\n }\n}" }, { "identifier": "TextRenderUtils", "path": "src/main/java/me/greencat/skyimprover/utils/TextRenderUtils.java", "snippet": "public class TextRenderUtils {\n public static final int backgroundColor = new Color(0,0,0,100).getRGB();\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, boolean seeThrough) {\n renderText(context, text, pos, 1, seeThrough);\n }\n\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, float scale, boolean seeThrough) {\n renderText(context, text, pos, scale, 0, seeThrough);\n }\n\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, float scale, float yOffset, boolean seeThrough) {\n renderText(context, text.asOrderedText(), pos, scale, yOffset, seeThrough);\n }\n public static void renderText(WorldRenderContext context, OrderedText text, Vec3d pos, float scale, float yOffset, boolean seeThrough) {\n MatrixStack matrices = context.matrixStack();\n Vec3d camera = context.camera().getPos();\n TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer;\n\n scale *= 0.025f;\n\n matrices.push();\n matrices.translate(pos.getX() - camera.getX(), pos.getY() - camera.getY(), pos.getZ() - camera.getZ());\n matrices.peek().getPositionMatrix().mul(RenderSystem.getModelViewMatrix());\n matrices.multiply(context.camera().getRotation());\n matrices.scale(-scale, -scale, scale);\n\n Matrix4f positionMatrix = matrices.peek().getPositionMatrix();\n float xOffset = -textRenderer.getWidth(text) / 2f;\n\n Tessellator tessellator = RenderSystem.renderThreadTesselator();\n BufferBuilder buffer = tessellator.getBuffer();\n VertexConsumerProvider.Immediate consumers = VertexConsumerProvider.immediate(buffer);\n\n RenderSystem.depthFunc(seeThrough ? GL11.GL_ALWAYS : GL11.GL_LEQUAL);\n\n textRenderer.draw(text, xOffset, yOffset, 0xFFFFFFFF, false, positionMatrix, consumers, TextRenderer.TextLayerType.SEE_THROUGH, 0, LightmapTextureManager.MAX_LIGHT_COORDINATE);\n consumers.draw();\n\n RenderSystem.depthFunc(GL11.GL_LEQUAL);\n matrices.pop();\n }\n public static void renderHUDText(DrawContext context,int x,int y,Text... text){\n int height = text.length * 10;\n int width = 0;\n for(Text t : text){\n int length = MinecraftClient.getInstance().textRenderer.getWidth(t.asOrderedText());\n if(length > width){\n width = length;\n }\n }\n context.fill(x - 3,y - 3,x + width + 3,y + height + 3,backgroundColor);\n for(int i = 0;i < text.length;i++){\n context.drawText(MinecraftClient.getInstance().textRenderer,text[i],x,y + i * 10,Color.WHITE.getRGB(),false);\n }\n }\n}" } ]
import me.greencat.skyimprover.config.Config; import me.greencat.skyimprover.event.RenderLivingEntityPreEvent; import me.greencat.skyimprover.feature.Module; import me.greencat.skyimprover.utils.BeaconBeamUtils; import me.greencat.skyimprover.utils.LocationUtils; import me.greencat.skyimprover.utils.TextRenderUtils; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.world.ClientWorld; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.decoration.ArmorStandEntity; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.world.World; import java.awt.*;
2,869
package me.greencat.skyimprover.feature.kuudraHelper; public class KuudraHelper implements Module { public static long lastRefresh = 0L; @Override public void registerEvent() { //SUPPLIES //BRING SUPPLY CHEST HERE //SUPPLIES RECEIVED //SUPPLY PILE //PROGRESS: //FUEL CELL WorldRenderEvents.LAST.register(KuudraHelper::onRender); } private static void onRender(WorldRenderContext worldRenderContext) { if(System.currentTimeMillis() - lastRefresh >= 5000){ lastRefresh = System.currentTimeMillis(); LocationUtils.update(); } if(!LocationUtils.isInKuudra){ return; }
package me.greencat.skyimprover.feature.kuudraHelper; public class KuudraHelper implements Module { public static long lastRefresh = 0L; @Override public void registerEvent() { //SUPPLIES //BRING SUPPLY CHEST HERE //SUPPLIES RECEIVED //SUPPLY PILE //PROGRESS: //FUEL CELL WorldRenderEvents.LAST.register(KuudraHelper::onRender); } private static void onRender(WorldRenderContext worldRenderContext) { if(System.currentTimeMillis() - lastRefresh >= 5000){ lastRefresh = System.currentTimeMillis(); LocationUtils.update(); } if(!LocationUtils.isInKuudra){ return; }
if(!Config.kuudraHelperEnable){
0
2023-10-19 09:19:09+00:00
4k
zilliztech/kafka-connect-milvus
src/main/java/com/milvus/io/kafka/MilvusSinkTask.java
[ { "identifier": "MilvusClientHelper", "path": "src/main/java/com/milvus/io/kafka/helper/MilvusClientHelper.java", "snippet": "public class MilvusClientHelper {\n public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) {\n ConnectParam connectParam = ConnectParam.newBuilder()\n .withUri(config.getUrl())\n .withToken(Utils.decryptToken(config.getToken().value()))\n .build();\n return new MilvusServiceClient(connectParam);\n }\n}" }, { "identifier": "DataConverter", "path": "src/main/java/com/milvus/io/kafka/utils/DataConverter.java", "snippet": "public class DataConverter {\n\n private final MilvusSinkConnectorConfig config;\n\n private static final Logger log = LoggerFactory.getLogger(DataConverter.class);\n\n public DataConverter(MilvusSinkConnectorConfig config) {\n this.config = config;\n }\n /*\n * Convert SinkRecord to List<InsertParam.Field>\n */\n public List<InsertParam.Field> convertRecord(SinkRecord sr, CollectionSchema collectionSchema) {\n // parse sinkRecord to get filed name and value\n if(sr.value() instanceof Struct) {\n return parseValue((Struct)sr.value(), collectionSchema);\n }else if (sr.value() instanceof HashMap) {\n return parseValue((HashMap<?, ?>)sr.value(), collectionSchema);\n }else {\n throw new RuntimeException(\"Unsupported SinkRecord data type\" + sr.value());\n }\n }\n\n private List<InsertParam.Field> parseValue(HashMap<?, ?> mapValue, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = new ArrayList<>();\n // convert collectionSchema.getFieldsList: Filed's Name and DataType to a Map\n Map<String, DataType> fieldType = collectionSchema.getFieldsList().stream().collect(Collectors.toMap(FieldSchema::getName, FieldSchema::getDataType));\n mapValue.forEach((key1, value) -> {\n // for each field, create a InsertParam.Field\n if(fieldType.containsKey(key1.toString())){\n // if the key exists in the collection, store the value by collectionSchema DataType\n fields.add(new InsertParam.Field(key1.toString(), Collections.singletonList(castValueToType(value, fieldType.get(key1.toString())))));\n }else if(collectionSchema.getEnableDynamicField()){\n // if the key not exists in the collection and the collection is dynamic, store the value directly\n fields.add(new InsertParam.Field(key1.toString(), Collections.singletonList(value)));\n }\n });\n return fields;\n }\n\n private List<InsertParam.Field> parseValue(Struct structValue, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = new ArrayList<>();\n // convert collectionSchema.getFieldsList: Filed's Name and DataType to a Map\n Map<String, DataType> fieldType = collectionSchema.getFieldsList().stream().collect(Collectors.toMap(FieldSchema::getName, FieldSchema::getDataType));\n structValue.schema().fields().forEach(field -> {\n // for each field, create a InsertParam.Field\n if(fieldType.containsKey(field.name())){\n // if the key exists in the collection, store the value by collectionSchema DataType\n fields.add(new InsertParam.Field(field.name(), Collections.singletonList(castValueToType(structValue.get(field.name()), fieldType.get(field.name())))));\n }else if(collectionSchema.getEnableDynamicField()){\n // if the key not exists in the collection and the collection is dynamic, store the value directly\n fields.add(new InsertParam.Field(field.name(), Collections.singletonList(structValue.get(field.name()))));\n }\n });\n\n return fields;\n }\n\n private Object castValueToType(Object value, DataType dataType) {\n switch (dataType){\n case Bool:\n return Boolean.parseBoolean(value.toString());\n case Int8:\n case Int16:\n return Short.parseShort(value.toString());\n case Int32:\n return Integer.parseInt(value.toString());\n case Int64:\n return Long.parseLong(value.toString());\n case Float:\n return Float.parseFloat(value.toString());\n case Double:\n return Double.parseDouble(value.toString());\n case VarChar:\n case String:\n return value.toString();\n case JSON:\n Gson gson = new Gson();\n return gson.toJson(value);\n case BinaryVector:\n return parseBinaryVectorField(value.toString());\n case FloatVector:\n return parseFloatVectorField(value.toString());\n default:\n throw new RuntimeException(\"Unsupported data type\" + dataType);\n }\n }\n\n protected List<Float> parseFloatVectorField(String vectors){\n try {\n log.debug(\"parse float vectors: {}\", vectors);\n\n String[] vectorArrays = vectors.replaceAll(\"\\\\[\", \"\").replaceAll(\"\\\\]\", \"\")\n .replaceAll(\" \",\"\").split(\",\");\n\n List<Float> floatList = Lists.newLinkedList();\n for (String vector : vectorArrays) {\n floatList.add(Float.valueOf(vector));\n }\n\n return floatList;\n }catch (Exception e){\n throw new RuntimeException(\"parse float vector field error: \" + e.getMessage() + vectors);\n }\n\n }\n protected ByteBuffer parseBinaryVectorField(String vectors){\n try {\n log.debug(\"parse binary vectors: {}\", vectors);\n\n String[] vectorArrays = vectors.replaceAll(\"\\\\[\", \"\").replaceAll(\"\\\\]\", \"\")\n .replaceAll(\" \", \"\").split(\",\");\n\n ByteBuffer buffer = ByteBuffer.allocate(vectorArrays.length);\n for (String vectorArray : vectorArrays) {\n int vector = Integer.parseInt(vectorArray);\n buffer.put((byte) vector);\n }\n\n return buffer;\n }catch (Exception e){\n throw new RuntimeException(\"parse binary vector field error: \" + e.getMessage() + vectors);\n }\n }\n\n public List<JSONObject> convertRecordWithDynamicSchema(SinkRecord sr, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = convertRecord(sr, collectionSchema);\n List<JSONObject> jsonObjects = new ArrayList<>();\n int rows = fields.get(0).getValues().size();\n for (int i = 0; i < rows; i++) {\n JSONObject jsonObject = new JSONObject();\n for (InsertParam.Field field : fields) {\n jsonObject.put(field.getName(), field.getValues().get(i));\n }\n jsonObjects.add(jsonObject);\n }\n return jsonObjects;\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/com/milvus/io/kafka/utils/Utils.java", "snippet": "public class Utils {\n private static final Logger log = LoggerFactory.getLogger(Utils.class);\n private static final SecretKey SECRET_KEY = generateSecretKey();\n\n public static String encryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8));\n return Base64.getEncoder().encodeToString(encryptedBytes);\n } catch (Exception e) {\n // Handle encryption errors\n log.error(\"encryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static String decryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = Base64.getDecoder().decode(token);\n byte[] decryptedBytes = cipher.doFinal(encryptedBytes);\n\n return new String(decryptedBytes, StandardCharsets.UTF_8);\n } catch (Exception e) {\n // Handle decryption errors\n log.error(\"decryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static SecretKey generateSecretKey() {\n try {\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"AES\");\n SecureRandom secureRandom = new SecureRandom();\n keyGenerator.init(128, secureRandom);\n return keyGenerator.generateKey();\n } catch (NoSuchAlgorithmException e) {\n log.error(e.getMessage());\n return null;\n }\n }\n\n}" }, { "identifier": "VersionUtil", "path": "src/main/java/com/milvus/io/kafka/utils/VersionUtil.java", "snippet": "public final class VersionUtil {\n private static final String VERSION;\n\n static {\n Properties prop = new Properties();\n try (InputStream in = VersionUtil.class.getResourceAsStream(\"/kafka-connect-milvus.properties\")) {\n prop.load(in);\n VERSION = prop.getProperty(\"version\", \"0.0.0.0\");\n } catch (IOException e) {\n throw new ExceptionInInitializerError(e);\n }\n }\n\n public static String getVersion() {\n return VERSION;\n }\n}" }, { "identifier": "TOKEN", "path": "src/main/java/com/milvus/io/kafka/MilvusSinkConnectorConfig.java", "snippet": "protected static final String TOKEN = \"token\";" } ]
import com.milvus.io.kafka.helper.MilvusClientHelper; import com.milvus.io.kafka.utils.DataConverter; import com.milvus.io.kafka.utils.Utils; import com.milvus.io.kafka.utils.VersionUtil; import io.milvus.client.MilvusServiceClient; import io.milvus.grpc.CollectionSchema; import io.milvus.grpc.DescribeCollectionResponse; import io.milvus.grpc.GetLoadStateResponse; import io.milvus.grpc.LoadState; import io.milvus.param.R; import io.milvus.param.collection.DescribeCollectionParam; import io.milvus.param.collection.GetLoadStateParam; import io.milvus.param.dml.InsertParam; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.Map; import static com.milvus.io.kafka.MilvusSinkConnectorConfig.TOKEN;
2,413
package com.milvus.io.kafka; public class MilvusSinkTask extends SinkTask { private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class); private MilvusSinkConnectorConfig config; private MilvusServiceClient myMilvusClient; private DataConverter converter; private CollectionSchema collectionSchema; @Override public String version() { return VersionUtil.getVersion(); } @Override public void start(Map<String, String> props) { start(props, null); } // make visible for test protected void start(Map<String, String> props, MilvusServiceClient milvusClient) { log.info("Starting MilvusSinkTask.");
package com.milvus.io.kafka; public class MilvusSinkTask extends SinkTask { private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class); private MilvusSinkConnectorConfig config; private MilvusServiceClient myMilvusClient; private DataConverter converter; private CollectionSchema collectionSchema; @Override public String version() { return VersionUtil.getVersion(); } @Override public void start(Map<String, String> props) { start(props, null); } // make visible for test protected void start(Map<String, String> props, MilvusServiceClient milvusClient) { log.info("Starting MilvusSinkTask.");
props.put(TOKEN, Utils.encryptToken(props.get(TOKEN)));
2
2023-10-18 02:11:08+00:00
4k
histevehu/12306
common/src/main/java/com/steve/train/common/interceptor/MemberInterceptor.java
[ { "identifier": "MemberLoginContext", "path": "common/src/main/java/com/steve/train/common/context/MemberLoginContext.java", "snippet": "public class MemberLoginContext {\n private static final Logger LOG = LoggerFactory.getLogger(MemberLoginContext.class);\n\n private static ThreadLocal<MemberLoginResp> member = new ThreadLocal<>();\n\n public static MemberLoginResp getMember() {\n return member.get();\n }\n\n public static void setMember(MemberLoginResp member) {\n MemberLoginContext.member.set(member);\n }\n\n public static Long getId() {\n try {\n return member.get().getId();\n } catch (Exception e) {\n LOG.error(\"获取用户登录信息异常\", e);\n throw e;\n }\n }\n}" }, { "identifier": "MemberLoginResp", "path": "common/src/main/java/com/steve/train/common/resp/MemberLoginResp.java", "snippet": "public class MemberLoginResp {\n private Long id;\n\n private String mobile;\n\n private String token;\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getMobile() {\n return mobile;\n }\n\n public void setMobile(String mobile) {\n this.mobile = mobile;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"MemberLoginResp{\");\n sb.append(\"id=\").append(id);\n sb.append(\", mobile='\").append(mobile).append('\\'');\n sb.append(\", token='\").append(token).append('\\'');\n sb.append('}');\n return sb.toString();\n }\n\n public MemberLoginResp(Long id, String mobile) {\n this.id = id;\n this.mobile = mobile;\n }\n}" }, { "identifier": "JWTUtil", "path": "common/src/main/java/com/steve/train/common/util/JWTUtil.java", "snippet": "public class JWTUtil {\n private static final Logger LOG = LoggerFactory.getLogger(JWTUtil.class);\n\n /**\n * 盐值很重要,不能泄漏,且每个项目都应该不一样,可以放到配置文件中\n */\n private static final String key = \"SteveHu_12306Train\";\n\n public static String createToken(Long id, String mobile) {\n LOG.info(\"开始生成JWT,id:{},mobile:{}\", id, mobile);\n // BouncyCastle类是hutool引用的一个加密的第三方类,如果将应用打包部署到服务器,其会检测到被再次打包,签名验证失败而发生错误,所以关闭它使用jdk自带的加密算法\n GlobalBouncyCastleProvider.setUseBouncyCastle(false);\n DateTime now = DateTime.now();\n // 设置JWT token过期时间\n DateTime expTime = now.offsetNew(DateField.HOUR, 24);\n Map<String, Object> payload = new HashMap<>();\n // 签发时间\n payload.put(JWTPayload.ISSUED_AT, now);\n // 过期时间\n payload.put(JWTPayload.EXPIRES_AT, expTime);\n // 生效时间\n payload.put(JWTPayload.NOT_BEFORE, now);\n // 内容\n payload.put(\"id\", id);\n payload.put(\"mobile\", mobile);\n String token = cn.hutool.jwt.JWTUtil.createToken(payload, key.getBytes());\n LOG.info(\"生成JWT:{}\", token);\n return token;\n }\n\n public static boolean validate(String token) {\n LOG.info(\"开始JWT校验,token:{}\", token);\n GlobalBouncyCastleProvider.setUseBouncyCastle(false);\n JWT jwt = cn.hutool.jwt.JWTUtil.parseToken(token).setKey(key.getBytes());\n // validate包含了verify\n boolean validate = jwt.validate(0);\n LOG.info(\"JWT校验结果:{}\", validate);\n return validate;\n }\n\n /**\n * token由id,mobile等其他信息经加密后生成。本函数将token解密并剥离其他数据,返回id,mobile\n *\n * @param token\n * @return Json格式的id, mobile字段\n */\n public static JSONObject getJSONObject(String token) {\n GlobalBouncyCastleProvider.setUseBouncyCastle(false);\n JWT jwt = cn.hutool.jwt.JWTUtil.parseToken(token).setKey(key.getBytes());\n JSONObject payloads = jwt.getPayloads();\n payloads.remove(JWTPayload.ISSUED_AT);\n payloads.remove(JWTPayload.EXPIRES_AT);\n payloads.remove(JWTPayload.NOT_BEFORE);\n LOG.info(\"根据token获取原始内容:{}\", payloads);\n return payloads;\n }\n}" } ]
import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.steve.train.common.context.MemberLoginContext; import com.steve.train.common.resp.MemberLoginResp; import com.steve.train.common.util.JWTUtil; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor;
1,746
package com.steve.train.common.interceptor; /* * @author : Steve Hu * @date : 2023/10/26 15:42 * @description: 用户拦截器,用于从用户请求的header中提取JWT,转为登录信息并保存在线程本地变量中 * 本类只声明了这一公共拦截器,若需要启用,需要在具体的模块中配置注入 * 知识:Spring中请求依次到达:Web容器->Filter过滤器->Interceptor拦截器->Controller->Service * 流程:用户请求首先到达gateway,经过MemberLoginFilter过滤器检查JWT有效后,再转发给相应模块,相应模块若启用本拦截器,则进一步从JWT中提取登录信息。 * 在接口入口获取会员信息,并放到线程本地变量,则在controller、service都可直接从线程本地变量获取会员信息 * */ @Component public class MemberInterceptor implements HandlerInterceptor { private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LOG.info("### MemberInterceptor开始 ###"); // 获取header的token参数 String token = request.getHeader("token"); if (StrUtil.isNotBlank(token)) { LOG.info("获取会员登录token:{}", token); JSONObject loginMember = JWTUtil.getJSONObject(token); LOG.info("当前登录会员:{}", loginMember); // 根据token还原后的字段生成登录信息类 MemberLoginResp member = JSONUtil.toBean(loginMember, MemberLoginResp.class); // 只要当前线程完成上述过程,即将登录信息保存在该线程的本地变量中,线程本地变量只在当前线程(一次请求)有效 // 后续接口中所有调用用户信息的接口都直接从线程本地变量中获取
package com.steve.train.common.interceptor; /* * @author : Steve Hu * @date : 2023/10/26 15:42 * @description: 用户拦截器,用于从用户请求的header中提取JWT,转为登录信息并保存在线程本地变量中 * 本类只声明了这一公共拦截器,若需要启用,需要在具体的模块中配置注入 * 知识:Spring中请求依次到达:Web容器->Filter过滤器->Interceptor拦截器->Controller->Service * 流程:用户请求首先到达gateway,经过MemberLoginFilter过滤器检查JWT有效后,再转发给相应模块,相应模块若启用本拦截器,则进一步从JWT中提取登录信息。 * 在接口入口获取会员信息,并放到线程本地变量,则在controller、service都可直接从线程本地变量获取会员信息 * */ @Component public class MemberInterceptor implements HandlerInterceptor { private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LOG.info("### MemberInterceptor开始 ###"); // 获取header的token参数 String token = request.getHeader("token"); if (StrUtil.isNotBlank(token)) { LOG.info("获取会员登录token:{}", token); JSONObject loginMember = JWTUtil.getJSONObject(token); LOG.info("当前登录会员:{}", loginMember); // 根据token还原后的字段生成登录信息类 MemberLoginResp member = JSONUtil.toBean(loginMember, MemberLoginResp.class); // 只要当前线程完成上述过程,即将登录信息保存在该线程的本地变量中,线程本地变量只在当前线程(一次请求)有效 // 后续接口中所有调用用户信息的接口都直接从线程本地变量中获取
MemberLoginContext.setMember(member);
0
2023-10-23 01:20:56+00:00
4k
aws-samples/trading-latency-benchmark
src/main/java/com/aws/trading/ExchangeClientLatencyTestHandler.java
[ { "identifier": "COIN_PAIRS", "path": "src/main/java/com/aws/trading/Config.java", "snippet": "public static final List<String> COIN_PAIRS;" }, { "identifier": "printResults", "path": "src/main/java/com/aws/trading/RoundTripLatencyTester.java", "snippet": "public static synchronized void printResults(SingleWriterRecorder hdr, long orderResponseCount) {\n long currentTime = System.nanoTime();\n var executionTime = currentTime - testStartTime;\n MESSAGE_COUNTER.add(orderResponseCount);\n\n var messageCount = MESSAGE_COUNTER.longValue();\n if (messageCount < WARMUP_COUNT * TEST_SIZE) {\n LOGGER.info(\"warming up... - message count: {}\", messageCount);\n return;\n }\n\n HISTOGRAM.add(hdr.getIntervalHistogram());\n if (messageCount % REPORT_SIZE == 0) {\n var executionTimeStr = LatencyTools.formatNanos(executionTime);\n var messagePerSecond = messageCount / TimeUnit.SECONDS.convert(executionTime, TimeUnit.NANOSECONDS);\n var logMsg = \"\\nTest Execution Time: {}s \\n Number of messages: {} \\n Message Per Second: {} \\n Percentiles: {} \\n\";\n\n try (PrintStream histogramLogFile = getLogFile()) {\n saveHistogramToFile(currentTime, histogramLogFile);\n histogramStartTime = currentTime;\n } catch (IOException e) {\n LOGGER.error(e);\n }\n\n LinkedHashMap<String, String> latencyReport = LatencyTools.createLatencyReport(HISTOGRAM);\n LOGGER.info(logMsg,\n executionTimeStr, messageCount, messagePerSecond, LatencyTools.toJSON(latencyReport)\n );\n\n hdr.reset();\n HISTOGRAM.reset();\n }\n}" } ]
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.CharsetUtil; import org.HdrHistogram.SingleWriterRecorder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import static com.aws.trading.Config.COIN_PAIRS; import static com.aws.trading.RoundTripLatencyTester.printResults;
1,901
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * 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. * * 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 com.aws.trading; public class ExchangeClientLatencyTestHandler extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = LogManager.getLogger(ExchangeClientLatencyTestHandler.class); private final WebSocketClientHandshaker handshaker; private final int apiToken; private final int test_size; public final URI uri; private final ExchangeProtocol protocol; private ChannelPromise handshakeFuture; private final ConcurrentHashMap<String, Long> orderSentTimeMap; private final ConcurrentHashMap<String, Long> cancelSentTimeMap; private long orderResponseCount = 0; private final SingleWriterRecorder hdrRecorderForAggregation; private long testStartTime = 0; private final Random random = new Random(); public ExchangeClientLatencyTestHandler(ExchangeProtocol protocol, URI uri, int apiToken, int test_size) { this.uri = uri; this.protocol = protocol; var header = HttpHeaders.EMPTY_HEADERS; this.handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, header, 1280000); this.apiToken = apiToken; this.orderSentTimeMap = new ConcurrentHashMap<>(test_size); this.cancelSentTimeMap = new ConcurrentHashMap<>(test_size); this.test_size = test_size; this.hdrRecorderForAggregation = new SingleWriterRecorder(Long.MAX_VALUE, 2); } @Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { this.handshakeFuture = ctx.newPromise(); } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("channel is active, starting websocket handshaking..."); handshaker.handshake(ctx.channel()); } @Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("Websocket client disconnected"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { final Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { LOGGER.info("Websocket client is connected"); var m = (FullHttpResponse) msg; handshaker.finishHandshake(ch, m); LOGGER.info("Websocket client is authenticating for {}", this.apiToken); //success, authenticate var channel = ctx.channel(); channel.write(authMessage()); channel.flush(); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame); } else if (frame instanceof PongWebSocketFrame) { } else if (frame instanceof CloseWebSocketFrame) { LOGGER.info("received CloseWebSocketFrame, closing the channel"); ch.close(); } else if (frame instanceof BinaryWebSocketFrame) { LOGGER.info(frame.content().toString()); } } private TextWebSocketFrame subscribeMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG)); } private TextWebSocketFrame authMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer( ExchangeProtocolImpl.AUTH_MSG_HEADER, Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8), ExchangeProtocolImpl.MSG_END) ); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { LOGGER.error(cause); if (!handshakeFuture.isDone()) { handshakeFuture.setFailure(cause); } ctx.close(); } public ChannelPromise getHandshakeFuture() { return handshakeFuture; } private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException { long eventReceiveTime = System.nanoTime(); ByteBuf buf = textFrame.content(); final byte[] bytes; int offset = 0; final int length = buf.readableBytes(); if (buf.hasArray()) { bytes = buf.array(); offset = buf.arrayOffset(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } buf.clear(); buf.release(); JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8); Object type = parsedObject.getString("type"); if ("BOOKED".equals(type) || type.equals("DONE")) { //LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject); String clientId = parsedObject.getString("client_id"); if (type.equals("BOOKED")) { if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return; var pair = parsedObject.getString("instrument_code"); sendCancelOrder(ctx, clientId, pair); } else { if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return; sendOrder(ctx); } if (orderResponseCount % test_size == 0) {
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * 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. * * 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 com.aws.trading; public class ExchangeClientLatencyTestHandler extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = LogManager.getLogger(ExchangeClientLatencyTestHandler.class); private final WebSocketClientHandshaker handshaker; private final int apiToken; private final int test_size; public final URI uri; private final ExchangeProtocol protocol; private ChannelPromise handshakeFuture; private final ConcurrentHashMap<String, Long> orderSentTimeMap; private final ConcurrentHashMap<String, Long> cancelSentTimeMap; private long orderResponseCount = 0; private final SingleWriterRecorder hdrRecorderForAggregation; private long testStartTime = 0; private final Random random = new Random(); public ExchangeClientLatencyTestHandler(ExchangeProtocol protocol, URI uri, int apiToken, int test_size) { this.uri = uri; this.protocol = protocol; var header = HttpHeaders.EMPTY_HEADERS; this.handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, header, 1280000); this.apiToken = apiToken; this.orderSentTimeMap = new ConcurrentHashMap<>(test_size); this.cancelSentTimeMap = new ConcurrentHashMap<>(test_size); this.test_size = test_size; this.hdrRecorderForAggregation = new SingleWriterRecorder(Long.MAX_VALUE, 2); } @Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { this.handshakeFuture = ctx.newPromise(); } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("channel is active, starting websocket handshaking..."); handshaker.handshake(ctx.channel()); } @Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("Websocket client disconnected"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { final Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { LOGGER.info("Websocket client is connected"); var m = (FullHttpResponse) msg; handshaker.finishHandshake(ch, m); LOGGER.info("Websocket client is authenticating for {}", this.apiToken); //success, authenticate var channel = ctx.channel(); channel.write(authMessage()); channel.flush(); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame); } else if (frame instanceof PongWebSocketFrame) { } else if (frame instanceof CloseWebSocketFrame) { LOGGER.info("received CloseWebSocketFrame, closing the channel"); ch.close(); } else if (frame instanceof BinaryWebSocketFrame) { LOGGER.info(frame.content().toString()); } } private TextWebSocketFrame subscribeMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG)); } private TextWebSocketFrame authMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer( ExchangeProtocolImpl.AUTH_MSG_HEADER, Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8), ExchangeProtocolImpl.MSG_END) ); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { LOGGER.error(cause); if (!handshakeFuture.isDone()) { handshakeFuture.setFailure(cause); } ctx.close(); } public ChannelPromise getHandshakeFuture() { return handshakeFuture; } private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException { long eventReceiveTime = System.nanoTime(); ByteBuf buf = textFrame.content(); final byte[] bytes; int offset = 0; final int length = buf.readableBytes(); if (buf.hasArray()) { bytes = buf.array(); offset = buf.arrayOffset(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } buf.clear(); buf.release(); JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8); Object type = parsedObject.getString("type"); if ("BOOKED".equals(type) || type.equals("DONE")) { //LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject); String clientId = parsedObject.getString("client_id"); if (type.equals("BOOKED")) { if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return; var pair = parsedObject.getString("instrument_code"); sendCancelOrder(ctx, clientId, pair); } else { if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return; sendOrder(ctx); } if (orderResponseCount % test_size == 0) {
printResults(hdrRecorderForAggregation, test_size);
1
2023-10-22 19:04:39+00:00
4k