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
gunnarmorling/1brc
src/main/java/dev/morling/onebrc/CreateMeasurements2.java
[ { "identifier": "CheaperCharBuffer", "path": "src/main/java/org/rschwietzke/CheaperCharBuffer.java", "snippet": "public class CheaperCharBuffer implements CharSequence {\n // our data, can grow - that is not safe and has be altered from the original code\n // to allow speed\n public char[] data_;\n\n // the current size of the string data\n public int length_;\n\n // the current size of the string data\n private final int growBy_;\n\n // how much do we grow if needed, half a cache line\n public static final int CAPACITY_GROWTH = 64 / 2;\n\n // what is our start size?\n // a cache line is 64 byte mostly, the overhead is mostly 24 bytes\n // a char is two bytes, let's use one cache lines\n public static final int INITIAL_CAPACITY = (64 - 24) / 2;\n\n // static empty version; DON'T MODIFY IT\n public static final CheaperCharBuffer EMPTY = new CheaperCharBuffer(0);\n\n // the � character\n private static final char REPLACEMENT_CHARACTER = '\\uFFFD';\n\n /**\n * Constructs an XMLCharBuffer with a default size.\n */\n public CheaperCharBuffer() {\n this.data_ = new char[INITIAL_CAPACITY];\n this.length_ = 0;\n this.growBy_ = CAPACITY_GROWTH;\n }\n\n /**\n * Constructs an XMLCharBuffer with a desired size.\n *\n * @param startSize the size of the buffer to start with\n */\n public CheaperCharBuffer(final int startSize) {\n this(startSize, CAPACITY_GROWTH);\n }\n\n /**\n * Constructs an XMLCharBuffer with a desired size.\n *\n * @param startSize the size of the buffer to start with\n * @param growBy by how much do we want to grow when needed\n */\n public CheaperCharBuffer(final int startSize, final int growBy) {\n this.data_ = new char[startSize];\n this.length_ = 0;\n this.growBy_ = Math.max(1, growBy);\n }\n\n /**\n * Constructs an XMLCharBuffer from another buffer. Copies the data\n * over. The new buffer capacity matches the length of the source.\n *\n * @param src the source buffer to copy from\n */\n public CheaperCharBuffer(final CheaperCharBuffer src) {\n this(src, 0);\n }\n\n /**\n * Constructs an XMLCharBuffer from another buffer. Copies the data\n * over. You can add more capacity on top of the source length. If\n * you specify 0, the capacity will match the src length.\n *\n * @param src the source buffer to copy from\n * @param addCapacity how much capacity to add to origin length\n */\n public CheaperCharBuffer(final CheaperCharBuffer src, final int addCapacity) {\n this.data_ = Arrays.copyOf(src.data_, src.length_ + Math.max(0, addCapacity));\n this.length_ = src.length();\n this.growBy_ = Math.max(1, CAPACITY_GROWTH);\n }\n\n /**\n * Constructs an XMLCharBuffer from a string. To avoid\n * too much allocation, we just take the string array as is and\n * don't allocate extra space in the first place.\n *\n * @param src the string to copy from\n */\n public CheaperCharBuffer(final String src) {\n this.data_ = src.toCharArray();\n this.length_ = src.length();\n this.growBy_ = CAPACITY_GROWTH;\n }\n\n /**\n * Constructs an XMLString structure preset with the specified values.\n * There will not be any room to grow, if you need that, construct an\n * empty one and append.\n *\n * <p>There are not range checks performed. Make sure your data is correct.\n *\n * @param ch The character array, must not be null\n * @param offset The offset into the character array.\n * @param length The length of characters from the offset.\n */\n public CheaperCharBuffer(final char[] ch, final int offset, final int length) {\n // just as big as we need it\n this(length);\n append(ch, offset, length);\n }\n\n /**\n * Check capacity and grow if needed automatically\n *\n * @param minimumCapacity how much space do we need at least\n */\n private void ensureCapacity(final int minimumCapacity) {\n if (minimumCapacity > this.data_.length) {\n final int newSize = Math.max(minimumCapacity + this.growBy_, (this.data_.length << 1) + 2);\n this.data_ = Arrays.copyOf(this.data_, newSize);\n }\n }\n\n /**\n * Returns the current max capacity without growth. Does not\n * indicate how much capacity is already in use. Use {@link #length()}\n * for that.\n *\n * @return the current capacity, not taken any usage into account\n */\n public int capacity() {\n return this.data_.length;\n }\n\n /**\n * Appends a single character to the buffer.\n *\n * @param c the character to append\n * @return this instance\n */\n public CheaperCharBuffer append(final char c) {\n final int oldLength = this.length_++;\n\n // ensureCapacity is not inlined by the compiler, so put that here for the most\n // called method of all appends. Duplicate code, but for a reason.\n if (oldLength == this.data_.length) {\n final int newSize = Math.max(oldLength + this.growBy_, (this.data_.length << 1) + 2);\n this.data_ = Arrays.copyOf(this.data_, newSize);\n }\n\n this.data_[oldLength] = c;\n\n return this;\n }\n\n /**\n * Append a string to this buffer without copying the string first.\n *\n * @param src the string to append\n * @return this instance\n */\n public CheaperCharBuffer append(final String src) {\n final int start = this.length_;\n this.length_ = this.length_ + src.length();\n ensureCapacity(this.length_);\n\n // copy char by char because we don't get a copy for free\n // from a string yet, this might change when immutable arrays\n // make it into Java, but that will not be very soon\n for (int i = 0; i < src.length(); i++) {\n this.data_[start + i] = src.charAt(i);\n }\n\n return this;\n }\n\n /**\n * Add another buffer to this one.\n *\n * @param src the buffer to append\n * @return this instance\n */\n public CheaperCharBuffer append(final CheaperCharBuffer src) {\n final int start = this.length_;\n this.length_ = this.length_ + src.length();\n ensureCapacity(this.length_);\n\n System.arraycopy(src.data_, 0, this.data_, start, src.length_);\n\n return this;\n }\n\n /**\n * Add data from a char array to this buffer with the ability to specify\n * a range to copy from\n *\n * @param src the source char array\n * @param offset the pos to start to copy from\n * @param length the length of the data to copy\n *\n * @return this instance\n */\n public CheaperCharBuffer append(final char[] src, final int offset, final int length) {\n final int start = this.length_;\n this.length_ = start + length;\n\n ensureCapacity(this.length_);\n\n System.arraycopy(src, offset, this.data_, start, length);\n\n return this;\n }\n\n /**\n * Returns the current length\n *\n * @return the length of the charbuffer data\n */\n public int length() {\n return length_;\n }\n\n /**\n * Tell us how much the capacity grows if needed\n *\n * @return the value that determines how much we grow the backing\n * array in case we have to\n */\n public int getGrowBy() {\n return this.growBy_;\n }\n\n /**\n * Resets the buffer to 0 length. It won't resize it to avoid memory\n * churn.\n *\n * @return this instance for fluid programming\n */\n public CheaperCharBuffer clear() {\n this.length_ = 0;\n\n return this;\n }\n\n /**\n * Resets the buffer to 0 length and sets the new data. This\n * is a little cheaper than clear().append(c) depending on\n * the where and the inlining decisions.\n *\n * @param c the char to set\n * @return this instance for fluid programming\n */\n public CheaperCharBuffer clearAndAppend(final char c) {\n this.length_ = 0;\n\n if (this.data_.length > 0) {\n this.data_[this.length_] = c;\n this.length_++;\n }\n else {\n // the rare case when we don't have any buffer at hand\n append(c);\n }\n\n return this;\n }\n\n /**\n * Does this buffer end with this string? If we check for\n * the empty string, we get true. If we would support JDK 11, we could\n * use Arrays.mismatch and be way faster.\n *\n * @param s the string to check the end against\n * @return true of the end matches the buffer, false otherwise\n */\n public boolean endsWith(final String s) {\n // length does not match, cannot be the end\n if (this.length_ < s.length()) {\n return false;\n }\n\n // check the string by each char, avoids a copy of the string\n final int start = this.length_ - s.length();\n\n // change this to Arrays.mismatch when going JDK 11 or higher\n for (int i = 0; i < s.length(); i++) {\n if (this.data_[i + start] != s.charAt(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Reduces the buffer to the content between start and end marker when\n * only whitespaces are found before the startMarker as well as after the end marker.\n * If both strings overlap due to identical characters such as \"foo\" and \"oof\"\n * and the buffer is \" foof \", we don't do anything.\n *\n * <p>If a marker is empty, it behaves like {@link java.lang.String#trim()} on that side.\n *\n * @param startMarker the start string to find, must not be null\n * @param endMarker the end string to find, must not be null\n * @return this instance\n *\n * @deprecated Use the new method {@link #trimToContent(String, String)} instead.\n */\n public CheaperCharBuffer reduceToContent(final String startMarker, final String endMarker) {\n return trimToContent(startMarker, endMarker);\n }\n\n /**\n * Reduces the buffer to the content between start and end marker when\n * only whitespaces are found before the startMarker as well as after the end marker.\n * If both strings overlap due to identical characters such as \"foo\" and \"oof\"\n * and the buffer is \" foof \", we don't do anything.\n *\n * <p>If a marker is empty, it behaves like {@link java.lang.String#trim()} on that side.\n *\n * @param startMarker the start string to find, must not be null\n * @param endMarker the end string to find, must not be null\n * @return this instance\n */\n public CheaperCharBuffer trimToContent(final String startMarker, final String endMarker) {\n // if both are longer or same length than content, don't do anything\n final int markerLength = startMarker.length() + endMarker.length();\n if (markerLength >= this.length_) {\n return this;\n }\n\n // run over starting whitespaces\n int sPos = 0;\n for (; sPos < this.length_ - markerLength; sPos++) {\n if (!Character.isWhitespace(this.data_[sPos])) {\n break;\n }\n }\n\n // run over ending whitespaces\n int ePos = this.length_ - 1;\n for (; ePos > sPos - markerLength; ePos--) {\n if (!Character.isWhitespace(this.data_[ePos])) {\n break;\n }\n }\n\n // if we have less content than marker length, give up\n // this also helps when markers overlap such as\n // <!-- and --> and the string is \" <!---> \"\n if (ePos - sPos + 1 < markerLength) {\n return this;\n }\n\n // check the start\n for (int i = 0; i < startMarker.length(); i++) {\n if (startMarker.charAt(i) != this.data_[i + sPos]) {\n // no start match, stop and don't do anything\n return this;\n }\n }\n\n // check the end, ePos is when the first good char\n // occurred\n final int endStartCheckPos = ePos - endMarker.length() + 1;\n for (int i = 0; i < endMarker.length(); i++) {\n if (endMarker.charAt(i) != this.data_[endStartCheckPos + i]) {\n // no start match, stop and don't do anything\n return this;\n }\n }\n\n // shift left and cut length\n final int newLength = ePos - sPos + 1 - markerLength;\n System.arraycopy(this.data_,\n sPos + startMarker.length(),\n this.data_,\n 0, newLength);\n this.length_ = newLength;\n\n return this;\n }\n\n /**\n * Check if we have only whitespaces\n *\n * @return true if we have only whitespace, false otherwise\n */\n public boolean isWhitespace() {\n for (int i = 0; i < this.length_; i++) {\n if (!Character.isWhitespace(this.data_[i])) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Trims the string similar to {@link java.lang.String#trim()}\n *\n * @return a string with removed whitespace at the beginning and the end\n */\n public CheaperCharBuffer trim() {\n // clean the end first, because it is cheap\n return trimTrailing().trimLeading();\n }\n\n /**\n * Removes all whitespace before the first non-whitespace char.\n * If all are whitespaces, we get an empty buffer\n *\n * @return this instance\n */\n public CheaperCharBuffer trimLeading() {\n // run over starting whitespace\n int sPos = 0;\n for (; sPos < this.length_; sPos++) {\n if (!Character.isWhitespace(this.data_[sPos])) {\n break;\n }\n }\n\n if (sPos == 0) {\n // nothing to do\n return this;\n }\n else if (sPos == this.length_) {\n // only whitespace\n this.length_ = 0;\n return this;\n }\n\n // shift left\n final int newLength = this.length_ - sPos;\n System.arraycopy(this.data_,\n sPos,\n this.data_,\n 0, newLength);\n this.length_ = newLength;\n\n return this;\n }\n\n /**\n * Removes all whitespace at the end.\n * If all are whitespace, we get an empty buffer\n *\n * @return this instance\n *\n * @deprecated Use {@link #trimTrailing()} instead.\n */\n public CheaperCharBuffer trimWhitespaceAtEnd() {\n return trimTrailing();\n }\n\n /**\n * Removes all whitespace at the end.\n * If all are whitespace, we get an empty buffer\n *\n * @return this instance\n */\n public CheaperCharBuffer trimTrailing() {\n // run over ending whitespaces\n int ePos = this.length_ - 1;\n for (; ePos >= 0; ePos--) {\n if (!Character.isWhitespace(this.data_[ePos])) {\n break;\n }\n }\n\n this.length_ = ePos + 1;\n\n return this;\n }\n\n /**\n * Shortens the buffer by that many positions. If the count is\n * larger than the length, we get just an empty buffer. If you pass in negative\n * values, we are failing, likely often silently. It is all about performance and\n * not a general all-purpose API.\n *\n * @param count a positive number, no runtime checks, if count is larger than\n * length, we get length = 0\n * @return this instance\n */\n public CheaperCharBuffer shortenBy(final int count) {\n final int newLength = this.length_ - count;\n this.length_ = newLength < 0 ? 0 : newLength;\n\n return this;\n }\n\n /**\n * Get the characters as char array, this will be a copy!\n *\n * @return a copy of the underlying char darta\n */\n public char[] getChars() {\n return Arrays.copyOf(this.data_, this.length_);\n }\n\n /**\n * Returns a string representation of this buffer. This will be a copy\n * operation. If the buffer is emoty, we get a constant empty String back\n * to avoid any overhead.\n *\n * @return a string of the content of this buffer\n */\n @Override\n public String toString() {\n if (this.length_ > 0) {\n return new String(this.data_, 0, this.length_);\n }\n else {\n return \"\";\n }\n }\n\n /**\n * Returns the char a the given position. Will complain if\n * we try to read outside the range. We do a range check here\n * because we might not notice when we are within the buffer\n * but outside the current length.\n *\n * @param index the position to read from\n * @return the char at the position\n * @throws IndexOutOfBoundsException\n * in case one tries to read outside of valid buffer range\n */\n @Override\n public char charAt(final int index) {\n if (index > this.length_ - 1 || index < 0) {\n throw new IndexOutOfBoundsException(\n \"Tried to read outside of the valid buffer data\");\n }\n\n return this.data_[index];\n }\n\n /**\n * Returns the char at the given position. No checks are\n * performed. It is up to the caller to make sure we\n * read correctly. Reading outside of the array will\n * cause an {@link IndexOutOfBoundsException} but using an\n * incorrect position in the array (such as beyond length)\n * might stay unnoticed! This is a performance method,\n * use at your own risk.\n *\n * @param index the position to read from\n * @return the char at the position\n */\n public char unsafeCharAt(final int index) {\n return this.data_[index];\n }\n\n /**\n * Returns a content copy of this buffer\n *\n * @return a copy of this buffer, the capacity might differ\n */\n @Override\n public CheaperCharBuffer clone() {\n return new CheaperCharBuffer(this);\n }\n\n /**\n * Returns a <code>CharSequence</code> that is a subsequence of this sequence.\n * The subsequence starts with the <code>char</code> value at the specified index and\n * ends with the <code>char</code> value at index <tt>end - 1</tt>. The length\n * (in <code>char</code>s) of the\n * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>\n * then an empty sequence is returned.\n *\n * @param start the start index, inclusive\n * @param end the end index, exclusive\n *\n * @return the specified subsequence\n *\n * @throws IndexOutOfBoundsException\n * if <tt>start</tt> or <tt>end</tt> are negative,\n * if <tt>end</tt> is greater than <tt>length()</tt>,\n * or if <tt>start</tt> is greater than <tt>end</tt>\n *\n * @return a charsequence of this buffer\n */\n @Override\n public CharSequence subSequence(final int start, final int end) {\n if (start < 0) {\n throw new StringIndexOutOfBoundsException(start);\n }\n if (end > this.length_) {\n throw new StringIndexOutOfBoundsException(end);\n }\n\n final int l = end - start;\n if (l < 0) {\n throw new StringIndexOutOfBoundsException(l);\n }\n\n return new String(this.data_, start, l);\n }\n\n /**\n * Two buffers are identical when the length and\n * the content of the backing array (only for the\n * data in view) are identical.\n *\n * @param o the object to compare with\n * @return true if length and array content match, false otherwise\n */\n @Override\n public boolean equals(final Object o) {\n if (o instanceof CharSequence) {\n final CharSequence ob = (CharSequence) o;\n\n if (ob.length() != this.length_) {\n return false;\n }\n\n // ok, in JDK 11 or up, we could use an\n // Arrays.mismatch, but we cannot do that\n // due to JDK 8 compatibility\n for (int i = 0; i < this.length_; i++) {\n if (ob.charAt(i) != this.data_[i]) {\n return false;\n }\n }\n\n // length and content match, be happy\n return true;\n }\n\n return false;\n }\n\n /**\n * We don't cache the hashcode because we mutate often. Don't use this in\n * hashmaps as key. But you can use that to look up in a hashmap against\n * a string using the CharSequence interface.\n *\n * @return the hashcode, similar to what a normal string would deliver\n */\n @Override\n public int hashCode() {\n int h = 0;\n\n for (int i = 0; i < this.length_; i++) {\n h = ((h << 5) - h) + this.data_[i];\n }\n\n return h;\n }\n\n /**\n * Append a character to an XMLCharBuffer. The character is an int value, and\n * can either be a single UTF-16 character or a supplementary character\n * represented by two UTF-16 code points.\n *\n * @param value The character value.\n * @return this instance for fluid programming\n *\n * @throws IllegalArgumentException if the specified\n * {@code codePoint} is not a valid Unicode code point.\n */\n public CheaperCharBuffer appendCodePoint(final int value) {\n if (value <= Character.MAX_VALUE) {\n return this.append((char) value);\n }\n else {\n try {\n final char[] chars = Character.toChars(value);\n return this.append(chars, 0, chars.length);\n }\n catch (final IllegalArgumentException e) {\n // when value is not valid as UTF-16\n this.append(REPLACEMENT_CHARACTER);\n throw e;\n }\n }\n }\n}" }, { "identifier": "FastRandom", "path": "src/main/java/org/rschwietzke/FastRandom.java", "snippet": "public class FastRandom {\n private long seed;\n\n public FastRandom() {\n this.seed = System.currentTimeMillis();\n }\n\n public FastRandom(long seed) {\n this.seed = seed;\n }\n\n protected int next(int nbits) {\n // N.B. Not thread-safe!\n long x = this.seed;\n x ^= (x << 21);\n x ^= (x >>> 35);\n x ^= (x << 4);\n this.seed = x;\n\n x &= ((1L << nbits) - 1);\n\n return (int) x;\n }\n\n /**\n * Borrowed from the JDK\n *\n * @param bound\n * @return\n */\n public int nextInt(int bound) {\n int r = next(31);\n int m = bound - 1;\n if ((bound & m) == 0) // i.e., bound is a power of 2\n r = (int) ((bound * (long) r) >> 31);\n else {\n for (int u = r; u - (r = u % bound) + m < 0; u = next(31))\n ;\n }\n return r;\n }\n\n /**\n * Borrowed from the JDK\n * @return\n */\n public int nextInt() {\n return next(32);\n }\n}" } ]
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.rschwietzke.CheaperCharBuffer; import org.rschwietzke.FastRandom;
6,682
/* * Copyright 2023 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart; final FastRandom r = new FastRandom(ThreadLocalRandom.current().nextLong()); WeatherStation(String id, double meanTemperature) { this.id = id; this.meanTemperature = (int) meanTemperature; // make it directly copyable this.firstPart = (id + ";").toCharArray(); } /** * We write out data into the buffer to avoid string conversion * We also no longer use double and gaussian, because for our * purpose, the fake numbers here will do it. Less * * @param buffer the buffer to append to */
/* * Copyright 2023 The original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart; final FastRandom r = new FastRandom(ThreadLocalRandom.current().nextLong()); WeatherStation(String id, double meanTemperature) { this.id = id; this.meanTemperature = (int) meanTemperature; // make it directly copyable this.firstPart = (id + ";").toCharArray(); } /** * We write out data into the buffer to avoid string conversion * We also no longer use double and gaussian, because for our * purpose, the fake numbers here will do it. Less * * @param buffer the buffer to append to */
void measurement(final CheaperCharBuffer buffer) {
0
2023-12-28 09:13:24+00:00
8k
EnigmaGuest/fnk-server
service-core/service-core-system/src/main/java/fun/isite/service/core/system/impl/AdminUserService.java
[ { "identifier": "BaseService", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java", "snippet": "public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> {\n public final static String[] BASE_ENTITY_FIELDS = {\"id\", \"create_time\", \"update_time\", \"deleted\"};\n\n public final static String LIMIT_ONE = \"limit 1\";\n\n @Override\n public T getFirst(QueryWrapper<T> queryWrapper) {\n if (queryWrapper != null) {\n queryWrapper.last(LIMIT_ONE);\n }\n return this.getOne(queryWrapper);\n }\n\n @Override\n public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) {\n LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())\n .eq(T::getId, id);\n if(wrapperConsumer!=null){\n wrapperConsumer.accept(wrapper);\n }\n wrapper.last(LIMIT_ONE);\n return this.getOne(wrapper);\n }\n\n @Override\n public T getFirst(LambdaQueryWrapper<T> queryWrapper) {\n if (queryWrapper != null) {\n queryWrapper.last(LIMIT_ONE);\n }\n return this.getOne(queryWrapper);\n }\n\n @Override\n public T getByField(SFunction<T, ?> field, String value) {\n return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value));\n }\n\n @Override\n public PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery) {\n QueryWrapper<T> wrapper = new QueryWrapper<>();\n wrapper.like(dto.getId() != null, \"id\", dto.getId());\n wrapper.ge(StrUtil.isNotBlank(dto.getCreateTime()), \"create_time\", dto.getCreateTime());\n wrapper.ge(StrUtil.isNotBlank(dto.getUpdateTime()), \"update_time\", dto.getUpdateTime());\n LambdaQueryWrapper<T> lambdaQueryWrapper = wrapper.lambda();\n lambdaQueryWrapper.orderBy(orderByField != null, dto.isAsc(), orderByField);\n if (customQuery != null) {\n customQuery.query(lambdaQueryWrapper);\n }\n int pageSize = dto.getPageSize();\n if (pageSize < 0) {\n pageSize = 1000;\n }\n return new PageVO<>(this.page(new Page<>(dto.getPage(), pageSize), wrapper));\n }\n\n @Override\n public void resetBaseField(T t) {\n if (t != null) {\n t.setId(null);\n t.setCreateTime(null);\n t.setUpdateTime(null);\n t.setDeleted((short) 0);\n }\n }\n\n private LambdaQueryWrapper<T> getIdCustomQueryConsumer(String id, Consumer<LambdaQueryWrapper<T>> consumer) {\n LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())\n .eq(T::getId, id);\n if (consumer != null) {\n consumer.accept(wrapper);\n }\n return wrapper;\n }\n\n @Override\n public T create(T req) {\n this.resetBaseField(req);\n AssertUtils.isFalse(req.insert(), \"创建\" + getServiceModelName() + \"失败\");\n this.redisHashSet(false, req);\n return req;\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public List<T> create(List<T> reqs) {\n reqs.forEach(this::resetBaseField);\n AssertUtils.isFalse(this.saveBatch(reqs), \"批量创建\" + getServiceModelName() + \"失败\");\n this.redisHashSet(false, reqs, null);\n return reqs;\n }\n\n @Override\n public T update(String id, T req) {\n return this.update(id, req, null);\n }\n\n @Override\n public T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query) {\n T model = this.detail(id, query);\n BeanUtils.copyProperties(req, model, BASE_ENTITY_FIELDS);\n AssertUtils.isFalse(model.updateById(), \"更新\" + getServiceModelName() + \"失败\");\n this.redisHashSet(false, req);\n return model;\n }\n\n @Override\n public void removeSingle(String id) {\n this.removeSingle(id, null);\n }\n\n @Override\n public void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {\n String msg = \"删除\" + getServiceModelName() + \"失败\";\n if (query == null) {\n AssertUtils.isFalse(this.removeById(id), msg);\n } else {\n AssertUtils.isFalse(this.remove(this.getIdCustomQueryConsumer(id, query)), msg);\n }\n this.redisHashSet(true, null, CollUtil.newArrayList(id));\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public void remove(List<String> idList) {\n this.remove(idList, null);\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query) {\n String msg = \"批量\" + getServiceModelName() + \"删除失败\";\n if (query == null) {\n AssertUtils.isFalse(this.removeBatchByIds(idList), msg);\n } else {\n LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())\n .in(T::getId, idList);\n query.accept(wrapper);\n AssertUtils.isFalse(this.remove(wrapper), msg);\n }\n this.redisHashSet(true, null, idList);\n }\n\n @Override\n public T detail(String id) {\n return this.detail(id, null);\n }\n\n @Override\n public T detail(Consumer<LambdaQueryWrapper<T>> consumer) {\n LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass());\n consumer.accept(wrapper);\n return this.getFirst(wrapper);\n }\n\n @Override\n public T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {\n T model;\n if (query == null) {\n model = this.redisHashGet(id);\n if (model != null) {\n return model;\n }\n model = this.getById(id);\n } else {\n model = this.getFirst(this.getIdCustomQueryConsumer(id, query));\n }\n AssertUtils.isNull(model, \"目标\" + getServiceModelName() + \"不存在\");\n return model;\n }\n private T redisHashGet(String id) {\n String cacheKey = this.getModelHashCacheKey();\n RedisUtils redisUtil = RedisUtils.getINSTANCE();\n if (cacheKey != null && redisUtil != null) {\n return redisUtil.hGet(cacheKey, id, getEntityClass());\n }\n return null;\n }\n\n\n @Override\n public T getLastByCreateTime(@Nullable CustomBasicPageQuery<T> customQuery) {\n LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>(getEntityClass()).orderByDesc(T::getCreateTime);\n if (customQuery != null) {\n customQuery.query(wrapper);\n }\n return this.getFirst(wrapper);\n }\n\n @Override\n public String getServiceModelName() {\n return \"\";\n }\n\n @Override\n public String getServiceModelCacheId(T t) {\n return t.getId();\n }\n\n\n\n @Override\n public String getModelHashCacheKey() {\n return null;\n }\n\n\n @Override\n public <V> PageVO<V> pageToVO(PageVO<T> page, Class<V> targetClass) {\n final PageVO<V> res = new PageVO<>();\n try {\n BeanUtils.copyProperties(page, res, \"records\");\n List<V> records = new ArrayList<>(page.getRecords().size());\n for (T record : page.getRecords()) {\n final V v = targetClass.newInstance();\n BeanUtils.copyProperties(record, v);\n records.add(v);\n }\n res.setRecords(records);\n } catch (Exception e) {\n log.error(\"分页数据转换失败\", e);\n throw new LogicException(\"分页数据转换失败\");\n }\n return res;\n }\n protected void redisHashSet(boolean remove, List<T> models, List<String> removeIdList) {\n String cacheKey = this.getModelHashCacheKey();\n RedisUtils redisUtil = RedisUtils.getINSTANCE();\n if (cacheKey != null && redisUtil != null) {\n if (CollUtil.isNotEmpty(models)) {\n for (T model : models) {\n String cacheId = this.getServiceModelCacheId(model);\n if (remove) {\n redisUtil.hDel(cacheKey, cacheId);\n } else {\n redisUtil.hSet(cacheKey, cacheId, model);\n }\n }\n }\n if (CollUtil.isNotEmpty(removeIdList)) {\n redisUtil.hDel(cacheKey, ArrayUtil.toArray(removeIdList, String.class));\n }\n }\n }\n\n private void redisHashSet(boolean remove, T model) {\n this.redisHashSet(remove, CollUtil.newArrayList(model), null);\n }\n}" }, { "identifier": "AssertUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/lang/AssertUtils.java", "snippet": "public class AssertUtils {\n public static void isTrue(Boolean expression, String message) {\n if (expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isFalse(Boolean expression, String message) {\n if (!expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isLeZero(Integer expression, String message) {\n if (expression <= 0) {\n throw new LogicException(message);\n }\n }\n\n public static void isNull(Object obj, String message) {\n if (obj == null || BeanUtil.isEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isNotNull(Object obj, String message) {\n if (BeanUtil.isNotEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(String str, String message) {\n if (StrUtil.isEmpty(str)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Collection<?> collection, String message) {\n if (CollUtil.isEmpty(collection)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Iterable<?> iterable, String message) {\n if (CollUtil.isEmpty(iterable)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Map<?, ?> map, String message) {\n if (CollUtil.isEmpty(map)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(List<?> list, String message) {\n if (CollUtil.isEmpty(list)) {\n throw new LogicException(message);\n }\n }\n\n public static void isBlank(String str, String message) {\n if (StrUtil.isBlank(str)) {\n throw new LogicException(message);\n }\n }\n}" }, { "identifier": "SaltUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/utils/SaltUtils.java", "snippet": "public class SaltUtils {\n\n // 生成盐\n public static String getSalt(int n) {\n char[] chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()\".toCharArray();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < n; i++) {\n sb.append(chars[(int) (Math.random() * chars.length)]);\n }\n return sb.toString();\n }\n\n}" }, { "identifier": "GenderType", "path": "service-core/service-core-basic/src/main/java/fun/isite/service/core/basic/enums/GenderType.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum GenderType implements IBaseEnum<String> {\n\n // 性别 男 女\n MAN(\"0\"),\n WOMAN(\"1\"),\n OTHER(\"2\");\n\n private final String value;\n}" }, { "identifier": "TokenVO", "path": "service-core/service-core-basic/src/main/java/fun/isite/service/core/basic/vo/TokenVO.java", "snippet": "@Data\n@Schema(name = \"授权信息\")\npublic class TokenVO implements Serializable {\n /**\n * token名称\n */\n @Schema(name = \"token名称\")\n public String tokenName;\n\n /**\n * token值\n */\n @Schema(name = \"token值\")\n public String tokenValue;\n\n /**\n * 此token是否已经登录\n */\n @Schema(name = \"此token是否已经登录\")\n public Boolean isLogin;\n\n /**\n * 此token对应的LoginId,未登录时为null\n */\n @Schema(name = \"此token对应的LoginId,未登录时为null\")\n public Object loginId;\n\n /**\n * 账号类型\n */\n @Schema(name = \"账号类型\")\n public String loginType;\n\n /**\n * token剩余有效期 (单位: 秒)\n */\n @Schema(name = \"token剩余有效期 (单位: 秒)\")\n public long tokenTimeout;\n\n /**\n * User-Session剩余有效时间 (单位: 秒)\n */\n @Schema(name = \"User-Session剩余有效时间 (单位: 秒)\")\n public long sessionTimeout;\n\n /**\n * Token-Session剩余有效时间 (单位: 秒)\n */\n @Schema(name = \"Token-Session剩余有效时间 (单位: 秒)\")\n public long tokenSessionTimeout;\n\n /**\n * token剩余无操作有效时间 (单位: 秒)\n */\n @Schema(name = \"token剩余无操作有效时间 (单位: 秒)\")\n public long tokenActivityTimeout;\n\n /**\n * 登录设备标识\n */\n @Schema(name = \"登录设备标识\")\n public String loginDevice;\n\n /**\n * 自定义数据\n */\n @Schema(name = \"自定义数据\")\n public String tag;\n\n\n\n\n public static TokenVO generateFromSaToken(SaTokenInfo info) {\n TokenVO vo = new TokenVO();\n BeanUtils.copyProperties(info, vo);\n return vo;\n }\n}" }, { "identifier": "AdminUser", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/AdminUser.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"admin_user\")\n@Schema(name = \"AdminUser\", description = \"系统用户\")\npublic class AdminUser extends BaseEntity<AdminUser> {\n\n\n\n /**\n * 手机号\n */\n @Schema(description=\"手机号\")\n @NotBlank(message = \"手机号码不能为空\")\n private String phone;\n\n /**\n * 密码\n */\n @Schema(description=\"密码\")\n private String password;\n\n /**\n * 盐\n */\n @Schema(description=\"盐\")\n private String salt;\n\n /**\n * 用户名称\n */\n @Schema(description=\"用户名称\")\n private String username;\n\n /**\n * 用户头像\n */\n @Schema(description=\"用户头像\")\n private String avatar;\n\n /**\n * 用户性别\n */\n @Schema(description=\"用户性别\")\n private GenderType sex;\n\n /**\n * 登录ip\n */\n @Schema(description=\"登录ip\")\n private String loginIp;\n\n /**\n * 部门ID\n */\n @Schema(description=\"部门ID\")\n private String deptId;\n\n /**\n * 用户状态;0正常 1不可用\n */\n @Schema(description=\"用户状态\")\n private Boolean status;\n\n /**\n * 角色ID\n */\n @TableField(exist = false)\n @Size(min = 1,message = \"必须分配角色给用户\")\n private List<String> roleIdList;\n\n}" }, { "identifier": "AdminUserMapper", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/mapper/AdminUserMapper.java", "snippet": "@Mapper\npublic interface AdminUserMapper extends BaseMapper<AdminUser> {\n\n}" }, { "identifier": "IAdminUserService", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/service/IAdminUserService.java", "snippet": "public interface IAdminUserService extends IBaseService<AdminUser> {\n\n void initAdminUser();\n\n /**\n * 保存用户\n * @param adminUser\n * @return\n */\n AdminUser saveAdminUser(AdminUser adminUser);\n\n /**\n * 更新用户\n * @param adminUser\n * @return\n */\n\n AdminUser updateAdminUser(AdminUser adminUser);\n\n /**\n * 查询用户详情\n * @param userId 用户id\n * @return 用户详情\n */\n AdminUser queryDetail(String userId);\n\n /**\n * 登录\n *\n * @param loginAdminDTO 登录信息\n * @return token\n */\n TokenVO login(LoginAdminDTO loginAdminDTO);\n\n /**\n * 手机号码是否存在\n *\n * @param phone 手机号码\n * @param userId 排除的用户id\n * @return true 存在\n */\n Boolean isPhoneExist(String phone, String userId);\n\n\n AdminUserVO getCurrentAdminInfo(String s);\n\n /**\n * 查询用户角色ID列表\n * @param userId\n * @return\n */\n List<String> queryUserRoleIds(String userId);\n}" }, { "identifier": "IUserRoleService", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/service/IUserRoleService.java", "snippet": "public interface IUserRoleService extends IBaseService<UserRole> {\n\n\n /**\n * 保存用户角色\n * @param userId\n * @param roleIds\n * @return\n */\n boolean saveUserRole(String userId, List<String> roleIds);\n\n int deleteByUserId(String userId);\n\n /**\n * 查询用户角色ID\n * @param userId 用户id\n * @return 用户角色id\n */\n List<String> queryRoleIdsByUserId(String userId);\n\n /**\n * 查询用户菜单\n * @param userId\n * @return\n */\n List<SystemMenu> queryMenusByUserId(String userId);\n\n /**\n * 查询用户角色key\n * @param userId\n * @return\n */\n List<String> queryRoleKey(String userId);\n\n\n\n /**\n * 查询用户权限key\n * @param userId\n * @return\n */\n List<String> queryPermissionKeyByUserId(String userId);\n}" }, { "identifier": "AdminUserVO", "path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/vo/AdminUserVO.java", "snippet": "@Data\n@Schema(description = \"管理员信息\")\npublic class AdminUserVO {\n\n\n private String id;\n\n /**\n * 手机号\n */\n @Schema(description = \"手机号\")\n private String phone;\n\n\n /**\n * 用户名称\n */\n @Schema(description = \"用户名称\")\n private String username;\n\n /**\n * 用户头像\n */\n @Schema(description = \"用户头像\")\n private String avatar;\n\n /**\n * 用户性别\n */\n @Schema(description = \"用户性别\")\n private GenderType sex;\n\n\n // 权限信息\n\n private List<String> roles;\n\n // 权限菜单\n private List<SystemMenu> menus;\n public static AdminUserVO build(AdminUser adminUser) {\n AdminUserVO adminUserVO = new AdminUserVO();\n BeanUtils.copyProperties(adminUser, adminUserVO);\n return adminUserVO;\n }\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import fun.isite.service.common.db.impl.BaseService; import fun.isite.service.common.tools.lang.AssertUtils; import fun.isite.service.common.tools.utils.SaltUtils; import fun.isite.service.core.basic.enums.GenderType; import fun.isite.service.core.basic.vo.TokenVO; import fun.isite.service.core.system.dto.LoginAdminDTO; import fun.isite.service.core.system.entity.AdminUser; import fun.isite.service.core.system.mapper.AdminUserMapper; import fun.isite.service.core.system.service.IAdminUserService; import fun.isite.service.core.system.service.IUserRoleService; import fun.isite.service.core.system.vo.AdminUserVO; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List;
5,096
package fun.isite.service.core.system.impl; /** * 系统用户 服务实现层 * * @author Enigma * @since 2023-12-18 */ @Service @AllArgsConstructor
package fun.isite.service.core.system.impl; /** * 系统用户 服务实现层 * * @author Enigma * @since 2023-12-18 */ @Service @AllArgsConstructor
public class AdminUserService extends BaseService<AdminUserMapper, AdminUser> implements IAdminUserService {
6
2023-12-26 01:55:01+00:00
8k
codingmiao/hppt
cc/src/main/java/org/wowtools/hppt/cc/StartCc.java
[ { "identifier": "CcConfig", "path": "cc/src/main/java/org/wowtools/hppt/cc/pojo/CcConfig.java", "snippet": "public class CcConfig {\n /**\n * 客户端id,每个cc.jar用一个,不要重复\n */\n public String clientId;\n\n /**\n * 服务端http地址,可以填nginx转发过的地址\n */\n public String serverUrl;\n\n /**\n * 开始时闲置几毫秒发一次http请求,越短延迟越低但越耗性能\n */\n public long initSleepTime = 1_000;\n\n /**\n * 当收到空消息时,闲置毫秒数增加多少毫秒\n */\n public long addSleepTime = 1_000;\n\n /**\n * 当用户端输入字节时,唤醒发送线程,此后多少毫秒不睡眠\n */\n public long awakenTime = 10_000;\n\n /**\n * 闲置毫秒数最大到多少毫秒\n */\n public long maxSleepTime = 60_000;\n\n /**\n * 兜底策略,会话超过多少毫秒未确认后自行关闭\n */\n public long sessionTimeout = 60_000;\n\n /**\n * 向服务端发数据请求体的字节数最大值\n * 有时会出现413 Request Entity Too Large问题,没办法改nginx的话就用这个值限制\n */\n public int maxSendBodySize = Integer.MAX_VALUE;\n\n /**\n * 是否启用压缩,默认启用 需和服务端保持一致\n */\n public boolean enableCompress = true;\n\n /**\n * 是否启用内容加密,默认启用 需和服务端保持一致\n */\n public boolean enableEncrypt = true;\n\n /**\n * 缓冲区最大允许缓冲多少条消息\n */\n public int messageQueueSize = 10240;\n}" }, { "identifier": "ClientSessionService", "path": "cc/src/main/java/org/wowtools/hppt/cc/service/ClientSessionService.java", "snippet": "@Slf4j\npublic class ClientSessionService {\n\n private static final String talkUri = StartCc.config.serverUrl + \"/talk?c=\";\n private static long sleepTime = StartCc.config.initSleepTime - StartCc.config.addSleepTime;\n private static long noSleepLimitTime = 0;\n private static final AtomicBoolean sleeping = new AtomicBoolean(false);\n\n private static final Thread sendThread;\n\n\n static {\n sendThread = new Thread(() -> {\n while (true) {\n try {\n /* 发请求 */\n boolean isEmpty = sendToSs();\n\n /* 睡眠发送线程策略 */\n if (noSleepLimitTime > System.currentTimeMillis()) {\n //线程刚刚被唤醒,不睡眠\n sleepTime = StartCc.config.initSleepTime;\n log.debug(\"线程刚刚被唤醒 {}\", sleepTime);\n } else if (isEmpty) {\n //收发数据包都为空,逐步增加睡眠时间\n if (sleepTime < StartCc.config.maxSleepTime) {\n sleepTime += StartCc.config.addSleepTime;\n }\n log.debug(\"收发数据包都为空,逐步增加睡眠时间 {}\", sleepTime);\n } else {\n sleepTime = StartCc.config.initSleepTime;\n log.debug(\"正常包 {}\", sleepTime);\n }\n if (sleepTime > 0) {\n sleeping.set(true);\n try {\n log.debug(\"sleep {}\", sleepTime);\n Thread.sleep(sleepTime);\n } catch (InterruptedException e) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n }\n } catch (Exception e) {\n log.warn(\"发消息到服务端发生异常\", e);\n sleeping.set(true);\n try {\n Thread.sleep(StartCc.config.maxSleepTime);\n } catch (InterruptedException e1) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n StartCc.tryLogin();\n }\n }\n });\n }\n\n public static void start() {\n //启动轮询发送http请求线程\n sendThread.start();\n //起一个线程,定期检查超时session\n new Thread(() -> {\n while (true) {\n try {\n Thread.sleep(StartCc.config.sessionTimeout);\n log.debug(\"定期检查,当前session数 {}\", ClientSessionManager.clientSessionMap.size());\n for (Map.Entry<Integer, ClientSession> entry : ClientSessionManager.clientSessionMap.entrySet()) {\n ClientSession session = entry.getValue();\n if (session.isTimeOut()) {\n ClientSessionManager.disposeClientSession(session, \"超时不活跃\");\n }\n }\n\n } catch (Exception e) {\n log.warn(\"定期检查超时session异常\", e);\n }\n }\n }).start();\n }\n\n /**\n * 发请求\n *\n * @return 是否为空包 即发送和接收都是空\n * @throws Exception Exception\n */\n private static boolean sendToSs() throws Exception {\n boolean isEmpty = true;\n List<ProtoMessage.BytesPb> bytePbList = new LinkedList<>();\n //发字节\n ClientSessionManager.clientSessionMap.forEach((sessionId, clientSession) -> {\n byte[] bytes = clientSession.fetchSendSessionBytes();\n if (bytes != null) {\n bytePbList.add(ProtoMessage.BytesPb.newBuilder()\n .setSessionId(clientSession.getSessionId())\n .setBytes(ByteString.copyFrom(bytes))\n .build()\n );\n }\n });\n if (!bytePbList.isEmpty()) {\n isEmpty = false;\n }\n //发命令\n List<String> commands = new LinkedList<>();\n {\n StringBuilder closeSession = new StringBuilder().append(Constant.CsCommands.CloseSession);\n StringBuilder checkActiveSession = new StringBuilder().append(Constant.CsCommands.CheckSessionActive);\n\n ClientSessionManager.clientSessionMap.forEach((sessionId, session) -> {\n if (session.isNeedCheckActive()) {\n checkActiveSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n });\n\n List<Integer> closedClientSessions = ClientSessionManager.fetchClosedClientSessions();\n if (null != closedClientSessions) {\n for (Integer sessionId : closedClientSessions) {\n closeSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n }\n\n if (closeSession.length() > 1) {\n commands.add(closeSession.toString());\n }\n if (checkActiveSession.length() > 1) {\n commands.add(checkActiveSession.toString());\n }\n }\n cutSendToSs(bytePbList, commands);\n return isEmpty;\n }\n\n //如果请求体过大,会出现413 Request Entity Too Large,拆分一下发送\n private static boolean cutSendToSs(List<ProtoMessage.BytesPb> bytePbs, List<String> commands) throws Exception {\n List<ProtoMessage.BytesPb> bytesPbList = new LinkedList<>();\n List<String> commandList = new LinkedList<>();\n int requestBodyLength = 0;\n\n while (!bytePbs.isEmpty()) {\n if (bytePbs.getFirst().getBytes().size() > StartCc.config.maxSendBodySize) {\n //单个bytePb包含的字节数就超过限制了,那把bytes拆小\n ProtoMessage.BytesPb bytePb = bytePbs.removeFirst();\n byte[][] splitBytes = BytesUtil.splitBytes(bytePb.getBytes().toByteArray(), StartCc.config.maxSendBodySize);\n for (int i = splitBytes.length - 1; i >= 0; i--) {\n bytePbs.addFirst(ProtoMessage.BytesPb.newBuilder()\n .setBytes(ByteString.copyFrom(splitBytes[i]))\n .setSessionId(bytePb.getSessionId())\n .build());\n }\n } else {\n requestBodyLength += bytePbs.getFirst().getBytes().size();\n if (requestBodyLength > StartCc.config.maxSendBodySize) {\n break;\n }\n bytesPbList.add(bytePbs.removeFirst());\n }\n\n }\n\n while (!commands.isEmpty()) {\n if (commands.getFirst().length() > StartCc.config.maxSendBodySize) {\n throw new RuntimeException(\"maxSendBodySize 的值过小导致无法发送命令,请调整\");\n }\n requestBodyLength += commands.getFirst().length();//注意,这里限定了命令只能是ASCII字符\n if (requestBodyLength > StartCc.config.maxSendBodySize) {\n break;\n }\n commandList.add(commands.removeFirst());\n }\n log.debug(\"requestBodyLength {}\", requestBodyLength);\n boolean isEmpty = subSendToSs(bytesPbList, commandList);\n if (bytePbs.isEmpty() && commands.isEmpty()) {\n return isEmpty;\n } else {\n return cutSendToSs(bytePbs, commands);\n }\n }\n\n\n //发送和接收\n private static boolean subSendToSs(List<ProtoMessage.BytesPb> bytesPbList, List<String> commandList) throws Exception {\n boolean isEmpty = true;\n\n ProtoMessage.MessagePb.Builder messagePbBuilder = ProtoMessage.MessagePb.newBuilder();\n if (!bytesPbList.isEmpty()) {\n messagePbBuilder.addAllBytesPbList(bytesPbList);\n }\n if (!commandList.isEmpty()) {\n messagePbBuilder.addAllCommandList(commandList);\n }\n byte[] requestBody = messagePbBuilder.build().toByteArray();\n\n //压缩、加密\n if (StartCc.config.enableCompress) {\n requestBody = BytesUtil.compress(requestBody);\n }\n if (StartCc.config.enableEncrypt) {\n requestBody = StartCc.aesCipherUtil.encryptor.encrypt(requestBody);\n }\n\n log.debug(\"发送数据 bytesPbs {} commands {} 字节数 {}\", bytesPbList.size(), commandList.size(), requestBody.length);\n\n Response response;\n if (log.isDebugEnabled()) {\n long t = System.currentTimeMillis();\n response = HttpUtil.doPost(talkUri + StartCc.loginCode, requestBody);\n log.debug(\"发送http请求耗时 {}\", System.currentTimeMillis() - t);\n } else {\n response = HttpUtil.doPost(talkUri + StartCc.loginCode, requestBody);\n }\n\n\n byte[] responseBody;\n try {\n if (\"not_login\".equals(response.headers().get(\"err\"))) {\n //发现未登录标识,尝试重新登录\n StartCc.tryLogin();\n return true;\n }\n assert response.body() != null;\n responseBody = response.body().bytes();\n } finally {\n response.close();\n }\n\n ProtoMessage.MessagePb rMessagePb;\n byte[] responseBody0 = responseBody;\n try {\n //解密、解压\n if (StartCc.config.enableEncrypt) {\n responseBody = StartCc.aesCipherUtil.descriptor.decrypt(responseBody);\n }\n if (StartCc.config.enableCompress) {\n responseBody = BytesUtil.decompress(responseBody);\n }\n log.debug(\"收到服务端发回字节数 {}\", responseBody.length);\n rMessagePb = ProtoMessage.MessagePb.parseFrom(responseBody);\n } catch (Exception e) {\n log.warn(\"服务端响应错误 [{}]\", new String(responseBody0, StandardCharsets.UTF_8), e);\n StartCc.tryLogin();\n return true;\n }\n\n //收命令\n for (String command : rMessagePb.getCommandListList()) {\n log.debug(\"收到服务端命令 {} \", command);\n char type = command.charAt(0);\n switch (type) {\n case Constant.CcCommands.CloseSession -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n if (strSessionId.isEmpty()) {\n continue;\n }\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(Integer.parseInt(strSessionId));\n if (null != clientSession) {\n ClientSessionManager.disposeClientSession(clientSession, \"服务端发送关闭命令\");\n }\n }\n }\n case Constant.CcCommands.ActiveSession -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n ClientSession session = ClientSessionManager.getClientSession(Integer.parseInt(strSessionId));\n if (session != null) {\n session.activeSession();\n }\n }\n }\n case Constant.CcCommands.CreateSession -> {\n //2sessionId host port\n String[] strs = command.substring(1).split(\" \");\n int sessionId = Integer.parseInt(strs[0]);\n String host = strs[1];\n int port = Integer.parseInt(strs[2]);\n ClientSessionManager.createClientSession(host, port, sessionId);\n }\n }\n }\n\n //收字节\n List<ProtoMessage.BytesPb> rBytesPbListList = rMessagePb.getBytesPbListList();\n if (!rBytesPbListList.isEmpty()) {\n isEmpty = false;\n for (ProtoMessage.BytesPb bytesPb : rBytesPbListList) {\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(bytesPb.getSessionId());\n if (clientSession != null) {\n clientSession.putBytes(bytesPb.getBytes().toByteArray());\n }\n }\n noSleepLimitTime = System.currentTimeMillis() + StartCc.config.awakenTime;\n }\n\n return isEmpty;\n }\n\n /**\n * 唤醒发送线程\n */\n public static void awakenSendThread() {\n if (sleeping.get()) {\n try {\n sleepTime = StartCc.config.initSleepTime;\n sendThread.interrupt();\n log.info(\"唤醒发送线程\");\n } catch (Exception e) {\n log.warn(\"唤醒线程异常\", e);\n }\n }\n }\n\n}" }, { "identifier": "AesCipherUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/AesCipherUtil.java", "snippet": "@Slf4j\npublic class AesCipherUtil {\n\n public final Encryptor encryptor;\n\n public final Descriptor descriptor;\n\n\n public AesCipherUtil(String strKey, long ts) {\n strKey = strKey + (ts / (30 * 60 * 1000));\n SecretKey key = generateKey(strKey);\n this.encryptor = new Encryptor(key);\n this.descriptor = new Descriptor(key);\n }\n\n /**\n * 加密器\n */\n public static final class Encryptor {\n private final Cipher cipher;\n\n private Encryptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.ENCRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] encrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n /**\n * 解密器\n */\n public static final class Descriptor {\n private final Cipher cipher;\n\n private Descriptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.DECRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] decrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n private static final int n = 16;\n\n private static SecretKey generateKey(String input) {\n try {\n KeyGenerator kgen = KeyGenerator.getInstance(\"AES\");// 创建AES的Key生产者\n SecureRandom secureRandom = SecureRandom.getInstance(\"SHA1PRNG\");\n secureRandom.setSeed(input.getBytes());\n kgen.init(128, secureRandom);\n\n SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥\n return secretKey;\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n}" }, { "identifier": "BytesUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/BytesUtil.java", "snippet": "public class BytesUtil {\n /**\n * 按每个数组的最大长度限制,将一个数组拆分为多个\n *\n * @param originalArray 原数组\n * @param maxChunkSize 最大长度限制\n * @return 拆分结果\n */\n public static byte[][] splitBytes(byte[] originalArray, int maxChunkSize) {\n int length = originalArray.length;\n int numOfChunks = (int) Math.ceil((double) length / maxChunkSize);\n byte[][] splitArrays = new byte[numOfChunks][];\n\n for (int i = 0; i < numOfChunks; i++) {\n int start = i * maxChunkSize;\n int end = Math.min((i + 1) * maxChunkSize, length);\n int chunkSize = end - start;\n\n byte[] chunk = new byte[chunkSize];\n System.arraycopy(originalArray, start, chunk, 0, chunkSize);\n\n splitArrays[i] = chunk;\n }\n\n return splitArrays;\n }\n\n /**\n * 合并字节集合为一个byte[]\n *\n * @param collection 字节集合\n * @return byte[]\n */\n public static byte[] merge(Collection<byte[]> collection) {\n byte[] bytes;\n try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {\n for (byte[] byteArray : collection) {\n byteArrayOutputStream.write(byteArray);\n }\n bytes = byteArrayOutputStream.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return bytes;\n }\n\n /**\n * bytes转base64字符串\n *\n * @param bytes bytes\n * @return base64字符串\n */\n public static String bytes2base64(byte[] bytes) {\n return Base64.getEncoder().encodeToString(bytes);\n }\n\n /**\n * base64字符串转bytes\n *\n * @param base64 base64字符串\n * @return bytes\n */\n public static byte[] base642bytes(String base64) {\n return Base64.getDecoder().decode(base64);\n }\n\n // 使用GZIP压缩字节数组\n public static byte[] compress(byte[] input) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {\n gzipOutputStream.write(input);\n }\n return baos.toByteArray();\n }\n\n // 使用GZIP解压缩字节数组\n public static byte[] decompress(byte[] compressed) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ByteArrayInputStream bais = new ByteArrayInputStream(compressed);\n try (java.util.zip.GZIPInputStream gzipInputStream = new java.util.zip.GZIPInputStream(bais)) {\n byte[] buffer = new byte[1024];\n int len;\n while ((len = gzipInputStream.read(buffer)) > 0) {\n baos.write(buffer, 0, len);\n }\n }\n return baos.toByteArray();\n }\n\n public static ByteBuf bytes2byteBuf(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = ctx.alloc().buffer(bytes.length, bytes.length);\n byteBuf.writeBytes(bytes);\n return byteBuf;\n }\n\n //把字节写入ChannelHandlerContext\n public static void writeToChannelHandlerContext(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = bytes2byteBuf(ctx, bytes);\n ctx.writeAndFlush(byteBuf);\n }\n\n public static byte[] byteBuf2bytes(ByteBuf byteBuf) {\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes(bytes);\n return bytes;\n }\n\n\n\n}" }, { "identifier": "Constant", "path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java", "snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory());\n\n public static final String sessionIdJoinFlag = \",\";\n\n //ss端执行的命令代码\n public static final class SsCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n }\n\n //Sc端执行的命令代码\n public static final class ScCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //Cs端执行的命令代码\n public static final class CsCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //cc端执行的命令代码\n public static final class CcCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n\n //新建会话 2sessionId host port\n public static final char CreateSession = '2';\n }\n\n}" }, { "identifier": "HttpUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/HttpUtil.java", "snippet": "@Slf4j\npublic class HttpUtil {\n\n private static final okhttp3.MediaType bytesMediaType = okhttp3.MediaType.parse(\"application/octet-stream\");\n\n private static final OkHttpClient okHttpClient;\n\n static {\n okHttpClient = new OkHttpClient.Builder()\n .sslSocketFactory(sslSocketFactory(), x509TrustManager())\n // 是否开启缓存\n .retryOnConnectionFailure(false)\n .connectionPool(pool())\n .connectTimeout(30L, TimeUnit.SECONDS)\n .readTimeout(30L, TimeUnit.SECONDS)\n .writeTimeout(30L, TimeUnit.SECONDS)\n .hostnameVerifier((hostname, session) -> true)\n // 设置代理\n// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"127.0.0.1\", 8888)))\n // 拦截器\n// .addInterceptor()\n .build();\n\n }\n\n\n public static Response doGet(String url) {\n Request.Builder builder = new Request.Builder();\n Request request = builder.url(url).build();\n return execute(request);\n }\n\n public static Response doPost(String url) {\n RequestBody body = RequestBody.create(bytesMediaType, new byte[0]);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n public static Response doPost(String url, byte[] bytes) {\n RequestBody body = RequestBody.create(bytesMediaType, bytes);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n\n public static Response execute(Request request) {\n java.io.InterruptedIOException interruptedIOException = null;\n for (int i = 0; i < 5; i++) {\n try {\n return okHttpClient.newCall(request).execute();\n } catch (java.io.InterruptedIOException e) {\n interruptedIOException = e;\n try {\n Thread.sleep(10);\n } catch (Exception ex) {\n log.debug(\"发送请求sleep被打断\");\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n throw new RuntimeException(interruptedIOException);\n\n }\n\n\n private static X509TrustManager x509TrustManager() {\n return new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n }\n\n private static SSLSocketFactory sslSocketFactory() {\n try {\n // 信任任何链接\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());\n return sslContext.getSocketFactory();\n } catch (NoSuchAlgorithmException | KeyManagementException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static ConnectionPool pool() {\n return new ConnectionPool(5, 1L, TimeUnit.MINUTES);\n }\n\n}" } ]
import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.apache.logging.log4j.core.config.Configurator; import org.wowtools.common.utils.ResourcesReader; import org.wowtools.hppt.cc.pojo.CcConfig; import org.wowtools.hppt.cc.service.ClientSessionService; import org.wowtools.hppt.common.util.AesCipherUtil; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.common.util.HttpUtil; import java.io.File; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
6,474
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc { public static CcConfig config;
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc { public static CcConfig config;
public static AesCipherUtil aesCipherUtil;
2
2023-12-22 14:14:27+00:00
8k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/SelfTrap.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final ExecutorService executorService;\n private final NavigationMeshManager navigationMeshManager;\n private final Pathfinder pathfinder;\n private final Minecraft minecraft;\n private final HoleManager holeManager;\n private final LagbackService lagbackService;\n private final LocalPlayerPositionService localPlayerPositionService;\n private final AttackService attackService;\n private final InvincibilityFrameService invincibilityFrameService;\n private final DamageService damageService;\n private final BlockPlacer blockPlacer;\n private final AntiCheat antiCheat;\n private final MotionUpdateService motionUpdateService;\n private final BlockUpdateService blockUpdateService;\n private final BlockDestructionService blockDestructionService;\n private final ServerService serverService;\n private final TotemPopService totemPopService;\n private final InventoryService inventoryService;\n private final ThreadSafeLevelService threadSafeLevelService;\n private final TaskService taskService;\n private final MovementService movementService;\n private final WorldVersionService worldVersionService;\n\n}" }, { "identifier": "BlockPlacingModule", "path": "src/main/java/me/earth/phobot/modules/BlockPlacingModule.java", "snippet": "@Getter\npublic abstract class BlockPlacingModule extends PhobotModule implements ChecksBlockPlacingValidity, BlockPlacer.PlacesBlocks {\n private final Setting<Integer> delay = number(\"Delay\", 30, 0, 500, \"Delay between placements.\");\n private final Setting<Boolean> noGlitchBlocks = bool(\"NoGlitchBlocks\", false, \"Does not place a block on the clientside.\");\n private final StopWatch.ForSingleThread timer = new StopWatch.ForSingleThread();\n private final BlockPlacer blockPlacer;\n private final int priority;\n\n public BlockPlacingModule(Phobot phobot, BlockPlacer blockPlacer, String name, Nameable category, String description, int priority) {\n super(phobot, name, category, description);\n this.blockPlacer = blockPlacer;\n this.priority = priority;\n // TODO: clear blockplacer when unregistered etc!\n blockPlacer.getModules().add(this);\n }\n\n @Override\n public boolean isActive() {\n return isEnabled();\n }\n\n @Override\n public void update(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n if (!timer.passed(delay.getValue())) {\n return;\n }\n\n updatePlacements(context, player, level, gameMode);\n }\n\n protected abstract void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode);\n\n public boolean isUsingSetCarriedItem() {\n return true;\n }\n\n @SuppressWarnings(\"UnusedReturnValue\")\n public boolean placePos(BlockPos pos, Block block, LocalPlayer player, ClientLevel level) {\n for (BlockPlacer.Action action : blockPlacer.getActions()) {\n if (action.getPos().equals(pos)) {\n return true;\n }\n }\n\n if (!level.getWorldBorder().isWithinBounds(pos)) {\n return false;\n }\n\n BlockState state = level.getBlockState(pos);\n if (!state.canBeReplaced()) {\n return false;\n }\n\n Set<BlockPlacer.Action> dependencies = new HashSet<>();\n Direction direction = getDirection(level, player, pos, dependencies);\n if (direction == null) {\n return false;\n }\n\n // TODO: not necessary for crystalpvp.cc, but trace the proper checks in BlockItem, they are much more accurate\n BlockPos placeOn = pos.relative(direction);\n BlockState futureState = block.defaultBlockState(); // TODO: use this!!! block.getStateForPlacement(blockPlaceContext) though for the simple blocks on cc this should be fine for now\n VoxelShape shape = futureState.getCollisionShape(level, pos, blockPlacer.getCollisionContext());\n if (!shape.isEmpty() && isBlockedByEntity(pos, shape, player, level, entity -> false)) {\n return false;\n }\n\n BlockPlacer.Action action = new BlockPlacer.Action(this, placeOn.immutable(), pos.immutable(), direction.getOpposite(), block.asItem(), !noGlitchBlocks.getValue(), isUsingSetCarriedItem(),\n isUsingPacketRotations(), getBlockPlacer(), requiresExactDirection());\n action.getDependencies().addAll(dependencies);\n addAction(blockPlacer, action);\n return true;\n }\n\n protected boolean isUsingPacketRotations() {\n return false;\n }\n\n protected boolean requiresExactDirection() { // for special stuff like piston aura, bedaura etc. where where we place matters.\n return false;\n }\n\n protected void addAction(BlockPlacer placer, BlockPlacer.Action action) {\n placer.addAction(action);\n timer.reset();\n }\n\n protected void updateOutsideOfTick(LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n phobot.getInventoryService().use(context -> {\n getBlockPlacer().startTick(player, level);\n update(context, player, level, gameMode);\n getBlockPlacer().endTick(context, player, level);\n });\n }\n\n public enum Rotate {\n None,\n Rotate,\n Packets\n }\n\n}" }, { "identifier": "BlockPathfinder", "path": "src/main/java/me/earth/phobot/pathfinder/blocks/BlockPathfinder.java", "snippet": "public class BlockPathfinder {\n private final BlockNode center;\n\n public BlockPathfinder() {\n BlockNodePoolBuilder builder = new BlockNodePoolBuilder();\n builder.build(10/* this is not radius but manhattan radius basically */, BlockNode::new);\n this.center = Objects.requireNonNull(builder.getCenter(), \"PoolBuilder center was null!\");\n }\n\n public @NotNull List<BlockPos> getShortestPath(BlockPos target, Block block, Player player, ClientLevel level, int maxCost, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BiPredicate<BlockPos, BlockPos> validityCheck = getDefaultValidityCheck(block, player, level, module, blockPlacer);\n BiPredicate<BlockPos, @Nullable BlockPos> goalCheck = getDefaultGoalCheck(player, block, level, module);\n return getShortestPath(target, maxCost, validityCheck, goalCheck);\n }\n\n public @NotNull List<BlockPos> getShortestPath(BlockPos target, int maxCost, BiPredicate<BlockPos, BlockPos> validityCheck, BiPredicate<BlockPos, @Nullable BlockPos> goalCheck) {\n center.setToOffsetFromCenter(target);\n BlockPathfinderAlgorithm firstSearchNoHeuristic = new BlockPathfinderAlgorithm(center, validityCheck, goalCheck, target, maxCost);\n List<BlockNode> result = firstSearchNoHeuristic.run(Cancellation.UNCANCELLABLE);\n if (result != null) {\n return result.stream().map(BlockNode::getCurrent).map(BlockPos::immutable).collect(Collectors.toList());\n }\n\n return Collections.emptyList();\n }\n\n public BiPredicate<BlockPos, @Nullable BlockPos> getDefaultGoalCheck(Player player, Block block, ClientLevel level, ChecksBlockPlacingValidity module) {\n BlockStateLevel.Delegating blockStateLevel = new BlockStateLevel.Delegating(level);\n return (testPos, from) -> {\n if (module.isOutsideRange(testPos, player) || from != null && !strictDirectionCheck(from, testPos, block, module, player, blockStateLevel)) {\n return false;\n }\n\n return module.isValidPlacePos(testPos, level, player) || module.hasActionCreatingPlacePos(testPos, null, player, level, null);\n };\n }\n\n public BiPredicate<BlockPos, BlockPos> getDefaultValidityCheck(Block block, Player player, ClientLevel level, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BlockStateLevel.Delegating blockStateLevel = new BlockStateLevel.Delegating(level);\n return (currentPos, testPos) -> {\n if (!level.getWorldBorder().isWithinBounds(testPos) || module.isOutsideRange(testPos, player)) {\n return false;\n }\n\n VoxelShape shape = block.defaultBlockState().getCollisionShape(level, testPos, blockPlacer.getCollisionContext());\n if (shape.isEmpty() || !module.isBlockedByEntity(testPos, shape, player, level, entity -> false, ((placer, endCrystal) -> {/*do not set crystal*/}))) {\n return strictDirectionCheck(currentPos, testPos, block, module, player, blockStateLevel);\n }\n\n return false;\n };\n }\n\n private boolean strictDirectionCheck(BlockPos currentPos, BlockPos testPos, Block block, ChecksBlockPlacingValidity module, Player player, BlockStateLevel.Delegating level) {\n if (module.getBlockPlacer().getAntiCheat().getStrictDirection().getValue() != StrictDirection.Type.Vanilla) {\n Direction direction = getDirectionBetweenAdjacent(currentPos, testPos);\n level.getMap().clear();\n BlockState state = level.getLevel().getBlockState(testPos);\n if (state.isAir()/* TODO: || isFluid || isGoingToBeReplaced by us?!?!?!*/) {\n state = block.defaultBlockState();\n }\n\n level.getMap().put(testPos, state); // do the other blocks we placed for the path also play a role during the check?\n return module.getBlockPlacer().getAntiCheat().getStrictDirectionCheck().strictDirectionCheck(testPos, direction, level, player);\n }\n\n return true;\n }\n\n private Direction getDirectionBetweenAdjacent(BlockPos pos, BlockPos placeOn) {\n if (pos.getY() > placeOn.getY()) {\n return Direction.UP;\n } else if (pos.getY() < placeOn.getY()) {\n return Direction.DOWN;\n } else if (pos.getX() > placeOn.getX()) {\n return Direction.EAST;\n } else if (pos.getX() < placeOn.getX()) {\n return Direction.WEST;\n } else if (pos.getZ() > placeOn.getZ()) {\n return Direction.SOUTH;\n }\n\n return Direction.NORTH;\n }\n\n}" }, { "identifier": "BlockPathfinderWithBlacklist", "path": "src/main/java/me/earth/phobot/pathfinder/blocks/BlockPathfinderWithBlacklist.java", "snippet": "@RequiredArgsConstructor\npublic class BlockPathfinderWithBlacklist extends BlockPathfinder {\n private final Map<BlockPos, Long> blacklist;\n\n @Override\n public BiPredicate<BlockPos, BlockPos> getDefaultValidityCheck(Block block, Player player, ClientLevel level, ChecksBlockPlacingValidity module, BlockPlacer blockPlacer) {\n BiPredicate<BlockPos, BlockPos> predicate = super.getDefaultValidityCheck(block, player, level, module, blockPlacer);\n return (currentPos, testPos) -> !blacklist.containsKey(testPos) && predicate.test(currentPos, testPos);\n }\n}" }, { "identifier": "InventoryContext", "path": "src/main/java/me/earth/phobot/services/inventory/InventoryContext.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PACKAGE)\npublic class InventoryContext {\n public static final int DEFAULT_SWAP_SWITCH = 0;\n public static final int PREFER_MAINHAND = 1;\n public static final int SWITCH_BACK = 2;\n public static final int SET_CARRIED_ITEM = 4;\n public static final int SKIP_OFFHAND = 8;\n\n private final List<Switch> switches = new ArrayList<>();\n private final InventoryService inventoryService;\n private final LocalPlayer player;\n private final MultiPlayerGameMode gameMode;\n private HotbarSwitch hotbarSwitch;\n\n public @Nullable SwitchResult switchTo(Item item, int flags) {\n if (!(player.containerMenu instanceof InventoryMenu)) {\n return null;\n }\n\n if (player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT).getItem().is(item)) {\n return SwitchResult.get(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n } else if (getSelectedSlot().getItem().is(item)) {\n return SwitchResult.get(getSelectedSlot());\n }\n\n Slot slot = find(s -> s.getItem().is(item) ? s : null);\n return switchTo(slot, flags);\n }\n\n public @Nullable SwitchResult switchTo(@Nullable Slot slot, int flags) {\n if (slot != null) {\n if ((flags & SKIP_OFFHAND) == 0 && slot.index == InventoryMenu.SHIELD_SLOT) {\n return SwitchResult.get(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n } else if (slot.getContainerSlot() == player.getInventory().selected) {\n return SwitchResult.get(getSelectedSlot());\n }\n\n Slot targetSlot = player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT);\n boolean slotIsHotbar = isHotbar(slot);\n if ((flags & PREFER_MAINHAND) != 0 || (flags & SET_CARRIED_ITEM) != 0 && slotIsHotbar) {\n targetSlot = getSelectedSlot();\n }\n\n // TODO: prefer SwapSwitch if we are mining!\n Switch action = (flags & SET_CARRIED_ITEM) != 0 && slotIsHotbar && isHotbar(targetSlot)\n ? new HotbarSwitch(targetSlot, slot, (flags & SWITCH_BACK) != 0)\n : new SwapSwitch(slot, targetSlot, (flags & SWITCH_BACK) != 0);\n\n action.execute(this);\n if (action instanceof HotbarSwitch hs) {\n if (this.hotbarSwitch == null) {\n this.hotbarSwitch = hs;\n }\n } else {\n switches.add(action);\n }\n\n /* TODO: if (isHotbar(slot) && (... || anticheat flagged too many swaps)) -> HotbarSwitch*/\n return SwitchResult.get(targetSlot, action);\n }\n\n return null;\n }\n\n public void moveWithTwoClicks(Slot from, Slot to) {\n if (player.containerMenu instanceof InventoryMenu) {\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, from.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, to.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n closeScreen();\n }\n }\n\n public void click(Slot slot) {\n if (player.containerMenu instanceof InventoryMenu) {\n gameMode.handleInventoryMouseClick(player.containerMenu.containerId, slot.index, Keys.MOUSE_1, ClickType.PICKUP, player);\n closeScreen();\n }\n }\n\n public void drop(Slot slot) {\n gameMode.handleInventoryMouseClick(player.inventoryMenu.containerId, slot.index, 0, ClickType.THROW, player);\n closeScreen();\n }\n\n public Slot getOffhand() {\n return player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT);\n }\n\n public static InteractionHand getHand(Slot slot) {\n return slot.index == InventoryMenu.SHIELD_SLOT ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;\n }\n\n public boolean has(Item... items) {\n return find(items) != null;\n }\n\n @SuppressWarnings({\"unchecked\", \"RedundantCast\"})\n public Item find(Item... items) {\n return (Item) find(Arrays.stream(items).map(this::findItemFunction).toArray(Function[]::new));\n }\n\n @SuppressWarnings({\"unchecked\", \"RedundantCast\"})\n public Block findBlock(Block... blocks) {\n return (Block) find(Arrays.stream(blocks).map(this::findBlockFunction).toArray(Function[]::new));\n }\n\n @SafeVarargs\n public final <T> @Nullable T find(Function<Slot, @Nullable T>... functions) {\n for (var function : functions) {\n T result = function.apply(player.inventoryMenu.getSlot(InventoryMenu.SHIELD_SLOT));\n if (result != null) {\n return result;\n }\n\n result = function.apply(getSelectedSlot());\n if (result != null) {\n return result;\n }\n\n for (int i = InventoryMenu.USE_ROW_SLOT_START; i < InventoryMenu.USE_ROW_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n for (int i = InventoryMenu.INV_SLOT_START; i < InventoryMenu.INV_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n for (int i = InventoryMenu.CRAFT_SLOT_START; i < InventoryMenu.CRAFT_SLOT_END; i++) {\n result = function.apply(player.inventoryMenu.getSlot(i));\n if (result != null) {\n return result;\n }\n }\n\n // TODO: carried slot\n }\n\n return null;\n }\n\n public int getCount(Predicate<ItemStack> check) {\n int count = 0;\n for (Slot slot : player.inventoryMenu.slots) {\n if (check.test(slot.getItem())) {\n count += slot.getItem().getCount();\n }\n }\n\n return count;\n }\n\n private int toInventoryMenuSlot(int slot) {\n if (slot == Inventory.SLOT_OFFHAND) {\n return InventoryMenu.SHIELD_SLOT;\n }\n\n if (slot >= 0 && slot < Inventory.getSelectionSize()/*9*/) {\n return InventoryMenu.USE_ROW_SLOT_START + slot;\n }\n\n if (slot < 0 || slot > InventoryMenu.USE_ROW_SLOT_END) {\n return Inventory.NOT_FOUND_INDEX;\n }\n\n return slot;\n }\n\n public Slot getSelectedSlot() {\n int slotIndex = toInventoryMenuSlot(player.getInventory().selected);\n if (slotIndex < InventoryMenu.USE_ROW_SLOT_START || slotIndex >= InventoryMenu.USE_ROW_SLOT_END) {\n slotIndex = InventoryMenu.USE_ROW_SLOT_START;\n }\n\n return player.inventoryMenu.getSlot(slotIndex);\n }\n\n public boolean isSelected(Slot slot) {\n return slot.getContainerSlot() == getSelectedSlot().getContainerSlot();\n }\n\n public boolean isOffHand(Slot slot) {\n return slot.getContainerSlot() == Inventory.SLOT_OFFHAND;\n }\n\n void end() {\n if (inventoryService.getSwitchBack().get() /* or was eating!!!*/) {\n for (int i = switches.size() - 1; i >= 0; i--) {\n Switch action = switches.get(i);\n if (!action.switchBack || !action.revert(this)) {\n break;\n }\n }\n\n if (hotbarSwitch != null && hotbarSwitch.switchBack) {\n hotbarSwitch.revert(this);\n }\n }\n }\n\n private void closeScreen() {\n if (inventoryService.getAntiCheat().getCloseInv().getValue() && player.containerMenu == player.inventoryMenu) {\n player.connection.send(new ServerboundContainerClosePacket(player.containerMenu.containerId));\n }\n }\n\n private Function<Slot, Block> findBlockFunction(Block block) {\n return slot -> slot.getItem().is(block.asItem()) && slot.getItem().getCount() != 0 ? block : null;\n }\n\n private Function<Slot, Item> findItemFunction(Item item) {\n return slot -> slot.getItem().is(item) && slot.getItem().getCount() != 0 ? item : null;\n }\n\n private static boolean isHotbar(Slot slot) {\n return slot.getContainerSlot() >= 0 && slot.getContainerSlot() < Inventory.getSelectionSize()/*9*/;\n }\n\n public record SwitchResult(Slot slot, InteractionHand hand, @Nullable Block block, @Nullable Switch action) {\n public static SwitchResult get(Slot slot) {\n return get(slot, null);\n }\n\n public static SwitchResult get(Slot slot, @Nullable Switch action) {\n return new SwitchResult(slot, getHand(slot), slot.getItem().getItem() instanceof BlockItem block ? block.getBlock() : null, action);\n }\n }\n\n @RequiredArgsConstructor\n public abstract static class Switch {\n protected final Slot from;\n protected final Slot to;\n protected final boolean switchBack;\n\n public abstract boolean execute(InventoryContext context, Slot from, Slot to);\n\n public boolean execute(InventoryContext context) {\n return execute(context, from, to);\n }\n\n public boolean revert(InventoryContext context) {\n return execute(context, to, from);\n }\n }\n\n public static class SwapSwitch extends Switch {\n public SwapSwitch(Slot from, Slot to, boolean silent) {\n super(from, to, silent);\n }\n\n @Override\n public boolean execute(InventoryContext context, Slot from, Slot to) {\n if (context.player.containerMenu instanceof InventoryMenu && (isHotbar(to) || to.getContainerSlot() == Inventory.SLOT_OFFHAND)) {\n context.gameMode.handleInventoryMouseClick(context.player.containerMenu.containerId, from.index, to.getContainerSlot(), ClickType.SWAP, context.player);\n context.closeScreen();\n return true;\n }\n\n return false;\n }\n\n @Override\n public boolean revert(InventoryContext context) {\n return execute(context, from, to);\n }\n }\n\n public static class HotbarSwitch extends Switch {\n public HotbarSwitch(Slot from, Slot to, boolean silent) {\n super(from, to, silent);\n }\n\n @Override\n public boolean execute(InventoryContext context, Slot from, Slot to) {\n if (isHotbar(to)) {\n context.player.getInventory().selected = to.getContainerSlot();\n // TODO: via reflection we could actually register an ASM transformer to make GameMode.carriedIndex volatile?!\n ((IMultiPlayerGameMode) context.gameMode).invokeEnsureHasSentCarriedItem();\n return true;\n }\n\n return false;\n }\n }\n\n}" }, { "identifier": "ResetUtil", "path": "src/main/java/me/earth/phobot/util/ResetUtil.java", "snippet": "@UtilityClass\npublic class ResetUtil {\n public static void disableOnRespawnAndWorldChange(Module module, Minecraft mc) {\n onRespawnOrWorldChange(module, mc, module::disable);\n }\n\n public static void onRespawnOrWorldChange(Subscriber module, Minecraft mc, Runnable runnable) {\n module.getListeners().add(new Listener<ChangeWorldEvent>() {\n @Override\n public void onEvent(ChangeWorldEvent event) {\n runnable.run();\n }\n });\n\n module.getListeners().add(new Listener<PacketEvent.Receive<ClientboundRespawnPacket>>() {\n @Override\n public void onEvent(PacketEvent.Receive<ClientboundRespawnPacket> event) {\n mc.submit(runnable);\n }\n });\n }\n\n}" } ]
import lombok.Getter; import me.earth.phobot.Phobot; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.pathfinder.blocks.BlockPathfinder; import me.earth.phobot.pathfinder.blocks.BlockPathfinderWithBlacklist; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.api.setting.Setting; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import java.util.HashSet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
5,732
package me.earth.phobot.modules.combat; @Getter public class SelfTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); public SelfTrap(Phobot phobot) { super(phobot, phobot.getBlockPlacer(), "SelfTrap", Categories.COMBAT, "Traps you.", 0); listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override
package me.earth.phobot.modules.combat; @Getter public class SelfTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); public SelfTrap(Phobot phobot) { super(phobot, phobot.getBlockPlacer(), "SelfTrap", Categories.COMBAT, "Traps you.", 0); listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override
protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {
4
2023-12-22 14:32:16+00:00
8k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/gui/LinkGUI.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"2.0\";\n\n Minecraft mc = Minecraft.getMinecraft();\n public static Logger logger;\n\n public static JsonObject roomsJson;\n public static JsonObject waypointsJson;\n static boolean updateChecked = false;\n public static boolean usingSBPSecrets = false;\n public static String guiToOpen = null;\n public static KeyBinding[] keyBindings = new KeyBinding[2];\n public static String hotkeyOpen = \"gui\";\n static int tickAmount = 1;\n public static List<String> motd = null;\n\n @EventHandler\n public void preInit(final FMLPreInitializationEvent event) {\n ClientCommandHandler.instance.registerCommand(new DungeonRoomCommand());\n logger = LogManager.getLogger(\"DungeonRooms\");\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new AutoRoom());\n MinecraftForge.EVENT_BUS.register(new Waypoints());\n\n ConfigHandler.reloadConfig();\n\n try {\n ResourceLocation roomsLoc = new ResourceLocation( \"dungeonrooms\",\"dungeonrooms.json\");\n InputStream roomsIn = Minecraft.getMinecraft().getResourceManager().getResource(roomsLoc).getInputStream();\n BufferedReader roomsReader = new BufferedReader(new InputStreamReader(roomsIn));\n\n ResourceLocation waypointsLoc = new ResourceLocation( \"dungeonrooms\",\"secretlocations.json\");\n InputStream waypointsIn = Minecraft.getMinecraft().getResourceManager().getResource(waypointsLoc).getInputStream();\n BufferedReader waypointsReader = new BufferedReader(new InputStreamReader(waypointsIn));\n\n Gson gson = new Gson();\n roomsJson = gson.fromJson(roomsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded dungeonrooms.json\");\n\n waypointsJson = gson.fromJson(waypointsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded secretlocations.json\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n keyBindings[0] = new KeyBinding(\"Open Room Images in DSG/SBP\", Keyboard.KEY_O, \"FakepixelDungeonHelper Mod\");\n keyBindings[1] = new KeyBinding(\"Open Waypoint Menu\", Keyboard.KEY_P, \"FakepixelDungeonHelper Mod\");\n for (KeyBinding keyBinding : keyBindings) {\n ClientRegistry.registerKeyBinding(keyBinding);\n }\n }\n\n @EventHandler\n public void postInit(final FMLPostInitializationEvent event) {\n usingSBPSecrets = Loader.isModLoaded(\"sbp\");\n DungeonRooms.logger.info(\"FDH: SBP Dungeon Secrets detection: \" + usingSBPSecrets);\n }\n\n /*\n Update Checker taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).\n This code was released under GNU General Public License v3.0 and remains under said license.\n Modified by Quantizr (_risk) in Feb. 2021.\n */\n @SubscribeEvent\n public void onJoin(EntityJoinWorldEvent event) {\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n\n if (!updateChecked) {\n updateChecked = true;\n\n // MULTI THREAD DRIFTING\n new Thread(() -> {\n try {\n DungeonRooms.logger.info(\"FDH: Checking for updates...\");\n\n URL url = new URL(\"https://discord.com/fakepixel\");\n URLConnection request = url.openConnection();\n request.connect();\n JsonParser json = new JsonParser();\n JsonObject latestRelease = json.parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonObject();\n\n String latestTag = latestRelease.get(\"tag_name\").getAsString();\n DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(VERSION);\n DefaultArtifactVersion latestVersion = new DefaultArtifactVersion(latestTag.substring(1));\n\n if (currentVersion.compareTo(latestVersion) < 0) {\n String releaseURL = \"https://discord.gg/Fakepixel\";\n ChatComponentText update = new ChatComponentText(EnumChatFormatting.GREEN + \"\" + EnumChatFormatting.BOLD + \" [UPDATE] \");\n update.setChatStyle(update.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, releaseURL)));\n\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"FakepixelDungeonHelper Mod is outdated. Please update to \" + latestTag + \".\\n\").appendSibling(update));\n }\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n\n try {\n URL url = new URL(\"https://gist.githubusercontent.com/Quantizr/0af2afd91cd8b1aa22e42bc2d65cfa75/raw/\");\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n String line;\n motd = new ArrayList<>();\n while ((line = in.readLine()) != null) {\n motd.add(line);\n }\n in.close();\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n }).start();\n }\n }\n\n @SubscribeEvent\n public void renderPlayerInfo(final RenderGameOverlayEvent.Post event) {\n if (event.type != RenderGameOverlayEvent.ElementType.ALL) return;\n if (Utils.inDungeons) {\n if (AutoRoom.guiToggled) {\n AutoRoom.renderText();\n }\n if (AutoRoom.coordToggled) {\n AutoRoom.renderCoord();\n }\n }\n }\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n\n // Checks every second\n if (tickAmount % 20 == 0) {\n if (player != null) {\n Utils.checkForSkyblock();\n Utils.checkForDungeons();\n tickAmount = 0;\n }\n }\n }\n\n @SubscribeEvent\n public void onKey(InputEvent.KeyInputEvent event) {\n EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;\n if (keyBindings[0].isPressed()) {\n if (!Utils.inDungeons) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: Use this hotkey in dungeons\"));\n return;\n }\n switch (hotkeyOpen) {\n case \"gui\":\n OpenLink.checkForLink(\"gui\");\n break;\n case \"dsg\":\n OpenLink.checkForLink(\"dsg\");\n break;\n case \"sbp\":\n OpenLink.checkForLink(\"sbp\");\n break;\n default:\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: hotkeyOpen config value improperly set, do \\\"/room set <gui | dsg | sbp>\\\" to change the value\"));\n break;\n }\n }\n if (keyBindings[1].isPressed()) {\n DungeonRooms.guiToOpen = \"waypoints\";\n }\n }\n\n // Delay GUI by 1 tick\n @SubscribeEvent\n public void onRenderTick(TickEvent.RenderTickEvent event) {\n if (guiToOpen != null) {\n switch (guiToOpen) {\n case \"link\":\n mc.displayGuiScreen(new LinkGUI());\n break;\n case \"waypoints\":\n mc.displayGuiScreen(new WaypointsGUI());\n break;\n }\n guiToOpen = null;\n }\n }\n}" }, { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatToggled = false;\n public static boolean guiToggled = true;\n public static boolean coordToggled = false;\n public static String lastRoomHash = null;\n public static JsonObject lastRoomJson;\n public static String lastRoomName = null;\n private static boolean newRoom = false;\n public static int worldLoad = 0;\n\n public static int scaleX = 50;\n public static int scaleY = 5;\n\n private final Executor executor = Executors.newFixedThreadPool(5);\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n if (worldLoad < 200) { //10 seconds\n worldLoad++;\n }\n\n // Checks every 1.5 seconds\n if (tickAmount % 30 == 0 && Utils.inDungeons && worldLoad == 200) {\n executor.execute(() -> {\n if (AutoRoom.chatToggled || AutoRoom.guiToggled || Waypoints.enabled){\n List<String> autoText = autoText();\n if (autoText != null) {\n autoTextOutput = autoText;\n }\n }\n if (AutoRoom.chatToggled) {\n toggledChat();\n }\n });\n tickAmount = 0;\n }\n }\n\n @SubscribeEvent\n public void onWorldChange(WorldEvent.Load event) {\n Utils.inDungeons = false;\n Utils.originBlock = null;\n Utils.originCorner = null;\n worldLoad = 0;\n Waypoints.allSecretsMap.clear();\n\n Random random = new Random();\n List<String> output = new ArrayList<>();\n\n if (random.nextBoolean()) {\n if (DungeonRooms.motd != null) {\n if (!DungeonRooms.motd.isEmpty()) {\n output.addAll(DungeonRooms.motd);\n }\n }\n }\n if (output.isEmpty()) {\n output.add(\"FDH: \" + EnumChatFormatting.GREEN+ \"Press the hotkey \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[1].getKeyCode()) +\"\\\" to configure\");\n output.add(EnumChatFormatting.GREEN + \"Secret Waypoints settings.\");\n output.add(EnumChatFormatting.WHITE + \"(You can change the keybinds in Minecraft controls menu)\");\n }\n autoTextOutput = output;\n\n }\n\n @SubscribeEvent\n public void onWorldUnload(WorldEvent.Unload event) {\n Utils.inDungeons = false;\n }\n\n public static List<String> autoText() {\n List<String> output = new ArrayList<>();\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n int x = (int) Math.floor(player.posX);\n int y = (int) Math.floor(player.posY);\n int z = (int) Math.floor(player.posZ);\n\n int top = Utils.dungeonTop(x, y, z);\n String blockFrequencies = Utils.blockFrequency(x, top, z, true);\n if (blockFrequencies == null) return output; //if not in room (under hallway or render distance too low)\n String MD5 = Utils.getMD5(blockFrequencies);\n String floorFrequencies = Utils.floorFrequency(x, top, z);\n String floorHash = Utils.getMD5(floorFrequencies);\n String text = \"FDH: You are in \" + EnumChatFormatting.GREEN;\n\n if (MD5.equals(\"16370f79b2cad049096f881d5294aee6\") && !floorHash.equals(\"94fb12c91c4b46bd0c254edadaa49a3d\")) {\n floorHash = \"e617eff1d7b77faf0f8dd53ec93a220f\"; //exception for box room because floorhash changes when you walk on it\n }\n\n if (MD5.equals(lastRoomHash) && lastRoomJson != null && floorHash != null) {\n if (lastRoomJson.get(\"floorhash\") != null) {\n if (floorHash.equals(lastRoomJson.get(\"floorhash\").getAsString())) {\n newRoom = false;\n return null;\n }\n } else {\n newRoom = false;\n return null;\n }\n }\n\n newRoom = true;\n lastRoomHash = MD5;\n //Setting this to true may prevent waypoint flicker, but may cause waypoints to break if Hypixel bugs out\n Waypoints.allFound = false;\n\n if (DungeonRooms.roomsJson.get(MD5) == null && Utils.getSize(x,top,z).equals(\"1x1\")) {\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n output.add(\"FDH: You are probably in: \");\n output.add(EnumChatFormatting.GREEN + \"Literally no idea, all the rooms should have been found\");\n lastRoomJson = null;\n return output;\n } else if (DungeonRooms.roomsJson.get(MD5) == null) {\n lastRoomJson = null;\n return output;\n }\n\n JsonArray MD5Array = DungeonRooms.roomsJson.get(MD5).getAsJsonArray();\n int arraySize = MD5Array.size();\n\n if (arraySize >= 2) {\n boolean floorHashFound = false;\n List<String> chatMessages = new ArrayList<>();\n\n for(int i = 0; i < arraySize; i++){\n JsonObject roomObject = MD5Array.get(i).getAsJsonObject();\n JsonElement jsonFloorHash = roomObject.get(\"floorhash\");\n if (floorHash != null && jsonFloorHash != null){\n if (floorHash.equals(jsonFloorHash.getAsString())){\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n floorHashFound = true;\n }\n } else {\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n chatMessages.add(EnumChatFormatting.GREEN + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n chatMessages.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n }\n }\n if (!floorHashFound) {\n output.add(\"FDH: You are probably in one of the following: \");\n output.add(EnumChatFormatting.AQUA + \"(check # of secrets to narrow down rooms)\");\n output.addAll(chatMessages);\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n lastRoomJson = null;\n }\n } else {\n JsonObject roomObject = MD5Array.get(0).getAsJsonObject();\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n }\n\n //Store/Retrieve which waypoints to enable\n if (lastRoomJson != null && lastRoomJson.get(\"name\") != null) {\n lastRoomName = lastRoomJson.get(\"name\").getAsString();\n Waypoints.allSecretsMap.putIfAbsent(lastRoomName, new ArrayList<>(Collections.nCopies(9, true)));\n Waypoints.secretsList = Waypoints.allSecretsMap.get(lastRoomName);\n } else {\n lastRoomName = null;\n }\n\n return output;\n }\n\n public static void toggledChat() {\n if (!newRoom) return;\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n for (String message:autoTextOutput) {\n player.addChatMessage(new ChatComponentText(message));\n }\n }\n\n public static void renderText() {\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n Minecraft mc = Minecraft.getMinecraft();\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n int y = 0;\n for (String message:autoTextOutput) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * scaleX) / 100) - (roomStringWidth / 2),\n ((scaledResolution.getScaledHeight() * scaleY) / 100) + y, 1D, true);\n y += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n\n public static void renderCoord() {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n\n BlockPos relativeCoord = Utils.actualToRelative(new BlockPos(player.posX,player.posY,player.posZ));\n if (relativeCoord == null) return;\n\n List<String> coordDisplay = new ArrayList<>();\n coordDisplay.add(\"Direction: \" + Utils.originCorner);\n coordDisplay.add(\"Origin: \" + Utils.originBlock.getX() + \",\" + Utils.originBlock.getY() + \",\" + Utils.originBlock.getZ());\n coordDisplay.add(\"Relative Pos.: \"+ relativeCoord.getX() + \",\" + relativeCoord.getY() + \",\" + relativeCoord.getZ());\n int yPos = 0;\n for (String message:coordDisplay) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * 95) / 100) - (roomStringWidth),\n ((scaledResolution.getScaledHeight() * 5) / 100) + yPos, 1D, true);\n yPos += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n}" }, { "identifier": "OpenLink", "path": "build/sources/main/java/io/github/quantizr/handlers/OpenLink.java", "snippet": "public class OpenLink {\n\n public static void checkForLink(String type){\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n\n if (!AutoRoom.chatToggled && !AutoRoom.guiToggled){\n List<String> autoText = AutoRoom.autoText();\n if (autoText != null) {\n AutoRoom.autoTextOutput = autoText;\n }\n }\n\n if (AutoRoom.lastRoomHash == null) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: You do not appear to be in a detected Dungeon room right now.\"));\n return;\n }\n if (AutoRoom.lastRoomJson == null) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: This command does not work when the current room is detected as one of multiple.\"));\n return;\n }\n if (AutoRoom.lastRoomJson.get(\"dsg\").getAsString().equals(\"null\") && AutoRoom.lastRoomJson.get(\"sbp\") == null) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: There are no channels/images for this room.\"));\n return;\n }\n\n switch (type) {\n case \"gui\":\n DungeonRooms.guiToOpen = \"link\";\n break;\n case \"dsg\":\n OpenLink.openDiscord(\"client\");\n break;\n case \"sbp\":\n if (DungeonRooms.usingSBPSecrets) {\n OpenLink.openSBPSecrets();\n } else {\n String sbpURL = \"https://discord.gg/2UjaFqfPwJ\";\n ChatComponentText sbp = new ChatComponentText(EnumChatFormatting.YELLOW + \"\" + EnumChatFormatting.UNDERLINE + sbpURL);\n sbp.setChatStyle(sbp.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, sbpURL)));\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: You need the Skyblock Personalized (SBP) Mod for this feature, get it from \").appendSibling(sbp));\n }\n break;\n }\n\n }\n\n public static void openDiscord(String type) {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n if (AutoRoom.lastRoomJson.get(\"dsg\").getAsString().equals(\"null\")) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: There is no DSG channel for this room.\"));\n return;\n }\n try {\n if (type.equals(\"client\")){\n player.addChatMessage(new ChatComponentText(\"FDH: Opening DSG Discord in Client...\"));\n Desktop.getDesktop().browse(new URI(\"discord://\" + AutoRoom.lastRoomJson.get(\"dsg\").getAsString()));\n } else {\n player.addChatMessage(new ChatComponentText(\"FDH: Opening DSG Discord in Browser...\"));\n Desktop.getDesktop().browse(new URI(\"https://discord.com\" + AutoRoom.lastRoomJson.get(\"dsg\").getAsString()));\n }\n } catch (IOException | URISyntaxException e) {\n e.printStackTrace();\n }\n }\n\n public static void openSBPSecrets() {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n if (AutoRoom.lastRoomJson.get(\"sbp\") == null) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: There are no SBP images for this room.\"));\n return;\n }\n String name = AutoRoom.lastRoomJson.get(\"sbp\").getAsString();\n\n String category = AutoRoom.lastRoomJson.get(\"category\").getAsString();\n switch (category) {\n case \"Puzzle\":\n category = \"puzzles\";\n break;\n case \"Trap\":\n category = \"puzzles\";\n break;\n case \"L-shape\":\n category = \"L\";\n break;\n }\n ClientCommandHandler.instance.executeCommand(FMLClientHandler.instance().getClientPlayerEntity(), \"/secretoverride \" + category + \" \" + name);\n }\n}" }, { "identifier": "TextRenderer", "path": "build/sources/main/java/io/github/quantizr/handlers/TextRenderer.java", "snippet": "public class TextRenderer extends Gui {\n public static void drawText(Minecraft mc, String text, int x, int y, double scale, boolean outline) {\n GlStateManager.pushMatrix();\n GlStateManager.scale(scale, scale, scale);\n y -= mc.fontRendererObj.FONT_HEIGHT;\n for (String line : text.split(\"\\n\")) {\n y += mc.fontRendererObj.FONT_HEIGHT * scale;\n if (outline) {\n String noColourLine = StringUtils.stripControlCodes(line);\n mc.fontRendererObj.drawString(noColourLine, (int) Math.round(x / scale) - 1, (int) Math.round(y / scale), 0x000000, false);\n mc.fontRendererObj.drawString(noColourLine, (int) Math.round(x / scale) + 1, (int) Math.round(y / scale), 0x000000, false);\n mc.fontRendererObj.drawString(noColourLine, (int) Math.round(x / scale), (int) Math.round(y / scale) - 1, 0x000000, false);\n mc.fontRendererObj.drawString(noColourLine, (int) Math.round(x / scale), (int) Math.round(y / scale) + 1, 0x000000, false);\n mc.fontRendererObj.drawString(line, (int) Math.round(x / scale), (int) Math.round(y / scale), 0xFFFFFF, false);\n } else {\n mc.fontRendererObj.drawString(line, (int) Math.round(x / scale), (int) Math.round(y / scale), 0xFFFFFF, true);\n }\n }\n GlStateManager.popMatrix();\n GlStateManager.color(1, 1, 1, 1);\n }\n}" } ]
import io.github.quantizr.DungeonRooms; import io.github.quantizr.core.AutoRoom; import io.github.quantizr.handlers.OpenLink; import io.github.quantizr.handlers.TextRenderer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.event.ClickEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting;
7,085
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class LinkGUI extends GuiScreen { private GuiButton discordClient; private GuiButton discordBrowser; private GuiButton SBPSecrets; private GuiButton close; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); discordClient = new GuiButton(0, width / 2 - 185, height / 6 + 96, 120, 20, "DSG Discord Client"); discordBrowser = new GuiButton(1, width / 2 - 60, height / 6 + 96, 120, 20, "DSG Discord Browser"); SBPSecrets = new GuiButton(2, width / 2 + 65, height / 6 + 96, 120, 20, "SBP Secrets Mod"); close = new GuiButton(3, width / 2 - 60, height / 6 + 136, 120, 20, "Close"); this.buttonList.add(discordClient); this.buttonList.add(discordBrowser); this.buttonList.add(SBPSecrets); this.buttonList.add(close); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText; if (AutoRoom.lastRoomName == null) { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.RED + "null"; } else { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.GREEN + AutoRoom.lastRoomName; } int displayWidth = mc.fontRendererObj.getStringWidth(displayText);
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class LinkGUI extends GuiScreen { private GuiButton discordClient; private GuiButton discordBrowser; private GuiButton SBPSecrets; private GuiButton close; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); discordClient = new GuiButton(0, width / 2 - 185, height / 6 + 96, 120, 20, "DSG Discord Client"); discordBrowser = new GuiButton(1, width / 2 - 60, height / 6 + 96, 120, 20, "DSG Discord Browser"); SBPSecrets = new GuiButton(2, width / 2 + 65, height / 6 + 96, 120, 20, "SBP Secrets Mod"); close = new GuiButton(3, width / 2 - 60, height / 6 + 136, 120, 20, "Close"); this.buttonList.add(discordClient); this.buttonList.add(discordBrowser); this.buttonList.add(SBPSecrets); this.buttonList.add(close); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText; if (AutoRoom.lastRoomName == null) { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.RED + "null"; } else { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.GREEN + AutoRoom.lastRoomName; } int displayWidth = mc.fontRendererObj.getStringWidth(displayText);
TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 + 56, 1D, false);
3
2023-12-22 04:44:39+00:00
8k
R2turnTrue/chzzk4j
src/test/java/ChannelApiTest.java
[ { "identifier": "Chzzk", "path": "src/main/java/xyz/r2turntrue/chzzk4j/Chzzk.java", "snippet": "public class Chzzk {\n public static String API_URL = \"https://api.chzzk.naver.com\";\n public static String GAME_API_URL = \"https://comm-api.game.naver.com/nng_main\";\n\n public boolean isDebug = false;\n\n private String nidAuth;\n private String nidSession;\n private boolean isAnonymous;\n\n private OkHttpClient httpClient;\n private Gson gson;\n\n Chzzk(ChzzkBuilder chzzkBuilder) {\n this.nidAuth = chzzkBuilder.nidAuth;\n this.nidSession = chzzkBuilder.nidSession;\n this.isAnonymous = chzzkBuilder.isAnonymous;\n this.gson = new Gson();\n\n OkHttpClient.Builder httpBuilder = new OkHttpClient().newBuilder();\n\n if (!chzzkBuilder.isAnonymous) {\n httpBuilder.addInterceptor(chain -> {\n Request original = chain.request();\n Request authorized = original.newBuilder()\n .addHeader(\"Cookie\",\n \"NID_AUT=\" + chzzkBuilder.nidAuth + \"; \" +\n \"NID_SES=\" + chzzkBuilder.nidSession)\n .build();\n\n return chain.proceed(authorized);\n });\n }\n\n httpClient = httpBuilder.build();\n }\n\n /**\n * Get this {@link Chzzk} logged in.\n */\n public boolean isLoggedIn() {\n return !isAnonymous;\n }\n\n /**\n * Get new an instance of {@link ChzzkChat} with this {@link Chzzk}.\n */\n public ChzzkChat chat() {\n return new ChzzkChat(this);\n }\n\n public OkHttpClient getHttpClient() {\n return httpClient;\n }\n\n /**\n * Get {@link ChzzkChannel} by the channel id.\n *\n * @param channelId ID of {@link ChzzkChannel} that to get.\n * @return {@link ChzzkChannel} to get\n * @throws IOException if the request to API failed\n * @throws ChannelNotExistsException if the channel doesn't exists\n */\n public ChzzkChannel getChannel(String channelId) throws IOException, ChannelNotExistsException {\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId).build());\n\n ChzzkChannel channel = gson.fromJson(\n contentJson,\n ChzzkChannel.class);\n\n if (channel.getChannelId() == null) {\n throw new ChannelNotExistsException(\"The channel does not exists!\");\n }\n\n return channel;\n }\n\n /**\n * Get channel's {@link ChzzkChannelRules} by the channel id.\n *\n * @param channelId ID of {@link ChzzkChannel}\n * @return {@link ChzzkChannelRules} of the channel\n * @throws IOException if the request to API failed\n * @throws NotExistsException if the channel doesn't exists or the rules of the channel doesn't available\n */\n public ChzzkChannelRules getChannelChatRules(String channelId) throws IOException, NotExistsException {\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId + \"/chat-rules\").build());\n\n ChzzkChannelRules rules = gson.fromJson(\n contentJson,\n ChzzkChannelRules.class);\n\n if (rules.getUpdatedDate() == null) {\n throw new NotExistsException(\"The channel or rules of the channel does not exists!\");\n }\n\n return rules;\n }\n\n /**\n * Get following status about channel.\n *\n * @param channelId ID of {@link ChzzkChannel} to get following status\n * @return user's {@link ChzzkChannelFollowingData} of the channel\n * @throws IOException if the request to API failed\n * @throws NotLoggedInException if this {@link Chzzk} didn't log in\n * @throws ChannelNotExistsException if the channel doesn't exists\n */\n public ChzzkChannelFollowingData getFollowingStatus(String channelId) throws IOException, NotLoggedInException, ChannelNotExistsException {\n if (isAnonymous) {\n throw new NotLoggedInException(\"Can't get following status without logging in!\");\n }\n\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(API_URL + \"/service/v1/channels/\" + channelId + \"/follow\").build());\n\n ChzzkFollowingStatusResponse followingDataResponse = gson.fromJson(\n contentJson,\n ChzzkFollowingStatusResponse.class);\n\n if (followingDataResponse.channel.getChannelId() == null) {\n throw new NotExistsException(\"The channel does not exists!\");\n }\n\n return followingDataResponse.channel.getPersonalData().getFollowing();\n }\n\n /**\n * Get {@link ChzzkUser} that the {@link Chzzk} logged in.\n *\n * @return {@link ChzzkUser} that current logged in\n * @throws IOException if the request to API failed\n * @throws NotLoggedInException if this {@link Chzzk} didn't log in\n */\n public ChzzkUser getLoggedUser() throws IOException, NotLoggedInException {\n if (isAnonymous) {\n throw new NotLoggedInException(\"Can't get information of logged user without logging in!\");\n }\n\n JsonElement contentJson = RawApiUtils.getContentJson(\n httpClient,\n RawApiUtils.httpGetRequest(GAME_API_URL + \"/v1/user/getUserStatus\").build());\n\n ChzzkUser user = gson.fromJson(\n contentJson,\n ChzzkUser.class);\n\n return user;\n }\n}" }, { "identifier": "ChzzkBuilder", "path": "src/main/java/xyz/r2turntrue/chzzk4j/ChzzkBuilder.java", "snippet": "public class ChzzkBuilder {\n boolean isAnonymous = false;\n String nidAuth;\n String nidSession;\n\n /**\n * Creates a new {@link ChzzkBuilder} that not logged in.\n */\n public ChzzkBuilder() {\n this.isAnonymous = true;\n }\n\n /**\n * Creates a new {@link ChzzkBuilder} that logged in.\n * To build an instance of {@link Chzzk} that logged in, we must have\n * the values of NID_AUT and NID_SES cookies.<br>\n *\n * You can get that values from developer tools of your browser.<br>\n * In Chrome, you can see the values from\n * {@code Application > Cookies > https://chzzk.naver.com}\n *\n * @param nidAuth The value of NID_AUT cookie\n * @param nidSession The value of NID_SES cookie\n */\n public ChzzkBuilder(String nidAuth, String nidSession) {\n this.nidAuth = nidAuth;\n this.nidSession = nidSession;\n }\n\n public Chzzk build() {\n return new Chzzk(this);\n }\n}" }, { "identifier": "ChannelNotExistsException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/ChannelNotExistsException.java", "snippet": "public class ChannelNotExistsException extends NotExistsException {\n /**\n * Constructs an {@code ChannelNotExistsException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n */\n public ChannelNotExistsException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "NotExistsException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/NotExistsException.java", "snippet": "public class NotExistsException extends InvalidObjectException {\n /**\n * Constructs an {@code NotExistsException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n */\n public NotExistsException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "NotLoggedInException", "path": "src/main/java/xyz/r2turntrue/chzzk4j/exception/NotLoggedInException.java", "snippet": "public class NotLoggedInException extends Exception {\n public NotLoggedInException(String reason) {\n super(reason);\n }\n}" }, { "identifier": "ChzzkUser", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/ChzzkUser.java", "snippet": "public class ChzzkUser {\n private boolean hasProfile;\n private String userIdHash;\n private String nickname;\n private String profileImageUrl;\n private Object[] penalties; // unknown\n private boolean officialNotiAgree;\n private String officialNotiAgreeUpdatedDate;\n private boolean verifiedMark;\n private boolean loggedIn;\n\n private ChzzkUser() {}\n\n /**\n * Get the user has profile.\n */\n public boolean isHasProfile() {\n return hasProfile;\n }\n\n /**\n * Get the user's id.\n */\n public String getUserId() {\n return userIdHash;\n }\n\n /**\n * Get the nickname of the user.\n */\n public String getNickname() {\n return nickname;\n }\n\n /**\n * Get url of the user's profile image.\n */\n public String getProfileImageUrl() {\n return profileImageUrl;\n }\n\n /**\n * Get user agreed to official notification.\n */\n public boolean isOfficialNotiAgree() {\n return officialNotiAgree;\n }\n\n /**\n * Get when user agreed to official notification in ISO-8601 format.\n */\n @Nullable\n public String getOfficialNotiAgreeUpdatedDate() {\n return officialNotiAgreeUpdatedDate;\n }\n\n /**\n * Get user has verified mark.\n */\n public boolean isVerifiedMark() {\n return verifiedMark;\n }\n\n @Override\n public String toString() {\n return \"ChzzkUser{\" +\n \"hasProfile=\" + hasProfile +\n \", userIdHash='\" + userIdHash + '\\'' +\n \", nickname='\" + nickname + '\\'' +\n \", profileImageUrl='\" + profileImageUrl + '\\'' +\n \", penalties=\" + Arrays.toString(penalties) +\n \", officialNotiAgree=\" + officialNotiAgree +\n \", officialNotiAgreeUpdatedDate='\" + officialNotiAgreeUpdatedDate + '\\'' +\n \", verifiedMark=\" + verifiedMark +\n \", loggedIn=\" + loggedIn +\n '}';\n }\n}" }, { "identifier": "ChzzkChannel", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannel.java", "snippet": "public class ChzzkChannel extends ChzzkPartialChannel {\n private String channelDescription;\n private int followerCount;\n private boolean openLive;\n\n private ChzzkChannel() {\n super();\n }\n\n /**\n * Get description of the channel.\n */\n public String getChannelDescription() {\n return channelDescription;\n }\n\n /**\n * Get the count of the channel's followers.\n */\n public int getFollowerCount() {\n return followerCount;\n }\n\n /**\n * Get is the channel broadcasting.\n */\n public boolean isBroadcasting() {\n return openLive;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannel{\" +\n \"parent=\" + super.toString() +\n \", channelDescription='\" + channelDescription + '\\'' +\n \", followerCount=\" + followerCount +\n \", openLive=\" + openLive +\n '}';\n }\n}" }, { "identifier": "ChzzkChannelFollowingData", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannelFollowingData.java", "snippet": "public class ChzzkChannelFollowingData {\n private boolean following;\n private boolean notification;\n private String followDate;\n\n private ChzzkChannelFollowingData() {}\n\n /**\n * Get is me following the channel.\n */\n public boolean isFollowing() {\n return following;\n }\n\n /**\n * Get is me enabled the channel notification.\n */\n public boolean isEnabledNotification() {\n return notification;\n }\n\n /**\n * Get when me followed the channel in yyyy-mm-dd HH:mm:ss format.\n */\n public String getFollowDate() {\n return followDate;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannelFollowingData{\" +\n \"following=\" + following +\n \", notification=\" + notification +\n \", followDate='\" + followDate + '\\'' +\n '}';\n }\n}" }, { "identifier": "ChzzkChannelRules", "path": "src/main/java/xyz/r2turntrue/chzzk4j/types/channel/ChzzkChannelRules.java", "snippet": "public class ChzzkChannelRules {\n private boolean agree;\n private String channelId;\n private String rule;\n private String updatedDate;\n private boolean serviceAgree;\n\n private ChzzkChannelRules() {}\n\n /**\n * Get the user is agreed to the rules of channel.\n */\n public boolean isAgree() {\n return agree;\n }\n\n /**\n * Get the id of channel.\n */\n public String getChannelId() {\n return channelId;\n }\n\n /**\n * Get the rule string of channel.\n */\n public String getRule() {\n return rule;\n }\n\n /**\n * Get when the rule updated in yyyy-mm-dd HH:mm:ss format.\n */\n public String getUpdatedDate() {\n return updatedDate;\n }\n\n /**\n * Get the user is agreed to the rules of channel.\n */\n public boolean isServiceAgree() {\n return serviceAgree;\n }\n\n @Override\n public String toString() {\n return \"ChzzkChannelRules{\" +\n \"agree=\" + agree +\n \", channelId='\" + channelId + '\\'' +\n \", rule='\" + rule + '\\'' +\n \", updatedDate='\" + updatedDate + '\\'' +\n \", serviceAgree=\" + serviceAgree +\n '}';\n }\n}" } ]
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import xyz.r2turntrue.chzzk4j.Chzzk; import xyz.r2turntrue.chzzk4j.ChzzkBuilder; import xyz.r2turntrue.chzzk4j.exception.ChannelNotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotLoggedInException; import xyz.r2turntrue.chzzk4j.types.ChzzkUser; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelFollowingData; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelRules;
4,057
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException {
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException {
Assertions.assertThrowsExactly(NotLoggedInException.class, () ->
4
2023-12-30 20:01:23+00:00
8k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/RecentsWindow.java
[ { "identifier": "GenericWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/generics/GenericWindow.java", "snippet": "public class GenericWindow {\n private static final String TAG = \"GenericWindow\";\n\n private static final int FADE_DURATION = 500;\n\n private static WindowManager mWM = null;\n private static final WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(\n WindowManager.LayoutParams.MATCH_PARENT,\n WindowManager.LayoutParams.MATCH_PARENT,\n WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,\n WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,\n PixelFormat.TRANSLUCENT);\n\n private final View mView;\n private final Context mContext;\n public GenericWindow(Context ctx, int res) {\n mContext = ctx;\n if (mWM == null) {\n mWM = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);\n }\n mView = View.inflate(ctx, res, null);\n }\n public View getView() {\n return mView;\n }\n public View findViewById(int id) {\n return getView().findViewById(id);\n }\n public Drawable getDrawable(int res) {\n return mContext.getDrawable(res);\n }\n public ContentResolver getContentResolver() {\n return mContext.getContentResolver();\n }\n public void startActivity(Intent intent) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n mContext.startActivity(intent);\n hide();\n }\n\n public void onShow() {}\n public void onHide() {}\n public boolean isVisible() {\n return mView.isAttachedToWindow();\n }\n final public void show() {\n if (mView.isAttachedToWindow())\n return;\n mContext.getMainExecutor().execute(()-> {\n mView.setVisibility(View.VISIBLE);\n mView.setAlpha(0);\n mWM.addView(mView, wmParams);\n onShow();\n mView.animate()\n .setDuration(FADE_DURATION)\n .alpha(1)\n .setListener(null)\n .start();\n });\n }\n final protected void hide() {\n if (!mView.isAttachedToWindow())\n return;\n mContext.getMainExecutor().execute(()-> {\n mView.animate()\n .setDuration(FADE_DURATION)\n .alpha(0)\n .setListener(new AnimatorListenerAdapter() {\n @Override\n public void onAnimationEnd(Animator animation) {\n mView.setVisibility(View.GONE);\n mWM.removeView(mView);\n }\n }).start();\n onHide();\n });\n }\n}" }, { "identifier": "ApkRepo", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/ApkRepo.java", "snippet": "public class ApkRepo extends BroadcastReceiver {\n private static final String TAG = \"ApkRepo\";\n @Override\n public void onReceive(Context context, Intent intent) {\n packageRepo.clear();\n initPriv(context);\n }\n\n\n private static final String[] PlatformPackageNames = new String[]{\n \"com.disney.disneyplus\", \"com.netflix.ninja\", \"com.apple.atve.androidtv.appletv\", \"com.apple.atve.androidtv.appletv\", \"com.google.android.videos\",\n \"com.amazon.amazonvideo.livingroom\", \"pl.tvn.avod.tv\", \"com.mubi\", \"com.nst.iptvhorizon\", \"com.liskovsoft.smartyoutubetv2.tv\",\n \"com.curiosity.curiositystream.androidtv\", \"\", \"com.yaddo.app\", \"pl.tvn.player.tv\", \"com.app.guidedoc.tv\",\n \"com.spamflix.tv\", \"tv.vhx.worldofwonder\", \"\", \"com.abide.magellantv\", \"com.twentyfouri.app.broadwayhdatvbigscreen\",\n \"com.filmzie.platform\", \"tv.vhx.dekkoo\", \"\", \"\", \"com.viewlift.hoichoi\",\n \"com.viaplay.android\", \"\", \"\", \"com.hbo.hbonow\", \"com.hbo.hbonow\",\n \"com.spiintl.tv.filmbox\", \"\", \"com.suntv.sunnxt\", \"\", \"com.showtime.standalone\",\n \"com.crunchyroll.crunchyroid\", \"com.amazon.amazonvideo.livingroom\",\"com.amazon.amazonvideo.livingroom\", \"net.mbc.shahidTV\", \"com.amazon.amazonvideo.livingroom\",\n \"ERROR\"\n };\n private static final String[] PlatformNames = {\n \"Disney Plus\", \"Netflix\", \"Apple TV\", \"Apple TV Plus\", \"Google Play Movies\",\n \"Amazon Prime Video\", \"VOD Poland\", \"MUBI\", \"Horizon\", \"YouTube\",\n \"Curiosity Stream\", \"Chili\", \"DOCSVILLE\", \"Player\", \"GuideDoc\",\n \"Spamflix\", \"WOW Presents Plus\", \"IPLA\", \"Magellan TV\", \"BroadwayHD\",\n \"Filmzie\", \"Dekkoo\", \"True Story\", \"DocAlliance Films\", \"Hoichoi\",\n \"Viaplay\", \"Eventive\", \"Cultpix\", \"HBO Max\", \"HBO Max Free\",\n \"FilmBox+\", \"Takflix\", \"Sun Nxt\", \"Classix\", \"SkyShowtime\",\n \"Crunchyroll\", \"Amazon Video\", \"Film Total Amazon Channel\", \"Shahid VIP\", \"MGM Amazon Channel\",\n \"ERROR\"\n };\n public enum Platform {\n DISNEY_PLUS, NETFLIX, APPLE_TV, APPLE_TV_PLUS, GOOGLE_PLAY_MOVIES,\n AMAZON_PRIME_VIDEO, VOD_POLAND, MUBI, HORIZON, YOUTUBE,\n CURIOSITY_STREAM, CHILI, DOCSVILLE, PLAYER, GUIDEDOC,\n SPAMFLIX, WOW_PRESENTS_PLUS, IPLA, MAGELLAN_TV, BROADWAY_HD,\n FILMZIE, DEKKOO, TRUE_STORY, DOCALLIANCE_FILMS, HOICHOI,\n VIAPLAY, EVENTIVE, CULTPIX, HBO_MAX, HBO_MAX_FREE,\n FILMBOX_PLUS, TAKFLIX, SUN_NXT, CLASSIX, SKYSHOWTIME,\n CRUNCHYROLL, AMAZON_VIDEO, FILM_TOTAL_AMAZON_CHANNEL, SHAHID_VIP, MGM_AMAZON_CHANNEL,\n ERROR\n };\n public static Platform getPlatform(String plaformStr) {\n for (int ix = 0; ix < PlatformPackageNames.length; ix++) {\n if (PlatformPackageNames[ix].equals(plaformStr) ||\n PlatformNames[ix].contains(plaformStr)) {\n return Platform.values()[ix];\n }\n }\n return Platform.ERROR;\n }\n public static Platform getPlatform(Intent intent) {\n intent.getDataString();\n ComponentName info = intent.resolveActivity(mPM);\n return getPlatform(info.getPackageName());\n }\n public static String getPlatformName(Platform platform) {\n return PlatformNames[platform.ordinal()];\n }\n public static App getPlatformApp(Platform platform) {\n return platformPackageRepo.get(PlatformPackageNames[platform.ordinal()]);\n }\n\n public static class App {\n public Intent launchIntent;\n public Intent leanbackIntent;\n public Intent mainIntent;\n public Intent defaultIntent;\n public String pkgName;\n public String name;\n public Platform platform;\n\n public Drawable icon;\n public Drawable badge;\n public List<MovieTitle> recommendations = new ArrayList<>();\n public long recommendationsTimestamp = 0;\n }\n public static Collection<App> getAllApps() {\n return packageRepo.values();\n }\n public static List<App> getApps(List<?> whitelist, List<?> blacklist) {\n List<App> apps = new ArrayList<>();\n if (whitelist != null && !whitelist.isEmpty()) {\n if (whitelist.get(0) instanceof String) {\n for (String pkg : packageRepo.keySet()) {\n if (whitelist.contains(pkg)) {\n apps.add(packageRepo.get(pkg));\n }\n }\n } else if (whitelist.get(0) instanceof App) {\n for (App pkg : packageRepo.values()) {\n if (whitelist.contains(pkg)) {\n apps.add(pkg);\n }\n }\n }\n } else if (blacklist != null && !blacklist.isEmpty()) {\n if (blacklist.get(0) instanceof String) {\n for (String pkg : packageRepo.keySet()) {\n if (!blacklist.contains(pkg)) {\n apps.add(packageRepo.get(pkg));\n }\n }\n } else if (blacklist.get(0) instanceof App) {\n for (App pkg : packageRepo.values()) {\n if (!blacklist.contains(pkg)) {\n apps.add(pkg);\n }\n }\n }\n }\n return apps;\n }\n public static Drawable getAppBadge(String packageName) {\n if (packageRepo.containsKey(packageName)) {\n return packageRepo.get(packageName).badge;\n }\n return null;\n }\n public static Drawable getAppIcon(String packageName) {\n if (packageRepo.containsKey(packageName)) {\n return packageRepo.get(packageName).icon;\n }\n return null;\n }\n public static Drawable getActionBadge(String action) {\n Intent intent = new Intent(action);\n List<ResolveInfo> activities = mPM.queryIntentActivities(intent, 0);\n if (!activities.isEmpty()) {\n for (ResolveInfo info : activities) {\n Drawable badge = getAppBadge(info.activityInfo.packageName);\n if (badge != null) {\n return badge;\n }\n badge = getAppIcon(info.activityInfo.packageName);\n if (badge != null) {\n return badge;\n }\n }\n }\n return null;\n }\n\n\n private static UsageStatsManager mUSM = null;\n private static PackageManager mPM = null;\n private static WindowManager mWM = null;\n private static ContentResolver mCR = null;\n private static Map<String, App> packageRepo = new HashMap<>();\n private static void initPriv(Context ctx) {\n if (mWM == null) {\n mWM = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);\n }\n if (mUSM == null) {\n mUSM = (UsageStatsManager) ctx.getSystemService(Context.USAGE_STATS_SERVICE);\n }\n if (mPM == null) {\n mPM = ctx.getPackageManager();\n }\n if (mCR == null) {\n mCR = ctx.getContentResolver();\n }\n if (packageRepo.isEmpty()) {\n packageRepo = new HashMap<>();\n\n Intent intent = new Intent(Intent.ACTION_MAIN, null);\n //intent.addCategory(Intent.CATEGORY_LEANBACK_LAUNCHER);\n //intent.addCategory(Intent.CATEGORY_LAUNCHER);\n\n List<String> platformApps = Arrays.asList(PlatformPackageNames);\n List<String> videoApps = Arrays.asList(\"org.jellyfin.androidtv\", \"org.videolan.vlc\", \"tv.twitch.android.app\", \"com.plexapp.android\", \"com.peacocktv.peacockandroid\", \"com.sling\", \"in.startv.hotstar\", \"com.sonyliv\", \"com.graymatrix.did\", \"com.tru\", \"com.wemesh.android\", \"com.jio.media.ondemand\", \"com.stremio\", \"com.haystack.android\", \"com.espn.score_center\",\n \"com.britbox.tv\", \"com.teamsmart.videomanager.tv\", \"com.google.android.youtube.tv\");\n List<String> audioApps = Arrays.asList(\"com.spotify.tv.android\", \"com.soundcloud.android\", \"com.amazon.music.tv\", \"com.google.android.youtube.tvmusic\", \"com.aspiro.tidal\", \"tunein.player\", \"com.pandora.android.atv\");\n List<String> gamingApps = Arrays.asList(\"com.valvesoftware.steamlink\", \"com.retroarch\", \"com.nvidia.geforcenow\");\n List<ResolveInfo> packagesResolve = mPM.queryIntentActivities(intent, 0);\n for (ResolveInfo pkg : packagesResolve) {\n App app = new App();\n app.pkgName = pkg.activityInfo.packageName;\n app.name = String.valueOf(pkg.activityInfo.loadLabel(mPM));\n Drawable icon = pkg.activityInfo.loadBanner(mPM);\n if (icon == null)\n icon = pkg.activityInfo.loadIcon(mPM);\n if (icon == null)\n icon = pkg.activityInfo.loadLogo(mPM);\n app.icon = icon;\n app.launchIntent = mPM.getLaunchIntentForPackage(app.pkgName);\n if (app.launchIntent != null)\n app.launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n app.leanbackIntent = mPM.getLeanbackLaunchIntentForPackage(app.pkgName);\n if (app.leanbackIntent != null)\n app.leanbackIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n if (pkg.activityInfo.targetActivity != null) {\n app.mainIntent = new Intent(Intent.ACTION_MAIN);\n app.mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n intent.setComponent(new ComponentName(app.pkgName, pkg.activityInfo.targetActivity));\n }\n app.defaultIntent = app.leanbackIntent != null ? app.leanbackIntent : (app.launchIntent != null ? app.launchIntent : app.mainIntent);\n try { app.badge = mPM.getApplicationBanner(app.pkgName); } catch (Exception ignored){}\n packageRepo.put(pkg.activityInfo.packageName, app);\n\n if (platformApps.contains(pkg.activityInfo.packageName)) {\n app.platform = Platform.values()[platformApps.indexOf(pkg.activityInfo.packageName)];\n platformPackageRepo.put(pkg.activityInfo.packageName, app);\n }\n if (platformApps.contains(pkg.activityInfo.packageName) || videoApps.contains(pkg.activityInfo.packageName))\n videoPackageRepo.put(pkg.activityInfo.packageName, app);\n if (!platformApps.contains(pkg.activityInfo.packageName) && videoApps.contains(pkg.activityInfo.packageName))\n nonplatformVideoPackageRepo.put(pkg.activityInfo.packageName, app);\n if (audioApps.contains(pkg.activityInfo.packageName))\n audioPackageRepo.put(pkg.activityInfo.packageName, app);\n if (gamingApps.contains(pkg.activityInfo.packageName))\n gamingPackageRepo.put(pkg.activityInfo.packageName, app);\n }\n }\n }\n private static final List<String> CHANNEL_NONTV = Arrays.asList(\n TvContract.Channels.TYPE_OTHER,\n TvContract.Channels.TYPE_PREVIEW);\n @SuppressLint(\"RestrictedApi\") private static List<PreviewProgram> getChannelPrograms(ContentResolver resolver, long id) {\n List<PreviewProgram> programs = new ArrayList<>();\n Cursor cursor = resolver.query(\n TvContract.buildPreviewProgramsUriForChannel(id),\n PreviewProgram.PROJECTION,\n null, new String[]{}, null);\n assert cursor != null;\n if (cursor.moveToFirst()) do {\n PreviewProgram prog = PreviewProgram.fromCursor(cursor);\n programs.add(prog);\n } while (cursor.moveToNext());\n cursor.close();\n\n return programs;\n }\n static void postInit(Context ctx) {\n getPreviewChannels();\n }\n @SuppressLint(\"RestrictedApi\") static void getPreviewChannels() {\n List<PreviewProgram> programs = new ArrayList<>();\n Cursor cursor = mCR.query(\n TvContract.Channels.CONTENT_URI,\n PreviewChannel.Columns.PROJECTION,\n null, new String[]{}, null);\n assert cursor != null;\n if (cursor.moveToFirst()) do {\n if (CHANNEL_NONTV.contains(cursor.getString(PreviewChannel.Columns.COL_TYPE))) {\n List<PreviewProgram> prog = getChannelPrograms(mCR, cursor.getLong(PreviewChannel.Columns.COL_ID));\n programs.addAll(prog);\n }\n } while (cursor.moveToNext());\n cursor.close();\n\n Map<String, AtomicInteger> requests = new HashMap<>();\n ReentrantLock mutexLocal = new ReentrantLock();\n for (PreviewProgram prog : programs) {\n String pkgName = prog.getPackageName();\n if (!packageRepo.containsKey(pkgName)) {\n Log.i(TAG, \"No pkg: \" + pkgName);\n continue;\n }\n if (!requests.containsKey(pkgName)) {\n requests.put(pkgName, new AtomicInteger(0));\n }\n requests.get(pkgName).incrementAndGet();\n JustWatch.Callback cb = new JustWatch.Callback() {\n @Override\n public void onFailure(String error) {\n MovieTitlePriv title = new MovieTitlePriv();\n String url = String.valueOf(prog.getThumbnailUri());\n Checksum crc32 = new CRC32();\n crc32.update(url.getBytes(), 0, url.length());\n File image = new File(AllRepos.CACHE_DIR, String.valueOf(crc32.getValue()));\n JustWatch.downloadImage(url, image, new JustWatch.Callback() {\n @Override\n public void onFailure(String error) {\n mutexLocal.lock();\n if (requests.get(pkgName).decrementAndGet() == 0) {\n packageRepo.get(pkgName).recommendationsTimestamp = System.currentTimeMillis();\n }\n mutexLocal.unlock();\n }\n @Override\n public void onSuccess(List<MovieTitle> titles_) {\n title.imageUrl = url;\n title.imagePath = image.getAbsolutePath();\n title.description = prog.getDescription();\n title.title = prog.getTitle();\n try {\n Intent intent = prog.getIntent();\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n title.offers.put(ApkRepo.getPlatform(intent), intent.getDataString());\n } catch (URISyntaxException ignored) {}\n mutexLocal.lock();\n MovieTitle title1 = new MovieTitle(title);\n if (!packageRepo.get(pkgName).recommendations.contains(title1)) {\n packageRepo.get(pkgName).recommendations.add(new MovieTitle(title1));\n }\n if (requests.get(pkgName).decrementAndGet() == 0) {\n packageRepo.get(pkgName).recommendationsTimestamp = System.currentTimeMillis();\n }\n mutexLocal.unlock();\n }\n });\n }\n @Override\n public void onSuccess(List<MovieTitle> titles_) {\n MovieTitle title = titles_.get(0);\n try {\n Intent intent = prog.getIntent();\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);\n title.offers.put(getPlatform(intent), intent.getDataString());\n } catch (URISyntaxException e) {\n Log.w(\"ApkRepo\", \"URISyntaxException: \" + e);\n title.offers.put(Platform.ERROR, \"\");\n }\n mutexLocal.lock();\n if (!packageRepo.get(pkgName).recommendations.contains(title)) {\n packageRepo.get(pkgName).recommendations.add(title);\n }\n if (requests.get(pkgName).decrementAndGet() == 0) {\n packageRepo.get(pkgName).recommendationsTimestamp = System.currentTimeMillis();\n }\n mutexLocal.unlock();\n }\n };\n if (platformPackageRepo.containsKey(pkgName)) {\n JustWatch.findMovieTitle(prog.getTitle(), cb);\n } else {\n cb.onFailure(\"\");\n }\n }\n }\n\n private static final Map<String, App> platformPackageRepo = new HashMap<>();\n private static final Map<String, App> nonplatformVideoPackageRepo = new HashMap<>();\n private static final Map<String, App> videoPackageRepo = new HashMap<>();\n private static final Map<String, App> audioPackageRepo = new HashMap<>();\n private static final Map<String, App> gamingPackageRepo = new HashMap<>();\n public static Collection<App> getNonPlatformVideoApps() {\n return nonplatformVideoPackageRepo.values();\n }\n public static Collection<App> getPlatformApps() {\n return platformPackageRepo.values();\n }\n public static Collection<App> getVideoApps() {\n return videoPackageRepo.values();\n }\n public static Collection<App> getAudioApps() {\n return audioPackageRepo.values();\n }\n public static Collection<App> getGamingApps() {\n return gamingPackageRepo.values();\n }\n public static boolean isPlatformApp(String pkg) {\n return platformPackageRepo.containsKey(pkg);\n }\n public static boolean isSystemApp(String packageName) {\n try {\n ApplicationInfo applicationInfo = mPM.getApplicationInfo(packageName, 0);\n return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;\n } catch (PackageManager.NameNotFoundException e) {\n return false;\n }\n }\n public static void init(Context ctx) {\n initPriv(ctx);\n }\n\n public static List<App> getRecentApps() {\n Date date = new Date();\n\n List<UsageStats> queryUsageStats = mUSM.queryUsageStats(\n UsageStatsManager.INTERVAL_BEST, date.getTime() - SystemClock.uptimeMillis(), date.getTime());\n queryUsageStats.sort((o1, o2) ->\n Long.compare(o2.getLastTimeUsed(), o1.getLastTimeUsed()));\n\n List<App> recentPkgs = new ArrayList<>();\n for (UsageStats pkgStats : queryUsageStats) {\n if (pkgStats.getLastTimeUsed() > 0 && pkgStats.getTotalTimeInForeground() > 5000) {\n App app = packageRepo.get(pkgStats.getPackageName());\n if (app != null && !recentPkgs.contains(app)) {\n recentPkgs.add(app);\n }\n }\n }\n return recentPkgs;\n }\n}" } ]
import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.leanback.widget.HorizontalGridView; import androidx.recyclerview.widget.RecyclerView; import net.lonelytransistor.launcher.generics.GenericWindow; import net.lonelytransistor.launcher.repos.ApkRepo; import java.util.List;
5,198
package net.lonelytransistor.launcher; public class RecentsWindow extends GenericWindow { private static final String TAG = "RecentsWindow"; private static final int SCALE_DURATION = 200; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private final HorizontalGridView mRecentsView; public RecentsWindow(Context ctx) { super(ctx, R.layout.activity_recents); mRecentsView = (HorizontalGridView) findViewById(R.id.recents_bar); mRecentsView.setAdapter(new RecentsBarAdapter()); getView().setOnKeyListener(mKeyListener); mRecentsView.setOnKeyListener(mKeyListener); } private class RecentsBarAdapter extends RecyclerView.Adapter<RecentsBarAdapter.ViewHolder> {
package net.lonelytransistor.launcher; public class RecentsWindow extends GenericWindow { private static final String TAG = "RecentsWindow"; private static final int SCALE_DURATION = 200; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private final HorizontalGridView mRecentsView; public RecentsWindow(Context ctx) { super(ctx, R.layout.activity_recents); mRecentsView = (HorizontalGridView) findViewById(R.id.recents_bar); mRecentsView.setAdapter(new RecentsBarAdapter()); getView().setOnKeyListener(mKeyListener); mRecentsView.setOnKeyListener(mKeyListener); } private class RecentsBarAdapter extends RecyclerView.Adapter<RecentsBarAdapter.ViewHolder> {
private List<ApkRepo.App> apps;
1
2023-12-28 18:24:12+00:00
8k
HChenX/ClipboardList
app/src/main/java/com/hchen/clipboardlist/unlockIme/UnlockIme.java
[ { "identifier": "returnConstant", "path": "app/src/main/java/com/hchen/clipboardlist/hook/Hook.java", "snippet": "public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(result);\n }\n };\n}" }, { "identifier": "Hook", "path": "app/src/main/java/com/hchen/clipboardlist/hook/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\n public void runHook(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n try {\n SetLoadPackageParam(loadPackageParam);\n init();\n logI(tag, \"Hook Done!\");\n } catch (Throwable s) {\n logE(tag, \"Unhandled errors: \" + s);\n }\n }\n\n public void SetLoadPackageParam(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n this.loadPackageParam = loadPackageParam;\n }\n\n public Class<?> findClass(String className) throws XposedHelpers.ClassNotFoundError {\n return findClass(className, loadPackageParam.classLoader);\n }\n\n public Class<?> findClass(String className, ClassLoader classLoader) throws XposedHelpers.ClassNotFoundError {\n return XposedHelpers.findClass(className, classLoader);\n }\n\n public Class<?> findClassIfExists(String className) {\n try {\n return findClass(className);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String newClassName, String oldClassName) {\n try {\n return findClass(findClassIfExists(newClassName) != null ? newClassName : oldClassName);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Find \" + newClassName + \" & \" + oldClassName + \" is null: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String className, ClassLoader classLoader) {\n try {\n return findClass(className, classLoader);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found 2: \" + e);\n return null;\n }\n }\n\n public abstract static class HookAction extends XC_MethodHook {\n\n protected void before(MethodHookParam param) throws Throwable {\n }\n\n protected void after(MethodHookParam param) throws Throwable {\n }\n\n public HookAction() {\n super();\n }\n\n public HookAction(int priority) {\n super(priority);\n }\n\n public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(result);\n }\n };\n }\n\n public static final HookAction DO_NOTHING = new HookAction(PRIORITY_HIGHEST * 2) {\n\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(null);\n }\n\n };\n\n @Override\n protected void beforeHookedMethod(MethodHookParam param) {\n try {\n before(param);\n } catch (Throwable e) {\n logE(\"before\", \"\" + e);\n }\n }\n\n @Override\n protected void afterHookedMethod(MethodHookParam param) {\n try {\n after(param);\n } catch (Throwable e) {\n logE(\"after\", \"\" + e);\n }\n }\n }\n\n public abstract static class ReplaceHookedMethod extends HookAction {\n\n public ReplaceHookedMethod() {\n super();\n }\n\n public ReplaceHookedMethod(int priority) {\n super(priority);\n }\n\n protected abstract Object replace(MethodHookParam param) throws Throwable;\n\n @Override\n public void beforeHookedMethod(MethodHookParam param) {\n try {\n Object result = replace(param);\n param.setResult(result);\n } catch (Throwable t) {\n logE(\"replace\", \"\" + t);\n }\n }\n }\n\n public void hookMethod(Method method, HookAction callback) {\n try {\n if (method == null) {\n logE(tag, \"method is null\");\n return;\n }\n XposedBridge.hookMethod(method, callback);\n logI(tag, \"hookMethod: \" + method);\n } catch (Throwable e) {\n logE(tag, \"hookMethod: \" + method);\n }\n }\n\n public void findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) {\n try {\n /*获取class*/\n if (parameterTypesAndCallback.length != 1) {\n Object[] newArray = new Object[parameterTypesAndCallback.length - 1];\n System.arraycopy(parameterTypesAndCallback, 0, newArray, 0, newArray.length);\n getDeclaredMethod(clazz, methodName, newArray);\n }\n XposedHelpers.findAndHookMethod(clazz, methodName, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz + \" method: \" + methodName);\n } catch (Throwable e) {\n logE(tag, \"Not find method: \" + methodName + \" in: \" + clazz);\n }\n }\n\n public void findAndHookMethod(String className, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className, classLoader), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookConstructor(Class<?> clazz, Object... parameterTypesAndCallback) {\n try {\n XposedHelpers.findAndHookConstructor(clazz, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz);\n } catch (Throwable f) {\n logE(tag, \"findAndHookConstructor: \" + f + \" class: \" + clazz);\n }\n }\n\n public void findAndHookConstructor(String className, Object... parameterTypesAndCallback) {\n findAndHookConstructor(findClassIfExists(className), parameterTypesAndCallback);\n }\n\n public void hookAllMethods(String className, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook The: \" + e);\n }\n }\n\n public void hookAllMethods(String className, ClassLoader classLoader, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className, classLoader);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + className + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllMethods(Class<?> hookClass, String methodName, HookAction callback) {\n try {\n int Num = XposedBridge.hookAllMethods(hookClass, methodName, callback).size();\n logI(tag, \"Hook: \" + hookClass + \" methodName: \" + methodName + \" Num is: \" + Num);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + hookClass.getSimpleName() + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllConstructors(String className, HookAction callback) {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public void hookAllConstructors(Class<?> hookClass, HookAction callback) {\n try {\n XposedBridge.hookAllConstructors(hookClass, callback);\n } catch (Throwable f) {\n logE(tag, \"hookAllConstructors: \" + f + \" class: \" + hookClass);\n }\n }\n\n public void hookAllConstructors(String className, ClassLoader classLoader, HookAction callback) {\n Class<?> hookClass = XposedHelpers.findClassIfExists(className, classLoader);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public Object callMethod(Object obj, String methodName, Object... args) {\n try {\n return XposedHelpers.callMethod(obj, methodName, args);\n } catch (Throwable e) {\n logE(tag, \"callMethod: \" + obj.toString() + \" method: \" + methodName + \" args: \" + Arrays.toString(args) + \" e: \" + e);\n return null;\n }\n }\n\n public Object callStaticMethod(Class<?> clazz, String methodName, Object... args) {\n try {\n return XposedHelpers.callStaticMethod(clazz, methodName, args);\n } catch (Throwable throwable) {\n logE(tag, \"callStaticMethod e: \" + throwable);\n return null;\n }\n }\n\n public Method getDeclaredMethod(String className, String method, Object... type) throws NoSuchMethodException {\n return getDeclaredMethod(findClassIfExists(className), method, type);\n }\n\n public Method getDeclaredMethod(Class<?> clazz, String method, Object... type) throws NoSuchMethodException {\n// String tag = \"getDeclaredMethod\";\n ArrayList<Method> haveMethod = new ArrayList<>();\n Method hqMethod = null;\n int methodNum;\n if (clazz == null) {\n logE(tag, \"find class is null: \" + method);\n throw new NoSuchMethodException(\"find class is null\");\n }\n for (Method getMethod : clazz.getDeclaredMethods()) {\n if (getMethod.getName().equals(method)) {\n haveMethod.add(getMethod);\n }\n }\n if (haveMethod.isEmpty()) {\n logE(tag, \"find method is null: \" + method);\n throw new NoSuchMethodException(\"find method is null\");\n }\n methodNum = haveMethod.size();\n if (type != null) {\n Class<?>[] classes = new Class<?>[type.length];\n Class<?> newclass = null;\n Object getType;\n for (int i = 0; i < type.length; i++) {\n getType = type[i];\n if (getType instanceof Class<?>) {\n newclass = (Class<?>) getType;\n }\n if (getType instanceof String) {\n newclass = findClassIfExists((String) getType);\n if (newclass == null) {\n logE(tag, \"get class error: \" + i);\n throw new NoSuchMethodException(\"get class error\");\n }\n }\n classes[i] = newclass;\n }\n boolean noError = true;\n for (int i = 0; i < methodNum; i++) {\n hqMethod = haveMethod.get(i);\n boolean allHave = true;\n if (hqMethod.getParameterTypes().length != classes.length) {\n if (methodNum - 1 == i) {\n logE(tag, \"class length bad: \" + Arrays.toString(hqMethod.getParameterTypes()));\n throw new NoSuchMethodException(\"class length bad\");\n } else {\n noError = false;\n continue;\n }\n }\n for (int t = 0; t < hqMethod.getParameterTypes().length; t++) {\n Class<?> getClass = hqMethod.getParameterTypes()[t];\n if (!getClass.getSimpleName().equals(classes[t].getSimpleName())) {\n allHave = false;\n break;\n }\n }\n if (!allHave) {\n if (methodNum - 1 == i) {\n logE(tag, \"type bad: \" + Arrays.toString(hqMethod.getParameterTypes())\n + \" input: \" + Arrays.toString(classes));\n throw new NoSuchMethodException(\"type bad\");\n } else {\n noError = false;\n continue;\n }\n }\n if (noError) {\n break;\n }\n }\n return hqMethod;\n } else {\n if (methodNum > 1) {\n logE(tag, \"no type method must only have one: \" + haveMethod);\n throw new NoSuchMethodException(\"no type method must only have one\");\n }\n }\n return haveMethod.get(0);\n }\n\n public void setDeclaredField(XC_MethodHook.MethodHookParam param, String iNeedString, Object iNeedTo) {\n if (param != null) {\n try {\n Field setString = param.thisObject.getClass().getDeclaredField(iNeedString);\n setString.setAccessible(true);\n try {\n setString.set(param.thisObject, iNeedTo);\n Object result = setString.get(param.thisObject);\n checkLast(\"getDeclaredField\", iNeedString, iNeedTo, result);\n } catch (IllegalAccessException e) {\n logE(tag, \"IllegalAccessException to: \" + iNeedString + \" Need to: \" + iNeedTo + \" :\" + e);\n }\n } catch (NoSuchFieldException e) {\n logE(tag, \"No such the: \" + iNeedString + \" : \" + e);\n }\n } else {\n logE(tag, \"Param is null Code: \" + iNeedString + \" & \" + iNeedTo);\n }\n }\n\n public void checkLast(String setObject, Object fieldName, Object value, Object last) {\n if (value != null && last != null) {\n if (value == last || value.equals(last)) {\n logSI(tag, setObject + \" Success! set \" + fieldName + \" to \" + value);\n } else {\n logSE(tag, setObject + \" Failed! set \" + fieldName + \" to \" + value + \" hope: \" + value + \" but: \" + last);\n }\n } else {\n logSE(tag, setObject + \" Error value: \" + value + \" or last: \" + last + \" is null\");\n }\n }\n\n public Object getObjectField(Object obj, String fieldName) {\n try {\n return XposedHelpers.getObjectField(obj, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getObjectField: \" + obj.toString() + \" field: \" + fieldName);\n return null;\n }\n }\n\n public Object getStaticObjectField(Class<?> clazz, String fieldName) {\n try {\n return XposedHelpers.getStaticObjectField(clazz, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName);\n return null;\n }\n }\n\n public void setStaticObjectField(Class<?> clazz, String fieldName, Object value) {\n try {\n XposedHelpers.setStaticObjectField(clazz, fieldName, value);\n } catch (Throwable e) {\n logE(tag, \"setStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName + \" value: \" + value);\n }\n }\n\n public void setInt(Object obj, String fieldName, int value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setIntField(obj, fieldName, value),\n () -> checkLast(\"setInt\", fieldName, value,\n XposedHelpers.getIntField(obj, fieldName)));\n }\n\n public void setBoolean(Object obj, String fieldName, boolean value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setBooleanField(obj, fieldName, value),\n () -> checkLast(\"setBoolean\", fieldName, value,\n XposedHelpers.getBooleanField(obj, fieldName)));\n }\n\n public void setObject(Object obj, String fieldName, Object value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setObjectField(obj, fieldName, value),\n () -> checkLast(\"setObject\", fieldName, value,\n XposedHelpers.getObjectField(obj, fieldName)));\n }\n\n public void checkDeclaredMethod(String className, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookClass.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n if (clazz != null) {\n clazz.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkAndHookField(Object obj, String fieldName, Runnable setField, Runnable checkLast) {\n try {\n obj.getClass().getDeclaredField(fieldName);\n setField.run();\n checkLast.run();\n } catch (Throwable e) {\n logE(tag, \"No such field: \" + fieldName + \" in param: \" + obj + \" : \" + e);\n }\n }\n\n public static Context findContext() {\n Context context;\n try {\n context = (Application) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\n \"android.app.ActivityThread\", null),\n \"currentApplication\");\n if (context == null) {\n Object currentActivityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.app.ActivityThread\",\n null),\n \"currentActivityThread\");\n if (currentActivityThread != null)\n context = (Context) XposedHelpers.callMethod(currentActivityThread,\n \"getSystemContext\");\n }\n return context;\n } catch (Throwable e) {\n logE(\"findContext\", \"null: \" + e);\n }\n return null;\n }\n\n public static String getProp(String key, String defaultValue) {\n try {\n return (String) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"get\", key, defaultValue);\n } catch (Throwable throwable) {\n logE(\"getProp\", \"key get e: \" + key + \" will return default: \" + defaultValue + \" e:\" + throwable);\n return defaultValue;\n }\n }\n\n public static void setProp(String key, String val) {\n try {\n XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"set\", key, val);\n } catch (Throwable throwable) {\n logE(\"setProp\", \"set key e: \" + key + \" e:\" + throwable);\n }\n }\n\n}" } ]
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import static com.hchen.clipboardlist.hook.Hook.HookAction.returnConstant; import com.hchen.clipboardlist.hook.Hook; import java.util.List;
5,290
package com.hchen.clipboardlist.unlockIme; public class UnlockIme extends Hook { private final String[] miuiImeList = new String[]{ "com.iflytek.inputmethod.miui", "com.sohu.inputmethod.sogou.xiaomi", "com.baidu.input_mi", "com.miui.catcherpatch" }; private int navBarColor = 0; @Override public void init() { if (getProp("ro.miui.support_miui_ime_bottom", "0").equals("1")) { startHook(loadPackageParam); } } private void startHook(LoadPackageParam param) { // 检查是否为小米定制输入法 boolean isNonCustomize = true; for (String isMiui : miuiImeList) { if (isMiui.equals(param.packageName)) { isNonCustomize = false; break; } } if (isNonCustomize) { Class<?> sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceInjector"); if (sInputMethodServiceInjector == null) sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceStubImpl"); if (sInputMethodServiceInjector != null) { hookSIsImeSupport(sInputMethodServiceInjector); hookIsXiaoAiEnable(sInputMethodServiceInjector); setPhraseBgColor(sInputMethodServiceInjector); } else { logE(tag, "Class not found: InputMethodServiceInjector"); } } hookDeleteNotSupportIme("android.inputmethodservice.InputMethodServiceInjector$MiuiSwitchInputMethodListener", param.classLoader); // 获取常用语的ClassLoader boolean finalIsNonCustomize = isNonCustomize; findAndHookMethod("android.inputmethodservice.InputMethodModuleManager", "loadDex", ClassLoader.class, String.class, new HookAction() { @Override protected void after(MethodHookParam param) { getSupportIme((ClassLoader) param.args[0]); hookDeleteNotSupportIme("com.miui.inputmethod.InputMethodBottomManager$MiuiSwitchInputMethodListener", (ClassLoader) param.args[0]); if (finalIsNonCustomize) { Class<?> InputMethodBottomManager = findClassIfExists("com.miui.inputmethod.InputMethodBottomManager", (ClassLoader) param.args[0]); if (InputMethodBottomManager != null) { hookSIsImeSupport(InputMethodBottomManager); hookIsXiaoAiEnable(InputMethodBottomManager); } else { logE(tag, "Class not found: com.miui.inputmethod.InputMethodBottomManager"); } } } } ); } /** * 跳过包名检查,直接开启输入法优化 * * @param clazz 声明或继承字段的类 */ private void hookSIsImeSupport(Class<?> clazz) { try { setStaticObjectField(clazz, "sIsImeSupport", 1); } catch (Throwable throwable) { logE(tag, "Hook field sIsImeSupport: " + throwable); } } /** * 小爱语音输入按钮失效修复 * * @param clazz 声明或继承方法的类 */ private void hookIsXiaoAiEnable(Class<?> clazz) { try {
package com.hchen.clipboardlist.unlockIme; public class UnlockIme extends Hook { private final String[] miuiImeList = new String[]{ "com.iflytek.inputmethod.miui", "com.sohu.inputmethod.sogou.xiaomi", "com.baidu.input_mi", "com.miui.catcherpatch" }; private int navBarColor = 0; @Override public void init() { if (getProp("ro.miui.support_miui_ime_bottom", "0").equals("1")) { startHook(loadPackageParam); } } private void startHook(LoadPackageParam param) { // 检查是否为小米定制输入法 boolean isNonCustomize = true; for (String isMiui : miuiImeList) { if (isMiui.equals(param.packageName)) { isNonCustomize = false; break; } } if (isNonCustomize) { Class<?> sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceInjector"); if (sInputMethodServiceInjector == null) sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceStubImpl"); if (sInputMethodServiceInjector != null) { hookSIsImeSupport(sInputMethodServiceInjector); hookIsXiaoAiEnable(sInputMethodServiceInjector); setPhraseBgColor(sInputMethodServiceInjector); } else { logE(tag, "Class not found: InputMethodServiceInjector"); } } hookDeleteNotSupportIme("android.inputmethodservice.InputMethodServiceInjector$MiuiSwitchInputMethodListener", param.classLoader); // 获取常用语的ClassLoader boolean finalIsNonCustomize = isNonCustomize; findAndHookMethod("android.inputmethodservice.InputMethodModuleManager", "loadDex", ClassLoader.class, String.class, new HookAction() { @Override protected void after(MethodHookParam param) { getSupportIme((ClassLoader) param.args[0]); hookDeleteNotSupportIme("com.miui.inputmethod.InputMethodBottomManager$MiuiSwitchInputMethodListener", (ClassLoader) param.args[0]); if (finalIsNonCustomize) { Class<?> InputMethodBottomManager = findClassIfExists("com.miui.inputmethod.InputMethodBottomManager", (ClassLoader) param.args[0]); if (InputMethodBottomManager != null) { hookSIsImeSupport(InputMethodBottomManager); hookIsXiaoAiEnable(InputMethodBottomManager); } else { logE(tag, "Class not found: com.miui.inputmethod.InputMethodBottomManager"); } } } } ); } /** * 跳过包名检查,直接开启输入法优化 * * @param clazz 声明或继承字段的类 */ private void hookSIsImeSupport(Class<?> clazz) { try { setStaticObjectField(clazz, "sIsImeSupport", 1); } catch (Throwable throwable) { logE(tag, "Hook field sIsImeSupport: " + throwable); } } /** * 小爱语音输入按钮失效修复 * * @param clazz 声明或继承方法的类 */ private void hookIsXiaoAiEnable(Class<?> clazz) { try {
hookAllMethods(clazz, "isXiaoAiEnable", returnConstant(false));
0
2023-12-22 15:07:33+00:00
8k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/mixin/LivingEntityMixin.java
[ { "identifier": "GliderEntity", "path": "src/main/java/eu/pb4/glideaway/entity/GliderEntity.java", "snippet": "public class GliderEntity extends Entity implements PolymerEntity {\n private static final TrackedData<Float> ROLL = DataTracker.registerData(GliderEntity.class, TrackedDataHandlerRegistry.FLOAT);\n private ItemStack itemStack = GlideItems.HANG_GLIDER.getDefaultStack();\n private ItemStack modelStack = GlideItems.HANG_GLIDER.getDefaultStack();\n private int damageTimer;\n private int lastAttack = -999;\n\n private final ElementHolder holder = new ElementHolder();\n private int soundTimer;\n private int attacks;\n\n public static boolean create(World world, LivingEntity rider, ItemStack stack, Hand hand) {\n if (rider.hasVehicle() || (rider.isSneaking() && !world.getGameRules().getBoolean(GlideGamerules.ALLOW_SNEAK_RELEASE))) {\n return false;\n }\n stack.damage((int) Math.max(0, -rider.getVelocity().y\n * world.getGameRules().get(GlideGamerules.INITIAL_VELOCITY_GLIDER_DAMAGE).get()\n * (90 - Math.abs(MathHelper.clamp(rider.getPitch(), -30, 80))) / 90),\n rider, player -> player.sendEquipmentBreakStatus(hand == Hand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND));\n\n if (stack.isEmpty()) {\n return false;\n }\n\n var entity = new GliderEntity(GlideEntities.GLIDER, world);\n var sitting = rider.getDimensions(EntityPose.SITTING);\n var currentDim = rider.getDimensions(rider.getPose());\n entity.setItemStack(stack);\n entity.setPosition(rider.getPos().add(0, currentDim.height - sitting.height - rider.getRidingOffset(entity), 0));\n entity.setYaw(rider.getYaw());\n entity.setPitch(rider.getPitch());\n entity.setVelocity(rider.getVelocity().add(rider.getRotationVector().multiply(0.2, 0.02, 0.2).multiply(rider.isSneaking() ? 2 : 1)));\n\n world.spawnEntity(entity);\n entity.playSound(GlideSoundEvents.HANG_GLIDER_OPENS, 0.8f, entity.random.nextFloat() * 0.2f + 1.2f);\n\n if (!rider.isSneaking()) {\n rider.startRiding(entity);\n }\n return true;\n }\n\n public static ItemStack createDispenser(BlockPointer pointer, ItemStack stack) {\n Direction direction = pointer.state().get(DispenserBlock.FACING);\n ServerWorld serverWorld = pointer.world();\n Vec3d vec3d = pointer.centerPos();\n\n var entity = new GliderEntity(GlideEntities.GLIDER, serverWorld);\n entity.setItemStack(stack.copyWithCount(1));\n entity.setPosition(vec3d.x, vec3d.y - 0.5f, vec3d.z);\n entity.setYaw(direction.getAxis() == Direction.Axis.Y ? 0 : direction.asRotation());\n entity.setPitch(direction.getAxis() != Direction.Axis.Y ? 0 : (direction == Direction.UP ? -90 : 90));\n entity.setVelocity(Vec3d.of(direction.getVector()).multiply(0.6));\n\n serverWorld.spawnEntity(entity);\n entity.playSound(GlideSoundEvents.HANG_GLIDER_OPENS, 0.8f, entity.random.nextFloat() * 0.2f + 1.2f);\n stack.decrement(1);\n return stack;\n }\n\n public void setItemStack(ItemStack stack) {\n this.itemStack = stack;\n this.modelStack = stack.getItem().getDefaultStack();\n if (stack.hasNbt() && stack.getItem() instanceof DyeableItem dyeableItem) {\n dyeableItem.setColor(this.modelStack, dyeableItem.getColor(stack));\n }\n }\n\n public GliderEntity(EntityType<?> type, World world) {\n super(type, world);\n this.setInvisible(true);\n var interaction = InteractionElement.redirect(this);\n interaction.setSize(0.8f, 1.2f);\n this.holder.addElement(interaction);\n }\n\n @Override\n public boolean damage(DamageSource source, float amount) {\n if (source.isIn(DamageTypeTags.CAN_BREAK_ARMOR_STAND)) {\n if (this.age - this.lastAttack > 30) {\n this.attacks = 0;\n } else if (this.attacks == 2) {\n this.giveOrDrop(this.getFirstPassenger());\n this.discard();\n }\n\n this.attacks++;\n this.lastAttack = this.age;\n var sign = Math.signum(this.dataTracker.get(ROLL));\n if (sign == 0) {\n sign = 1;\n }\n\n this.dataTracker.set(ROLL, -sign * Math.min(Math.abs(this.dataTracker.get(ROLL) + 0.2f), 1) );\n return true;\n } else if (source.isIn(DamageTypeTags.ALWAYS_KILLS_ARMOR_STANDS)) {\n this.giveOrDrop(this.getFirstPassenger());\n this.discard();\n return true;\n } else if (source.isIn(DamageTypeTags.IGNITES_ARMOR_STANDS)) {\n this.damageStack((int) (amount * 2));\n return true;\n }\n\n return super.damage(source, amount);\n }\n\n private boolean damageStack(int i) {\n var serverWorld = (ServerWorld) this.getWorld();\n if (itemStack.damage(i, this.random, null)) {\n var old = this.itemStack;\n this.setItemStack(ItemStack.EMPTY);\n if (this.getFirstPassenger() != null) {\n this.getFirstPassenger().stopRiding();\n }\n serverWorld.spawnParticles(new ItemStackParticleEffect(ParticleTypes.ITEM, old), this.getX(), this.getY() + 0.5, this.getZ(), 80, 1, 1, 1, 0.1);\n this.discard();\n return true;\n }\n return false;\n }\n\n @Override\n public boolean handleAttack(Entity attacker) {\n return false;\n }\n\n @Override\n protected Vector3f getPassengerAttachmentPos(Entity passenger, EntityDimensions dimensions, float scaleFactor) {\n return new Vector3f();\n }\n\n @Override\n public boolean canBeHitByProjectile() {\n return false;\n }\n\n @Override\n public boolean canHit() {\n return false;\n }\n\n public void giveOrDrop(@Nullable Entity entity) {\n if (this.isRemoved()) {\n return;\n }\n\n if (entity instanceof LivingEntity livingEntity && entity.isAlive()) {\n if (livingEntity.getStackInHand(Hand.MAIN_HAND).isEmpty()) {\n livingEntity.setStackInHand(Hand.MAIN_HAND, this.getItemStack());\n } else if (livingEntity.getStackInHand(Hand.OFF_HAND).isEmpty()) {\n livingEntity.setStackInHand(Hand.OFF_HAND, this.getItemStack());\n } else if (!(entity instanceof PlayerEntity player && player.giveItemStack(this.getItemStack()))) {\n this.dropStack(this.getItemStack());\n }\n } else {\n this.dropStack(this.getItemStack());\n }\n this.setItemStack(ItemStack.EMPTY);\n this.discard();\n }\n\n @Override\n public void tick() {\n if (!(this.getWorld() instanceof ServerWorld serverWorld)) {\n return;\n }\n\n super.tick();\n var passenger = this.getFirstPassenger();\n\n if (passenger != null && !passenger.isAlive()) {\n passenger.stopRiding();\n passenger = null;\n }\n\n if (passenger == null && this.holder.getAttachment() == null) {\n EntityAttachment.of(this.holder, this);\n VirtualEntityUtils.addVirtualPassenger(this, this.holder.getEntityIds().getInt(0));\n } else if (passenger != null && this.holder.getAttachment() != null) {\n VirtualEntityUtils.removeVirtualPassenger(this, this.holder.getEntityIds().getInt(0));\n this.holder.destroy();\n }\n\n if ((this.isOnGround() || (passenger != null && passenger.isOnGround())) && this.age > 10) {\n this.giveOrDrop(passenger);\n return;\n }\n\n if (passenger != null) {\n this.setYaw(MathHelper.lerpAngleDegrees(0.175f, this.getYaw(), passenger.getYaw()));\n this.setPitch(MathHelper.lerpAngleDegrees(0.175f, this.getPitch(), MathHelper.clamp(passenger.getPitch(), -30, 80)));\n var roll = MathHelper.clamp((-MathHelper.subtractAngles(passenger.getYaw(), this.getYaw())) * MathHelper.RADIANS_PER_DEGREE * 0.5f, -1f, 1f);\n\n if (Math.abs(roll - this.getDataTracker().get(ROLL)) > MathHelper.RADIANS_PER_DEGREE / 2) {\n this.getDataTracker().set(ROLL, roll);\n }\n } else {\n var roll = this.getDataTracker().get(ROLL) * 0.98f;\n\n if (Math.abs(roll - this.getDataTracker().get(ROLL)) > MathHelper.RADIANS_PER_DEGREE / 2 || Math.abs(roll) > MathHelper.RADIANS_PER_DEGREE / 2) {\n this.getDataTracker().set(ROLL, roll);\n }\n }\n\n int dmgTimeout = serverWorld.getRegistryKey() == World.NETHER ? 6 : 10;\n int dmgFrequency = 2;\n int dmg = 1;\n\n var mut = this.getBlockPos().mutableCopy();\n for (int i = 0; i < 32; i++) {\n var state = serverWorld.getBlockState(mut);\n if (state.isOf(Blocks.FIRE) || state.isOf(Blocks.CAMPFIRE) && i < 24) {\n this.addVelocity(0, ((32 - i) / 32f) * this.getWorld().getGameRules().get(GlideGamerules.FIRE_BOOST).get(), 0);\n dmgFrequency = 1;\n } else if (state.isOf(Blocks.LAVA) && i < 6) {\n this.addVelocity(0, ((6 - i) / 6f) * this.getWorld().getGameRules().get(GlideGamerules.LAVA_BOOST).get(), 0);\n dmgTimeout = 2;\n dmgFrequency = 1;\n dmg = 2;\n } else if (state.isSideSolidFullSquare(serverWorld, mut, Direction.UP)) {\n break;\n }\n\n mut.move(0, -1, 0);\n }\n\n\n double gravity = 0.07;\n if (serverWorld.hasRain(this.getBlockPos())) {\n gravity = 0.1;\n } else if (GlideDimensionTypeTags.isIn(serverWorld, GlideDimensionTypeTags.HIGH_GRAVITY)) {\n gravity = 0.084;\n } else if (GlideDimensionTypeTags.isIn(serverWorld, GlideDimensionTypeTags.LOW_GRAVITY)) {\n gravity = 0.056;\n }\n\n this.limitFallDistance();\n if (passenger != null) {\n passenger.limitFallDistance();\n }\n Vec3d velocity = this.getVelocity();\n Vec3d rotationVector = this.getRotationVector();\n float pitch = this.getPitch() * (float) (Math.PI / 180.0);\n double rotationLength = Math.sqrt(rotationVector.x * rotationVector.x + rotationVector.z * rotationVector.z);\n double horizontalVelocity = velocity.horizontalLength();\n double rotationVectorLength = rotationVector.length();\n double cosPitch = Math.cos((double)pitch);\n cosPitch = cosPitch * cosPitch * Math.min(1.0, rotationVectorLength / 0.4);\n velocity = this.getVelocity().add(0.0, gravity * (-1.0 + cosPitch * 0.75), 0.0);\n if (velocity.y < 0.0 && rotationLength > 0.0) {\n double m = velocity.y * -0.1 * cosPitch;\n velocity = velocity.add(rotationVector.x * m / rotationLength, m, rotationVector.z * m / rotationLength);\n }\n\n if (pitch < 0.0F && rotationLength > 0.0) {\n double m = horizontalVelocity * (double)(-MathHelper.sin(pitch)) * 0.04;\n velocity = velocity.add(-rotationVector.x * m / rotationLength, m * 3.2, -rotationVector.z * m / rotationLength);\n }\n\n if (rotationLength > 0.0) {\n velocity = velocity.add((rotationVector.x / rotationLength * horizontalVelocity - velocity.x) * 0.1, 0.0, (rotationVector.z / rotationLength * horizontalVelocity - velocity.z) * 0.1);\n }\n\n if (this.isInFluid()) {\n this.setVelocity(velocity.multiply(0.8F, 0.8F, 0.8F));\n\n if (this.getVelocity().horizontalLength() < 0.04) {\n if (passenger != null) {\n passenger.stopRiding();\n }\n this.giveOrDrop(passenger);\n return;\n }\n } else {\n this.setVelocity(velocity.multiply(0.985F, 0.96F, 0.985F));\n }\n\n if (passenger instanceof ServerPlayerEntity player && this.age > 20 * 5 && this.soundTimer++ % 20 * 4 == 0) {\n var l = this.getVelocity().length();\n\n if (l > 0.05 && serverWorld.getGameRules().getBoolean(GlideGamerules.WIND_SOUND)) {\n player.networkHandler.sendPacket(new PlaySoundFromEntityS2CPacket(GlideSoundEvents.WIND, SoundCategory.AMBIENT, player, (float) MathHelper.clamp(l, 0.05, 0.8), this.random.nextFloat() * 0.2f + 0.9f, this.random.nextLong()));\n }\n }\n\n if (this.itemStack.getItem() instanceof HangGliderItem gliderItem) {\n gliderItem.tickGlider(serverWorld, this, passenger, this.itemStack);\n }\n\n this.move(MovementType.SELF, this.getVelocity());\n if (this.horizontalCollision && passenger != null) {\n double m = this.getVelocity().horizontalLength();\n double n = horizontalVelocity - m;\n float o = (float)(n * 10.0 - 3.0);\n if (o > 0.0F) {\n //this.playSound(passenger.getFallSound((int)o), 1.0F, 1.0F);\n passenger.damage(this.getDamageSources().flyIntoWall(), o);\n }\n }\n\n int i = ++this.damageTimer;\n if ((i % dmgTimeout == 0 && (i / dmgFrequency) % dmgTimeout == 0) || this.isOnFire()) {\n this.damageStack(dmg);\n this.emitGameEvent(GameEvent.ELYTRA_GLIDE);\n }\n }\n\n @Override\n public ActionResult interact(PlayerEntity player, Hand hand) {\n if (this.getFirstPassenger() != null) {\n return ActionResult.FAIL;\n }\n\n player.startRiding(this);\n\n return ActionResult.SUCCESS;\n }\n\n @Override\n protected void tickInVoid() {\n if (GlideDimensionTypeTags.isIn(this.getWorld(), GlideDimensionTypeTags.VOID_PICKUP)) {\n this.giveOrDrop(this.getFirstPassenger());\n } else {\n super.tickInVoid();\n }\n }\n\n @Override\n public EntityType<?> getPolymerEntityType(ServerPlayerEntity player) {\n return EntityType.ITEM_DISPLAY;\n }\n\n @Override\n public void modifyRawTrackedData(List<DataTracker.SerializedEntry<?>> data, ServerPlayerEntity player, boolean initial) {\n if (initial) {\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.TELEPORTATION_DURATION, 2));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.INTERPOLATION_DURATION, 2));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.Item.ITEM, this.modelStack));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.TRANSLATION, new Vector3f(0, 1.2f, -0.05f)));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.SCALE, new Vector3f(1.5f)));\n }\n\n for (var entry : data.toArray(new DataTracker.SerializedEntry<?>[0])) {\n if (entry.id() == ROLL.getId()) {\n data.remove(entry);\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.LEFT_ROTATION, new Quaternionf().rotateZ((Float) entry.value())));\n data.add(DataTracker.SerializedEntry.of(DisplayTrackedData.START_INTERPOLATION, 0));\n }\n }\n }\n\n @Override\n protected void initDataTracker() {\n this.dataTracker.startTracking(ROLL, 0f);\n }\n\n @Override\n protected void readCustomDataFromNbt(NbtCompound nbt) {\n setItemStack(ItemStack.fromNbt(nbt.getCompound(\"stack\")));\n }\n\n @Override\n protected void writeCustomDataToNbt(NbtCompound nbt) {\n nbt.put(\"stack\", this.itemStack.writeNbt(new NbtCompound()));\n }\n\n public ItemStack getItemStack() {\n return this.itemStack;\n }\n}" }, { "identifier": "GlideGamerules", "path": "src/main/java/eu/pb4/glideaway/util/GlideGamerules.java", "snippet": "public class GlideGamerules {\n public static final GameRules.Key<GameRules.BooleanRule> PICK_HANG_GLIDER = GameRuleRegistry.register(\"glideaway:pick_hang_glider\", GameRules.Category.MISC,\n GameRuleFactory.createBooleanRule(false));\n\n public static final GameRules.Key<GameRules.BooleanRule> WIND_SOUND = GameRuleRegistry.register(\"glideaway:wind_sound\", GameRules.Category.MISC,\n GameRuleFactory.createBooleanRule(true));\n\n public static final GameRules.Key<GameRules.BooleanRule> ALLOW_SNEAK_RELEASE = GameRuleRegistry.register(\"glideaway:allow_sneak_release\", GameRules.Category.MISC,\n GameRuleFactory.createBooleanRule(true));\n\n\n public static final GameRules.Key<DoubleRule> INITIAL_VELOCITY_GLIDER_DAMAGE = GameRuleRegistry.register(\"glideaway:initial_velocity_glider_damage\", GameRules.Category.MISC,\n GameRuleFactory.createDoubleRule(50, 0));\n\n public static final GameRules.Key<DoubleRule> FIRE_BOOST = GameRuleRegistry.register(\"glideaway:fire_velocity_boost\", GameRules.Category.MISC,\n GameRuleFactory.createDoubleRule(0.04, 0, 1));\n\n public static final GameRules.Key<DoubleRule> LAVA_BOOST = GameRuleRegistry.register(\"glideaway:lava_velocity_boost\", GameRules.Category.MISC,\n GameRuleFactory.createDoubleRule(0.01, 0, 1));\n public static void register() {}\n}" } ]
import eu.pb4.glideaway.entity.GliderEntity; import eu.pb4.glideaway.util.GlideGamerules; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraft.world.World; 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;
4,754
package eu.pb4.glideaway.mixin; @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity { @Shadow protected abstract void initDataTracker(); public LivingEntityMixin(EntityType<?> type, World world) { super(type, world); } @SuppressWarnings("ConstantValue") @Inject(method = "onDismounted", at = @At("HEAD")) private void returnGlider(Entity vehicle, CallbackInfo ci) {
package eu.pb4.glideaway.mixin; @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity { @Shadow protected abstract void initDataTracker(); public LivingEntityMixin(EntityType<?> type, World world) { super(type, world); } @SuppressWarnings("ConstantValue") @Inject(method = "onDismounted", at = @At("HEAD")) private void returnGlider(Entity vehicle, CallbackInfo ci) {
if (vehicle instanceof GliderEntity entity) {
0
2023-12-22 11:00:52+00:00
8k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/controller/ShoppingCartController.java
[ { "identifier": "Product", "path": "src/main/java/es/storeapp/business/entities/Product.java", "snippet": "@Entity(name = Constants.PRODUCT_ENTITY)\n@Table(name = Constants.PRODUCTS_TABLE)\npublic class Product implements Serializable{ \n\n private static final long serialVersionUID = 70079876312519893L;\n \n @Id\n private Long productId;\n \n @ManyToOne\n @JoinColumn(name = \"category\", nullable = false)\n private Category category;\n \n @Column(name = \"name\", nullable = false, unique = true)\n private String name;\n \n @Column(name = \"description\", nullable = false)\n private String description;\n \n @Column(name = \"icon\", nullable = false)\n private String icon;\n \n @Column(name = \"price\", nullable = false)\n private Integer price;\n\n @Column(name = \"totalScore\", nullable = false)\n private Integer totalScore;\n\n @Column(name = \"totalComments\", nullable = false)\n private Integer totalComments;\n \n @Column(name = \"sales\", nullable = false)\n private Integer sales;\n \n @OneToMany(mappedBy = \"product\")\n private List<Comment> comments = new ArrayList<>();\n \n public Long getProductId() {\n return productId;\n }\n\n public void setProductId(Long productId) {\n this.productId = productId;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public void setCategory(Category category) {\n this.category = category;\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public Integer getPrice() {\n return price;\n }\n\n public void setPrice(Integer price) {\n this.price = price;\n }\n\n public Integer getTotalScore() {\n return totalScore;\n }\n\n public void setTotalScore(Integer totalScore) {\n this.totalScore = totalScore;\n }\n\n public Integer getTotalComments() {\n return totalComments;\n }\n\n public void setTotalComments(Integer totalComments) {\n this.totalComments = totalComments;\n }\n\n public Integer getSales() {\n return sales;\n }\n\n public void setSales(Integer sales) {\n this.sales = sales;\n }\n\n public List<Comment> getComments() {\n return comments;\n }\n\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n \n public Integer getRating() {\n return totalComments == 0 ? 0 : totalScore / totalComments;\n }\n\n @Override\n public String toString() {\n return String.format(\"Product{productId=%s, category=%s, name=%s, description=%s, icon=%s, price=%s, totalScore=%s, totalComments=%s, sales=%s}\", \n productId, category, name, description, icon, price, totalScore, totalComments, sales);\n }\n \n \n \n}" }, { "identifier": "InstanceNotFoundException", "path": "src/main/java/es/storeapp/business/exceptions/InstanceNotFoundException.java", "snippet": "public class InstanceNotFoundException extends Exception {\n\n private static final long serialVersionUID = -4208426212843868046L;\n\n private final Long id;\n private final String type;\n\n public InstanceNotFoundException(Long id, String type, String message) {\n super(message);\n this.id = id;\n this.type = type;\n }\n\n public Object getId() {\n return id;\n }\n\n public String getType() {\n return type;\n }\n \n}" }, { "identifier": "ProductService", "path": "src/main/java/es/storeapp/business/services/ProductService.java", "snippet": "@Service\npublic class ProductService {\n\n private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ProductService.class);\n\n @Autowired\n ConfigurationParameters configurationParameters;\n\n @Autowired\n private ProductRepository productRepository;\n\n @Autowired\n private CategoryRepository categoryRepository;\n\n @Autowired\n private CommentRepository rateRepository;\n\n @Autowired\n ExceptionGenerationUtils exceptionGenerationUtils;\n \n @Transactional(readOnly = true)\n public List<Product> findAllProducts() {\n return productRepository.findAll(Constants.PRICE_FIELD);\n }\n\n @Transactional(readOnly = true)\n public List<Product> findProducts(String category) {\n if (category == null || category.length() == 0) {\n return productRepository.findAll(Constants.PRICE_FIELD);\n } else {\n return productRepository.findByCategory(category, Constants.PRICE_FIELD);\n }\n }\n\n @Transactional(readOnly = false)\n public Product findProductById(Long id) throws InstanceNotFoundException {\n return productRepository.findById(id);\n }\n\n @Transactional(readOnly = true)\n public List<Category> findAllCategories() {\n return categoryRepository.findAll();\n }\n\n @Transactional(readOnly = true)\n public List<Category> findHighlightedCategories() {\n return categoryRepository.findHighlighted();\n }\n\n @Transactional()\n public Comment findCommentByUserAndProduct(User user, Long productId)\n throws InstanceNotFoundException {\n try {\n Product product = productRepository.findById(productId);\n if(logger.isDebugEnabled()) {\n logger.debug(MessageFormat.format(\"Searching if the user {0} has commented the product {1}\", \n user.getEmail(), product.getName()));\n }\n return rateRepository.findByUserAndProduct(user.getUserId(), productId);\n } catch (EmptyResultDataAccessException e) {\n return null;\n }\n }\n\n @Transactional()\n public Comment comment(User user, Long productId, String text, Integer rating)\n throws InstanceNotFoundException {\n Product product = productRepository.findById(productId);\n try {\n Comment comment = rateRepository.findByUserAndProduct(user.getUserId(), product.getProductId());\n if(logger.isDebugEnabled()) {\n logger.debug(MessageFormat.format(\"{0} has modified his comment of the product {1}\", \n user.getName(), product.getName()));\n }\n product.setTotalScore(product.getTotalScore() - comment.getRating() + rating);\n comment.setRating(rating);\n comment.setText(text);\n comment.setTimestamp(System.currentTimeMillis());\n productRepository.update(product);\n return rateRepository.update(comment);\n } catch (EmptyResultDataAccessException e) {\n if(logger.isDebugEnabled()) {\n logger.debug(MessageFormat.format(\"{0} created a comment of the product {1}\", \n user.getName(), product.getName()));\n }\n Comment comment = new Comment();\n comment.setUser(user);\n comment.setProduct(product);\n comment.setRating(rating);\n comment.setText(text);\n comment.setTimestamp(System.currentTimeMillis());\n product.setTotalComments(product.getTotalComments() + 1);\n product.setTotalScore(product.getTotalScore() + rating);\n productRepository.update(product);\n return rateRepository.create(comment);\n }\n }\n\n}" }, { "identifier": "Constants", "path": "src/main/java/es/storeapp/common/Constants.java", "snippet": "public class Constants {\n\n private Constants() {\n }\n \n /* Messages */\n \n public static final String AUTH_INVALID_USER_MESSAGE = \"auth.invalid.user\";\n public static final String AUTH_INVALID_PASSWORD_MESSAGE = \"auth.invalid.password\";\n public static final String AUTH_INVALID_TOKEN_MESSAGE = \"auth.invalid.token\";\n public static final String REGISTRATION_INVALID_PARAMS_MESSAGE = \"registration.invalid.parameters\";\n public static final String UPDATE_PROFILE_INVALID_PARAMS_MESSAGE = \"update.profile.invalid.parameters\";\n public static final String CHANGE_PASSWORD_INVALID_PARAMS_MESSAGE = \"change.password.invalid.parameters\";\n public static final String RESET_PASSWORD_INVALID_PARAMS_MESSAGE = \"reset.password.invalid.parameters\";\n public static final String LOGIN_INVALID_PARAMS_MESSAGE = \"login.invalid.parameters\";\n public static final String INSTANCE_NOT_FOUND_MESSAGE = \"instance.not.found.exception\";\n public static final String DUPLICATED_INSTANCE_MESSAGE = \"duplicated.instance.exception\";\n public static final String DUPLICATED_COMMENT_MESSAGE = \"duplicated.comment.exception\";\n public static final String INVALID_PROFILE_IMAGE_MESSAGE = \"invalid.profile.image\";\n public static final String INVALID_STATE_EXCEPTION_MESSAGE = \"invalid.state\";\n public static final String INVALID_EMAIL_MESSAGE = \"invalid.email\";\n \n public static final String PRODUCT_ADDED_TO_THE_SHOPPING_CART = \"product.added.to.the.cart\";\n public static final String PRODUCT_REMOVED_FROM_THE_SHOPPING_CART = \"product.removed.from.the.cart\";\n public static final String PRODUCT_ALREADY_IN_SHOPPING_CART = \"product.already.in.cart\";\n public static final String PRODUCT_NOT_IN_SHOPPING_CART = \"product.not.in.cart\";\n public static final String EMPTY_SHOPPING_CART = \"shopping.cart.empty\";\n public static final String PRODUCT_COMMENT_CREATED = \"product.comment.created\";\n \n public static final String ORDER_AUTOGENERATED_NAME = \"order.name.autogenerated\";\n public static final String ORDER_SINGLE_PRODUCT_AUTOGENERATED_NAME_MESSAGE = \"order.name.single.product.autogenerated\";\n public static final String CREATE_ORDER_INVALID_PARAMS_MESSAGE = \"create.order.invalid.parameters\";\n public static final String PAY_ORDER_INVALID_PARAMS_MESSAGE = \"pay.order.invalid.parameters\";\n public static final String CANCEL_ORDER_INVALID_PARAMS_MESSAGE = \"cancel.order.invalid.parameters\";\n \n public static final String ORDER_CREATED_MESSAGE = \"order.created\";\n public static final String ORDER_PAYMENT_COMPLETE_MESSAGE = \"order.payment.completed\";\n public static final String ORDER_CANCEL_COMPLETE_MESSAGE = \"order.cancellation.completed\";\n \n public static final String REGISTRATION_SUCCESS_MESSAGE = \"registration.success\";\n public static final String PROFILE_UPDATE_SUCCESS = \"profile.updated.success\";\n public static final String CHANGE_PASSWORD_SUCCESS = \"change.password.success\";\n \n public static final String MAIL_SUBJECT_MESSAGE = \"mail.subject\";\n public static final String MAIL_TEMPLATE_MESSAGE = \"mail.template\";\n public static final String MAIL_HTML_NOT_SUPPORTED_MESSAGE = \"mail.html.not.supported\";\n public static final String MAIL_SUCCESS_MESSAGE = \"mail.sent.success\";\n public static final String MAIL_NOT_CONFIGURED_MESSAGE = \"mail.not.configured\";\n \n /* Web Endpoints */\n \n public static final String ROOT_ENDPOINT = \"/\";\n public static final String ALL_ENDPOINTS = \"/**\";\n public static final String LOGIN_ENDPOINT = \"/login\";\n public static final String LOGOUT_ENDPOINT = \"/logout\";\n public static final String USER_PROFILE_ALL_ENDPOINTS = \"/profile/**\";\n public static final String USER_PROFILE_ENDPOINT = \"/profile\";\n public static final String USER_PROFILE_IMAGE_ENDPOINT = \"/profile/image\";\n public static final String USER_PROFILE_IMAGE_REMOVE_ENDPOINT = \"/profile/image/remove\";\n public static final String REGISTRATION_ENDPOINT = \"/registration\";\n public static final String ORDERS_ALL_ENDPOINTS = \"/orders/**\";\n public static final String ORDERS_ENDPOINT = \"/orders\";\n public static final String ORDER_ENDPOINT = \"/orders/{id}\";\n public static final String ORDER_ENDPOINT_TEMPLATE = \"/orders/{0}\";\n public static final String ORDER_CONFIRM_ENDPOINT = \"/orders/complete\";\n public static final String ORDER_PAYMENT_ENDPOINT = \"/orders/{id}/pay\";\n public static final String ORDER_PAYMENT_ENDPOINT_TEMPLATE = \"/orders/{0}/pay\";\n public static final String ORDER_CANCEL_ENDPOINT = \"/orders/{id}/cancel\";\n public static final String PRODUCTS_ENDPOINT = \"/products\";\n public static final String PRODUCT_ENDPOINT = \"/products/{id}\";\n public static final String PRODUCT_TEMPLATE = \"/products/{0}\";\n public static final String CHANGE_PASSWORD_ENDPOINT = \"/changePassword\";\n public static final String RESET_PASSWORD_ENDPOINT = \"/resetPassword\";\n public static final String SEND_EMAIL_ENDPOINT = \"/sendEmail\";\n public static final String CART_ADD_PRODUCT_ENDPOINT = \"/products/{id}/addToCart\";\n public static final String CART_REMOVE_PRODUCT_ENDPOINT = \"/products/{id}/removeFromCart\";\n public static final String CART_ENDPOINT = \"/cart\";\n public static final String COMMENT_PRODUCT_ENDPOINT = \"/products/{id}/rate\";\n public static final String EXTERNAL_RESOURCES = \"/resources/**\";\n public static final String LIBS_RESOURCES = \"/webjars/**\";\n public static final String SEND_REDIRECT = \"redirect:\";\n \n /* Web Pages */\n \n public static final String LOGIN_PAGE = \"Login\";\n public static final String HOME_PAGE = \"Index\";\n public static final String ERROR_PAGE = \"error\";\n public static final String PASSWORD_PAGE = \"ChangePassword\";\n public static final String SEND_EMAIL_PAGE = \"SendEmail\";\n public static final String RESET_PASSWORD_PAGE = \"ResetPassword\";\n public static final String USER_PROFILE_PAGE = \"Profile\";\n public static final String PRODUCTS_PAGE = \"Products\";\n public static final String PRODUCT_PAGE = \"Product\";\n public static final String SHOPPING_CART_PAGE = \"Cart\";\n public static final String ORDER_COMPLETE_PAGE = \"OrderConfirm\";\n public static final String ORDER_PAGE = \"Order\";\n public static final String ORDER_PAYMENT_PAGE = \"Payment\";\n public static final String ORDERS_PAGE = \"Orders\";\n public static final String PAYMENTS_PAGE = \"Orders\";\n public static final String COMMENT_PAGE = \"Comment\";\n \n /* Request/session/model Attributes */\n \n public static final String PARAMS = \"?\";\n public static final String PARAM_VALUE = \"=\";\n public static final String NEW_PARAM_VALUE = \"&\";\n public static final String USER_SESSION = \"user\";\n public static final String SHOPPING_CART_SESSION = \"shoppingCart\";\n public static final String ERROR_MESSAGE = \"errorMessage\";\n public static final String EXCEPTION = \"exception\";\n public static final String WARNING_MESSAGE = \"warningMessage\";\n public static final String SUCCESS_MESSAGE = \"successMessage\";\n public static final String MESSAGE = \"message\"; /* predefined */\n public static final String LOGIN_FORM = \"loginForm\";\n public static final String USER_PROFILE_FORM = \"userProfileForm\";\n public static final String PASSWORD_FORM = \"passwordForm\";\n public static final String RESET_PASSWORD_FORM = \"resetPasswordForm\";\n public static final String COMMENT_FORM = \"commentForm\";\n public static final String PAYMENT_FORM = \"paymentForm\";\n public static final String NEXT_PAGE = \"next\";\n public static final String CATEGORIES = \"categories\";\n public static final String PRODUCTS = \"products\";\n public static final String PRODUCTS_ARRAY = \"products[]\";\n public static final String PRODUCT = \"product\";\n public static final String ORDER_FORM = \"orderForm\";\n public static final String ORDERS = \"orders\";\n public static final String ORDER = \"order\";\n public static final String PAY_NOW = \"pay\";\n public static final String BUY_BY_USER = \"buyByUser\";\n public static final String EMAIL_PARAM = \"email\";\n public static final String TOKEN_PARAM = \"token\";\n \n /* Entities, attributes and tables */\n \n public static final String USER_ENTITY = \"User\";\n public static final String PRODUCT_ENTITY = \"Product\";\n public static final String CATEGORY_ENTITY = \"Category\";\n public static final String COMMENT_ENTITY = \"Comment\";\n public static final String ORDER_ENTITY = \"Order\";\n public static final String ORDER_LINE_ENTITY = \"OrderLine\";\n \n public static final String USERS_TABLE = \"Users\";\n public static final String PRODUCTS_TABLE = \"Products\";\n public static final String CATEGORIES_TABLE = \"Categories\";\n public static final String COMMENTS_TABLE = \"Comments\";\n public static final String ORDERS_TABLE = \"Orders\";\n public static final String ORDER_LINES_TABLE = \"OrderLines\";\n \n public static final String PRICE_FIELD = \"price\";\n public static final String NAME_FIELD = \"name\";\n public static final String EMAIL_FIELD = \"email\";\n \n /* Other */\n \n public static final String CONTENT_TYPE_HEADER = \"Content-Type\";\n public static final String CONTENT_DISPOSITION_HEADER = \"Content-Disposition\";\n public static final String CONTENT_DISPOSITION_HEADER_VALUE = \"attachment; filename={0}-{1}\";\n public static final String PERSISTENT_USER_COOKIE = \"user-info\";\n public static final String URL_FORMAT = \"{0}://{1}:{2}{3}{4}\";\n \n}" }, { "identifier": "ErrorHandlingUtils", "path": "src/main/java/es/storeapp/web/exceptions/ErrorHandlingUtils.java", "snippet": "@Component\npublic class ErrorHandlingUtils {\n\n private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ErrorHandlingUtils.class);\n\n @Autowired\n private MessageSource messageSource;\n \n public String handleInvalidFormError(BindingResult result, String template, \n Model model, Locale locale) {\n if(logger.isErrorEnabled()) {\n logger.error(result.toString());\n }\n String message = messageSource.getMessage(template, new Object[0], locale);\n model.addAttribute(Constants.ERROR_MESSAGE, message);\n return Constants.ERROR_PAGE;\n }\n \n public String handleInstanceNotFoundException(InstanceNotFoundException e, Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n \n public String handleDuplicatedResourceException(DuplicatedResourceException e, String targetPage,\n Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return targetPage;\n }\n\n public String handleAuthenticationException(AuthenticationException e, String user, String targetPage,\n Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return targetPage;\n }\n \n public String handleInvalidStateException(InvalidStateException e, Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n \n public String handleUnexpectedException(Exception e, Model model) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n}" }, { "identifier": "ShoppingCart", "path": "src/main/java/es/storeapp/web/session/ShoppingCart.java", "snippet": "public class ShoppingCart implements Serializable {\n\n private static final long serialVersionUID = 8032734613287752106L; \n \n private final List<Product> products = new ArrayList<>();\n\n public List<Product> getProducts() {\n return products;\n }\n \n public boolean contains(Long id) {\n return products.stream().anyMatch(product -> (product.getProductId().equals(id)));\n }\n \n public int getTotalPrice() {\n int totalPrice = 0;\n return products.stream().map(product -> product.getPrice()).reduce(totalPrice, Integer::sum);\n }\n \n public void clear() {\n products.clear();\n }\n \n}" }, { "identifier": "EscapingLoggerWrapper", "path": "src/main/java/es/storeapp/common/EscapingLoggerWrapper.java", "snippet": "public class EscapingLoggerWrapper {\n private final Logger wrappedLogger;\n\n public EscapingLoggerWrapper(Class<?> clazz) {\n this.wrappedLogger = LoggerFactory.getLogger(clazz);\n }\n\n // Implementa todos los métodos de la interfaz org.slf4j.Logger\n // y agrega la lógica de escape de caracteres antes de llamar a los métodos del logger subyacente\n\n public void info(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.info(escapedFormat, arguments);\n }\n\n public void error(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.error(escapedFormat, arguments);\n }\n\n public void debug(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.debug(escapedFormat, arguments);\n }\n\n public void warn(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.warn(escapedFormat, arguments);\n }\n\n public boolean isWarnEnabled(){\n return wrappedLogger.isWarnEnabled();\n }\n\n public boolean isDebugEnabled(){\n return wrappedLogger.isDebugEnabled();\n }\n\n public boolean isErrorEnabled(){\n return wrappedLogger.isErrorEnabled();\n }\n\n // Método de escape de caracteres\n private String escapeCharacters(String input) {\n String string = Encode.forHtml(input);//evita javascript inyection\n return Encode.forJava(string);//codifica los saltos de linea\n }\n}" } ]
import es.storeapp.business.entities.Product; import es.storeapp.business.exceptions.InstanceNotFoundException; import es.storeapp.business.services.ProductService; import es.storeapp.common.Constants; import es.storeapp.web.exceptions.ErrorHandlingUtils; import es.storeapp.web.session.ShoppingCart; import java.text.MessageFormat; import java.util.List; import java.util.Locale; import es.storeapp.common.EscapingLoggerWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.SessionAttribute; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
4,981
package es.storeapp.web.controller; @Controller public class ShoppingCartController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ShoppingCartController.class); @Autowired private ProductService productService; @Autowired private MessageSource messageSource; @Autowired ErrorHandlingUtils exceptionHandlingUtils; @GetMapping(value = {Constants.CART_ENDPOINT})
package es.storeapp.web.controller; @Controller public class ShoppingCartController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ShoppingCartController.class); @Autowired private ProductService productService; @Autowired private MessageSource messageSource; @Autowired ErrorHandlingUtils exceptionHandlingUtils; @GetMapping(value = {Constants.CART_ENDPOINT})
public String doGetCartPage(@SessionAttribute(Constants.SHOPPING_CART_SESSION) ShoppingCart shoppingCart,
5
2023-12-24 19:24:49+00:00
8k
Brath1024/SensiCheck
src/main/java/cn/brath/sensicheck/strategy/SensiHolder.java
[ { "identifier": "SenKey", "path": "src/main/java/cn/brath/sensicheck/core/SenKey.java", "snippet": "public class SenKey implements Serializable {\n private static final long serialVersionUID = -8879895979621579720L;\n /** The beginning index, inclusive. */\n private final int begin;\n /** The ending index, exclusive. */\n private final int end;\n private final String keyword;\n\n public SenKey(int begin, int end, String keyword) {\n this.begin = begin;\n this.end = end;\n this.keyword = keyword;\n }\n\n public int getBegin() {\n return begin;\n }\n\n public int getEnd() {\n return end;\n }\n\n public int getLength() {\n return end - begin;\n }\n\n public String getKeyword() {\n return keyword;\n }\n\n public boolean overlaps(SenKey o) {\n return this.begin < o.end && this.end > o.begin;\n }\n\n public boolean contains(SenKey o) {\n return this.begin <= o.begin && this.end >= o.end;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (!(o instanceof SenKey))\n return false;\n SenKey that = (SenKey) o;\n return this.begin == that.begin\n && this.end == that.end\n && Objects.equals(this.keyword, that.keyword);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(begin, end, keyword);\n }\n\n @Override\n public String toString() {\n return begin + \":\" + end + \"=\" + keyword;\n }\n}" }, { "identifier": "SenKeys", "path": "src/main/java/cn/brath/sensicheck/core/SenKeys.java", "snippet": "public class SenKeys extends ArrayList<SenKey> {\n private static final long serialVersionUID = -9117361135147927914L;\n private final CharSequence source;\n\n public SenKeys(CharSequence source) {\n this.source = source;\n }\n\n private SenKeys(SenKeys senKeys) {\n super(senKeys);\n this.source = senKeys.source;\n }\n\n public CharSequence getSource() {\n return source;\n }\n\n public List<SenWord> tokenize() {\n SenKeys senKeys = this.copy();\n senKeys.removeContains();\n String source = senKeys.getSource().toString();\n List<SenWord> senWords = new ArrayList<>(senKeys.size() * 2 + 1);\n if (senKeys.isEmpty()) {\n senWords.add(new SenWord(source, null));\n return senWords;\n }\n int index = 0;\n for (SenKey senKey : senKeys) {\n if (index < senKey.getBegin()) {\n senWords.add(new SenWord(source.substring(index, senKey.getBegin()), null));\n }\n senWords.add(new SenWord(source.substring(senKey.getBegin(), senKey.getEnd()), senKey));\n index = senKey.getEnd();\n }\n SenKey last = senKeys.get(senKeys.size() - 1);\n if (last.getEnd() < source.length()) {\n senWords.add(new SenWord(source.substring(last.getEnd()), null));\n }\n return senWords;\n }\n\n public String replaceWith(String replacement) {\n SenKeys senKeys = this.copy();\n senKeys.removeContains();\n String source = senKeys.getSource().toString();\n if (senKeys.isEmpty()) {\n return source;\n }\n int index = 0;\n StringBuilder sb = new StringBuilder();\n for (SenKey senKey : this) {\n if (index < senKey.getBegin()) {\n sb.append(source, index, senKey.getBegin());\n index = senKey.getBegin();\n }\n sb.append(mask(replacement, index, senKey.getEnd()));\n index = senKey.getEnd();\n }\n SenKey last = senKeys.get(senKeys.size() - 1);\n if (last.getEnd() < source.length()) {\n sb.append(source, last.getEnd(), source.length());\n }\n return sb.toString();\n }\n\n public void removeOverlaps() {\n removeIf(SenKey::overlaps);\n }\n\n public void removeContains() {\n removeIf(SenKey::contains);\n }\n\n private void removeIf(BiPredicate<SenKey, SenKey> predicate) {\n if (this.size() <= 1) {\n return;\n }\n this.sort();\n Iterator<SenKey> iterator = this.iterator();\n SenKey senKey = iterator.next();\n while (iterator.hasNext()) {\n SenKey next = iterator.next();\n if (predicate.test(senKey, next)) {\n iterator.remove();\n } else {\n senKey = next;\n }\n }\n }\n\n private void sort() {\n this.sort((a, b) -> {\n if (a.getBegin() != b.getBegin()) {\n return Integer.compare(a.getBegin(), b.getBegin());\n } else {\n return Integer.compare(b.getEnd(), a.getEnd());\n }\n });\n }\n\n private String mask(String replacement, int begin, int end) {\n int count = end - begin;\n int len = replacement != null ? replacement.length() : 0;\n if (len == 0) {\n return repeat(\"*\", count);\n } else if (len == 1) {\n return repeat(replacement, count);\n } else {\n char[] chars = new char[count];\n for (int i = 0; i < count; i++) {\n chars[i] = replacement.charAt((i + begin) % len);\n }\n return new String(chars);\n }\n }\n\n private String repeat(String s, int count) {\n if (count < 0) {\n throw new IllegalArgumentException(\"count is negative: \" + count);\n }\n if (count == 1) {\n return s;\n }\n final int len = s.length();\n if (len == 0 || count == 0) {\n return \"\";\n }\n if (Integer.MAX_VALUE / count < len) {\n throw new OutOfMemoryError(\"Required length exceeds implementation limit\");\n }\n if (len == 1) {\n final char[] single = new char[count];\n Arrays.fill(single, s.charAt(0));\n return new String(single);\n }\n final int limit = len * count;\n final char[] multiple = new char[limit];\n System.arraycopy(s.toCharArray(), 0, multiple, 0, len);\n int copied = len;\n for (; copied < limit - copied; copied <<= 1) {\n System.arraycopy(multiple, 0, multiple, copied, copied);\n }\n System.arraycopy(multiple, 0, multiple, copied, limit - copied);\n return new String(multiple);\n }\n\n private SenKeys copy() {\n return new SenKeys(this);\n }\n}" }, { "identifier": "SenTrie", "path": "src/main/java/cn/brath/sensicheck/core/SenTrie.java", "snippet": "public class SenTrie implements Serializable {\n private static final long serialVersionUID = 7464998650081881647L;\n private final SenNode root;\n\n public SenTrie() {\n this.root = new SenNode(0);\n }\n\n public SenTrie(Set<String> keywords) {\n this.root = new SenNode(0);\n this.addKeywords(keywords);\n }\n\n public SenTrie(String... keywords) {\n this.root = new SenNode(0);\n this.addKeywords(keywords);\n }\n\n public SenTrie(InputStream src) {\n this.root = new SenNode(0);\n this.addKeywords(src);\n }\n\n public SenTrie addKeywords(Set<String> keywords) {\n for (String keyword : keywords) {\n if (keyword != null && !keyword.isEmpty()) {\n root.addNode(keyword).addKeyword(keyword);\n }\n }\n Queue<SenNode> nodes = new LinkedList<>();\n root.getSuccess().forEach((ignored, state) -> {\n state.setFailure(root);\n nodes.add(state);\n });\n while (!nodes.isEmpty()) {\n SenNode state = nodes.poll();\n state.getSuccess().forEach((c, next) -> {\n SenNode f = state.getFailure();\n SenNode fn = f.nextState(c);\n while (fn == null) {\n f = f.getFailure();\n fn = f.nextState(c);\n }\n next.setFailure(fn);\n next.addKeywords(fn.getKeywords());\n nodes.add(next);\n });\n }\n return this;\n }\n\n public void addKeywords(String... keywords) {\n if (keywords == null || keywords.length == 0) {\n return;\n }\n Set<String> keywordSet = new HashSet<>();\n Collections.addAll(keywordSet, keywords);\n addKeywords(keywordSet);\n }\n\n public void addKeywords(InputStream src) {\n Set<String> keywords = new HashSet<>();\n try (InputStreamReader inputStreamReader = new InputStreamReader(src);\n BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n keywords.add(line);\n }\n } catch (IOException e) {\n throw new IllegalArgumentException(e);\n }\n addKeywords(keywords);\n }\n\n public SenKeys findAll(CharSequence text, boolean ignoreCase) {\n SenKeys senKeys = new SenKeys(text);\n SenNode state = root;\n for (int i = 0, len = text.length(); i < len; i++) {\n state = nextState(state, text.charAt(i), ignoreCase);\n for (String keyword : state.getKeywords()) {\n senKeys.add(new SenKey(i - keyword.length() + 1, i + 1, keyword));\n }\n }\n return senKeys;\n }\n\n public SenKeys findAll(CharSequence text) {\n return findAll(text, false);\n }\n\n public SenKeys findAllIgnoreCase(CharSequence text) {\n return findAll(text, true);\n }\n\n public SenKey findFirst(CharSequence text, boolean ignoreCase) {\n SenNode state = root;\n for (int i = 0, len = text.length(); i < len; i++) {\n state = nextState(state, text.charAt(i), ignoreCase);\n String keyword = state.getFirstKeyword();\n if (keyword != null) {\n return new SenKey(i - keyword.length() + 1, i + 1, keyword);\n }\n }\n return null;\n }\n\n public SenKey findFirst(CharSequence text) {\n return findFirst(text, false);\n }\n\n public SenKey findFirstIgnoreCase(CharSequence text) {\n return findFirst(text, true);\n }\n\n private SenNode nextState(SenNode state, char c, boolean ignoreCase) {\n SenNode next = state.nextState(c, ignoreCase);\n while (next == null) {\n state = state.getFailure();\n next = state.nextState(c, ignoreCase);\n }\n return next;\n }\n}" }, { "identifier": "StringUtil", "path": "src/main/java/cn/brath/sensicheck/utils/StringUtil.java", "snippet": "public class StringUtil {\n\n public static boolean isEmpty(String str) {\n if (null == str) {\n return true;\n } else {\n return \"\".equals(str);\n }\n }\n}" } ]
import cn.brath.sensicheck.core.SenKey; import cn.brath.sensicheck.core.SenKeys; import cn.brath.sensicheck.core.SenTrie; import cn.brath.sensicheck.utils.StringUtil; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors;
3,725
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构 private SenTrie senTrie; //当前敏感词列表 private List<String> lines; /** * 默认构造 */ public SensiHolder() { try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 自定义FilePath * * @param filepath */ public SensiHolder(String filepath) { this.filepath = filepath; try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; logger.info("The current sensitive word text source comes from - {}", filepath); } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 读取敏感词Base64文本 * * @return * @throws IOException */ private List<String> readLines() throws IOException { List<String> lines = new ArrayList<>(); try (InputStream inputStream = getClass().getResourceAsStream(filepath)) { assert inputStream != null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { byte[] decode = Base64.getDecoder().decode(line); String decodedString = new String(decode, StandardCharsets.UTF_8); lines.add(decodedString); } } } return lines; } /** * 是否存在敏感词 * * @param input * @param ifLog * @return */ public boolean exists(String input, boolean ifLog) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty() && ifLog) { logger.warn("存在敏感词:{}", String.join(",", senKeys.stream().map(SenKey::getKeyword).collect(Collectors.toList()))); } return !senKeys.isEmpty(); } /** * 是否存在敏感词 * * @param input * @return */ public String existsStr(String input) { SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty()) { return senKeys.stream().map(SenKey::getKeyword).collect(Collectors.joining(",")); } return null; } /** * 是否存在敏感词 * * @param input * @return */ public boolean exists(String input) { return exists(input, true); } /** * 是否存在敏感词 * * @param data * @return */ public boolean exists(Object data) { Objects.requireNonNull(data, "Data cannot be null"); return exists(JSON.toJSONString(data)); } /** * 替换 * * @param input * @param replaceValue * @return */ public String replace(String input, String replaceValue) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAllIgnoreCase(input); if (senKeys.isEmpty()) { return input; }
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构 private SenTrie senTrie; //当前敏感词列表 private List<String> lines; /** * 默认构造 */ public SensiHolder() { try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 自定义FilePath * * @param filepath */ public SensiHolder(String filepath) { this.filepath = filepath; try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; logger.info("The current sensitive word text source comes from - {}", filepath); } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 读取敏感词Base64文本 * * @return * @throws IOException */ private List<String> readLines() throws IOException { List<String> lines = new ArrayList<>(); try (InputStream inputStream = getClass().getResourceAsStream(filepath)) { assert inputStream != null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { byte[] decode = Base64.getDecoder().decode(line); String decodedString = new String(decode, StandardCharsets.UTF_8); lines.add(decodedString); } } } return lines; } /** * 是否存在敏感词 * * @param input * @param ifLog * @return */ public boolean exists(String input, boolean ifLog) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty() && ifLog) { logger.warn("存在敏感词:{}", String.join(",", senKeys.stream().map(SenKey::getKeyword).collect(Collectors.toList()))); } return !senKeys.isEmpty(); } /** * 是否存在敏感词 * * @param input * @return */ public String existsStr(String input) { SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty()) { return senKeys.stream().map(SenKey::getKeyword).collect(Collectors.joining(",")); } return null; } /** * 是否存在敏感词 * * @param input * @return */ public boolean exists(String input) { return exists(input, true); } /** * 是否存在敏感词 * * @param data * @return */ public boolean exists(Object data) { Objects.requireNonNull(data, "Data cannot be null"); return exists(JSON.toJSONString(data)); } /** * 替换 * * @param input * @param replaceValue * @return */ public String replace(String input, String replaceValue) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAllIgnoreCase(input); if (senKeys.isEmpty()) { return input; }
if (StringUtil.isEmpty(replaceValue)) {
3
2023-12-28 04:50:04+00:00
8k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/view/RankFrame.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素\", currentUser = \"\";\r\n public static final String[] themeList = {\"典雅\", \"激情\", \"像素\"};\r\n\r\n private static RankFrame rankFrame = null;\r\n public static boolean hasLogon = false;\r\n public static int currentUserId = 0, mode = 0;\r\n public static Map<String, JsonElement> data;\r\n public static ArrayList<String> userList = new ArrayList<>();\r\n public static ArrayList<Integer> scoresList = new ArrayList<>();\r\n\r\n public static void main(String[] args) {\r\n Gson gson = new Gson();\r\n\r\n FlatLightLaf.setup();\r\n\r\n String raw = FileUtils.getDataFromFile(\"data\");\r\n if (raw == null) raw = \"{}\";\r\n try {\r\n data = JsonParser.parseString(raw).getAsJsonObject().asMap();\r\n } catch (Exception e) {\r\n System.out.println(e.getMessage());\r\n data = new HashMap<>();\r\n }\r\n if (gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType()) == null)\r\n userList.add(\"test\");\r\n else\r\n userList = gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType());\r\n if (gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType()) == null)\r\n scoresList.add(0);\r\n else\r\n scoresList = gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType());\r\n theme = gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType()) == null ? \"像素\" : gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType());\r\n\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/FZShiGKSJW.TTF\");\r\n titleFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n titleFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SweiSpringCJKtc-Medium.ttf\");\r\n serifFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n serifFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SourceHanSansCN-Regular.otf\");\r\n sansFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n sansFont = Font.getFont(Font.SANS_SERIF);\r\n }\r\n\r\n SwingUtilities.invokeLater(Main::backStart);\r\n\r\n playBGMusic();\r\n }\r\n\r\n public static void startGame(int mode) {\r\n Main.mode = mode;\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n if (startFrame != null) startFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n playNotifyMusic(\"gamestart\");\r\n }\r\n\r\n public static void goRank() {\r\n rankFrame = new RankFrame(480, 720);\r\n rankFrame.setVisible(true);\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (startFrame != null) startFrame.dispose();\r\n }\r\n\r\n public static void refreshGame() {\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n }\r\n\r\n public static void backStart() {\r\n startFrame = new StartFrame(480, 720);\r\n startFrame.setVisible(true);\r\n if (rankFrame != null) rankFrame.dispose();\r\n if (gameFrame != null) gameFrame.dispose();\r\n }\r\n\r\n\r\n public static String getThemeResource(String type) {\r\n switch (type) {\r\n case \"bg\":\r\n if (theme.equals(themeList[0])) return \"Resources/background1.jpg\";\r\n if (theme.equals(themeList[1])) return \"Resources/background2.jpg\";\r\n else return \"Resources/background3.jpg\";\r\n case \"startbtn\":\r\n if (theme.equals(themeList[0])) return \"Resources/button2.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/button1.png\";\r\n else return \"Resources/button3.png\";\r\n case \"btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"md-btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn-md.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"board\":\r\n if (theme.equals(themeList[0])) return \"Resources/board1.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/board2.png\";\r\n else return \"Resources/board3.png\";\r\n case \"chess-pixel\":\r\n return \"Resources/pixel-chess.png\";\r\n case \"chess-pixel-sel\":\r\n return \"Resources/pixel-chess-sel.png\";\r\n case \"chess-pixel-opq\":\r\n return \"Resources/pixel-chess-opq.png\";\r\n case \"chessfill\":\r\n if (theme.equals(themeList[0])) return \"#f6b731\";\r\n else return \"#E28B24\";\r\n case \"chessfillopaque\":\r\n if (theme.equals(themeList[0])) return \"#f2deb2\";\r\n else return \"#dca35f\";\r\n case \"chessborder\":\r\n if (theme.equals(themeList[0])) return \"#e3914a\";\r\n else return \"#B3391F\";\r\n }\r\n return \"\";\r\n }\r\n\r\n public static Color getThemeColor(String type) {\r\n switch (type) {\r\n case \"indicatorBlack\":\r\n if (theme.equals(themeList[0]) || theme.equals(themeList[2]))\r\n return ChessColor.BLACK.getColor();\r\n else return Color.WHITE;\r\n case \"indicatorRed\":\r\n return ChessColor.RED.getColor();\r\n case \"title\":\r\n if (theme.equals(themeList[0])) return Color.WHITE;\r\n else return Color.BLACK;\r\n case \"black\":\r\n return Color.BLACK;\r\n }\r\n return Color.BLACK;\r\n }\r\n\r\n public static void playBGMusic() {\r\n playMusic(\"Resources/bgm1.wav\", 0f, true);\r\n }\r\n\r\n public static void playNotifyMusic(String id) {\r\n playMusic(\"Resources/\" + id + \".wav\", (id.equals(\"click\") ? 5f : 0f), false);\r\n }\r\n\r\n private static void playMusic(String filePath, float volume, boolean shouldLoop) {\r\n try {\r\n if (Main.class.getResourceAsStream(filePath) != null) {\r\n BufferedInputStream musicPath =\r\n new BufferedInputStream(Objects.requireNonNull(Main.class.getResourceAsStream(filePath)));\r\n Clip clip1;\r\n AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);\r\n clip1 = AudioSystem.getClip();\r\n clip1.open(audioInput);\r\n FloatControl gainControl = (FloatControl) clip1.getControl(FloatControl.Type.MASTER_GAIN);\r\n gainControl.setValue(volume); //设置音量,范围为 -60.0f 到 6.0f\r\n clip1.start();\r\n clip1.loop(shouldLoop ? Clip.LOOP_CONTINUOUSLY : 0);\r\n } else {\r\n log(\"Cannot find music\");\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "ImageUtils", "path": "CS109_2022_Fall/Chess/utils/ImageUtils.java", "snippet": "public class ImageUtils {\r\n public static ImageIcon changeImageSize(ImageIcon image, float i) {\r\n int width = (int) (image.getIconWidth() * i);\r\n int height = (int) (image.getIconHeight() * i);\r\n Image img = image.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);\r\n return new ImageIcon(img);\r\n }\r\n\r\n public static ImageIcon changeToOriginalSize(ImageIcon image, int width, int height) {\r\n Image img = image.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);\r\n return new ImageIcon(img);\r\n }\r\n}\r" }, { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素\", currentUser = \"\";\r\n public static final String[] themeList = {\"典雅\", \"激情\", \"像素\"};\r\n\r\n private static RankFrame rankFrame = null;\r\n public static boolean hasLogon = false;\r\n public static int currentUserId = 0, mode = 0;\r\n public static Map<String, JsonElement> data;\r\n public static ArrayList<String> userList = new ArrayList<>();\r\n public static ArrayList<Integer> scoresList = new ArrayList<>();\r\n\r\n public static void main(String[] args) {\r\n Gson gson = new Gson();\r\n\r\n FlatLightLaf.setup();\r\n\r\n String raw = FileUtils.getDataFromFile(\"data\");\r\n if (raw == null) raw = \"{}\";\r\n try {\r\n data = JsonParser.parseString(raw).getAsJsonObject().asMap();\r\n } catch (Exception e) {\r\n System.out.println(e.getMessage());\r\n data = new HashMap<>();\r\n }\r\n if (gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType()) == null)\r\n userList.add(\"test\");\r\n else\r\n userList = gson.fromJson(data.get(\"userList\"), new TypeToken<ArrayList<String>>() {\r\n }.getType());\r\n if (gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType()) == null)\r\n scoresList.add(0);\r\n else\r\n scoresList = gson.fromJson(data.get(\"userScores\"), new TypeToken<ArrayList<Integer>>() {\r\n }.getType());\r\n theme = gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType()) == null ? \"像素\" : gson.fromJson(data.get(\"theme\"), new TypeToken<String>() {\r\n }.getType());\r\n\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/FZShiGKSJW.TTF\");\r\n titleFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n titleFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SweiSpringCJKtc-Medium.ttf\");\r\n serifFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n serifFont = Font.getFont(Font.SERIF);\r\n }\r\n try {\r\n InputStream stream = Main.class.getResourceAsStream(\"Resources/SourceHanSansCN-Regular.otf\");\r\n sansFont = Font.createFont(Font.TRUETYPE_FONT, stream);\r\n } catch (Exception e) {\r\n sansFont = Font.getFont(Font.SANS_SERIF);\r\n }\r\n\r\n SwingUtilities.invokeLater(Main::backStart);\r\n\r\n playBGMusic();\r\n }\r\n\r\n public static void startGame(int mode) {\r\n Main.mode = mode;\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n if (startFrame != null) startFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n playNotifyMusic(\"gamestart\");\r\n }\r\n\r\n public static void goRank() {\r\n rankFrame = new RankFrame(480, 720);\r\n rankFrame.setVisible(true);\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (startFrame != null) startFrame.dispose();\r\n }\r\n\r\n public static void refreshGame() {\r\n if (gameFrame != null) gameFrame.dispose();\r\n if (rankFrame != null) rankFrame.dispose();\r\n gameFrame = new ChessGameFrame(480, 720, mode);\r\n gameFrame.setVisible(true);\r\n }\r\n\r\n public static void backStart() {\r\n startFrame = new StartFrame(480, 720);\r\n startFrame.setVisible(true);\r\n if (rankFrame != null) rankFrame.dispose();\r\n if (gameFrame != null) gameFrame.dispose();\r\n }\r\n\r\n\r\n public static String getThemeResource(String type) {\r\n switch (type) {\r\n case \"bg\":\r\n if (theme.equals(themeList[0])) return \"Resources/background1.jpg\";\r\n if (theme.equals(themeList[1])) return \"Resources/background2.jpg\";\r\n else return \"Resources/background3.jpg\";\r\n case \"startbtn\":\r\n if (theme.equals(themeList[0])) return \"Resources/button2.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/button1.png\";\r\n else return \"Resources/button3.png\";\r\n case \"btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"md-btn\":\r\n if (theme.equals(themeList[2])) return \"Resources/pixel-btn-md.png\";\r\n else return \"Resources/normal-btn.png\";\r\n case \"board\":\r\n if (theme.equals(themeList[0])) return \"Resources/board1.png\";\r\n if (theme.equals(themeList[1])) return \"Resources/board2.png\";\r\n else return \"Resources/board3.png\";\r\n case \"chess-pixel\":\r\n return \"Resources/pixel-chess.png\";\r\n case \"chess-pixel-sel\":\r\n return \"Resources/pixel-chess-sel.png\";\r\n case \"chess-pixel-opq\":\r\n return \"Resources/pixel-chess-opq.png\";\r\n case \"chessfill\":\r\n if (theme.equals(themeList[0])) return \"#f6b731\";\r\n else return \"#E28B24\";\r\n case \"chessfillopaque\":\r\n if (theme.equals(themeList[0])) return \"#f2deb2\";\r\n else return \"#dca35f\";\r\n case \"chessborder\":\r\n if (theme.equals(themeList[0])) return \"#e3914a\";\r\n else return \"#B3391F\";\r\n }\r\n return \"\";\r\n }\r\n\r\n public static Color getThemeColor(String type) {\r\n switch (type) {\r\n case \"indicatorBlack\":\r\n if (theme.equals(themeList[0]) || theme.equals(themeList[2]))\r\n return ChessColor.BLACK.getColor();\r\n else return Color.WHITE;\r\n case \"indicatorRed\":\r\n return ChessColor.RED.getColor();\r\n case \"title\":\r\n if (theme.equals(themeList[0])) return Color.WHITE;\r\n else return Color.BLACK;\r\n case \"black\":\r\n return Color.BLACK;\r\n }\r\n return Color.BLACK;\r\n }\r\n\r\n public static void playBGMusic() {\r\n playMusic(\"Resources/bgm1.wav\", 0f, true);\r\n }\r\n\r\n public static void playNotifyMusic(String id) {\r\n playMusic(\"Resources/\" + id + \".wav\", (id.equals(\"click\") ? 5f : 0f), false);\r\n }\r\n\r\n private static void playMusic(String filePath, float volume, boolean shouldLoop) {\r\n try {\r\n if (Main.class.getResourceAsStream(filePath) != null) {\r\n BufferedInputStream musicPath =\r\n new BufferedInputStream(Objects.requireNonNull(Main.class.getResourceAsStream(filePath)));\r\n Clip clip1;\r\n AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);\r\n clip1 = AudioSystem.getClip();\r\n clip1.open(audioInput);\r\n FloatControl gainControl = (FloatControl) clip1.getControl(FloatControl.Type.MASTER_GAIN);\r\n gainControl.setValue(volume); //设置音量,范围为 -60.0f 到 6.0f\r\n clip1.start();\r\n clip1.loop(shouldLoop ? Clip.LOOP_CONTINUOUSLY : 0);\r\n } else {\r\n log(\"Cannot find music\");\r\n }\r\n } catch (Exception ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n}\r" } ]
import Chess.Main; import Chess.utils.ImageUtils; import com.google.gson.Gson; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import static Chess.Main.*; import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
4,230
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("board")); JLabel lbBg = null; try {
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("board")); JLabel lbBg = null; try {
lbBg = new JLabel(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), HEIGHT * 2 / 5, HEIGHT * 4 / 5));
1
2023-12-31 05:50:13+00:00
8k
Patbox/serveruifix
src/main/java/eu/pb4/serveruifix/ModInit.java
[ { "identifier": "PolydexCompat", "path": "src/main/java/eu/pb4/serveruifix/polydex/PolydexCompat.java", "snippet": "public class PolydexCompat {\n private static final boolean IS_PRESENT = FabricLoader.getInstance().isModLoaded(\"polydex2\");\n\n\n public static void register() {\n if (IS_PRESENT) {\n PolydexCompatImpl.register();\n } else {\n //LOGGER.warn(\"[PolyDecorations] Polydex not found! It's highly suggested to install it!\");\n }\n }\n\n\n public static GuiElement getButton(RecipeType<?> type) {\n if (IS_PRESENT) {\n return PolydexCompatImpl.getButton(type);\n }\n return GuiElement.EMPTY;\n }\n}" }, { "identifier": "GuiTextures", "path": "src/main/java/eu/pb4/serveruifix/util/GuiTextures.java", "snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> STONECUTTER = background(\"stonecutter\");\n\n public static final Supplier<GuiElementBuilder> POLYDEX_BUTTON = icon32(\"polydex\");\n public static final Supplier<GuiElementBuilder> LEFT_BUTTON = icon16(\"left\");\n public static final Supplier<GuiElementBuilder> RIGHT_BUTTON = icon16(\"right\");\n\n public static void register() {\n }\n\n\n public record Progress(GuiElement[] elements) {\n\n public GuiElement get(float progress) {\n return elements[Math.min((int) (progress * elements.length), elements.length - 1)];\n }\n\n public static Progress createVertical(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n public static Progress createVertical32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n }\n\n}" }, { "identifier": "UiResourceCreator", "path": "src/main/java/eu/pb4/serveruifix/util/UiResourceCreator.java", "snippet": "public class UiResourceCreator {\n public static final String BASE_MODEL = \"minecraft:item/generated\";\n public static final String X32_MODEL = \"serveruifix:sgui/button_32\";\n public static final String X32_RIGHT_MODEL = \"serveruifix:sgui/button_32_right\";\n\n private static final Style STYLE = Style.EMPTY.withColor(0xFFFFFF).withFont(id(\"gui\"));\n private static final String ITEM_TEMPLATE = \"\"\"\n {\n \"parent\": \"|BASE|\",\n \"textures\": {\n \"layer0\": \"|ID|\"\n }\n }\n \"\"\".replace(\" \", \"\").replace(\"\\n\", \"\");\n\n private static final List<SlicedTexture> VERTICAL_PROGRESS = new ArrayList<>();\n private static final List<SlicedTexture> HORIZONTAL_PROGRESS = new ArrayList<>();\n private static final List<Pair<PolymerModelData, String>> SIMPLE_MODEL = new ArrayList<>();\n private static final Char2IntMap SPACES = new Char2IntOpenHashMap();\n private static final Char2ObjectMap<Identifier> TEXTURES = new Char2ObjectOpenHashMap<>();\n private static final Object2ObjectMap<Pair<Character, Character>, Identifier> TEXTURES_POLYDEX = new Object2ObjectOpenHashMap<>();\n private static final List<String> TEXTURES_NUMBERS = new ArrayList<>();\n private static char character = 'a';\n\n private static final char CHEST_SPACE0 = character++;\n private static final char CHEST_SPACE1 = character++;\n\n public static Supplier<GuiElementBuilder> icon16(String path) {\n var model = genericIconRaw(Items.ALLIUM, path, BASE_MODEL);\n return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n }\n\n public static Supplier<GuiElementBuilder> icon32(String path) {\n var model = genericIconRaw(Items.ALLIUM, path, X32_MODEL);\n return () -> new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n }\n\n public static IntFunction<GuiElementBuilder> icon32Color(String path) {\n var model = genericIconRaw(Items.LEATHER_LEGGINGS, path, X32_MODEL);\n return (i) -> {\n var b = new GuiElementBuilder(model.item()).setName(Text.empty()).hideFlags().setCustomModelData(model.value());\n var display = new NbtCompound();\n display.putInt(\"color\", i);\n b.getOrCreateNbt().put(\"display\", display);\n return b;\n };\n }\n\n public static IntFunction<GuiElementBuilder> icon16(String path, int size) {\n var models = new PolymerModelData[size];\n\n for (var i = 0; i < size; i++) {\n models[i] = genericIconRaw(Items.ALLIUM, path + \"_\" + i, BASE_MODEL);\n }\n return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress16(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, BASE_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress32(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> horizontalProgress32Right(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, HORIZONTAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress32(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress32Right(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, X32_RIGHT_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> verticalProgress16(String path, int start, int stop, boolean reverse) {\n return genericProgress(path, start, stop, reverse, BASE_MODEL, VERTICAL_PROGRESS);\n }\n\n public static IntFunction<GuiElementBuilder> genericProgress(String path, int start, int stop, boolean reverse, String base, List<SlicedTexture> progressType) {\n\n var models = new PolymerModelData[stop - start];\n\n progressType.add(new SlicedTexture(path, start, stop, reverse));\n\n for (var i = start; i < stop; i++) {\n models[i - start] = genericIconRaw(Items.ALLIUM, \"gen/\" + path + \"_\" + i, base);\n }\n return (i) -> new GuiElementBuilder(models[i].item()).setName(Text.empty()).hideFlags().setCustomModelData(models[i].value());\n }\n\n public static PolymerModelData genericIconRaw(Item item, String path, String base) {\n var model = PolymerResourcePackUtils.requestModel(item, elementPath(path));\n SIMPLE_MODEL.add(new Pair<>(model, base));\n return model;\n }\n\n private static Identifier elementPath(String path) {\n return id(\"sgui/elements/\" + path);\n }\n\n public static Function<Text, Text> background(String path) {\n var builder = new StringBuilder().append(CHEST_SPACE0);\n var c = (character++);\n builder.append(c);\n builder.append(CHEST_SPACE1);\n TEXTURES.put(c, id(\"sgui/\" + path));\n\n return new TextBuilders(Text.literal(builder.toString()).setStyle(STYLE));\n }\n\n public static Pair<Text, Text> polydexBackground(String path) {\n var c = (character++);\n var d = (character++);\n TEXTURES_POLYDEX.put(new Pair<>(c, d), id(\"sgui/polydex/\" + path));\n\n return new Pair<>(\n Text.literal(Character.toString(c)).setStyle(STYLE),\n Text.literal(Character.toString(d)).setStyle(STYLE)\n );\n }\n\n public static void setup() {\n SPACES.put(CHEST_SPACE0, -8);\n SPACES.put(CHEST_SPACE1, -168);\n\n if (ModInit.DYNAMIC_ASSETS) {\n PolymerResourcePackUtils.RESOURCE_PACK_CREATION_EVENT.register((b) -> UiResourceCreator.generateAssets(b::addData));\n }\n }\n\n /*private static void generateProgress(BiConsumer<String, byte[]> assetWriter, List<SlicedTexture> list, boolean horizontal) {\n for (var pair : list) {\n var sourceImage = ResourceUtils.getTexture(elementPath(pair.path()));\n\n var image = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\n var xw = horizontal ? image.getHeight() : image.getWidth();\n\n var mult = pair.reverse ? -1 : 1;\n var offset = pair.reverse ? pair.stop + pair.start - 1 : 0;\n\n for (var y = pair.start; y < pair.stop; y++) {\n var path = elementPath(\"gen/\" + pair.path + \"_\" + y);\n var pos = offset + y * mult;\n\n for (var x = 0; x < xw; x++) {\n if (horizontal) {\n image.setRGB(pos, x, sourceImage.getRGB(pos, x));\n } else {\n image.setRGB(x, pos, sourceImage.getRGB(x, pos));\n }\n }\n\n var out = new ByteArrayOutputStream();\n try {\n ImageIO.write(image, \"png\", out);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n assetWriter.accept(AssetPaths.texture(path.getNamespace(), path.getPath() + \".png\"), out.toByteArray());\n }\n }\n }*/\n\n public static void generateAssets(BiConsumer<String, byte[]> assetWriter) {\n for (var texture : SIMPLE_MODEL) {\n assetWriter.accept(\"assets/\" + texture.getLeft().modelPath().getNamespace() + \"/models/\" + texture.getLeft().modelPath().getPath() + \".json\",\n ITEM_TEMPLATE.replace(\"|ID|\", texture.getLeft().modelPath().toString()).replace(\"|BASE|\", texture.getRight()).getBytes(StandardCharsets.UTF_8));\n }\n\n //generateProgress(assetWriter, VERTICAL_PROGRESS, false);\n //generateProgress(assetWriter, HORIZONTAL_PROGRESS, true);\n\n var fontBase = new JsonObject();\n var providers = new JsonArray();\n\n {\n var spaces = new JsonObject();\n spaces.addProperty(\"type\", \"space\");\n var advances = new JsonObject();\n SPACES.char2IntEntrySet().stream().sorted(Comparator.comparing(Char2IntMap.Entry::getCharKey)).forEach((c) -> advances.addProperty(Character.toString(c.getCharKey()), c.getIntValue()));\n spaces.add(\"advances\", advances);\n providers.add(spaces);\n }\n\n\n TEXTURES.char2ObjectEntrySet().stream().sorted(Comparator.comparing(Char2ObjectMap.Entry::getCharKey)).forEach((entry) -> {\n var bitmap = new JsonObject();\n bitmap.addProperty(\"type\", \"bitmap\");\n bitmap.addProperty(\"file\", entry.getValue().toString() + \".png\");\n bitmap.addProperty(\"ascent\", 13);\n bitmap.addProperty(\"height\", 256);\n var chars = new JsonArray();\n chars.add(Character.toString(entry.getCharKey()));\n bitmap.add(\"chars\", chars);\n providers.add(bitmap);\n });\n\n TEXTURES_POLYDEX.entrySet().stream().sorted(Comparator.comparing(x -> x.getKey().getLeft())).forEach((entry) -> {\n var bitmap = new JsonObject();\n bitmap.addProperty(\"type\", \"bitmap\");\n bitmap.addProperty(\"file\", entry.getValue().toString() + \".png\");\n bitmap.addProperty(\"ascent\", -4);\n bitmap.addProperty(\"height\", 128);\n var chars = new JsonArray();\n chars.add(Character.toString(entry.getKey().getLeft()));\n chars.add(Character.toString(entry.getKey().getRight()));\n bitmap.add(\"chars\", chars);\n providers.add(bitmap);\n });\n\n fontBase.add(\"providers\", providers);\n\n assetWriter.accept(\"assets/serveruifix/font/gui.json\", fontBase.toString().getBytes(StandardCharsets.UTF_8));\n }\n\n private record TextBuilders(Text base) implements Function<Text, Text> {\n @Override\n public Text apply(Text text) {\n return Text.empty().append(base).append(text);\n }\n }\n\n public record SlicedTexture(String path, int start, int stop, boolean reverse) {};\n}" } ]
import eu.pb4.serveruifix.polydex.PolydexCompat; import eu.pb4.serveruifix.util.GuiTextures; import eu.pb4.serveruifix.util.UiResourceCreator; import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
3,808
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); }
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); }
UiResourceCreator.setup();
2
2023-12-28 23:01:30+00:00
8k
psobiech/opengr8on
tftp/src/main/java/pl/psobiech/opengr8on/tftp/transfer/TFTPReceivingTransfer.java
[ { "identifier": "TFTP", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTP.java", "snippet": "public class TFTP implements Closeable {\n private static final Logger LOGGER = LoggerFactory.getLogger(TFTP.class);\n\n public static final int DEFAULT_PORT = 69;\n\n static final int MIN_PACKET_SIZE = 4;\n\n static final int MAX_PACKET_SIZE = TFTPPacket.SEGMENT_SIZE + 4;\n\n private final byte[] receiveBuffer = new byte[MAX_PACKET_SIZE];\n\n protected final byte[] sendBuffer = new byte[MAX_PACKET_SIZE];\n\n private final UDPSocket socket;\n\n public TFTP(UDPSocket socket) {\n this.socket = socket;\n }\n\n public void open() {\n socket.open();\n }\n\n public int getPort() {\n return socket.getLocalPort();\n }\n\n public void discard() {\n socket.discard(new DatagramPacket(receiveBuffer, receiveBuffer.length));\n }\n\n public void send(TFTPPacket packet) throws IOException {\n LOGGER.trace(\"{}: {}\", \">\", packet);\n\n socket.send(packet.newDatagram(sendBuffer));\n }\n\n public Optional<TFTPPacket> receive(Duration timeout) throws TFTPPacketException {\n final DatagramPacket datagramPacket = new DatagramPacket(receiveBuffer, 0, receiveBuffer.length);\n\n do {\n final long startedAt = System.nanoTime();\n\n final Optional<Payload> payloadOptional = socket.tryReceive(datagramPacket, timeout);\n if (payloadOptional.isPresent()) {\n final Payload payload = payloadOptional.get();\n\n final byte[] buffer = payload.buffer();\n if (buffer.length < MIN_PACKET_SIZE) {\n throw new TFTPPacketException(\"Bad packet. Datagram data length is too short: \" + ToStringUtil.toString(buffer));\n }\n\n try {\n final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(payload);\n LOGGER.trace(\"{}: {}\", \"<\", newTFTPPacket);\n\n return Optional.of(newTFTPPacket);\n } catch (TFTPPacketException e) {\n LOGGER.warn(e.getMessage(), e);\n }\n }\n\n timeout = timeout.minusNanos(System.nanoTime() - startedAt);\n } while (timeout.isPositive() && !Thread.interrupted());\n\n return Optional.empty();\n }\n\n @Override\n public void close() {\n socket.close();\n }\n}" }, { "identifier": "TFTPTransferMode", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPTransferMode.java", "snippet": "public enum TFTPTransferMode {\n /**\n * The netascii/ascii transfer mode\n */\n NETASCII(0, \"netascii\"),\n /**\n * The binary/octet transfer mode\n */\n OCTET(1, \"octet\"),\n //\n ;\n\n private final int code;\n\n private final String value;\n\n TFTPTransferMode(int code, String value) {\n this.code = code;\n this.value = value;\n\n }\n\n public static TFTPTransferMode ofMode(String mode) throws TFTPPacketException {\n for (TFTPTransferMode value : values()) {\n if (value.value().equalsIgnoreCase(mode)) {\n return value;\n }\n }\n\n throw new TFTPPacketException(\"Unrecognized TFTP transfer mode: \" + mode);\n }\n\n public int code() {\n return code;\n }\n\n public byte[] valueAsBytes() {\n return value.getBytes(StandardCharsets.US_ASCII);\n }\n\n public String value() {\n return value;\n }\n}" }, { "identifier": "TFTPException", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/exceptions/TFTPException.java", "snippet": "public class TFTPException extends RuntimeException {\n private final TFTPErrorType error;\n\n public TFTPException(TFTPErrorPacket errorPacket) {\n this(errorPacket.getError(), errorPacket.getMessage());\n }\n\n public TFTPException(TFTPErrorType error, IOException exception) {\n super(exception);\n\n this.error = error;\n }\n\n public TFTPException(TFTPErrorType error, String message) {\n super(message);\n\n this.error = error;\n }\n\n public TFTPException(TFTPErrorType error, String message, Throwable throwable) {\n super(message, throwable);\n\n this.error = error;\n }\n\n public TFTPException(String message) {\n super(message);\n\n this.error = TFTPErrorType.UNDEFINED;\n }\n\n public TFTPErrorPacket asError(InetAddress address, int port) {\n final String message;\n final Throwable cause = getCause();\n if (cause == null) {\n message = getMessage();\n } else {\n message = cause.getClass().getSimpleName() + \": \" + getMessage();\n }\n\n return new TFTPErrorPacket(\n address, port,\n getError(), message\n );\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n}" }, { "identifier": "TFTPPacketException", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/exceptions/TFTPPacketException.java", "snippet": "public class TFTPPacketException extends Exception {\n private final TFTPErrorType error;\n\n public TFTPPacketException(TFTPErrorPacket errorPacket) {\n this(errorPacket.getError(), errorPacket.getMessage());\n }\n\n public TFTPPacketException(TFTPErrorType error, IOException exception) {\n super(exception);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message) {\n super(message);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message, Throwable throwable) {\n super(message, throwable);\n\n this.error = error;\n }\n\n public TFTPPacketException(String message) {\n super(message);\n\n this.error = TFTPErrorType.UNDEFINED;\n }\n\n public TFTPErrorPacket asError(InetAddress address, int port) {\n final String message;\n final Throwable cause = getCause();\n if (cause == null) {\n message = getMessage();\n } else {\n message = cause.getClass().getSimpleName() + \": \" + getMessage();\n }\n\n return new TFTPErrorPacket(\n address, port,\n getError(), message\n );\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n}" }, { "identifier": "TFTPAckPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPAckPacket.java", "snippet": "public class TFTPAckPacket extends TFTPBlockPacket {\n private static final int PACKET_SIZE = HEADER_SIZE;\n\n public TFTPAckPacket(Payload datagram) throws TFTPPacketException {\n super(TFTPPacketType.ACKNOWLEDGEMENT, datagram.address(), datagram.port(), getBlockNumber(datagram));\n\n final byte[] buffer = datagram.buffer();\n if (getType().packetType() != buffer[OPERATOR_TYPE_OFFSET]) {\n throw new TFTPPacketException(\"TFTP operator code does not match type.\");\n }\n }\n\n public TFTPAckPacket(InetAddress destination, int port, int blockNumber) {\n super(TFTPPacketType.ACKNOWLEDGEMENT, destination, port, blockNumber);\n }\n\n @Override\n public DatagramPacket newDatagram() {\n return newDatagram(new byte[PACKET_SIZE]);\n }\n\n @Override\n public DatagramPacket newDatagram(byte[] data) {\n writeHeader(data);\n\n return new DatagramPacket(data, 0, PACKET_SIZE, getAddress(), getPort());\n }\n\n @Override\n public String toString() {\n return super.toString() + \" ACK \" + getBlockNumber();\n }\n}" }, { "identifier": "TFTPDataPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPDataPacket.java", "snippet": "public class TFTPDataPacket extends TFTPBlockPacket {\n public static final int MAX_DATA_LENGTH = 512;\n\n private final int length;\n\n private final int offset;\n\n private final byte[] buffer;\n\n public TFTPDataPacket(Payload payload) throws TFTPPacketException {\n super(TFTPPacketType.DATA, payload.address(), payload.port(), getBlockNumber(payload));\n\n this.buffer = payload.buffer();\n if (getType().packetType() != this.buffer[OPERATOR_TYPE_OFFSET]) {\n throw new TFTPPacketException(\"TFTP operator code does not match type.\");\n }\n\n this.offset = HEADER_SIZE;\n this.length = Math.min(buffer.length - HEADER_SIZE, MAX_DATA_LENGTH);\n }\n\n public TFTPDataPacket(InetAddress destination, int port, int blockNumber, byte[] buffer, int offset, int length) {\n super(TFTPPacketType.DATA, destination, port, blockNumber);\n\n this.buffer = buffer;\n this.offset = offset;\n\n this.length = Math.min(length, MAX_DATA_LENGTH);\n }\n\n public byte[] getBuffer() {\n return buffer;\n }\n\n public int getDataLength() {\n return length;\n }\n\n public int getDataOffset() {\n return offset;\n }\n\n @Override\n public DatagramPacket newDatagram() {\n return newDatagram(new byte[HEADER_SIZE + length]);\n }\n\n @Override\n public DatagramPacket newDatagram(byte[] buffer) {\n if (buffer == this.buffer) {\n throw new UncheckedIOException(new IOException(\"Unexpected buffer passed to method\"));\n }\n\n writeHeader(buffer);\n System.arraycopy(this.buffer, offset, buffer, HEADER_SIZE, length);\n\n return new DatagramPacket(buffer, 0, HEADER_SIZE + length, getAddress(), getPort());\n }\n\n @Override\n public String toString() {\n return super.toString() + \" DATA \" + getBlockNumber() + \" \" + length;\n }\n}" }, { "identifier": "TFTPErrorPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPErrorPacket.java", "snippet": "public class TFTPErrorPacket extends TFTPPacket {\n private static final int HEADER_SIZE = 4;\n\n private static final int ERROR_OFFSET = 2;\n\n private final TFTPErrorType error;\n\n private final String message;\n\n public TFTPErrorPacket(Payload payload) throws TFTPPacketException {\n super(TFTPPacketType.ERROR, payload.address(), payload.port());\n\n final byte[] buffer = payload.buffer();\n if (getType().packetType() != buffer[OPERATOR_TYPE_OFFSET]) {\n throw new TFTPPacketException(\"TFTP operator code does not match type.\");\n }\n\n final int length = buffer.length;\n if (length < HEADER_SIZE + 1) {\n throw new TFTPPacketException(\"Bad error packet. No message.\");\n }\n\n error = TFTPErrorType.ofErrorCode(readInt(buffer, ERROR_OFFSET));\n message = readNullTerminatedString(buffer, HEADER_SIZE, length);\n }\n\n public TFTPErrorPacket(InetAddress destination, int port, TFTPErrorType error, String message) {\n super(TFTPPacketType.ERROR, destination, port);\n\n this.error = error;\n this.message = message;\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n\n public String getMessage() {\n return message;\n }\n\n @Override\n public DatagramPacket newDatagram() {\n final byte[] messageAsBytes = message.getBytes(StandardCharsets.US_ASCII);\n final byte[] data = new byte[HEADER_SIZE + messageAsBytes.length + 1];\n\n return newDatagram(data);\n }\n\n @Override\n public DatagramPacket newDatagram(byte[] data) {\n writeHeader(data);\n\n final int messageLength = writeNullTerminatedString(message, data, HEADER_SIZE);\n\n return new DatagramPacket(data, 0, HEADER_SIZE + messageLength, getAddress(), getPort());\n }\n\n private void writeHeader(byte[] data) {\n data[0] = 0;\n data[OPERATOR_TYPE_OFFSET] = type.packetType();\n writeInt(error.errorCode(), data, ERROR_OFFSET);\n }\n\n @Override\n public String toString() {\n return super.toString() + \" ERR \" + error + \" \" + message;\n }\n}" }, { "identifier": "TFTPErrorType", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPErrorType.java", "snippet": "public enum TFTPErrorType {\n UNDEFINED(0),\n FILE_NOT_FOUND(1),\n ACCESS_VIOLATION(2),\n OUT_OF_SPACE(3),\n ILLEGAL_OPERATION(4),\n UNKNOWN_TID(5),\n FILE_EXISTS(6),\n //\n ;\n\n private final int errorCode;\n\n TFTPErrorType(long errorCode) {\n if (errorCode < 0 || errorCode > 0xFFFFFFFFL) {\n throw new IllegalArgumentException();\n }\n\n this.errorCode = (int) (errorCode & 0xFFFFFFFFL);\n }\n\n public int errorCode() {\n return errorCode;\n }\n\n public static TFTPErrorType ofErrorCode(int errorCode) {\n for (TFTPErrorType value : values()) {\n if (value.errorCode() == errorCode) {\n return value;\n }\n }\n\n return UNDEFINED;\n }\n}" }, { "identifier": "TFTPPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPPacket.java", "snippet": "public abstract class TFTPPacket {\n protected static final int OPERATOR_TYPE_OFFSET = 1;\n\n public static final int SEGMENT_SIZE = 512;\n\n final TFTPPacketType type;\n\n private int port;\n\n private InetAddress address;\n\n TFTPPacket(TFTPPacketType type, InetAddress address, int port) {\n this.type = type;\n this.address = address;\n this.port = port;\n }\n\n public static TFTPPacket newTFTPPacket(Payload payload) throws TFTPPacketException {\n return TFTPPacketType.ofPacketType(payload.buffer()[OPERATOR_TYPE_OFFSET])\n .parse(payload);\n }\n\n public InetAddress getAddress() {\n return address;\n }\n\n public int getPort() {\n return port;\n }\n\n public TFTPPacketType getType() {\n return type;\n }\n\n public abstract DatagramPacket newDatagram();\n\n public abstract DatagramPacket newDatagram(byte[] data);\n\n public void setAddress(InetAddress address) {\n this.address = address;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public static String readNullTerminatedString(byte[] buffer, int from, int to) {\n return new String(\n readNullTerminated(buffer, from, to), StandardCharsets.US_ASCII\n );\n }\n\n public static byte[] readNullTerminated(byte[] buffer, int from, int to) {\n int nullTerminator = -1;\n for (int i = from; i < to; i++) {\n if (buffer[i] == 0) {\n nullTerminator = i;\n break;\n }\n }\n\n if (nullTerminator < 0) {\n return Arrays.copyOfRange(buffer, from, to);\n }\n\n return Arrays.copyOfRange(buffer, from, nullTerminator);\n }\n\n public static int writeNullTerminatedString(String value, byte[] buffer, int offset) {\n final byte[] valueAsBytes = value.getBytes(StandardCharsets.US_ASCII);\n\n System.arraycopy(valueAsBytes, 0, buffer, offset, valueAsBytes.length);\n buffer[offset + valueAsBytes.length] = 0;\n\n return valueAsBytes.length + 1;\n }\n\n public static int readInt(byte[] buffer, int offset) {\n return asInt(buffer[offset], buffer[offset + 1]);\n }\n\n public static void writeInt(int value, byte[] buffer, int offset) {\n buffer[offset] = highNibble(value);\n buffer[offset + 1] = lowNibble(value);\n }\n\n public static byte highNibble(int value) {\n return (byte) ((value & 0xFFFF) >> (Integer.BYTES * 2));\n }\n\n public static byte lowNibble(int value) {\n return (byte) (value & 0xFF);\n }\n\n public static int asInt(byte highNibble, byte lowNibble) {\n return asInt(highNibble) << (Integer.BYTES * 2) | asInt(lowNibble);\n }\n\n private static int asInt(byte value) {\n return value & 0xFF;\n }\n\n @Override\n public String toString() {\n return address + \" \" + port + \" \" + type;\n }\n}" }, { "identifier": "TFTPRequestPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPRequestPacket.java", "snippet": "public abstract class TFTPRequestPacket extends TFTPPacket {\n private static final int HEADER_SIZE = 2;\n\n private static final int FILE_NAME_OFFSET = 2;\n\n private final TFTPTransferMode mode;\n\n private final String fileName;\n\n TFTPRequestPacket(InetAddress destination, int port, TFTPPacketType type, String fileName, TFTPTransferMode mode) {\n super(type, destination, port);\n\n this.fileName = fileName;\n this.mode = mode;\n }\n\n TFTPRequestPacket(TFTPPacketType type, Payload payload) throws TFTPPacketException {\n super(type, payload.address(), payload.port());\n\n final byte[] buffer = payload.buffer();\n if (getType().packetType() != buffer[OPERATOR_TYPE_OFFSET]) {\n throw new TFTPPacketException(\"TFTP operator code does not match type.\");\n }\n\n final int length = buffer.length;\n\n final byte[] fileNameAsBytes = readNullTerminated(buffer, FILE_NAME_OFFSET, length);\n this.fileName = new String(fileNameAsBytes, StandardCharsets.US_ASCII);\n\n if (2 + fileNameAsBytes.length >= length) {\n throw new TFTPPacketException(\"Bad file name and mode format.\");\n }\n\n final String modeAsString = readNullTerminatedString(buffer, FILE_NAME_OFFSET + fileNameAsBytes.length + 1, length)\n .toLowerCase(java.util.Locale.ENGLISH);\n\n this.mode = TFTPTransferMode.ofMode(modeAsString);\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public TFTPTransferMode getMode() {\n return mode;\n }\n\n @Override\n public DatagramPacket newDatagram() {\n final byte[] fileNameAsBytes = fileName.getBytes(StandardCharsets.US_ASCII);\n final byte[] modeAsBytes = mode.valueAsBytes();\n\n final byte[] data = new byte[HEADER_SIZE + fileNameAsBytes.length + 1 + modeAsBytes.length + 1];\n\n return newDatagram(data);\n }\n\n @Override\n public DatagramPacket newDatagram(byte[] data) {\n data[0] = 0;\n data[OPERATOR_TYPE_OFFSET] = type.packetType();\n\n final int fileNameLength = writeNullTerminatedString(fileName, data, FILE_NAME_OFFSET);\n final int modeLength = writeNullTerminatedString(mode.value(), data, HEADER_SIZE + fileNameLength);\n\n return new DatagramPacket(\n data, 0, HEADER_SIZE + fileNameLength + modeLength,\n getAddress(), getPort()\n );\n }\n}" }, { "identifier": "FileUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/FileUtil.java", "snippet": "public final class FileUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);\n\n private static final String TMPDIR_PROPERTY = \"java.io.tmpdir\";\n\n private static final String TEMPORARY_FILE_PREFIX = \"tmp_\";\n\n private static final Pattern DISALLOWED_FILENAME_CHARACTERS = Pattern.compile(\"[/\\\\\\\\:*?\\\"<>|\\0]+\");\n\n private static final Pattern WHITESPACE_CHARACTERS = Pattern.compile(\"\\\\s+\");\n\n private static final Path TEMPORARY_DIRECTORY;\n\n private static final TemporaryFileTracker FILE_TRACKER = new TemporaryFileTracker();\n\n static {\n try {\n TEMPORARY_DIRECTORY = Files.createTempDirectory(\n Paths.get(System.getProperty(TMPDIR_PROPERTY))\n .toAbsolutePath(),\n TEMPORARY_FILE_PREFIX\n );\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n\n ThreadUtil.getInstance()\n .scheduleAtFixedRate(FILE_TRACKER::log, 1, 1, TimeUnit.MINUTES);\n\n mkdir(TEMPORARY_DIRECTORY);\n ThreadUtil.shutdownHook(() -> FileUtil.deleteRecursively(TEMPORARY_DIRECTORY));\n }\n\n private FileUtil() {\n // NOP\n }\n\n public static Path temporaryDirectory() {\n return temporaryDirectory(null);\n }\n\n public static Path temporaryDirectory(Path parentPath) {\n try {\n return Files.createTempDirectory(\n parentPath == null ? TEMPORARY_DIRECTORY : parentPath,\n TEMPORARY_FILE_PREFIX\n )\n .toAbsolutePath();\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static Path temporaryFile() {\n return temporaryFile(null, null);\n }\n\n public static Path temporaryFile(String fileName) {\n return temporaryFile(null, fileName);\n }\n\n public static Path temporaryFile(Path parentPath) {\n return temporaryFile(parentPath, null);\n }\n\n public static Path temporaryFile(Path parentPath, String fileName) {\n try {\n return FILE_TRACKER.tracked(\n Files.createTempFile(\n parentPath == null ? TEMPORARY_DIRECTORY : parentPath,\n TEMPORARY_FILE_PREFIX, sanitize(fileName)\n )\n .toAbsolutePath()\n );\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void mkdir(Path path) {\n try {\n Files.createDirectories(path);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void touch(Path path) {\n try {\n Files.newOutputStream(path, StandardOpenOption.CREATE).close();\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void linkOrCopy(Path from, Path to) {\n deleteQuietly(to);\n\n if (!SystemUtils.IS_OS_WINDOWS && !Files.exists(to)) {\n try {\n Files.createLink(to, from);\n\n return;\n } catch (Exception e) {\n // log exception and revert to copy\n LOGGER.trace(e.getMessage(), e);\n }\n }\n\n try {\n Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void deleteQuietly(Path... paths) {\n for (Path path : paths) {\n deleteQuietly(path);\n }\n }\n\n public static void deleteQuietly(Path path) {\n if (path == null) {\n return;\n }\n\n try {\n Files.deleteIfExists(path);\n } catch (IOException e) {\n final boolean isFileOrLinkOrDoesNotExist = !Files.isDirectory(path);\n if (isFileOrLinkOrDoesNotExist) {\n LOGGER.warn(e.getMessage(), e);\n } else if (LOGGER.isTraceEnabled()) {\n // directories might be not-empty, hence not removable\n LOGGER.trace(e.getMessage(), e);\n }\n }\n }\n\n public static void deleteRecursively(Path rootDirectory) {\n if (rootDirectory == null) {\n return;\n }\n\n try {\n Files.walkFileTree(rootDirectory, new SimpleFileVisitor<>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n FileUtil.deleteQuietly(file);\n\n return super.visitFile(file, attrs);\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path directory, IOException exc) throws IOException {\n FileUtil.deleteQuietly(directory);\n\n return super.postVisitDirectory(directory, exc);\n }\n });\n } catch (IOException e) {\n LOGGER.warn(e.getMessage(), e);\n }\n\n FileUtil.deleteQuietly(rootDirectory);\n }\n\n public static void closeQuietly(AutoCloseable... closeables) {\n for (AutoCloseable closeable : closeables) {\n closeQuietly(closeable);\n }\n }\n\n public static void closeQuietly(AutoCloseable closeable) {\n if (closeable == null) {\n return;\n }\n\n try {\n closeable.close();\n } catch (Exception e) {\n LOGGER.warn(e.getMessage(), e);\n }\n }\n\n public static String sanitize(String fileName) {\n fileName = StringUtils.stripToNull(fileName);\n if (fileName == null) {\n return null;\n }\n\n final String fileNameNoDisallowedCharacters = DISALLOWED_FILENAME_CHARACTERS.matcher(fileName)\n .replaceAll(\"_\");\n\n return WHITESPACE_CHARACTERS.matcher(fileNameNoDisallowedCharacters)\n .replaceAll(\"_\");\n }\n\n public static long size(Path path) {\n try {\n return Files.size(path);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static class TemporaryFileTracker {\n private final Map<String, UnexpectedException> stacktraces = new HashMap<>();\n\n private final Map<Path, Boolean> reachablePaths = new WeakHashMap<>();\n\n private TemporaryFileTracker() {\n // NOP\n }\n\n public void log() {\n final Map<Path, UnexpectedException> unreachablePaths = new HashMap<>();\n\n synchronized (stacktraces) {\n final Iterator<Entry<String, UnexpectedException>> iterator = stacktraces.entrySet().iterator();\n while (iterator.hasNext()) {\n final Entry<String, UnexpectedException> entry = iterator.next();\n\n final Path path = Paths.get(entry.getKey());\n synchronized (reachablePaths) {\n if (reachablePaths.containsKey(path)) {\n continue;\n }\n }\n\n iterator.remove();\n\n if (Files.exists(path)) {\n unreachablePaths.put(path, entry.getValue());\n }\n }\n }\n\n for (Entry<Path, UnexpectedException> entry : unreachablePaths.entrySet()) {\n final Path path = entry.getKey();\n\n if (Files.exists(path)) {\n final UnexpectedException e = entry.getValue();\n\n LOGGER.warn(e.getMessage(), e);\n }\n }\n }\n\n public Path tracked(Path path) {\n final Path absolutePath = path.toAbsolutePath();\n final String absolutePathAsString = absolutePath.toString();\n\n final UnexpectedException stacktrace =\n new UnexpectedException(\"Temporary Path went out of scope, and the file was not removed: \" + absolutePathAsString);\n synchronized (stacktraces) {\n stacktraces.put(absolutePathAsString, stacktrace);\n }\n\n synchronized (reachablePaths) {\n reachablePaths.put(absolutePath, Boolean.TRUE);\n }\n\n return absolutePath;\n }\n }\n}" } ]
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.tftp.TFTP; import pl.psobiech.opengr8on.tftp.TFTPTransferMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPException; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.tftp.packets.TFTPAckPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPDataPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.tftp.packets.TFTPPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPRequestPacket; import pl.psobiech.opengr8on.util.FileUtil;
7,143
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.transfer; public abstract class TFTPReceivingTransfer extends TFTPTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPReceivingTransfer.class); protected void incomingTransfer( TFTP tftp, boolean server, TFTPTransferMode mode, InetAddress requestAddress, int requestPort, Path targetPath
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.transfer; public abstract class TFTPReceivingTransfer extends TFTPTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPReceivingTransfer.class); protected void incomingTransfer( TFTP tftp, boolean server, TFTPTransferMode mode, InetAddress requestAddress, int requestPort, Path targetPath
) throws IOException, TFTPPacketException {
3
2023-12-23 09:56:14+00:00
8k
Pigmice2733/frc-2024
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DrivetrainConfig", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final static class DrivetrainConfig {\n public static final double MAX_DRIVE_SPEED = 4.5; // max meters / second\n public static final double MAX_TURN_SPEED = 5; // max radians / second\n public static final double SLOWMODE_MULTIPLIER = 0.5;\n\n // distance from the center of one wheel to another\n public static final double TRACK_WIDTH_METERS = 0.5842;\n\n private final static SwerveDriveKinematics KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Front left\n new Translation2d(TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2), // Front right\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Back left\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2) // Back right\n );\n\n // Constants found in Sysid (volts)\n private static final SimpleMotorFeedforward DRIVE_FEED_FORWARD = new SimpleMotorFeedforward(\n 0.35493, 2.3014, 0.12872);\n\n // From what I have seen, it is common to only use a P value in path following\n private static final PathConstraints PATH_CONSTRAINTS = new PathConstraints(2, 2); // 3, 2.5\n private static final PIDController PATH_DRIVE_PID = new PIDController(0.3, 0, 0);\n private static final PIDController PATH_TURN_PID = new PIDController(0.31, 0, 0);\n\n // Offset from chassis center that the robot will rotate about\n private static final Translation2d ROTATION_CENTER_OFFSET = new Translation2d(0, 0);\n\n private static final MkSwerveModuleBuilder FRONT_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(0, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(73));\n\n private static final MkSwerveModuleBuilder FRONT_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(1, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-99));\n\n private static final MkSwerveModuleBuilder BACK_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(2, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(219));\n\n private static final MkSwerveModuleBuilder BACK_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(3, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-285));\n\n public static final SwerveConfig SWERVE_CONFIG = new SwerveConfig(\n FRONT_LEFT_MODULE, FRONT_RIGHT_MODULE, BACK_LEFT_MODULE,\n BACK_RIGHT_MODULE,\n PATH_CONSTRAINTS, PATH_DRIVE_PID, PATH_TURN_PID,\n MAX_DRIVE_SPEED, MAX_TURN_SPEED,\n SLOWMODE_MULTIPLIER, KINEMATICS, DRIVE_FEED_FORWARD, SWERVE_TAB,\n ROTATION_CENTER_OFFSET);\n}" }, { "identifier": "ArmState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum ArmState {\n HIGH(90),\n MIDDLE(45),\n DOWN(0);\n\n private double position;\n\n ArmState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "ClimberState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum ClimberState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n ClimberState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "IntakeState", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static enum IntakeState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n IntakeState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}" }, { "identifier": "FireShooter", "path": "src/main/java/frc/robot/commands/actions/FireShooter.java", "snippet": "public class FireShooter extends SequentialCommandGroup {\n public FireShooter(Arm arm, Shooter shooter, ArmState armAngle) {\n addCommands(Commands.sequence(arm.setTargetState(armAngle), shooter.spinFlywheelsForward(),\n Commands.waitSeconds(AutoConfig.FLYWHEEL_SPINUP_TIME), shooter.spinFeederForward()));\n addRequirements(arm, shooter);\n }\n\n}" }, { "identifier": "HandoffToShooter", "path": "src/main/java/frc/robot/commands/actions/HandoffToShooter.java", "snippet": "public class HandoffToShooter extends SequentialCommandGroup {\n public HandoffToShooter(Intake intake, Shooter shooter) {\n addCommands(intake.setTargetState(IntakeState.UP),\n Commands.waitSeconds(AutoConfig.INTAKE_MOVE_TIME), intake.runWheelsBackward(),\n shooter.spinFeederForward(), Commands.waitSeconds(AutoConfig.INTAKE_FEED_TIME),\n Commands.runOnce(() -> ControllerRumbler.rumblerOperator(RumbleType.kBothRumble, 0.25, 0.3)));\n addRequirements(intake, shooter);\n }\n}" }, { "identifier": "Arm", "path": "src/main/java/frc/robot/subsystems/Arm.java", "snippet": "public class Arm extends PIDSubsystemBase {\n\n public Arm() {\n super(new CANSparkMax(CANConfig.ARM, MotorType.kBrushless), ArmConfig.P, ArmConfig.i, ArmConfig.D,\n new Constraints(ArmConfig.MAX_VELOCITY, ArmConfig.MAX_ACCELERATION), false,\n ArmConfig.MOTOR_POSITION_CONVERSION, 50, Constants.ARM_TAB, true);\n }\n\n /** Sets the rotation state of the arm */\n public Command setTargetState(ArmState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "ClimberExtension", "path": "src/main/java/frc/robot/subsystems/ClimberExtension.java", "snippet": "public class ClimberExtension extends PIDSubsystemBase {\n public ClimberExtension() {\n super(new CANSparkMax(CANConfig.CLIMBER_EXTENSION, MotorType.kBrushless), ClimberConfig.P, ClimberConfig.I,\n ClimberConfig.D, new Constraints(ClimberConfig.MAX_VELOCITY, ClimberConfig.MAX_ACCELERATION), false,\n ClimberConfig.MOTOR_POSITION_CONVERSION, 50, Constants.CLIMBER_TAB, true);\n }\n\n @Override\n public void periodic() {\n }\n\n /** Sets the height state of the climber */\n public Command setTargetState(ClimberState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "Intake", "path": "src/main/java/frc/robot/subsystems/Intake.java", "snippet": "public class Intake extends PIDSubsystemBase {\n private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);\n\n public Intake() {\n super(new CANSparkMax(CANConfig.INTAKE_PIVOT, MotorType.kBrushless), IntakeConfig.P, IntakeConfig.I,\n IntakeConfig.D, new Constraints(IntakeConfig.MAX_VELOCITY, IntakeConfig.MAX_ACCELERATION), false,\n IntakeConfig.MOTOR_POSITION_CONVERSION, 50, Constants.INTAKE_TAB, true);\n\n wheelsMotor.restoreFactoryDefaults();\n wheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.INTAKE_TAB, () -> wheelsMotor.get());\n }\n\n /** Sets the intake motor to a percent output (0.0 - 1.0) */\n public void outputToMotor(double percent) {\n wheelsMotor.set(percent);\n }\n\n /** Spins intake wheels to intake balls. */\n public Command runWheelsForward() {\n return Commands.runOnce(() -> outputToMotor(IntakeConfig.WHEELS_SPEED));\n }\n\n /** Spins intake wheels to eject balls. */\n public Command runWheelsBackward() {\n return Commands.runOnce(() -> outputToMotor(-IntakeConfig.WHEELS_SPEED));\n }\n\n /** Sets intake wheels to zero output. */\n public Command stopWheels() {\n return Commands.runOnce(() -> outputToMotor(0));\n }\n\n /** Sets the rotation state of the intake */\n public Command setTargetState(IntakeState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}" }, { "identifier": "Shooter", "path": "src/main/java/frc/robot/subsystems/Shooter.java", "snippet": "public class Shooter extends SubsystemBase {\n private final CANSparkMax flywheelsMotor = new CANSparkMax(CANConfig.SHOOTER_MOTOR, MotorType.kBrushless);\n private final CANSparkMax feederMotor = new CANSparkMax(CANConfig.FEEDER_MOTOR, MotorType.kBrushless);\n\n public Shooter() {\n flywheelsMotor.restoreFactoryDefaults();\n flywheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.SHOOTER_TAB, () -> flywheelsMotor.get());\n }\n\n private void outputToFlywheels(double output) {\n flywheelsMotor.set(output);\n }\n\n public Command spinFlywheelsForward() {\n return Commands.runOnce(() -> outputToFlywheels(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFlywheelsBackward() {\n return Commands.runOnce(() -> outputToFlywheels(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFlywheels() {\n return Commands.runOnce(() -> outputToFlywheels(0));\n }\n\n private void outputToFeeder(double output) {\n feederMotor.set(output);\n }\n\n public Command spinFeederForward() {\n return Commands.runOnce(() -> outputToFeeder(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFeederBackward() {\n return Commands.runOnce(() -> outputToFeeder(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFeeder() {\n return Commands.runOnce(() -> outputToFeeder(0));\n }\n}" }, { "identifier": "Vision", "path": "src/main/java/frc/robot/subsystems/Vision.java", "snippet": "public class Vision extends SubsystemBase {\n private static String camName = VisionConfig.CAM_NAME;\n\n private Results targetingResults;\n private LimelightTarget_Fiducial bestTarget;\n private boolean hasTarget;\n\n public Vision() {\n ShuffleboardHelper.addOutput(\"Target X\", Constants.VISION_TAB,\n () -> bestTarget == null ? 0 : bestTarget.tx);\n ShuffleboardHelper.addOutput(\"Target Y\", Constants.VISION_TAB,\n () -> bestTarget == null ? 0 : bestTarget.ty);\n\n ShuffleboardHelper.addOutput(\"Bot Pose X\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getEstimatedRobotPose().getX());\n ShuffleboardHelper.addOutput(\"Bot Pose Y\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getEstimatedRobotPose().getY());\n\n ShuffleboardHelper.addOutput(\"Pose to tag X\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getTranslationToBestTarget().getX());\n ShuffleboardHelper.addOutput(\"Pose to tag Y\", Constants.VISION_TAB,\n () -> targetingResults == null ? 0 : getTranslationToBestTarget().getY());\n }\n\n @Override\n public void periodic() {\n LimelightResults results = LimelightHelpers.getLatestResults(camName);\n hasTarget = results != null;\n\n if (hasTarget) {\n bestTarget = null;\n return;\n }\n\n targetingResults = results.targetingResults;\n\n var allTargets = results.targetingResults.targets_Fiducials;\n bestTarget = allTargets[0];\n }\n\n /** Returns the best target's id or -1 if no target is seen */\n public int getBestTargetID() {\n return (int) (!hasTarget ? -1 : bestTarget.fiducialID);\n }\n\n /** Returns the robot's estimated 2d pose or null if no target is seen */\n public Pose2d getEstimatedRobotPose() {\n return !hasTarget ? null : targetingResults.getBotPose2d();\n }\n\n /** Returns the estimated 2d translation to the best target */\n public Pose2d getTranslationToBestTarget() {\n return !hasTarget ? null : bestTarget.getRobotPose_TargetSpace2D();\n }\n}" } ]
import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler; import com.pigmice.frc.lib.drivetrain.swerve.SwerveDrivetrain; import com.pigmice.frc.lib.drivetrain.swerve.commands.DriveWithJoysticksSwerve; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.XboxController.Button; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.DrivetrainConfig; import frc.robot.Constants.ArmConfig.ArmState; import frc.robot.Constants.ClimberConfig.ClimberState; import frc.robot.Constants.IntakeConfig.IntakeState; import frc.robot.commands.actions.FireShooter; import frc.robot.commands.actions.HandoffToShooter; import frc.robot.subsystems.Arm; import frc.robot.subsystems.ClimberExtension; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; import frc.robot.subsystems.Vision;
3,902
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm();
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm();
private final ClimberExtension climberExtension = new ClimberExtension();
7
2023-12-30 06:06:45+00:00
8k
fatorius/DUCO-Android-Miner
DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/services/MinerBackgroundService.java
[ { "identifier": "MiningActivity", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/activities/MiningActivity.java", "snippet": "public class MiningActivity extends AppCompatActivity { //implements UIThreadMethods {\n RequestQueue requestQueue;\n JsonObjectRequest getMiningPoolRequester;\n\n TextView miningNodeDisplay;\n TextView acceptedSharesTextDisplay;\n TextView hashrateDisplay;\n TextView miningLogsTextDisplay;\n TextView performancePerThread;\n\n Button stopMining;\n\n ProgressBar gettingPoolProgress;\n\n String poolName;\n String poolIp;\n int poolPort;\n String poolServerName;\n\n String ducoUsername;\n float efficiency;\n int numberOfMiningThreads;\n\n int sentShares;\n int acceptedShares;\n\n float acceptedPercetage;\n\n List<String> minerLogLines;\n List<Integer> threadsHashrate;\n\n SharedPreferences sharedPreferences;\n\n private BroadcastReceiver broadcastReceiver;\n\n boolean isAppOnFocus;\n\n public static final String COMMUNICATION_ACTION = \"com.fatorius.duinocoinminer.COMMUNICATION_ACTION\";\n static final String GET_MINING_POOL_URL = \"https://server.duinocoin.com/getPool\";\n\n public MiningActivity(){\n MiningActivity miningActivity = this;\n\n sentShares = 0;\n acceptedShares = 0;\n acceptedPercetage = 100.0f;\n\n minerLogLines = new ArrayList<>();\n threadsHashrate = new ArrayList<>();\n\n getMiningPoolRequester = new JsonObjectRequest(\n Request.Method.GET, GET_MINING_POOL_URL, null,\n\n response -> {\n gettingPoolProgress.setVisibility(View.GONE);\n\n try {\n poolName = response.getString(\"name\");\n poolIp = response.getString(\"ip\");\n poolPort = response.getInt(\"port\");\n poolServerName = response.getString(\"server\");\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n\n String newMiningText = \"Mining node: \" + poolName;\n miningNodeDisplay.setText(newMiningText);\n\n Intent miningServiceIntent = new Intent(miningActivity, MinerBackgroundService.class);\n\n miningServiceIntent.putExtra(\"poolIp\", poolIp);\n miningServiceIntent.putExtra(\"numberOfThreads\", numberOfMiningThreads);\n miningServiceIntent.putExtra(\"poolPort\", poolPort);\n miningServiceIntent.putExtra(\"ducoUsername\", ducoUsername);\n miningServiceIntent.putExtra(\"efficiency\", efficiency);\n\n miningActivity.startForegroundService(miningServiceIntent);\n\n stopMining.setOnClickListener(view -> {\n stopService(miningServiceIntent);\n\n Intent intent = new Intent(miningActivity, MinerBackgroundService.class);\n intent.setAction(MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING);\n startService(intent);\n\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.clear();\n editor.apply();\n\n finish();\n });\n },\n\n error -> {\n gettingPoolProgress.setVisibility(View.GONE);\n\n String errorMsg = \"Fail getting mining node\";\n\n String errorType = error.toString();\n\n switch (errorType){\n case \"com.android.volley.TimeoutError\":\n errorMsg = \"Error: Timeout connecting to server.duinocoin.com\";\n break;\n case \"com.android.volley.NoConnectionError: java.net.UnknownHostException: Unable to resolve host \\\"server.duinocoin.com\\\": No address associated with hostname\":\n errorMsg = \"Error: no internet connection\";\n break;\n case \"com.android.volley.ServerError\":\n errorMsg = \"Error: server.duinocoin.com internal error\";\n break;\n }\n\n Log.i(\"Resquest error\", error.toString());\n\n miningNodeDisplay.setText(errorMsg);\n\n String stopMiningNewText = \"Back\";\n\n stopMining.setText(stopMiningNewText);\n\n stopMining.setOnClickListener(view -> {\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.clear();\n editor.apply();\n\n finish();\n });\n }\n );\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_mining);\n\n miningNodeDisplay = findViewById(R.id.miningNodeDisplay);\n acceptedSharesTextDisplay = findViewById(R.id.acceptedSharesDisplay);\n hashrateDisplay = findViewById(R.id.hashrateDisplayText);\n miningLogsTextDisplay = findViewById(R.id.minerlogsMultiline);\n performancePerThread = findViewById(R.id.threadPerformanceView);\n\n stopMining = findViewById(R.id.stopMiningButton);\n\n gettingPoolProgress = findViewById(R.id.gettingPoolLoading);\n\n sharedPreferences = getSharedPreferences(\"com.fatorius.duinocoinminer\", MODE_PRIVATE);\n ducoUsername = sharedPreferences.getString(\"username_value\", \"---------------------\");\n numberOfMiningThreads = sharedPreferences.getInt(\"threads_value\", 1);\n\n for (int t = 0; t < numberOfMiningThreads; t++){\n threadsHashrate.add(t, 0);\n }\n\n int miningIntensity = sharedPreferences.getInt(\"mining_intensity_value\", 0);\n\n efficiency = calculateEfficiency(miningIntensity);\n\n requestQueue = Volley.newRequestQueue(this);\n requestQueue.add(getMiningPoolRequester);\n\n broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n if (intent.getAction() != null && intent.getAction().equals(COMMUNICATION_ACTION) && isAppOnFocus) {\n int threadNo = intent.getIntExtra(\"threadNo\", 0);\n int hr = intent.getIntExtra(\"hashrate\", 0);\n int nonceFound = intent.getIntExtra(\"nonce\", 0);\n float timeElapsed = intent.getFloatExtra(\"timeElapsed\", 0.0f);\n\n sentShares = intent.getIntExtra(\"sharesSent\", 0);\n acceptedShares = intent.getIntExtra(\"sharesAccepted\", 0);\n\n updatePercentage();\n\n String minerNewLine = \"Thread \" + threadNo + \" | Nonce found: \" + nonceFound + \" | Time elapsed: \" + timeElapsed + \"s | Hashrate: \" + hr;\n addNewLineFromMiner(minerNewLine);\n\n threadsHashrate.add(threadNo, hr);\n\n int totalHashrate = 0;\n StringBuilder displayHashratePerThread = new StringBuilder();\n\n int threadHs;\n\n for (int th = 0; th < numberOfMiningThreads; th++){\n threadHs = threadsHashrate.get(th);\n totalHashrate += threadHs;\n displayHashratePerThread.append(\"Thread \").append(th).append(\": \").append(threadHs).append(\"h/s \\n\");\n }\n\n hashrateDisplay.setText(convertHashrate(totalHashrate));\n performancePerThread.setText(displayHashratePerThread.toString());\n }\n }\n };\n }\n\n @Override\n public void onResume(){\n super.onResume();\n\n isAppOnFocus = true;\n\n IntentFilter filter = new IntentFilter(COMMUNICATION_ACTION);\n registerReceiver(broadcastReceiver, filter);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n\n isAppOnFocus = false;\n\n unregisterReceiver(broadcastReceiver);\n }\n\n public void addNewLineFromMiner(String line) {\n long currentTimeMillis = System.currentTimeMillis();\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.getDefault());\n Date currentDate = new Date(currentTimeMillis);\n String formattedDate = sdf.format(currentDate);\n\n String newLine = formattedDate + \" | \" + line;\n minerLogLines.add(0, newLine);\n\n if (minerLogLines.size() > 8){\n minerLogLines.remove(8);\n }\n\n StringBuilder newMultiLineText = new StringBuilder();\n\n for (int i = 0; i < minerLogLines.size(); i++){\n newMultiLineText.append(minerLogLines.get(i)).append(\"\\n\");\n }\n\n miningLogsTextDisplay.setText(newMultiLineText.toString());\n }\n\n private void updatePercentage(){\n acceptedPercetage = (((float) acceptedShares / (float) sentShares)) * 10000;\n acceptedPercetage = Math.round(acceptedPercetage) / 100.0f;\n\n String newText = \"Accepted shares: \" + acceptedShares + \"/\" + sentShares + \" (\" + acceptedPercetage + \"%)\";\n\n acceptedSharesTextDisplay.setText(newText);\n }\n\n static float calculateEfficiency(int eff){\n if (eff >= 90){\n return 0.005f;\n }\n else if (eff >= 70){\n return 0.1f;\n }\n else if (eff >= 50){\n return 0.8f;\n }\n else if (eff >= 30) {\n return 1.8f;\n }\n\n return 3.0f;\n }\n\n static String convertHashrate(int hr){\n float roundedHashrate;\n\n if (hr >= 1_000_000){\n hr /= 1_000;\n roundedHashrate = hr / 1_000.0f;\n\n return roundedHashrate + \"M\";\n }\n else if (hr >= 1_000){\n hr /= 100;\n roundedHashrate = hr / 10.0f;\n return roundedHashrate + \"k\";\n }\n\n return String.valueOf(hr);\n }\n}" }, { "identifier": "ServiceNotificationActivity", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/activities/ServiceNotificationActivity.java", "snippet": "public class ServiceNotificationActivity extends AppCompatActivity {\n @Override\n public void onCreate(Bundle savedInstanceState){\n super.onCreate(savedInstanceState);\n\n Intent intent = new Intent(this, MinerBackgroundService.class);\n intent.setAction(MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING);\n startService(intent);\n\n finish();\n }\n}" }, { "identifier": "MiningThread", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/MiningThread.java", "snippet": "public class MiningThread implements Runnable{\n static{\n System.loadLibrary(\"ducohasher\");\n }\n\n public final static String MINING_THREAD_NAME_ID = \"duinocoin_mining_thread\";\n\n String ip;\n int port;\n\n int threadNo;\n\n Client tcpClient;\n\n String username;\n\n DUCOS1Hasher hasher;\n\n float miningEfficiency;\n\n ServiceCommunicationMethods service;\n\n public MiningThread(String ip, int port, String username, float miningEfficiency, int threadNo, ServiceCommunicationMethods service) throws IOException {\n this.ip = ip;\n this.port = port;\n this.username = username;\n this.miningEfficiency = miningEfficiency;\n this.service = service;\n this.threadNo = threadNo;\n\n hasher = new DUCOS1Hasher();\n\n Log.d(\"Mining thread\" + threadNo, threadNo + \" created\");\n }\n\n @Override\n public void run() {\n Log.d(\"Mining thread\" + threadNo, threadNo + \" started\");\n\n try {\n String responseData;\n\n try {\n tcpClient = new Client(ip, port);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n while (!Thread.currentThread().isInterrupted()) {\n tcpClient.send(\"JOB,\" + username + \",LOW\");\n\n try {\n responseData = tcpClient.readLine();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n Log.d(\"Thread \" + threadNo + \" | JOB received\", responseData);\n\n String[] values = responseData.split(\",\");\n\n String lastBlockHash = values[0];\n String expectedHash = values[1];\n\n int difficulty = Integer.parseInt(values[2]);\n\n int nonce = hasher.mine(lastBlockHash, expectedHash, difficulty, miningEfficiency);\n\n float timeElapsed = hasher.getTimeElapsed();\n float hashrate = hasher.getHashrate();\n\n Log.d(\"Thread \" + threadNo + \" | Nonce found\", nonce + \" Time elapsed: \" + timeElapsed + \"s Hashrate: \" + (int) hashrate);\n\n service.newShareSent();\n\n tcpClient.send(nonce + \",\" + (int) hashrate + \",\" + MinerInfo.MINER_NAME + \",\" + Build.MODEL);\n\n String shareResult;\n try {\n shareResult = tcpClient.readLine();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n if (shareResult.contains(\"GOOD\")) {\n service.newShareAccepted(threadNo, (int) hashrate, timeElapsed, nonce);\n }\n\n Log.d(\"Share accepted\", shareResult);\n }\n }\n catch (RuntimeException e){\n e.printStackTrace();\n }\n finally {\n try {\n tcpClient.closeConnection();\n Log.d(\"Mining thread \" + threadNo, \"Thread \" + threadNo + \" interrupted\");\n } catch (IOException e) {\n Log.w(\"Miner thread\", \"Couldn't properly end socket connection\");\n }\n }\n }\n}" }, { "identifier": "ServiceCommunicationMethods", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/ServiceCommunicationMethods.java", "snippet": "public interface ServiceCommunicationMethods {\n void newShareSent();\n void newShareAccepted(int threadNo, int hashrate, float timeElapsed, int nonce);\n}" } ]
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.ServiceInfo; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.fatorius.duinocoinminer.R; import com.fatorius.duinocoinminer.activities.MiningActivity; import com.fatorius.duinocoinminer.activities.ServiceNotificationActivity; import com.fatorius.duinocoinminer.threads.MiningThread; import com.fatorius.duinocoinminer.threads.ServiceCommunicationMethods; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
4,112
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started"); Intent notificationIntent = new Intent(this, ServiceNotificationActivity.class); pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); Notification notification = new NotificationCompat.Builder(this, "duinoCoinAndroidMinerChannel") .setContentTitle("Duino Coin Android Miner") .setContentText("The Miner is running in the background") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_launcher_foreground, "Stop mining", pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setTicker("The Miner is running") .setOngoing(true) .setOnlyAlertOnce(true) .build(); int type = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ type = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC; } startForeground(NOTIFICATION_ID, notification, type); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); for (int t = 0; t < numberOfMiningThreads; t++){ Thread miningThread; try {
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started"); Intent notificationIntent = new Intent(this, ServiceNotificationActivity.class); pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); Notification notification = new NotificationCompat.Builder(this, "duinoCoinAndroidMinerChannel") .setContentTitle("Duino Coin Android Miner") .setContentText("The Miner is running in the background") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_launcher_foreground, "Stop mining", pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setTicker("The Miner is running") .setOngoing(true) .setOnlyAlertOnce(true) .build(); int type = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ type = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC; } startForeground(NOTIFICATION_ID, notification, type); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); for (int t = 0; t < numberOfMiningThreads; t++){ Thread miningThread; try {
miningThread = new Thread(new MiningThread(poolIp, poolPort, ducoUsername, efficiency, t, this), MiningThread.MINING_THREAD_NAME_ID);
2
2023-12-27 06:00:05+00:00
8k
fanxiaoning/framifykit
framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/KD100Executor.java
[ { "identifier": "ServiceException", "path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/exception/ServiceException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 错误码\n * {@link ServiceErrorCodeRange}\n */\n private Integer code;\n\n /**\n * 错误信息\n */\n private String msg;\n\n /**\n * 空构造方法,避免反序列化问题\n */\n public ServiceException() {\n }\n\n public ServiceException(AbstractCode exception) {\n this.code = exception.getCode();\n this.msg = exception.getMsg();\n }\n\n public ServiceException(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n}" }, { "identifier": "FramifyResult", "path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/result/FramifyResult.java", "snippet": "@Data\npublic class FramifyResult<T> implements Serializable {\n\n /**\n * 响应码\n * {@link ErrorCode#getCode()}\n * {@link SuccessCode#getCode()}\n */\n private Integer code;\n\n /**\n * 响应信息\n * {@link ErrorCode#getCode()}\n * {@link SuccessCode#getCode()}\n */\n private String msg;\n\n\n /**\n * 返回数据\n */\n private T data;\n\n\n /**\n * 将传入的 result 对象,转换成另外一个泛型结果的对象\n * <p>\n * 因为 A 方法返回的 FramifyResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。\n * </p>\n *\n * @param result 传入的 result 对象\n * @param <T> 返回的泛型\n * @return 新的 FramifyResult 对象\n */\n public static <T> FramifyResult<T> error(FramifyResult<?> result) {\n return error(result.getCode(), result.getMsg());\n }\n\n public static <T> FramifyResult<T> error(Integer code, String message) {\n FramifyResult<T> result = new FramifyResult<>();\n result.code = code;\n result.msg = message;\n return result;\n }\n\n public static <T> FramifyResult<T> error(AbstractCode errorCode) {\n return error(errorCode.getCode(), errorCode.getMsg());\n }\n\n public static <T> FramifyResult<T> success(T data) {\n FramifyResult<T> result = new FramifyResult<>();\n result.code = GlobalCodeConstants.SUCCESS.getCode();\n result.data = data;\n result.msg = \"\";\n return result;\n }\n\n public static boolean isSuccess(Integer code) {\n return Objects.equals(code, GlobalCodeConstants.SUCCESS.getCode());\n }\n\n @JsonIgnore\n public boolean isSuccess() {\n return isSuccess(code);\n }\n\n @JsonIgnore\n public boolean isError() {\n return !isSuccess();\n }\n\n\n /**\n * 异常体系集成\n */\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n */\n public void checkError() throws ServiceException {\n if (isSuccess()) {\n return;\n }\n // 业务异常\n throw new ServiceException(code, msg);\n }\n\n /**\n * 判断是否有异常。如果有,则抛出 {@link ServiceException} 异常\n * 如果没有,则返回 {@link #data} 数据\n */\n @JsonIgnore\n public T getCheckedData() {\n checkError();\n return data;\n }\n\n public static <T> FramifyResult<T> error(ServiceException serviceException) {\n return error(serviceException.getCode(), serviceException.getMessage());\n }\n}" }, { "identifier": "LogisticsTypeEnum", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/constant/LogisticsTypeEnum.java", "snippet": "public enum LogisticsTypeEnum {\n\n\n /**\n * 京东物流\n */\n JD(\"1000\", \"京东物流\"),\n\n /**\n * 快递100\n */\n KD_100(\"1001\", \"快递100\"),\n\n /**\n * 顺丰\n */\n SF(\"1002\", \"顺丰快递\"),\n\n /**\n * 其他\n */\n OTHER(\"1003\", \"其他物流\");\n\n\n private String code;\n private String name;\n\n LogisticsTypeEnum(String code, String name) {\n this.code = code;\n this.name = name;\n }\n\n public static LogisticsTypeEnum getType(String code) {\n for (LogisticsTypeEnum type : values()) {\n if (type.getCode().equals(code)) {\n return type;\n }\n }\n return OTHER;\n }\n\n public String getCode() {\n return code;\n }\n\n\n public String getName() {\n return name;\n }\n\n\n}" }, { "identifier": "ILogisticsGetConfig", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/config/ILogisticsGetConfig.java", "snippet": "public interface ILogisticsGetConfig<CONFIG> {\n\n /**\n * 获取配置类\n *\n * @return\n */\n CONFIG getApiConfig();\n}" }, { "identifier": "KD100Req", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/req/KD100Req.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class KD100Req extends BaseReq {\n\n\n /**\n * 查询物流信息\n */\n private KD100QueryTrackReq queryTrackReq;\n\n\n /**\n * 下单\n */\n private KD100PlaceOrderReq placeOrderReq;\n\n /**\n * 取消下单\n */\n private KD100CancelOrderReq cancelOrderReq;\n\n\n /**\n * 查询运力\n */\n private KD100QueryCapacityReq queryCapacityReq;\n\n /**\n * 获取验证码\n */\n private KD100GetCodeReq getCodeReq;\n\n /**\n * 校验地址\n */\n private KD100CheckAddressReq checkAddressReq;\n\n\n /**\n * 订阅接口参数\n */\n private KD100SubscribeReq subscribeReq;\n}" }, { "identifier": "KD100Res", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/res/KD100Res.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class KD100Res extends BaseRes {\n\n\n /**\n * 查询物流信息\n */\n private KD100QueryTrackRes queryTrackRes;\n\n /**\n * 下单\n */\n private KD100PlaceOrderRes placeOrderRes;\n\n /**\n * 取消下单\n */\n private KD100CancelOrderRes cancelOrderRes;\n\n /**\n * 获取验证码\n */\n private KD100GetCodeRes getCodeRes;\n\n /**\n * 校验地址\n */\n private KD100CheckAddressRes checkAddressRes;\n\n\n /**\n * 查询运力\n */\n private KD100QueryCapacityRes<KD100QueryCapacityResParam> queryCapacityRes;\n\n /**\n * 订阅\n */\n private KD100SubscribeRes subscribeRes;\n}" }, { "identifier": "DefaultKD100Client", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/client/DefaultKD100Client.java", "snippet": "@Data\npublic class DefaultKD100Client implements IKD100Client {\n\n private String key;\n\n private String customer;\n\n private String secret;\n\n private String userId;\n\n\n public DefaultKD100Client(String key, String customer, String secret) {\n this.key = key;\n this.customer = customer;\n this.secret = secret;\n }\n\n @Override\n public String execute(String url, Object req) throws ServiceException {\n //TODO 调用第三方物流接口 此次待优化\n return HttpUtils.doPost(url, req);\n }\n}" }, { "identifier": "KD100ApiConfig", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/config/KD100ApiConfig.java", "snippet": "public class KD100ApiConfig {\n\n private String appKey;\n\n private String customer;\n\n private String appSecret;\n\n\n private DefaultKD100Client KD100Client;\n\n\n private KD100ApiConfig() {\n\n }\n\n public static KD100ApiConfig builder() {\n return new KD100ApiConfig();\n }\n\n public KD100ApiConfig build() {\n this.KD100Client = new DefaultKD100Client(getAppKey(), getCustomer(), getAppSecret());\n return this;\n }\n\n public String getAppKey() {\n if (StrUtil.isBlank(appKey)) {\n throw new IllegalStateException(\"appKey 未被赋值\");\n }\n return appKey;\n }\n\n public KD100ApiConfig setKey(String appKey) {\n if (StrUtil.isEmpty(appKey)) {\n throw new IllegalArgumentException(\"appKey 值不能为 null\");\n }\n this.appKey = appKey;\n return this;\n }\n\n public String getCustomer() {\n if (StrUtil.isBlank(customer)) {\n throw new IllegalStateException(\"customer 未被赋值\");\n }\n return customer;\n }\n\n public KD100ApiConfig setCustomer(String customer) {\n if (StrUtil.isEmpty(customer)) {\n throw new IllegalArgumentException(\"customer 值不能为 null\");\n }\n this.customer = customer;\n return this;\n }\n\n public String getAppSecret() {\n if (StrUtil.isBlank(appSecret)) {\n throw new IllegalStateException(\"appSecret 未被赋值\");\n }\n return appSecret;\n }\n\n public KD100ApiConfig setAppSecret(String appSecret) {\n if (StrUtil.isEmpty(appSecret)) {\n throw new IllegalArgumentException(\"appSecret 值不能为 null\");\n }\n this.appSecret = appSecret;\n return this;\n }\n\n\n public DefaultKD100Client getKD100Client() {\n if (KD100Client == null) {\n throw new IllegalStateException(\"KD100Client 未被初始化\");\n }\n return KD100Client;\n }\n}" }, { "identifier": "KD100ApiConfigKit", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/config/KD100ApiConfigKit.java", "snippet": "public class KD100ApiConfigKit {\n\n private static final ThreadLocal<String> TL = new ThreadLocal<>();\n\n private static final Map<String, KD100ApiConfig> CFG_MAP = new ConcurrentHashMap<>();\n private static final String DEFAULT_CFG_KEY = \"_default_key_\";\n\n /**\n * <p>向缓存中设置 KD100ApiConfig </p>\n * <p>每个 appId 只需添加一次,相同 appId 将被覆盖</p>\n *\n * @param KD100ApiConfig 快递100api配置\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig putApiConfig(KD100ApiConfig KD100ApiConfig) {\n if (CFG_MAP.size() == 0) {\n CFG_MAP.put(DEFAULT_CFG_KEY, KD100ApiConfig);\n }\n return CFG_MAP.put(KD100ApiConfig.getAppKey(), KD100ApiConfig);\n }\n\n /**\n * 向当前线程中设置 {@link KD100ApiConfig}\n *\n * @param KD100ApiConfig {@link KD100ApiConfig} 快递100api配置对象\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig setThreadLocalApiConfig(KD100ApiConfig KD100ApiConfig) {\n if (StrUtil.isNotEmpty(KD100ApiConfig.getAppKey())) {\n setThreadLocalAppId(KD100ApiConfig.getAppKey());\n }\n return putApiConfig(KD100ApiConfig);\n }\n\n /**\n * 通过 KD100ApiConfig 移除快递100api配置\n *\n * @param KD100ApiConfig {@link KD100ApiConfig} 京东物流api配置对象\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig removeApiConfig(KD100ApiConfig KD100ApiConfig) {\n return removeApiConfig(KD100ApiConfig.getAppKey());\n }\n\n /**\n * 通过 appKey 移除快递100配置\n *\n * @param appKey 快递100api 应用key\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig removeApiConfig(String appKey) {\n return CFG_MAP.remove(appKey);\n }\n\n /**\n * 向当前线程中设置 appKey\n *\n * @param appKey 快递100 api 应用key\n */\n public static void setThreadLocalAppId(String appKey) {\n if (StrUtil.isEmpty(appKey)) {\n appKey = CFG_MAP.get(DEFAULT_CFG_KEY).getAppKey();\n }\n TL.set(appKey);\n }\n\n /**\n * 移除当前线程中的 appKey\n */\n public static void removeThreadLocalAppId() {\n TL.remove();\n }\n\n /**\n * 获取当前线程中的 appKey\n *\n * @return 快递100 api 应用key\n */\n public static String getAppKey() {\n String appId = TL.get();\n if (StrUtil.isEmpty(appId)) {\n appId = CFG_MAP.get(DEFAULT_CFG_KEY).getAppKey();\n }\n return appId;\n }\n\n /**\n * 获取当前线程中的 KD100ApiConfig\n *\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig getApiConfig() {\n String appId = getAppKey();\n return getApiConfig(appId);\n }\n\n /**\n * 通过 appKey 获取 KD100ApiConfig\n *\n * @param appKey 快递100 api 应用key\n * @return {@link KD100ApiConfig}\n */\n public static KD100ApiConfig getApiConfig(String appKey) {\n KD100ApiConfig cfg = CFG_MAP.get(appKey);\n if (cfg == null) {\n throw new IllegalStateException(\"需事先调用 KD100ApiConfigKit.putApiConfig(KD100ApiConfig) 将 appKey对应的 KD100ApiConfig 对象存入,才可以使用 KD100ApiConfigKit.getJdApiConfig() 的系列方法\");\n }\n return cfg;\n }\n}" }, { "identifier": "KD100CheckAddressResParam", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100CheckAddressResParam.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class KD100CheckAddressResParam {\n\n private String taskId;\n\n private List<ToReachableDetail> toReachable;\n\n\n /**\n * @author: fanxiaoning\n * @description: 校验地址详情内部类\n * @date: 2023/5/4\n * @since v1.0.0\n **/\n @Data\n public static class ToReachableDetail {\n\n /**\n * 是否可达,0:不可达,1:可达\n */\n private String reachable;\n\n /**\n * 快递公司编码\n */\n private String expressCode;\n\n /**\n * 不可达的原因\n */\n private String reason;\n }\n}" }, { "identifier": "KD100QueryCapacityResParam", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryCapacityResParam.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class KD100QueryCapacityResParam {\n\n private String province;\n\n private String city;\n\n private String district;\n\n private String addr;\n\n private String latitude;\n\n private String longitude;\n\n private List<KD100QueryCapacityResParameters> queryCapacityResParameters;\n}" }, { "identifier": "SignUtils", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/util/SignUtils.java", "snippet": "public class SignUtils {\n\n\n /**\n * 快递100加密方式统一为MD5后转大写\n *\n * @param msg\n * @return\n */\n public static String sign(String msg) {\n return DigestUtil.md5Hex(msg).toUpperCase();\n }\n\n /**\n * 查询加密\n *\n * @param param\n * @param key\n * @param customer\n * @return\n */\n public static String querySign(String param, String key, String customer) {\n return sign(param + key + customer);\n }\n\n /**\n * 打印/下单 加密\n *\n * @param param\n * @param t\n * @param key\n * @param secret\n * @return\n */\n public static String printSign(String param, String t, String key, String secret) {\n return sign(param + t + key + secret);\n }\n\n /**\n * 云平台 加密\n *\n * @param key\n * @param secret\n * @return\n */\n public static String cloudSign(String key, String secret) {\n return sign(key + secret);\n }\n\n\n /**\n * 短信加密\n *\n * @param key\n * @param userId\n * @return\n */\n public static String smsSign(String key, String userId) {\n return sign(key + userId);\n }\n}" }, { "identifier": "KD100ApiConstant", "path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/constant/KD100ApiConstant.java", "snippet": "public class KD100ApiConstant {\n\n\n /**\n * 签名盐值\n */\n private static String SALT = \"ecnow\";\n\n /**\n * 查询url\n */\n public static final String QUERY_URL = \"https://poll.kuaidi100.com/poll/query.do\";\n\n /**\n * 商家寄件\n */\n public static final String B_ORDER_URL = \"https://order.kuaidi100.com/order/borderbestapi.do\";\n /**\n * 商家寄件查询运力\n */\n public static final String B_ORDER_QUERY_TRANSPORT_CAPACITY_METHOD = \"querymkt\";\n /**\n * 商家寄件下单\n */\n public static final String B_ORDER_SEND_METHOD = \"bOrderBest\";\n /**\n * 商家寄件获取验证码\n */\n public static final String B_ORDER_CODE_METHOD = \"getCode\";\n /**\n * 商家寄件取消\n */\n public static final String B_ORDER_CANCEL_METHOD = \"cancelBest\";\n\n\n /**\n * 订阅url\n */\n public static final String SUBSCRIBE_URL = \"https://poll.kuaidi100.com/poll\";\n /**\n * 订阅SCHEMA\n */\n public static final String SUBSCRIBE_SCHEMA = \"json\";\n /**\n * 智能单号识别url\n */\n public static final String AUTO_NUM_URL = \"http://www.kuaidi100.com/autonumber/auto?num=%s&key=%s\";\n /**\n * 电子面单html url\n */\n public static final String ELECTRONIC_ORDER_HTML_URL = \"http://poll.kuaidi100.com/eorderapi.do\";\n /**\n * 电子面单html方法\n */\n public static final String ELECTRONIC_ORDER_HTML_METHOD = \"getElecOrder\";\n /**\n * 电子面单获取图片 url\n */\n public static final String ELECTRONIC_ORDER_PIC_URL = \"https://poll.kuaidi100.com/printapi/printtask.do\";\n /**\n * 电子面单获取图片\n */\n public static final String ELECTRONIC_ORDER_PIC_METHOD = \"getPrintImg\";\n /**\n * 电子面单打印 url\n */\n public static final String ELECTRONIC_ORDER_PRINT_URL = \"https://poll.kuaidi100.com/printapi/printtask.do\";\n /**\n * 电子面单打印方法\n */\n public static final String ELECTRONIC_ORDER_PRINT_METHOD = \"eOrder\";\n /**\n * 菜鸟淘宝账号授权\n */\n public static final String AUTH_THIRD_URL = \"https://poll.kuaidi100.com/printapi/authThird.do\";\n /**\n * 云打印url\n */\n public static final String CLOUD_PRINT_URL = \"http://poll.kuaidi100.com/printapi/printtask.do?method=%s&t=%s&key=%s&sign=%s&param=%s\";\n /**\n * 自定义打印方法\n */\n public static final String CLOUD_PRINT_CUSTOM_METHOD = \"printOrder\";\n /**\n * 附件打印方法\n */\n public static final String CLOUD_PRINT_ATTACHMENT_METHOD = \"imgOrder\";\n /**\n * 复打方法\n */\n public static final String CLOUD_PRINT_OLD_METHOD = \"printOld\";\n /**\n * 复打方法\n */\n public static final String SEND_SMS_URL = \"http://apisms.kuaidi100.com:9502/sms/send.do\";\n /**\n * 云平台通用请求url\n */\n public static final String CLOUD_NORMAL_URL = \"http://cloud.kuaidi100.com/api\";\n\n /**\n * 可用性请求地址\n */\n public static final String REACHABLE_URL = \"http://api.kuaidi100.com/reachable.do\";\n /**\n * 可用性方法\n */\n public static final String REACHABLE_METHOD = \"reachable\";\n}" } ]
import cn.hutool.core.lang.TypeReference; import cn.hutool.core.util.ReflectUtil; import com.alibaba.fastjson.JSONObject; import com.famifykit.starter.common.exception.ServiceException; import com.famifykit.starter.common.result.FramifyResult; import com.framifykit.starter.logistics.executor.constant.LogisticsTypeEnum; import com.framifykit.starter.logistics.executor.config.ILogisticsGetConfig; import com.framifykit.starter.logistics.executor.domain.req.KD100Req; import com.framifykit.starter.logistics.executor.domain.res.KD100Res; import com.framifykit.starter.logistics.platform.kd100.client.DefaultKD100Client; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfig; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfigKit; import com.framifykit.starter.logistics.platform.kd100.domain.res.*; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100CheckAddressResParam; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryCapacityResParam; import com.framifykit.starter.logistics.platform.kd100.util.SignUtils; import lombok.extern.slf4j.Slf4j; import java.util.Map; import static com.framifykit.starter.logistics.common.constant.LogisticsErrorCodeConstants.THIRD_PARTY_API_ERROR; import static com.framifykit.starter.logistics.platform.kd100.constant.KD100ApiConstant.*;
6,112
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) {
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) {
log.error("第三方物流平台:{}调用系统异常", LogisticsTypeEnum.KD_100.getName(), e);
2
2023-12-31 03:48:33+00:00
8k
yangpluseven/Simulate-Something
simulation/src/test/DisplayerTest.java
[ { "identifier": "Painter", "path": "simulation/src/interfaces/Painter.java", "snippet": "@FunctionalInterface\npublic interface Painter {\n\tpublic abstract void paint(Graphics g, int x, int y, int w, int h);\n}" }, { "identifier": "Displayer", "path": "simulation/src/simulator/Displayer.java", "snippet": "public class Displayer extends JFrame {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate DisplayArea displayArea;\n\n\t/**\n\t * Create a simulator window.\n\t */\n\tpublic Displayer() {\n\n\t\tsetTitle(\"simulation\");\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n\t\t// Create menu bar\n\t\tJMenuBar menuBar = new JMenuBar();\n\t\tsetJMenuBar(menuBar);\n\n\t\t// Create Simulator menu\n\t\tJMenu simulatorMenu = new JMenu(\"Simulator\");\n\t\tmenuBar.add(simulatorMenu);\n\n\t\t// Add Simulator menu items\n\t\tJMenuItem startMenuItem = new JMenuItem(\"Start\");\n\t\tJMenuItem stepMenuItem = new JMenuItem(\"Step\");\n\t\tJMenuItem stopMenuItem = new JMenuItem(\"Stop\");\n\t\tsimulatorMenu.add(startMenuItem);\n\t\tsimulatorMenu.add(stepMenuItem);\n\t\tsimulatorMenu.add(stopMenuItem);\n\n\t\t// Add Simulator menu item listeners\n\t\tstartMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO start menu item\n\t\t\t\tshowMenuItemName(\"start\");\n\t\t\t}\n\t\t});\n\n\t\tstepMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO step menu item\n\t\t\t\tshowMenuItemName(\"step\");\n\t\t\t}\n\t\t});\n\n\t\tstopMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t// TODO show menu item\n\t\t\t\tshowMenuItemName(\"stop\");\n\t\t\t}\n\t\t});\n\n\t\t// Create Window menu\n\t\tJMenu windowMenu = new JMenu(\"Window\");\n\t\tmenuBar.add(windowMenu);\n\n\t\t// Add Window menu items\n\t\tJMenuItem packMenuItem = new JMenuItem(\"Pack\");\n\t\tJMenuItem zoomInMenuItem = new JMenuItem(\"Zoom In(+)\");\n\t\tJMenuItem zoomOutMenuItem = new JMenuItem(\"Zoom Out(-)\");\n\t\tJMenuItem fixMenuItem = new JMenuItem(\"Fix\");\n\t\twindowMenu.add(packMenuItem);\n\t\twindowMenu.add(zoomInMenuItem);\n\t\twindowMenu.add(zoomOutMenuItem);\n\t\twindowMenu.add(fixMenuItem);\n\n\t\t// Add Window menu item listeners\n\t\tpackMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tpack();\n\t\t\t\tdisplayArea.refresh();\n\t\t\t\tdisplayArea.drawAll();\n\t\t\t\tdisplayArea.repaint();\n\t\t\t}\n\t\t});\n\t\t\n\t\tzoomInMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.zoom(Constants.ZOOM_IN);\n\t\t\t}\n\t\t});\n\t\t\n\t\tzoomOutMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.zoom(Constants.ZOOM_OUT);\n\t\t\t}\n\t\t});\n\t\t\n\t\tfixMenuItem.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tdisplayArea.fix();\n\t\t\t}\n\t\t});\n\t\t\n\t\taddWindowStateListener(new WindowStateListener() {\n\t\t\t@Override\n\t\t\tpublic void windowStateChanged(WindowEvent e) {\n\t\t\t\tdisplayArea.fix();\n\t\t\t}\n\t\t});\n\n\t\tsetLayout(new BorderLayout());\n\n\t\tdisplayArea = new DisplayArea();\n\t\tgetContentPane().add(displayArea, BorderLayout.CENTER);\n\n\t\t// Add a panel for the bottom area\n\t\tJPanel bottomPanel = new JPanel();\n\t\tbottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT));\n\n\t\t// Add the speed label and value\n\t\tJLabel speedLabel = new JLabel(\"Speed:\");\n\t\t// TODO display speed\n\t\tJLabel speedValueLabel = new JLabel(Integer.toString(0));\n\n\t\tbottomPanel.add(speedLabel);\n\t\tbottomPanel.add(speedValueLabel);\n\n\t\t// Add the bottom panel to the frame\n\t\tadd(bottomPanel, BorderLayout.SOUTH);\n\n\t\tsetLocationRelativeTo(null);\n\t\tpack();\n\t\tsetVisible(true);\n\t}\n\t\n\t\n\t/**\n\t * Return the gridMap of displayArea.\n\t * \n\t * @return the grid map.\n\t */\n\tpublic GridMap getGridMap() {\n\t\treturn displayArea.gridMap;\n\t}\n\n\t/**\n\t * Display the name of the menu item in a message dialog for testing.\n\t * \n\t * @param menuItemName the name of the menu item.\n\t */\n\tprivate void showMenuItemName(String menuItemName) {\n\t\tJOptionPane.showMessageDialog(this, \"Menu Item Clicked: \" + menuItemName);\n\t}\n\n\t/**\n\t * Display the window.\n\t */\n\tpublic void display() {\n\t\tdisplayArea.refresh();\n\t\tdisplayArea.drawAll();\n\t\tdisplayArea.repaint();\n\t\tsetVisible(true);\n\t}\n\n\tpublic void addObjectAt(SimuObject simuObj, Location location) {\n\t\tdisplayArea.gridMap.addObjectAt(simuObj, location);\n\t}\n\n\tprivate class DisplayArea extends JPanel {\n\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tprivate final Size numCR = Constants.NUM_OF_COL_ROW;\n\t\tprivate Size gridSize = Constants.INIT_GRID_SIZE;\n\t\tprivate Size totalSize = new Size();\n\t\tprivate Image image;\n\t\tprivate Graphics graphic;\n\t\tprivate GridMap gridMap;\n\n\t\tprivate DisplayArea() {\n\t\t\tthis(new GridMap());\n\t\t}\n\n\t\tprivate DisplayArea(GridMap gridMap) {\n\t\t\ttotalSize.update(numCR.getWidth() * gridSize.getWidth(), numCR.getHeight() * gridSize.getHeight());\n\t\t\tthis.gridMap = gridMap;\n\t\t\tsetPreferredSize(new Dimension(totalSize.getWidth(), totalSize.getHeight()));\n\t\t}\n\t\t\n\t\tprivate void fix() {\n\t\t\tdouble xScale = (double) getWidth() / totalSize.getWidth();\n\t\t\tdouble yScale = (double) getHeight() / totalSize.getHeight();\n\t\t\tdouble scale = Math.min(xScale, yScale);\n\t\t\tint newHeight = totalSize.getHeight(), newWidth = totalSize.getWidth();\n\t\t\tint tmpTotalWidth = (int) (totalSize.getWidth() * scale);\n\t\t\tint tmpTotalHeight = (int) (totalSize.getHeight() * scale);\n\t\t\t// Ensure that the view of the simulator object is still an integer after being\n\t\t\t// resized.\n\t\t\tfor (int i = tmpTotalWidth; i >= 0; i--)\n\t\t\t\tif (i % numCR.getWidth() == 0) {\n\t\t\t\t\tnewWidth = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\tfor (int i = tmpTotalHeight; i >= 0; i--)\n\t\t\t\tif (i % numCR.getHeight() == 0) {\n\t\t\t\t\tnewHeight = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t// Resize the display area.\n\t\t\tdisplayArea.setPreferredSize(new Dimension(newWidth, newHeight));\n\n\t\t\t// Resize all the simulation objects' view.\n\t\t\ttotalSize.update(newWidth, newHeight);\n\t\t\tint newGridWidth = newWidth / numCR.getWidth();\n\t\t\tint newGridHeight = newHeight / numCR.getHeight();\n\t\t\tgridSize.update(newGridWidth, newGridHeight);\n\t\t\tdisplay();\n\t\t}\n\t\t\n\t\tprivate void zoom(boolean zoomIn) {\n\t\t\tint newGridWidth = gridSize.getWidth() + (zoomIn ? 1 : -1);\n\t\t\tint newGridHeight = gridSize.getHeight() + (zoomIn ? 1 : -1);\n\t\t\tgridSize.update(newGridWidth, newGridHeight);\n\t\t\ttotalSize.update(newGridWidth * numCR.getWidth(), newGridHeight * numCR.getHeight());\n\t\t\tsetSize(new Dimension(totalSize.getWidth(), totalSize.getHeight()));\n\t\t\tdisplay();\n\t\t}\n\n\t\tprivate void refresh() {\n\t\t\timage = createImage(totalSize.getWidth(), totalSize.getHeight());\n\t\t\tgraphic = image.getGraphics();\n\t\t}\n\n\t\tprivate void drawObject(SimuObject simuObj) {\n\t\t\tPainter painter = simuObj.getPainter();\n\t\t\tLocation location = simuObj.getLocation();\n\t\t\tint x = location.getCol() * gridSize.getWidth();\n\t\t\tint y = location.getRow() * gridSize.getHeight();\n\t\t\tgraphic.setColor(simuObj.getColor());\n\t\t\tpainter.paint(graphic, x, y, gridSize.getWidth(), gridSize.getHeight());\n\t\t}\n\n\t\tprivate void drawAll() {\n\t\t\tfor (Iterator<SimuObject> iter : gridMap.getAllIterator()) {\n\t\t\t\twhile (iter.hasNext()) {\n\t\t\t\t\tSimuObject simuObj = iter.next();\n\t\t\t\t\tdrawObject(simuObj);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic Dimension getPreferredSize() {\n\t\t\treturn new Dimension(totalSize.getWidth(), totalSize.getHeight());\n\t\t}\n\n\t\tpublic void paintComponent(Graphics g) {\n\t\t\tg.drawImage(image, 0, 0, null);\n\t\t}\n\t}\n\n}" }, { "identifier": "GridMap", "path": "simulation/src/simulator/GridMap.java", "snippet": "public class GridMap implements Map<Location, simulator.GridMap.Grid> {\n\n\tprivate Grid[][] grids;\n\tprivate Size numCR;\n\tprivate int numOfObjs;\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic GridMap() {\n\t\tnumCR = Constants.NUM_OF_COL_ROW;\n\t\tint numCol = numCR.getWidth();\n\t\tint numRow = numCR.getHeight();\n\t\tgrids = new Grid[numCol][numRow];\n\t\tnumOfObjs = 0;\n\t}\n\n\t/**\n\t * Create a GridMap with the given numbers of columns and rows.\n\t * \n\t * @param numCR\n\t */\n\tpublic GridMap(Size numCR) {\n\t\tthis.numCR = numCR;\n\t\tint numCol = numCR.getWidth();\n\t\tint numRow = numCR.getHeight();\n\t\tgrids = new Grid[numCol][numRow];\n\t\tnumOfObjs = 0;\n\t}\n\n\t/**\n\t * Add the SimuObject at the given location.\n\t * \n\t * @param simuObj\n\t * @param location\n\t */\n\tpublic void addObjectAt(SimuObject simuObj, Location location) {\n\t\tif (grids[location.getCol()][location.getRow()] == null)\n\t\t\tgrids[location.getCol()][location.getRow()] = new Grid();\n\t\tgrids[location.getCol()][location.getRow()].add(simuObj);\n\t\tnumOfObjs++;\n\t}\n\n\t/**\n\t * Return the Iterator of the Grid at the Given location.\n\t * \n\t * @param location\n\t * @return the Iterator at the given location.\n\t */\n\tpublic Iterator<SimuObject> getIteratorAt(Location location) {\n\t\treturn grids[location.getCol()][location.getRow()].iterator();\n\t}\n\t\n\t/**\n\t * Return iterators of those grids.\n\t * \n\t * @return all the iterators\n\t */\n\tpublic Collection<Iterator<SimuObject>> getAllIterator() {\n\t\tArrayList<Iterator<SimuObject>> iterators = new ArrayList<Iterator<SimuObject>>(size());\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\titerators.add(grids[i][j].iterator());\n\t\treturn iterators;\n\t}\n\n\t/**\n\t * Return the number of SimuObjects in the GridMap.\n\t *\n\t * @return the number of SimuObjects.\n\t */\n\t@Override\n\tpublic int size() {\n\t\treturn numOfObjs;\n\t}\n\n\t/**\n\t * Return {@code true} if there's no SimuObjects in this GridMap.\n\t *\n\t * @return {@code true} if no SimuObjects in map.\n\t */\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn numOfObjs == 0;\n\t}\n\n\t@Override\n\tpublic boolean containsKey(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn false;\n\t\tLocation location = (Location) key;\n\t\tGrid grid = grids[location.getCol()][location.getRow()];\n\t\treturn grid != null && grid.isEmpty();\n\t}\n\n\t@Override\n\tpublic boolean containsValue(Object value) {\n\t\tif (!(value instanceof SimuObject || value instanceof Grid))\n\t\t\treturn false;\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j].contains(value))\n\t\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Grid get(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn null;\n\t\tLocation location = (Location) key;\n\t\treturn grids[location.getCol()][location.getRow()];\n\t}\n\n\t@Override\n\tpublic Grid put(Location key, Grid value) {\n\t\tnumOfObjs += value.size();\n\t\treturn grids[key.getCol()][key.getRow()] = value;\n\t}\n\n\t@Override\n\tpublic Grid remove(Object key) {\n\t\tif (!(key instanceof Location))\n\t\t\treturn null;\n\t\tLocation location = (Location) key;\n\t\tGrid grid = grids[location.getCol()][location.getRow()];\n\t\tgrids[location.getCol()][location.getRow()] = null;\n\t\tnumOfObjs -= grid.size();\n\t\treturn grid;\n\t}\n\n\t@Override\n\tpublic void putAll(Map<? extends Location, ? extends Grid> m) {\n\t\tfor (Entry<? extends Location, ? extends Grid> entry : m.entrySet()) {\n\t\t\tput(entry.getKey(), entry.getValue());\n\t\t\tnumOfObjs += entry.getValue().size();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tgrids[i][j] = null;\n\t\tnumOfObjs = 0;\n\t}\n\n\t@Override\n\tpublic Set<Location> keySet() {\n\t\tSet<Location> set = new HashSet<Location>();\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tset.add(new Location(i, j));\n\t\treturn set;\n\t}\n\n\t@Override\n\tpublic Collection<Grid> values() {\n\t\tCollection<Grid> collection = new ArrayList<Grid>(size());\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tcollection.add(grids[i][j]);\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Set<Entry<Location, Grid>> entrySet() {\n\t\tSet<Entry<Location, Grid>> set = new HashSet<Entry<Location, Grid>>();\n\t\tfor (int i = 0; i < numCR.getWidth(); i++)\n\t\t\tfor (int j = 0; j < numCR.getHeight(); j++)\n\t\t\t\tif (grids[i][j] != null)\n\t\t\t\t\tset.add(new Pair<Location, Grid>(new Location(i, j), grids[i][j]));\n\t\treturn set;\n\t}\n\n\t/**\n\t * I don't know why do I need this class. I kinda just encapsulated a ArrayList\n\t * in it.\n\t * \n\t * @author pluseven\n\t */\n\tpublic class Grid implements Collection<SimuObject> {\n\n\t\tprivate ArrayList<SimuObject> simuObjs;\n\n\t\t/**\n\t\t * Default constructor.\n\t\t */\n\t\tpublic Grid() {\n\t\t\tsimuObjs = new ArrayList<SimuObject>();\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn simuObjs == null ? 0 : simuObjs.size();\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isEmpty() {\n\t\t\treturn simuObjs == null || simuObjs.size() == 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object o) {\n\t\t\treturn simuObjs == null ? false : simuObjs.contains(o);\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<SimuObject> iterator() {\n\t\t\treturn simuObjs.iterator();\n\t\t}\n\n\t\t@Override\n\t\tpublic Object[] toArray() {\n\t\t\treturn simuObjs.toArray();\n\t\t}\n\n\t\t@Override\n\t\tpublic <T> T[] toArray(T[] a) {\n\t\t\treturn simuObjs.toArray(a);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean add(SimuObject e) {\n\t\t\treturn simuObjs.add(e);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean remove(Object o) {\n\t\t\treturn simuObjs.remove(o);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean containsAll(Collection<?> c) {\n\t\t\treturn simuObjs.containsAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean addAll(Collection<? extends SimuObject> c) {\n\t\t\treturn simuObjs.addAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean removeAll(Collection<?> c) {\n\t\t\treturn simuObjs.removeAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean retainAll(Collection<?> c) {\n\t\t\treturn simuObjs.retainAll(c);\n\t\t}\n\n\t\t@Override\n\t\tpublic void clear() {\n\t\t\tsimuObjs.clear();\n\t\t}\n\n\t}\n\n}" } ]
import java.awt.Color; import entities.*; import entities.painters.*; import interfaces.Painter; import simulator.Displayer; import simulator.GridMap;
4,469
package test; public class DisplayerTest { public static void main(String[] args) { Displayer displayer = new Displayer(); Line line = new Line(); line.addDirection(0, -1); line.addDirection(1, 0); SimuObject simuObjA = new Obj(Color.BLACK, line, displayer.getGridMap()); Location locationA = new Location(0, 0); simuObjA.moveTo(locationA); displayer.addObjectAt(simuObjA, locationA); SimuObject simuObjB = new Obj(Color.BLUE, new Rectangle(), displayer.getGridMap()); Location locationB = new Location(49, 29); simuObjB.moveTo(locationB); displayer.addObjectAt(simuObjB, locationB); SimuObject simuObjC = new Obj(Color.RED, new Oval(), displayer.getGridMap()); Location locationC = new Location(49, 29); simuObjC.moveTo(locationC); displayer.addObjectAt(simuObjC, locationC); simuObjA.moveTo(new Location(10, 10)); displayer.display(); } } class Obj extends SimuObject {
package test; public class DisplayerTest { public static void main(String[] args) { Displayer displayer = new Displayer(); Line line = new Line(); line.addDirection(0, -1); line.addDirection(1, 0); SimuObject simuObjA = new Obj(Color.BLACK, line, displayer.getGridMap()); Location locationA = new Location(0, 0); simuObjA.moveTo(locationA); displayer.addObjectAt(simuObjA, locationA); SimuObject simuObjB = new Obj(Color.BLUE, new Rectangle(), displayer.getGridMap()); Location locationB = new Location(49, 29); simuObjB.moveTo(locationB); displayer.addObjectAt(simuObjB, locationB); SimuObject simuObjC = new Obj(Color.RED, new Oval(), displayer.getGridMap()); Location locationC = new Location(49, 29); simuObjC.moveTo(locationC); displayer.addObjectAt(simuObjC, locationC); simuObjA.moveTo(new Location(10, 10)); displayer.display(); } } class Obj extends SimuObject {
public Obj(Color color, Painter painter, GridMap gridMap) {
0
2023-12-23 13:51:12+00:00
8k
bmarwell/sipper
impl/src/main/java/io/github/bmarwell/sipper/impl/proto/SipMessageFactory.java
[ { "identifier": "SipConfiguration", "path": "api/src/main/java/io/github/bmarwell/sipper/api/SipConfiguration.java", "snippet": "@Value.Immutable\[email protected](jdkOnly = true, stagedBuilder = true)\npublic interface SipConfiguration {\n\n /**\n * Registrar is the domain of your SIP endpoint.\n *\n * <p>Typical values:</p>\n * <ul>\n * <li>{@code tel.t-online.de} (Deutsche Telekom)</li>\n * <li>{@code sip.kabelfon.vodafone.de} (Vodafone Cable)</li>\n * </ul>\n *\n * <p>You can check whether you have a valid registrar by executing:\n * {@code dig +short SRV _sip._udp.${domain}}.</p>\n *\n * @return the address of the registrar.\n */\n String getRegistrar();\n\n /**\n * The ID of your SIP account, which is usually the phone number in a specific format.\n *\n * <p>Typical values:</p>\n * <ul>\n * <li>{@code 012345678901} (Deutsche Telekom)</li>\n * <li>{@code +4912345678901} (Vodafone Cable)</li>\n * </ul>\n *\n * @return the SIP ID, which should usually correspond to a correctly formatted phone number.\n */\n String getSipId();\n\n @Value.Default\n default Duration getConnectTimeout() {\n return Duration.ofMillis(2_000L);\n }\n\n /**\n * The user to be used for Login. Depending on your provider, this could be the same\n * as the phone number, or your email-address or anything else.\n *\n * <p>Typical values:</p>\n * <ul>\n * <li>{@code login email address} (Deutsche Telekom)</li>\n * <li>{@code +4912345678901} (Vodafone Cable)</li>\n * </ul>\n *\n * @return the login user ID for authorization and authentication.\n */\n String getLoginUserId();\n\n String getLoginPassword();\n\n @Value.Default\n default Duration getReadTimeout() {\n return Duration.ofMillis(2_000);\n }\n}" }, { "identifier": "ConnectedSipConnection", "path": "impl/src/main/java/io/github/bmarwell/sipper/impl/internal/ConnectedSipConnection.java", "snippet": "public class ConnectedSipConnection implements SipConnection {\n\n private static final Logger LOG = LoggerFactory.getLogger(ConnectedSipConnection.class);\n\n private final AtomicLong cseq = new AtomicLong(10);\n\n private final Socket socket;\n\n private final SocketInConnectionReader inReader;\n\n private final BufferedOutputStream out;\n private final PrintWriter outWriter;\n private final ReentrantLock outWriterLock = new ReentrantLock();\n\n private final ExecutorService executorService;\n private final Future<?> inReaderThread;\n private final String tag;\n private final String callId;\n private final String registrar;\n private final String sipId;\n\n private InetAddress publicIp;\n private String authorizationString;\n\n public ConnectedSipConnection(\n Socket socket,\n BufferedOutputStream out,\n SocketInConnectionReader inReader,\n String registrar,\n String sipId,\n String tag,\n String callId,\n InetAddress publicIp) {\n this.socket = socket;\n this.out = out;\n this.outWriter = new PrintWriter(out, false, StandardCharsets.UTF_8);\n this.inReader = inReader;\n this.executorService = Executors.newVirtualThreadPerTaskExecutor();\n this.inReaderThread = this.executorService.submit(inReader);\n\n this.registrar = registrar;\n this.sipId = sipId;\n this.tag = tag;\n this.callId = callId;\n this.publicIp = publicIp;\n }\n\n @Override\n public void listen(SipEventHandler sipEventHandler) {\n // TODO: implement\n throw new UnsupportedOperationException(\n \"not yet implemented: [io.github.bmarwell.sipper.impl.internal.ConnectedSipConnection::listen].\");\n }\n\n @Override\n public boolean isConnected() {\n return this.socket.isConnected();\n }\n\n @Override\n public boolean isRegistered() {\n return false;\n }\n\n @Override\n public InetAddress getPublicIp() {\n return this.publicIp;\n }\n\n protected void writeAndFlush(String message) {\n this.outWriterLock.lock();\n try {\n LOG.trace(\"Writing message: [{}]\", message);\n this.outWriter.write(message);\n this.outWriter.flush();\n } finally {\n this.outWriterLock.unlock();\n }\n }\n\n @Override\n public void close() throws Exception {\n this.inReader.interrupt();\n this.inReaderThread.cancel(true);\n this.executorService.shutdownNow();\n\n try {\n this.executorService.awaitTermination(10, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ie) {\n // ignore on close\n }\n\n this.socket.close();\n }\n\n public long getAndUpdateCseq() {\n return this.cseq.getAndUpdate(operand -> operand + 1L);\n }\n\n public String getRegistrar() {\n return this.registrar;\n }\n\n public String getSipId() {\n return this.sipId;\n }\n\n public Socket getSocket() {\n return this.socket;\n }\n\n public String getTag() {\n return tag;\n }\n\n public String getCallId() {\n return callId;\n }\n\n public Optional<String> getAuthorization() {\n return Optional.ofNullable(this.authorizationString);\n }\n\n public void setAuthorizationString(String authorizationString) {\n this.authorizationString = authorizationString;\n }\n\n protected BufferedOutputStream getOut() {\n return this.out;\n }\n\n protected SocketInConnectionReader getInReader() {\n return inReader;\n }\n\n protected PrintWriter getOutWriter() {\n return outWriter;\n }\n\n @Override\n public String toString() {\n return new StringJoiner(\", \", ConnectedSipConnection.class.getSimpleName() + \"[\", \"]\")\n .add(\"socket=\" + socket)\n .add(\"inReader=\" + inReader)\n .add(\"out=\" + out)\n .add(\"outWriter=\" + outWriter)\n .add(\"executorService=\" + executorService)\n .add(\"inReaderThread=\" + inReaderThread)\n .toString();\n }\n}" }, { "identifier": "DefaultRegisteredSipConnection", "path": "impl/src/main/java/io/github/bmarwell/sipper/impl/internal/DefaultRegisteredSipConnection.java", "snippet": "public class DefaultRegisteredSipConnection implements RegisteredSipConnection {\n\n private final ConnectedSipConnection sipConnection;\n private boolean closedByHook;\n private boolean registered;\n\n private final Thread shutdownHook;\n\n public DefaultRegisteredSipConnection(ConnectedSipConnection sipConnection) {\n this.sipConnection = sipConnection;\n this.registered = true;\n this.shutdownHook = new Thread(() -> {\n try {\n this.closedByHook = true;\n this.close();\n } catch (Exception e) {\n // ignore on shutdown\n }\n });\n Runtime.getRuntime().addShutdownHook(this.shutdownHook);\n }\n\n @Override\n public void listen(SipEventHandler sipEventHandler) {\n this.sipConnection.listen(sipEventHandler);\n }\n\n @Override\n public boolean isConnected() {\n return this.sipConnection.isConnected();\n }\n\n @Override\n public boolean isRegistered() {\n return this.registered;\n }\n\n @Override\n public InetAddress getPublicIp() {\n return this.sipConnection.getPublicIp();\n }\n\n @Override\n public void close() throws Exception {\n if (!closedByHook) {\n try {\n Runtime.getRuntime().removeShutdownHook(this.shutdownHook);\n } catch (IllegalStateException ise) {\n // no worries.\n }\n }\n this.registered = false;\n final var unregister = new SipMessageFactory(this.sipConnection.getRegistrar(), this.sipConnection.getSipId())\n .getUnregister(this);\n this.sipConnection.writeAndFlush(unregister);\n\n // short amount of time of judiciously waiting for a response, as we don't want to unnecessarily lengthen the\n // shutdown.\n try {\n Thread.sleep(100);\n } catch (InterruptedException ie) {\n // ignore on shutdown\n }\n\n this.sipConnection.close();\n }\n\n public Socket getSocket() {\n return this.sipConnection.getSocket();\n }\n\n public String getTag() {\n return this.sipConnection.getTag();\n }\n\n public String getCallId() {\n return this.sipConnection.getCallId();\n }\n\n public long getAndUpdateCseq() {\n return this.sipConnection.getAndUpdateCseq();\n }\n\n public Optional<String> getAuthorization() {\n return this.sipConnection.getAuthorization();\n }\n}" } ]
import io.github.bmarwell.sipper.api.SipConfiguration; import io.github.bmarwell.sipper.impl.internal.ConnectedSipConnection; import io.github.bmarwell.sipper.impl.internal.DefaultRegisteredSipConnection; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.HexFormat; import java.util.Locale; import java.util.random.RandomGeneratorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
4,065
final var cnonceBytes = new byte[12]; RandomGeneratorFactory.getDefault().create().nextBytes(cnonceBytes); final var cnonce = base64enc.encodeToString(cnonceBytes); try { // hash1: base64(md5(user:realm:pw)) final var h1md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash1Contents = (loginUserId + ":" + sipAuthenticationRequest.realm() + ":" + loginPassword) .getBytes(StandardCharsets.UTF_8); final var hash1 = base64enc.encodeToString(h1md5.digest(hash1Contents)); // hash2: base64(md5(sipmethod:uri)) final var h2md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash2Contents = ("REGISTER:" + uri).getBytes(StandardCharsets.UTF_8); final var hash2 = base64enc.encodeToString(h2md5.digest(hash2Contents)); // hash3: base64(md5(hash1:nonce:nc:cnonce:qop:hash2)) final var h3md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var h3Contents = (hash1 + ":" + sipAuthenticationRequest.nonce() + ":" + ncHex + ":" + cnonce + ":" + qop + ":" + hash2) .getBytes(StandardCharsets.UTF_8); final var hashResponse = base64enc.encodeToString(h3md5.digest(h3Contents)); return new AuthorizationResponse(hashResponse, cnonce); } catch (NoSuchAlgorithmException nsae) { LOG.error("Problem with login algorithm", nsae); throw new IllegalArgumentException( "Problem with login algorithm: " + sipAuthenticationRequest.algorithm(), nsae); } } public LoginRequest getLogin( SipAuthenticationRequest sipAuthenticationRequest, ConnectedSipConnection sipConnection, String loginUserId, String loginPassword) { final var qop = "auth"; final var nc = 1L; final var ncHex = HexFormat.of().toHexDigits(nc, 8); final var authorizationResponse = getAuthorizationString(sipAuthenticationRequest, this.registrar, nc, qop, loginUserId, loginPassword); final var authValue = String.format( Locale.ROOT, "Digest realm=\"%1$s\", nonce=\"%2$s\", algorithm=%3$s, username=\"%4$s\", uri=\"sip:%5$s\", response=\"%6$s\", cnonce=\"%8$s\", nc=%8$s, qop=%9$s", // 1 - realm sipAuthenticationRequest.realm(), // 2 - nonce sipAuthenticationRequest.nonce(), // 3 - algorithm sipAuthenticationRequest.algorithm(), // 4 - username loginUserId, // 5 - registrar this.registrar, // 6 - response (see #getAuthorizationString) authorizationResponse.response(), // 7 - client nonce authorizationResponse.clientNonce(), // 8 - nc ncHex, // 9 - qop qop // end ); String template = """ %1$s sip:%2$s SIP/2.0 Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s CSeq: %9$s %1$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp> Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 Authorization: %10$s """; final var register = String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq(), // 10 - authValue authValue // end ); return new LoginRequest(register, authValue); }
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl.proto; public class SipMessageFactory { private static final Logger LOG = LoggerFactory.getLogger(SipMessageFactory.class); private final String registrar; private final String sipId; public SipMessageFactory(SipConfiguration conf) { this.registrar = conf.getRegistrar(); this.sipId = conf.getSipId(); } public SipMessageFactory(String registrar, String sipId) { this.registrar = registrar; this.sipId = sipId; } public String getRegisterPreflight(ConnectedSipConnection sipConnection) { final var template = """ %1$s sip:%2$s SIP/2.0 CSeq: %9$s %1$s Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp>;q=1 Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 """; return String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq()); } private AuthorizationResponse getAuthorizationString( SipAuthenticationRequest sipAuthenticationRequest, String uri, long nc, String qop, String loginUserId, String loginPassword) { final var ncHex = HexFormat.of().toHexDigits(nc, 6); final var base64enc = Base64.getEncoder(); final var cnonceBytes = new byte[12]; RandomGeneratorFactory.getDefault().create().nextBytes(cnonceBytes); final var cnonce = base64enc.encodeToString(cnonceBytes); try { // hash1: base64(md5(user:realm:pw)) final var h1md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash1Contents = (loginUserId + ":" + sipAuthenticationRequest.realm() + ":" + loginPassword) .getBytes(StandardCharsets.UTF_8); final var hash1 = base64enc.encodeToString(h1md5.digest(hash1Contents)); // hash2: base64(md5(sipmethod:uri)) final var h2md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash2Contents = ("REGISTER:" + uri).getBytes(StandardCharsets.UTF_8); final var hash2 = base64enc.encodeToString(h2md5.digest(hash2Contents)); // hash3: base64(md5(hash1:nonce:nc:cnonce:qop:hash2)) final var h3md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var h3Contents = (hash1 + ":" + sipAuthenticationRequest.nonce() + ":" + ncHex + ":" + cnonce + ":" + qop + ":" + hash2) .getBytes(StandardCharsets.UTF_8); final var hashResponse = base64enc.encodeToString(h3md5.digest(h3Contents)); return new AuthorizationResponse(hashResponse, cnonce); } catch (NoSuchAlgorithmException nsae) { LOG.error("Problem with login algorithm", nsae); throw new IllegalArgumentException( "Problem with login algorithm: " + sipAuthenticationRequest.algorithm(), nsae); } } public LoginRequest getLogin( SipAuthenticationRequest sipAuthenticationRequest, ConnectedSipConnection sipConnection, String loginUserId, String loginPassword) { final var qop = "auth"; final var nc = 1L; final var ncHex = HexFormat.of().toHexDigits(nc, 8); final var authorizationResponse = getAuthorizationString(sipAuthenticationRequest, this.registrar, nc, qop, loginUserId, loginPassword); final var authValue = String.format( Locale.ROOT, "Digest realm=\"%1$s\", nonce=\"%2$s\", algorithm=%3$s, username=\"%4$s\", uri=\"sip:%5$s\", response=\"%6$s\", cnonce=\"%8$s\", nc=%8$s, qop=%9$s", // 1 - realm sipAuthenticationRequest.realm(), // 2 - nonce sipAuthenticationRequest.nonce(), // 3 - algorithm sipAuthenticationRequest.algorithm(), // 4 - username loginUserId, // 5 - registrar this.registrar, // 6 - response (see #getAuthorizationString) authorizationResponse.response(), // 7 - client nonce authorizationResponse.clientNonce(), // 8 - nc ncHex, // 9 - qop qop // end ); String template = """ %1$s sip:%2$s SIP/2.0 Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s CSeq: %9$s %1$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp> Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 Authorization: %10$s """; final var register = String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq(), // 10 - authValue authValue // end ); return new LoginRequest(register, authValue); }
public String getUnregister(DefaultRegisteredSipConnection registeredSipConnection) {
2
2023-12-28 13:13:07+00:00
8k
HChenX/HideCleanUp
app/src/main/java/com/hchen/hidecleanup/HookMain.java
[ { "identifier": "HideCleanUp", "path": "app/src/main/java/com/hchen/hidecleanup/hideCleanUp/HideCleanUp.java", "snippet": "public class HideCleanUp extends Hook {\n\n @Override\n public void init() {\n hookAllMethods(\"com.miui.home.recents.views.RecentsContainer\",\n \"onFinishInflate\",\n new HookAction() {\n @Override\n protected void after(MethodHookParam param) throws Throwable {\n View mView = (View) getObjectField(param.thisObject, \"mClearAnimView\");\n mView.setVisibility(View.GONE);\n }\n }\n );\n }\n}" }, { "identifier": "Hook", "path": "app/src/main/java/com/hchen/hidecleanup/hook/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\n public void runHook(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n try {\n SetLoadPackageParam(loadPackageParam);\n init();\n logI(tag, \"Hook Done!\");\n } catch (Throwable s) {\n// logE(tag, \"Hook Failed: \" + e);\n }\n }\n\n public void SetLoadPackageParam(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n this.loadPackageParam = loadPackageParam;\n }\n\n public Class<?> findClass(String className) {\n return findClass(className, loadPackageParam.classLoader);\n }\n\n public Class<?> findClass(String className, ClassLoader classLoader) {\n return XposedHelpers.findClass(className, classLoader);\n }\n\n public Class<?> findClassIfExists(String className) {\n try {\n return findClass(className);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String newClassName, String oldClassName) {\n try {\n return findClass(findClassIfExists(newClassName) != null ? newClassName : oldClassName);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Find \" + newClassName + \" & \" + oldClassName + \" is null: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String className, ClassLoader classLoader) {\n try {\n return findClass(className, classLoader);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found 2: \" + e);\n return null;\n }\n }\n\n public abstract static class HookAction extends XC_MethodHook {\n\n protected void before(MethodHookParam param) throws Throwable {\n }\n\n protected void after(MethodHookParam param) throws Throwable {\n }\n\n public HookAction() {\n super();\n }\n\n public HookAction(int priority) {\n super(priority);\n }\n\n public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(result);\n }\n };\n }\n\n public static final HookAction DO_NOTHING = new HookAction(PRIORITY_HIGHEST * 2) {\n\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(null);\n }\n\n };\n\n @Override\n protected void beforeHookedMethod(MethodHookParam param) {\n try {\n before(param);\n } catch (Throwable e) {\n logE(\"before\", \"\" + e);\n }\n }\n\n @Override\n protected void afterHookedMethod(MethodHookParam param) {\n try {\n after(param);\n } catch (Throwable e) {\n logE(\"after\", \"\" + e);\n }\n }\n }\n\n public abstract static class ReplaceHookedMethod extends HookAction {\n\n public ReplaceHookedMethod() {\n super();\n }\n\n public ReplaceHookedMethod(int priority) {\n super(priority);\n }\n\n protected abstract Object replace(MethodHookParam param) throws Throwable;\n\n @Override\n public void beforeHookedMethod(MethodHookParam param) {\n try {\n Object result = replace(param);\n param.setResult(result);\n } catch (Throwable t) {\n logE(\"replace\", \"\" + t);\n }\n }\n }\n\n public void hookMethod(Method method, HookAction callback) {\n try {\n if (method == null) {\n logE(tag, \"method is null\");\n return;\n }\n XposedBridge.hookMethod(method, callback);\n logI(tag, \"Hook: \" + method);\n } catch (Throwable e) {\n logE(tag, \"Hook: \" + method);\n }\n }\n\n public void findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) {\n try {\n /*获取class*/\n if (parameterTypesAndCallback.length != 1) {\n Object[] newArray = new Object[parameterTypesAndCallback.length - 1];\n System.arraycopy(parameterTypesAndCallback, 0, newArray, 0, newArray.length);\n getDeclaredMethod(clazz, methodName, newArray);\n }\n XposedHelpers.findAndHookMethod(clazz, methodName, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz + \" method: \" + methodName);\n } catch (Throwable e) {\n logE(tag, \"Not find method: \" + methodName + \" in: \" + clazz);\n }\n }\n\n public void findAndHookMethod(String className, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className, classLoader), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookConstructor(Class<?> clazz, Object... parameterTypesAndCallback) {\n try {\n XposedHelpers.findAndHookConstructor(clazz, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz);\n } catch (Throwable f) {\n logE(tag, \"findAndHookConstructor: \" + f + \" class: \" + clazz);\n }\n }\n\n public void findAndHookConstructor(String className, Object... parameterTypesAndCallback) {\n findAndHookConstructor(findClassIfExists(className), parameterTypesAndCallback);\n }\n\n public void hookAllMethods(String className, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook The: \" + e);\n }\n }\n\n public void hookAllMethods(String className, ClassLoader classLoader, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className, classLoader);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + className + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllMethods(Class<?> hookClass, String methodName, HookAction callback) {\n try {\n int Num = XposedBridge.hookAllMethods(hookClass, methodName, callback).size();\n logI(tag, \"Hook: \" + hookClass + \" methodName: \" + methodName + \" Num is: \" + Num);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + hookClass.getSimpleName() + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllConstructors(String className, HookAction callback) {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public void hookAllConstructors(Class<?> hookClass, HookAction callback) {\n try {\n XposedBridge.hookAllConstructors(hookClass, callback);\n } catch (Throwable f) {\n logE(tag, \"hookAllConstructors: \" + f + \" class: \" + hookClass);\n }\n }\n\n public void hookAllConstructors(String className, ClassLoader classLoader, HookAction callback) {\n Class<?> hookClass = XposedHelpers.findClassIfExists(className, classLoader);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public Object callMethod(Object obj, String methodName, Object... args) throws Throwable {\n try {\n return XposedHelpers.callMethod(obj, methodName, args);\n } catch (Throwable e) {\n logE(tag, \"callMethod: \" + obj.toString() + \" method: \" + methodName + \" args: \" + Arrays.toString(args) + \" e: \" + e);\n throw new Throwable(tag + \": callMethod error\");\n }\n }\n\n public Object callStaticMethod(Class<?> clazz, String methodName, Object... args) {\n try {\n return XposedHelpers.callStaticMethod(clazz, methodName, args);\n } catch (Throwable throwable) {\n logE(tag, \"callStaticMethod e: \" + throwable);\n return null;\n }\n }\n\n public Method getDeclaredMethod(String className, String method, Object... type) throws NoSuchMethodException {\n return getDeclaredMethod(findClassIfExists(className), method, type);\n }\n\n public Method getDeclaredMethod(Class<?> clazz, String method, Object... type) throws NoSuchMethodException {\n// String tag = \"getDeclaredMethod\";\n ArrayList<Method> haveMethod = new ArrayList<>();\n Method hqMethod = null;\n int methodNum;\n if (clazz == null) {\n logE(tag, \"find class is null: \" + method);\n throw new NoSuchMethodException(\"find class is null\");\n }\n for (Method getMethod : clazz.getDeclaredMethods()) {\n if (getMethod.getName().equals(method)) {\n haveMethod.add(getMethod);\n }\n }\n if (haveMethod.isEmpty()) {\n logE(tag, \"find method is null: \" + method);\n throw new NoSuchMethodException(\"find method is null\");\n }\n methodNum = haveMethod.size();\n if (type != null) {\n Class<?>[] classes = new Class<?>[type.length];\n Class<?> newclass = null;\n Object getType;\n for (int i = 0; i < type.length; i++) {\n getType = type[i];\n if (getType instanceof Class<?>) {\n newclass = (Class<?>) getType;\n }\n if (getType instanceof String) {\n newclass = findClassIfExists((String) getType);\n if (newclass == null) {\n logE(tag, \"get class error: \" + i);\n throw new NoSuchMethodException(\"get class error\");\n }\n }\n classes[i] = newclass;\n }\n boolean noError = true;\n for (int i = 0; i < methodNum; i++) {\n hqMethod = haveMethod.get(i);\n boolean allHave = true;\n if (hqMethod.getParameterTypes().length != classes.length) {\n if (methodNum - 1 == i) {\n logE(tag, \"class length bad: \" + Arrays.toString(hqMethod.getParameterTypes()));\n throw new NoSuchMethodException(\"class length bad\");\n } else {\n noError = false;\n continue;\n }\n }\n for (int t = 0; t < hqMethod.getParameterTypes().length; t++) {\n Class<?> getClass = hqMethod.getParameterTypes()[t];\n if (!getClass.getSimpleName().equals(classes[t].getSimpleName())) {\n allHave = false;\n break;\n }\n }\n if (!allHave) {\n if (methodNum - 1 == i) {\n logE(tag, \"type bad: \" + Arrays.toString(hqMethod.getParameterTypes())\n + \" input: \" + Arrays.toString(classes));\n throw new NoSuchMethodException(\"type bad\");\n } else {\n noError = false;\n continue;\n }\n }\n if (noError) {\n break;\n }\n }\n return hqMethod;\n } else {\n if (methodNum > 1) {\n logE(tag, \"no type method must only have one: \" + haveMethod);\n throw new NoSuchMethodException(\"no type method must only have one\");\n }\n }\n return haveMethod.get(0);\n }\n\n public void getDeclaredField(XC_MethodHook.MethodHookParam param, String iNeedString, Object iNeedTo) {\n if (param != null) {\n try {\n Field setString = param.thisObject.getClass().getDeclaredField(iNeedString);\n setString.setAccessible(true);\n try {\n setString.set(param.thisObject, iNeedTo);\n Object result = setString.get(param.thisObject);\n checkLast(\"getDeclaredField\", iNeedString, iNeedTo, result);\n } catch (IllegalAccessException e) {\n logE(tag, \"IllegalAccessException to: \" + iNeedString + \" Need to: \" + iNeedTo + \" :\" + e);\n }\n } catch (NoSuchFieldException e) {\n logE(tag, \"No such the: \" + iNeedString + \" : \" + e);\n }\n } else {\n logE(tag, \"Param is null Code: \" + iNeedString + \" & \" + iNeedTo);\n }\n }\n\n public void checkLast(String setObject, Object fieldName, Object value, Object last) {\n if (value != null && last != null) {\n if (value == last || value.equals(last)) {\n logSI(tag, setObject + \" Success! set \" + fieldName + \" to \" + value);\n } else {\n logSE(tag, setObject + \" Failed! set \" + fieldName + \" to \" + value + \" hope: \" + value + \" but: \" + last);\n }\n } else {\n logSE(tag, setObject + \" Error value: \" + value + \" or last: \" + last + \" is null\");\n }\n }\n\n public Object getObjectField(Object obj, String fieldName) throws Throwable {\n try {\n return XposedHelpers.getObjectField(obj, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getObjectField: \" + obj.toString() + \" field: \" + fieldName);\n throw new Throwable(tag + \": getObjectField error\");\n }\n }\n\n public Object getStaticObjectField(Class<?> clazz, String fieldName) throws Throwable {\n try {\n return XposedHelpers.getStaticObjectField(clazz, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName);\n throw new Throwable(tag + \": getStaticObjectField error\");\n }\n }\n\n public void setStaticObjectField(Class<?> clazz, String fieldName, Object value) throws Throwable {\n try {\n XposedHelpers.setStaticObjectField(clazz, fieldName, value);\n } catch (Throwable e) {\n logE(tag, \"setStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName + \" value: \" + value);\n throw new Throwable(tag + \": setStaticObjectField error\");\n }\n }\n\n public void setInt(Object obj, String fieldName, int value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setIntField(obj, fieldName, value),\n () -> checkLast(\"setInt\", fieldName, value,\n XposedHelpers.getIntField(obj, fieldName)));\n }\n\n public void setBoolean(Object obj, String fieldName, boolean value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setBooleanField(obj, fieldName, value),\n () -> checkLast(\"setBoolean\", fieldName, value,\n XposedHelpers.getBooleanField(obj, fieldName)));\n }\n\n public void setObject(Object obj, String fieldName, Object value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setObjectField(obj, fieldName, value),\n () -> checkLast(\"setObject\", fieldName, value,\n XposedHelpers.getObjectField(obj, fieldName)));\n }\n\n public void checkDeclaredMethod(String className, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookClass.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n if (clazz != null) {\n clazz.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkAndHookField(Object obj, String fieldName, Runnable setField, Runnable checkLast) {\n try {\n obj.getClass().getDeclaredField(fieldName);\n setField.run();\n checkLast.run();\n } catch (Throwable e) {\n logE(tag, \"No such field: \" + fieldName + \" in param: \" + obj + \" : \" + e);\n }\n }\n\n public static Context findContext() {\n Context context;\n try {\n context = (Application) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\n \"android.app.ActivityThread\", null),\n \"currentApplication\");\n if (context == null) {\n Object currentActivityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.app.ActivityThread\",\n null),\n \"currentActivityThread\");\n if (currentActivityThread != null)\n context = (Context) XposedHelpers.callMethod(currentActivityThread,\n \"getSystemContext\");\n }\n return context;\n } catch (Throwable ignore) {\n }\n return null;\n }\n\n public static String getProp(String key, String defaultValue) {\n try {\n return (String) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"get\", key, defaultValue);\n } catch (Throwable throwable) {\n logE(\"getProp\", \"key get e: \" + key + \" will return default: \" + defaultValue + \" e:\" + throwable);\n return defaultValue;\n }\n }\n\n public static void setProp(String key, String val) {\n try {\n XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"set\", key, val);\n } catch (Throwable throwable) {\n logE(\"setProp\", \"set key e: \" + key + \" e:\" + throwable);\n }\n }\n\n}" } ]
import com.hchen.hidecleanup.hideCleanUp.HideCleanUp; import com.hchen.hidecleanup.hook.Hook; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
4,651
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) {
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) {
initHook(new HideCleanUp(), lpparam);
0
2023-12-24 13:57:39+00:00
8k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/gui/controllers/dropdown/EnumDropdownController.java
[ { "identifier": "Option", "path": "common/src/main/java/dev/tcl/api/Option.java", "snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n @NotNull Controller<T> controller();\n\n /**\n * Binding for the option.\n * Controls setting, getting and default value.\n *\n * @see Binding\n */\n @NotNull Binding<T> binding();\n\n /**\n * If the option can be configured\n */\n boolean available();\n\n /**\n * Sets if the option can be configured after being built\n *\n * @see Option#available()\n */\n void setAvailable(boolean available);\n\n /**\n * Tasks that needs to be executed upon applying changes.\n */\n @NotNull ImmutableSet<OptionFlag> flags();\n\n /**\n * Checks if the pending value is not equal to the current set value\n */\n boolean changed();\n\n /**\n * Value in the GUI, ready to set the actual bound value or be undone.\n */\n @NotNull T pendingValue();\n\n /**\n * Sets the pending value\n */\n void requestSet(@NotNull T value);\n\n /**\n * Applies the pending value to the bound value.\n * Cannot be undone.\n *\n * @return if there were changes to apply {@link Option#changed()}\n */\n boolean applyValue();\n\n /**\n * Sets the pending value to the bound value.\n */\n void forgetPendingValue();\n\n /**\n * Sets the pending value to the default bound value.\n */\n void requestSetDefault();\n\n /**\n * Checks if the current pending value is equal to its default value\n */\n boolean isPendingValueDefault();\n\n default boolean canResetToDefault() {\n return true;\n }\n\n /**\n * Adds a listener for when the pending value changes\n */\n void addListener(BiConsumer<Option<T>, T> changedListener);\n\n static <T> Builder<T> createBuilder() {\n return new OptionImpl.BuilderImpl<>();\n }\n\n interface Builder<T> {\n /**\n * Sets the name to be used by the option.\n *\n * @see Option#name()\n */\n Builder<T> name(@NotNull Component name);\n\n /**\n * Sets the description to be used by the option.\n * @see OptionDescription\n * @param description the static description.\n * @return this builder\n */\n Builder<T> description(@NotNull OptionDescription description);\n\n /**\n * Sets the function to get the description by the option's current value.\n *\n * @see OptionDescription\n * @param descriptionFunction the function to get the description by the option's current value.\n * @return this builder\n */\n Builder<T> description(@NotNull Function<T, OptionDescription> descriptionFunction);\n\n Builder<T> controller(@NotNull Function<Option<T>, ControllerBuilder<T>> controllerBuilder);\n\n /**\n * Sets the controller for the option.\n * This is how you interact and change the options.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n Builder<T> customController(@NotNull Function<Option<T>, Controller<T>> control);\n\n /**\n * Sets the binding for the option.\n * Used for default, getter and setter.\n *\n * @see Binding\n */\n Builder<T> binding(@NotNull Binding<T> binding);\n\n /**\n * Sets the binding for the option.\n * Shorthand of {@link Binding#generic(Object, Supplier, Consumer)}\n *\n * @param def default value of the option, used to reset\n * @param getter should return the current value of the option\n * @param setter should set the option to the supplied value\n * @see Binding\n */\n Builder<T> binding(@NotNull T def, @NotNull Supplier<@NotNull T> getter, @NotNull Consumer<@NotNull T> setter);\n\n /**\n * Sets if the option can be configured\n *\n * @see Option#available()\n */\n Builder<T> available(boolean available);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flag(@NotNull OptionFlag... flag);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flags(@NotNull Collection<? extends OptionFlag> flags);\n\n /**\n * Instantly invokes the binder's setter when modified in the GUI.\n * Prevents the user from undoing the change\n * <p>\n * Does not support {@link Option#flags()}!\n */\n Builder<T> instant(boolean instant);\n\n /**\n * Adds a listener to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listener(@NotNull BiConsumer<Option<T>, T> listener);\n\n /**\n * Adds multiple listeners to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listeners(@NotNull Collection<BiConsumer<Option<T>, T>> listeners);\n\n Option<T> build();\n }\n}" }, { "identifier": "Dimension", "path": "common/src/main/java/dev/tcl/api/utils/Dimension.java", "snippet": "public interface Dimension<T extends Number> {\n T x();\n T y();\n\n T width();\n T height();\n\n T xLimit();\n T yLimit();\n\n T centerX();\n T centerY();\n\n boolean isPointInside(T x, T y);\n\n MutableDimension<T> copy();\n\n Dimension<T> withX(T x);\n Dimension<T> withY(T y);\n Dimension<T> withWidth(T width);\n Dimension<T> withHeight(T height);\n\n Dimension<T> moved(T x, T y);\n Dimension<T> expanded(T width, T height);\n\n static MutableDimension<Integer> ofInt(int x, int y, int width, int height) {\n return new DimensionIntegerImpl(x, y, width, height);\n }\n}" }, { "identifier": "ValueFormatter", "path": "common/src/main/java/dev/tcl/api/controller/ValueFormatter.java", "snippet": "@FunctionalInterface\npublic interface ValueFormatter<T> extends Function<T, Component> {\n @NotNull Component format(@NotNull T value);\n\n @Override\n default @NotNull Component apply(@NotNull T t) {\n return format(t);\n }\n}" }, { "identifier": "AbstractWidget", "path": "common/src/main/java/dev/tcl/gui/AbstractWidget.java", "snippet": "@Environment(EnvType.CLIENT)\npublic abstract class AbstractWidget implements GuiEventListener, Renderable, NarratableEntry {\n private static final WidgetSprites SPRITES = new WidgetSprites(\n new ResourceLocation(\"widget/button\"), // normal\n new ResourceLocation(\"widget/button_disabled\"), // disabled & !focused\n new ResourceLocation(\"widget/button_highlighted\"), // !disabled & focused\n new ResourceLocation(\"widget/slider_highlighted\") // disabled & focused\n );\n\n protected final Minecraft client = Minecraft.getInstance();\n protected final Font textRenderer = client.font;\n protected final int inactiveColor = 0xFFA0A0A0;\n\n private dev.tcl.api.utils.Dimension<Integer> dim;\n\n public AbstractWidget(dev.tcl.api.utils.Dimension<Integer> dim) {\n this.dim = dim;\n }\n\n public boolean canReset() {\n return false;\n }\n\n @Override\n public boolean isMouseOver(double mouseX, double mouseY) {\n if (dim == null) return false;\n return this.dim.isPointInside((int) mouseX, (int) mouseY);\n }\n\n public void setDimension(dev.tcl.api.utils.Dimension<Integer> dim) {\n this.dim = dim;\n }\n\n public Dimension<Integer> getDimension() {\n return dim;\n }\n\n @Override\n public @NotNull NarrationPriority narrationPriority() {\n return NarrationPriority.NONE;\n }\n\n public void unfocus() {\n\n }\n\n public boolean matchesSearch(String query) {\n return true;\n }\n\n @Override\n public void updateNarration(NarrationElementOutput builder) {\n\n }\n\n protected void drawButtonRect(GuiGraphics graphics, int x1, int y1, int x2, int y2, boolean hovered, boolean enabled) {\n if (x1 > x2) {\n int xx1 = x1;\n x1 = x2;\n x2 = xx1;\n }\n if (y1 > y2) {\n int yy1 = y1;\n y1 = y2;\n y2 = yy1;\n }\n int width = x2 - x1;\n int height = y2 - y1;\n\n graphics.blitSprite(SPRITES.get(enabled, hovered), x1, y1, width, height);\n }\n\n protected void drawOutline(GuiGraphics graphics, int x1, int y1, int x2, int y2, int width, int color) {\n graphics.fill(x1, y1, x2, y1 + width, color);\n graphics.fill(x2, y1, x2 - width, y2, color);\n graphics.fill(x1, y2, x2, y2 - width, color);\n graphics.fill(x1, y1, x1 + width, y2, color);\n }\n\n protected int multiplyColor(int hex, float amount) {\n Color color = new Color(hex, true);\n\n return new Color(Math.max((int)(color.getRed() * amount), 0),\n Math.max((int)(color.getGreen() * amount), 0),\n Math.max((int)(color.getBlue() * amount), 0),\n color.getAlpha()).getRGB();\n }\n\n public void playDownSound() {\n Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));\n }\n}" }, { "identifier": "TCLScreen", "path": "common/src/main/java/dev/tcl/gui/TCLScreen.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class TCLScreen extends Screen {\n public final TheConfigLib config;\n\n private final Screen parent;\n\n public final TabManager tabManager = new TabManager(this::addRenderableWidget, this::removeWidget);\n public TabNavigationBar tabNavigationBar;\n public ScreenRectangle tabArea;\n\n public Component saveButtonMessage;\n public Tooltip saveButtonTooltipMessage;\n private int saveButtonMessageTime;\n\n private boolean pendingChanges;\n\n public TCLScreen(TheConfigLib config, Screen parent) {\n super(config.title());\n this.config = config;\n this.parent = parent;\n\n OptionUtils.forEachOptions(config, option -> {\n option.addListener((opt, val) -> onOptionsChanged());\n });\n }\n\n @Override\n protected void init() {\n int currentTab = tabNavigationBar != null\n ? tabNavigationBar.tabs.indexOf(tabManager.getCurrentTab())\n : 0;\n if (currentTab == -1)\n currentTab = 0;\n\n tabNavigationBar = new ScrollableNavigationBar(this.width, tabManager, config.categories()\n .stream()\n .map(category -> {\n if (category instanceof PlaceholderCategory placeholder)\n return new PlaceholderTab(placeholder);\n return new CategoryTab(category);\n }).toList());\n tabNavigationBar.selectTab(currentTab, false);\n tabNavigationBar.arrangeElements();\n ScreenRectangle navBarArea = tabNavigationBar.getRectangle();\n tabArea = new ScreenRectangle(0, navBarArea.height() - 1, this.width, this.height - navBarArea.height() + 1);\n tabManager.setTabArea(tabArea);\n addRenderableWidget(tabNavigationBar);\n\n config.initConsumer().accept(this);\n }\n\n @Override\n public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) {\n renderDirtBackground(graphics);\n super.render(graphics, mouseX, mouseY, delta);\n }\n\n protected void finishOrSave() {\n saveButtonMessage = null;\n\n if (pendingChanges()) {\n Set<OptionFlag> flags = new HashSet<>();\n OptionUtils.forEachOptions(config, option -> {\n if (option.applyValue()) {\n flags.addAll(option.flags());\n }\n });\n OptionUtils.forEachOptions(config, option -> {\n if (option.changed()) {\n // if still changed after applying, reset to the current value from binding\n // as something has gone wrong.\n option.forgetPendingValue();\n TheConfigLib.LOGGER.error(\"Option '{}' value mismatch after applying! Reset to binding's getter.\", option.name().getString());\n }\n });\n config.saveFunction().run();\n onOptionsChanged();\n flags.forEach(flag -> flag.accept(minecraft));\n } else onClose();\n }\n\n protected void cancelOrReset() {\n if (pendingChanges()) { // if pending changes, button acts as a cancel button\n OptionUtils.forEachOptions(config, Option::forgetPendingValue);\n onClose();\n } else { // if not, button acts as a reset button\n OptionUtils.forEachOptions(config, Option::requestSetDefault);\n }\n }\n\n protected void undo() {\n OptionUtils.forEachOptions(config, Option::forgetPendingValue);\n }\n\n @Override\n public void tick() {\n if (tabManager.getCurrentTab() instanceof TabExt tabExt) {\n tabExt.tick();\n }\n\n if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) {\n if (saveButtonMessage != null) {\n if (saveButtonMessageTime > 140) {\n saveButtonMessage = null;\n saveButtonTooltipMessage = null;\n saveButtonMessageTime = 0;\n } else {\n saveButtonMessageTime++;\n categoryTab.saveFinishedButton.setMessage(saveButtonMessage);\n if (saveButtonTooltipMessage != null) {\n categoryTab.saveFinishedButton.setTooltip(saveButtonTooltipMessage);\n }\n }\n }\n }\n }\n\n private void setSaveButtonMessage(Component message, Component tooltip) {\n saveButtonMessage = message;\n saveButtonTooltipMessage = Tooltip.create(tooltip);\n saveButtonMessageTime = 0;\n }\n\n private boolean pendingChanges() {\n return pendingChanges;\n }\n\n private void onOptionsChanged() {\n pendingChanges = false;\n\n OptionUtils.consumeOptions(config, opt -> {\n pendingChanges |= opt.changed();\n return pendingChanges;\n });\n\n if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) {\n categoryTab.updateButtons();\n }\n }\n\n @Override\n public boolean shouldCloseOnEsc() {\n if (pendingChanges()) {\n setSaveButtonMessage(Component.translatable(\"tcl.gui.save_before_exit\").withStyle(ChatFormatting.RED), Component.translatable(\"tcl.gui.save_before_exit.tooltip\"));\n return false;\n }\n return true;\n }\n\n @Override\n public void onClose() {\n minecraft.setScreen(parent);\n }\n\n public static void renderMultilineTooltip(GuiGraphics graphics, Font font, MultiLineLabel text, int centerX, int yAbove, int yBelow, int screenWidth, int screenHeight) {\n if (text.getLineCount() > 0) {\n int maxWidth = text.getWidth();\n int lineHeight = font.lineHeight + 1;\n int height = text.getLineCount() * lineHeight - 1;\n\n int belowY = yBelow + 12;\n int aboveY = yAbove - height + 12;\n int maxBelow = screenHeight - (belowY + height);\n int minAbove = aboveY - height;\n int y = aboveY;\n if (minAbove < 8)\n y = maxBelow > minAbove ? belowY : aboveY;\n\n int x = Math.max(centerX - text.getWidth() / 2 - 12, -6);\n\n int drawX = x + 12;\n int drawY = y - 12;\n\n graphics.pose().pushPose();\n Tesselator tesselator = Tesselator.getInstance();\n BufferBuilder bufferBuilder = tesselator.getBuilder();\n RenderSystem.setShader(GameRenderer::getPositionColorShader);\n bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);\n TooltipRenderUtil.renderTooltipBackground(\n graphics,\n drawX,\n drawY,\n maxWidth,\n height,\n 400\n );\n RenderSystem.enableDepthTest();\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n BufferUploader.drawWithShader(bufferBuilder.end());\n RenderSystem.disableBlend();\n graphics.pose().translate(0.0, 0.0, 400.0);\n\n text.renderLeftAligned(graphics, drawX, drawY, lineHeight, -1);\n\n graphics.pose().popPose();\n }\n }\n\n public class CategoryTab implements TabExt {\n private final ConfigCategory category;\n private final Tooltip tooltip;\n\n private ListHolderWidget<OptionListWidget> optionList;\n public final Button saveFinishedButton;\n private final Button cancelResetButton;\n private final Button undoButton;\n private final SearchFieldWidget searchField;\n private OptionDescriptionWidget descriptionWidget;\n\n public CategoryTab(ConfigCategory category) {\n this.category = category;\n this.tooltip = Tooltip.create(category.tooltip());\n\n int columnWidth = width / 3;\n int padding = columnWidth / 20;\n columnWidth = Math.min(columnWidth, 400);\n int paddedWidth = columnWidth - padding * 2;\n MutableDimension<Integer> actionDim = Dimension.ofInt(width / 3 * 2 + width / 6, height - padding - 20, paddedWidth, 20);\n\n saveFinishedButton = Button.builder(Component.literal(\"Done\"), btn -> finishOrSave())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .build();\n\n actionDim.expand(-actionDim.width() / 2 - 2, 0).move(-actionDim.width() / 2 - 2, -22);\n cancelResetButton = Button.builder(Component.literal(\"Cancel\"), btn -> cancelOrReset())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .build();\n\n actionDim.move(actionDim.width() + 4, 0);\n undoButton = Button.builder(Component.translatable(\"tcl.gui.undo\"), btn -> undo())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .tooltip(Tooltip.create(Component.translatable(\"tcl.gui.undo.tooltip\")))\n .build();\n\n searchField = new SearchFieldWidget(\n font,\n width / 3 * 2 + width / 6 - paddedWidth / 2 + 1,\n undoButton.getY() - 22,\n paddedWidth - 2, 18,\n Component.translatable(\"gui.recipebook.search_hint\"),\n Component.translatable(\"gui.recipebook.search_hint\"),\n searchQuery -> optionList.getList().updateSearchQuery(searchQuery)\n );\n\n this.optionList = new ListHolderWidget<>(\n () -> new ScreenRectangle(tabArea.position(), tabArea.width() / 3 * 2 + 1, tabArea.height()),\n new OptionListWidget(TCLScreen.this, category, minecraft, 0, 0, width / 3 * 2 + 1, height, desc -> {\n descriptionWidget.setOptionDescription(desc);\n })\n );\n\n descriptionWidget = new OptionDescriptionWidget(\n () -> new ScreenRectangle(\n width / 3 * 2 + padding,\n tabArea.top() + padding,\n paddedWidth,\n searchField.getY() - 1 - tabArea.top() - padding * 2\n ),\n null\n );\n\n updateButtons();\n }\n\n @Override\n public @NotNull Component getTabTitle() {\n return category.name();\n }\n\n @Override\n public void visitChildren(Consumer<AbstractWidget> consumer) {\n consumer.accept(optionList);\n consumer.accept(saveFinishedButton);\n consumer.accept(cancelResetButton);\n consumer.accept(undoButton);\n consumer.accept(searchField);\n consumer.accept(descriptionWidget);\n }\n\n @Override\n public void doLayout(ScreenRectangle screenRectangle) {\n\n }\n\n @Override\n public void tick() {\n descriptionWidget.tick();\n }\n\n @Nullable\n @Override\n public Tooltip getTooltip() {\n return tooltip;\n }\n\n public void updateButtons() {\n boolean pendingChanges = pendingChanges();\n\n undoButton.active = pendingChanges;\n saveFinishedButton.setMessage(pendingChanges ? Component.translatable(\"tcl.gui.save\") : GuiUtils.translatableFallback(\"tcl.gui.done\", CommonComponents.GUI_DONE));\n saveFinishedButton.setTooltip(new TCLTooltip(pendingChanges ? Component.translatable(\"tcl.gui.save.tooltip\") : Component.translatable(\"tcl.gui.finished.tooltip\"), saveFinishedButton));\n cancelResetButton.setMessage(pendingChanges ? GuiUtils.translatableFallback(\"tcl.gui.cancel\", CommonComponents.GUI_CANCEL) : Component.translatable(\"controls.reset\"));\n cancelResetButton.setTooltip(new TCLTooltip(pendingChanges ? Component.translatable(\"tcl.gui.cancel.tooltip\") : Component.translatable(\"tcl.gui.reset.tooltip\"), cancelResetButton));\n }\n }\n\n public class PlaceholderTab implements TabExt {\n private final PlaceholderCategory category;\n private final Tooltip tooltip;\n\n public PlaceholderTab(PlaceholderCategory category) {\n this.category = category;\n this.tooltip = Tooltip.create(category.tooltip());\n }\n\n @Override\n public @NotNull Component getTabTitle() {\n return category.name();\n }\n\n @Override\n public void visitChildren(Consumer<AbstractWidget> consumer) {\n\n }\n\n @Override\n public void doLayout(ScreenRectangle screenRectangle) {\n minecraft.setScreen(category.screen().apply(minecraft, TCLScreen.this));\n }\n\n @Override\n public @Nullable Tooltip getTooltip() {\n return this.tooltip;\n }\n }\n}" } ]
import dev.tcl.api.Option; import dev.tcl.api.utils.Dimension; import dev.tcl.api.controller.ValueFormatter; import dev.tcl.gui.AbstractWidget; import dev.tcl.gui.TCLScreen; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream;
6,111
package dev.tcl.gui.controllers.dropdown; public class EnumDropdownController<E extends Enum<E>> extends AbstractDropdownController<E> { /** * The function used to convert enum constants to strings used for display, suggestion, and validation. Defaults to {@link Enum#toString}. */ protected final ValueFormatter<E> formatter; public EnumDropdownController(Option<E> option, ValueFormatter<E> formatter, Collection<? extends E> values) { super(option, (values == null ? Arrays.stream(option.pendingValue().getDeclaringClass().getEnumConstants()) : values.stream()).map(formatter::format).map(Component::getString).toList()); this.formatter = formatter; } @Override public String getString() { return formatter.format(option().pendingValue()).getString(); } @Override public void setFromString(String value) { option().requestSet(getEnumFromString(value)); } /** * Searches through enum constants for one whose {@link #formatter} result equals {@code value} * * @return The enum constant associated with the {@code value} or the pending value if none are found * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ private E getEnumFromString(String value) { value = value.toLowerCase(); for (E constant : option().pendingValue().getDeclaringClass().getEnumConstants()) { if (formatter.format(constant).getString().toLowerCase().equals(value)) return constant; } return option().pendingValue(); } @Override public boolean isValueValid(String value) { value = value.toLowerCase(); for (String constant : getAllowedValues()) { if (constant.equals(value)) return true; } return false; } @Override protected String getValidValue(String value, int offset) { return getValidEnumConstants(value) .skip(offset) .findFirst() .orElseGet(this::getString); } /** * Filters and sorts through enum constants for those whose {@link #formatter} result equals {@code value} * * @return a sorted stream containing enum constants associated with the {@code value} * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ @NotNull protected Stream<String> getValidEnumConstants(String value) { String valueLowerCase = value.toLowerCase(); return getAllowedValues().stream() .filter(constant -> constant.toLowerCase().contains(valueLowerCase)) .sorted((s1, s2) -> { String s1LowerCase = s1.toLowerCase(); String s2LowerCase = s2.toLowerCase(); if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; return s1.compareTo(s2); }); } @Override
package dev.tcl.gui.controllers.dropdown; public class EnumDropdownController<E extends Enum<E>> extends AbstractDropdownController<E> { /** * The function used to convert enum constants to strings used for display, suggestion, and validation. Defaults to {@link Enum#toString}. */ protected final ValueFormatter<E> formatter; public EnumDropdownController(Option<E> option, ValueFormatter<E> formatter, Collection<? extends E> values) { super(option, (values == null ? Arrays.stream(option.pendingValue().getDeclaringClass().getEnumConstants()) : values.stream()).map(formatter::format).map(Component::getString).toList()); this.formatter = formatter; } @Override public String getString() { return formatter.format(option().pendingValue()).getString(); } @Override public void setFromString(String value) { option().requestSet(getEnumFromString(value)); } /** * Searches through enum constants for one whose {@link #formatter} result equals {@code value} * * @return The enum constant associated with the {@code value} or the pending value if none are found * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ private E getEnumFromString(String value) { value = value.toLowerCase(); for (E constant : option().pendingValue().getDeclaringClass().getEnumConstants()) { if (formatter.format(constant).getString().toLowerCase().equals(value)) return constant; } return option().pendingValue(); } @Override public boolean isValueValid(String value) { value = value.toLowerCase(); for (String constant : getAllowedValues()) { if (constant.equals(value)) return true; } return false; } @Override protected String getValidValue(String value, int offset) { return getValidEnumConstants(value) .skip(offset) .findFirst() .orElseGet(this::getString); } /** * Filters and sorts through enum constants for those whose {@link #formatter} result equals {@code value} * * @return a sorted stream containing enum constants associated with the {@code value} * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ @NotNull protected Stream<String> getValidEnumConstants(String value) { String valueLowerCase = value.toLowerCase(); return getAllowedValues().stream() .filter(constant -> constant.toLowerCase().contains(valueLowerCase)) .sorted((s1, s2) -> { String s1LowerCase = s1.toLowerCase(); String s2LowerCase = s2.toLowerCase(); if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; return s1.compareTo(s2); }); } @Override
public AbstractWidget provideWidget(TCLScreen screen, Dimension<Integer> widgetDimension) {
3
2023-12-25 14:48:27+00:00
8k
behnamnasehi/playsho
app/src/main/java/com/playsho/android/base/BaseActivity.java
[ { "identifier": "ActivityLauncher", "path": "app/src/main/java/com/playsho/android/component/ActivityLauncher.java", "snippet": "public class ActivityLauncher<Input, Result> {\n /**\n * Register activity result using a {@link ActivityResultContract} and an in-place activity result callback like\n * the default approach. You can still customise callback using {@link #launch(Object, OnActivityResult)}.\n */\n @NonNull\n public static <Input, Result> ActivityLauncher<Input, Result> registerForActivityResult(\n @NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract,\n @Nullable OnActivityResult<Result> onActivityResult) {\n return new ActivityLauncher<>(caller, contract, onActivityResult);\n }\n\n /**\n * Same as {@link #registerForActivityResult(ActivityResultCaller, ActivityResultContract, OnActivityResult)} except\n * the last argument is set to {@code null}.\n */\n @NonNull\n public static <Input, Result> ActivityLauncher<Input, Result> registerForActivityResult(\n @NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract) {\n return registerForActivityResult(caller, contract, null);\n }\n\n /**\n * Specialised method for launching new activities.\n */\n @NonNull\n public static ActivityLauncher<Intent, ActivityResult> registerActivityForResult(\n @NonNull ActivityResultCaller caller) {\n return registerForActivityResult(caller, new ActivityResultContracts.StartActivityForResult());\n }\n\n /**\n * Callback interface\n */\n public interface OnActivityResult<O> {\n /**\n * Called after receiving a result from the target activity\n */\n void onActivityResult(O result);\n }\n\n private final ActivityResultLauncher<Input> launcher;\n @Nullable\n private OnActivityResult<Result> onActivityResult;\n\n private ActivityLauncher(@NonNull ActivityResultCaller caller,\n @NonNull ActivityResultContract<Input, Result> contract,\n @Nullable OnActivityResult<Result> onActivityResult) {\n this.onActivityResult = onActivityResult;\n this.launcher = caller.registerForActivityResult(contract, this::callOnActivityResult);\n }\n\n public void setOnActivityResult(@Nullable OnActivityResult<Result> onActivityResult) {\n this.onActivityResult = onActivityResult;\n }\n\n /**\n * Launch activity, same as {@link ActivityResultLauncher#launch(Object)} except that it allows a callback\n * executed after receiving a result from the target activity.\n */\n public void launch(Input input, @Nullable OnActivityResult<Result> onActivityResult) {\n if (onActivityResult != null) {\n this.onActivityResult = onActivityResult;\n }\n launcher.launch(input);\n }\n\n /**\n * Same as {@link #launch(Object, OnActivityResult)} with last parameter set to {@code null}.\n */\n public void launch(Input input) {\n launch(input, this.onActivityResult);\n }\n\n private void callOnActivityResult(Result result) {\n if (onActivityResult != null) onActivityResult.onActivityResult(result);\n }\n}" }, { "identifier": "SessionStorage", "path": "app/src/main/java/com/playsho/android/db/SessionStorage.java", "snippet": "public class SessionStorage {\n private final SharedPreferences pref;\n private final SharedPreferences.Editor editor;\n\n // Name of the shared preference file\n private final String SHARED_PREFERENCE_NAME = \"main_sp\";\n\n /**\n * Constructs a SessionStorage instance and initializes SharedPreferences and its editor.\n */\n public SessionStorage() {\n this.pref = ApplicationLoader.getAppContext().getSharedPreferences(\n SHARED_PREFERENCE_NAME,\n Context.MODE_PRIVATE\n );\n editor = pref.edit();\n editor.apply();\n }\n\n /**\n * Clears all entries in the SharedPreferences.\n */\n public void clearAll(){\n pref.edit().clear().apply();\n }\n\n /**\n * Gets a String value from the SharedPreferences with the specified key.\n *\n * @param key The key for the String value.\n * @return The String value associated with the key, or {@code null} if not found.\n */\n public String getString(String key) {\n return pref.getString(key, null);\n }\n\n\n /**\n * Gets a String value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the String value.\n * @param defValue The default value to return if the key is not found.\n * @return The String value associated with the key, or the default value if not found.\n */\n public String getString(String key , String defValue) {\n return pref.getString(key, defValue);\n }\n\n /**\n * Sets a String value in the SharedPreferences with the specified key.\n *\n * @param key The key for the String value.\n * @param value The String value to set.\n */\n public void setString(String key, String value) {\n editor.putString(key, value);\n editor.apply();\n editor.commit();\n }\n\n /**\n * Gets an integer value from the SharedPreferences with the specified key.\n *\n * @param key The key for the integer value.\n * @return The integer value associated with the key, or 0 if not found.\n */\n public int getInteger(String key) {\n return pref.getInt(key, 0);\n }\n\n /**\n * Gets an integer value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the integer value.\n * @param defValue The default value to return if the key is not found.\n * @return The integer value associated with the key, or the default value if not found.\n */\n public int getInteger(String key , int defValue) {\n return pref.getInt(key, defValue);\n }\n\n /**\n * Sets an integer value in the SharedPreferences with the specified key.\n *\n * @param key The key for the integer value.\n * @param value The integer value to set.\n */\n public void setInteger(String key, int value) {\n editor.putInt(key, value);\n editor.apply();\n editor.commit();\n }\n\n\n /**\n * Deserializes a JSON string stored in SharedPreferences into an object of the specified class.\n *\n * @param key The key for the JSON string.\n * @param clazz The class type to deserialize the JSON into.\n * @param <T> The type of the class.\n * @return An object of the specified class, or a default object if the JSON is not found.\n */\n public <T> T deserialize(String key, Class<T> clazz) {\n String json = this.getString(key);\n if (Validator.isNullOrEmpty(json)) {\n json = \"{}\";\n }\n return ApplicationLoader.getGson().fromJson(json, clazz);\n }\n\n /**\n * Inserts a JSON-serializable object into SharedPreferences with the specified key.\n *\n * @param key The key for storing the JSON string.\n * @param o The object to be serialized and stored.\n */\n public void insertJson(String key, Object o) {\n this.editor.putString(key,ApplicationLoader.getGson().toJson(o));\n editor.apply();\n editor.commit();\n }\n\n\n /**\n * Gets a boolean value from the SharedPreferences with the specified key.\n *\n * @param key The key for the boolean value.\n * @return The boolean value associated with the key, or {@code false} if not found.\n */\n public boolean getBoolean(String key) {\n return pref.getBoolean(key, false);\n }\n\n /**\n * Gets a boolean value from the SharedPreferences with the specified key, providing a default value if not found.\n *\n * @param key The key for the boolean value.\n * @param defValue The default value to return if the key is not found.\n * @return The boolean value associated with the key, or the default value if not found.\n */\n public boolean getBoolean(String key, boolean defValue) {\n return pref.getBoolean(key, defValue);\n }\n\n /**\n * Sets a boolean value in the SharedPreferences with the specified key.\n *\n * @param key The key for the boolean value.\n * @param value The boolean value to set.\n */\n public void setBoolean(String key, boolean value) {\n editor.putBoolean(key, value);\n editor.apply();\n editor.commit();\n }\n\n}" }, { "identifier": "NetworkListener", "path": "app/src/main/java/com/playsho/android/utils/NetworkListener.java", "snippet": "public class NetworkListener extends ConnectivityManager.NetworkCallback {\n\n // ConnectivityManager instance for network monitoring\n private ConnectivityManager connectivityManager;\n\n // AtomicBoolean to ensure thread-safe access to network availability status\n private final AtomicBoolean isNetworkAvailable = new AtomicBoolean(false);\n\n /**\n * Initializes the NetworkListener by registering it with the ConnectivityManager.\n * This method should be called to start monitoring network changes.\n */\n public void init() {\n // Obtain ConnectivityManager from the application context\n connectivityManager = (ConnectivityManager) ApplicationLoader.getAppContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n\n // Register the NetworkListener to receive network status callbacks\n connectivityManager.registerDefaultNetworkCallback(this);\n }\n\n /**\n * Checks the current network availability status.\n *\n * @return True if the network is available, false otherwise.\n */\n public boolean checkNetworkAvailability() {\n // Obtain the currently active network\n Network network = connectivityManager.getActiveNetwork();\n\n if (network == null) {\n // No active network, set availability to false\n isNetworkAvailable.set(false);\n return isNetworkAvailable();\n }\n\n // Obtain the network capabilities of the active network\n NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);\n\n if (networkCapabilities == null) {\n // Network capabilities not available, set availability to false\n isNetworkAvailable.set(false);\n return isNetworkAvailable();\n }\n\n // Check if the network has any of the specified transport types (e.g., WiFi, Cellular)\n isNetworkAvailable.set(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)\n || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH));\n\n return isNetworkAvailable();\n }\n\n /**\n * Gets the real-time network availability status.\n *\n * @return True if the network is available, false otherwise.\n */\n public boolean isNetworkAvailable() {\n return isNetworkAvailable.get();\n }\n\n /**\n * Called when a network becomes available.\n *\n * @param network The Network object representing the available network.\n */\n @Override\n public void onAvailable(@NonNull Network network) {\n // Set network availability status to true\n isNetworkAvailable.set(true);\n }\n\n /**\n * Called when a network is lost or becomes unavailable.\n *\n * @param network The Network object representing the lost network.\n */\n @Override\n public void onLost(@NonNull Network network) {\n // Set network availability status to false\n isNetworkAvailable.set(false);\n }\n}" }, { "identifier": "SystemUtilities", "path": "app/src/main/java/com/playsho/android/utils/SystemUtilities.java", "snippet": "public class SystemUtilities {\n /**\n * Tag for logging purposes.\n */\n private static final String TAG = \"SystemUtils\";\n\n /**\n * Changes the color of status bar icons based on the specified mode.\n *\n * @param activity The activity where the status bar icons are changed.\n * @param isDark True if the status bar icons should be dark, false otherwise.\n */\n public static void changeStatusBarIconColor(Activity activity, boolean isDark) {\n View decorView = activity.getWindow().getDecorView();\n int flags = decorView.getSystemUiVisibility();\n if (!isDark) {\n // Make status bar icons dark (e.g., for light background)\n flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;\n } else {\n // Make status bar icons light (e.g., for dark background)\n flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;\n }\n decorView.setSystemUiVisibility(flags);\n }\n\n /**\n * Changes the background color of the status bar and adjusts the icon color.\n *\n * @param activity The activity where the status bar color is changed.\n * @param color The color resource ID for the status bar.\n * @param isDark True if the status bar icons should be dark, false otherwise.\n */\n public static void changeStatusBarBackgroundColor(Activity activity, int color, boolean isDark) {\n changeStatusBarIconColor(activity, isDark);\n activity.getWindow().setStatusBarColor(LocalController.getColor(color));\n }\n\n /**\n * Shares plain text through the available sharing options.\n *\n * @param context The context from which the sharing is initiated.\n * @param title The title of the shared content.\n * @param body The body or content to be shared.\n */\n public static void sharePlainText(Context context, String title, String body) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"text/plain\");\n intent.putExtra(Intent.EXTRA_SUBJECT, title);\n intent.putExtra(Intent.EXTRA_TEXT, body);\n context.startActivity(Intent.createChooser(intent, title));\n }\n\n /**\n * Initiates a phone call to the specified phone number.\n *\n * @param context The context from which the phone call is initiated.\n * @param phone The phone number to call.\n */\n public static void callPhoneNumber(Context context, String phone) {\n context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts(\"tel\", phone, null)));\n }\n\n /**\n * Vibrates the device for the specified duration.\n *\n * @param milisecond The duration of the vibration in milliseconds.\n */\n public static void doVibrate(int milisecond) {\n Vibrator v = (Vibrator) ApplicationLoader.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n Objects.requireNonNull(v).vibrate(VibrationEffect.createOneShot(milisecond, VibrationEffect.DEFAULT_AMPLITUDE));\n } else {\n Objects.requireNonNull(v).vibrate(milisecond);\n }\n }\n\n /**\n * Copies the specified text to the clipboard.\n *\n * @param label The label for the copied text.\n * @param text The text to be copied.\n */\n public static void copyToClipboard(String label, String text) {\n ClipboardManager clipboard = (ClipboardManager) ApplicationLoader.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);\n ClipData clip = ClipData.newPlainText(label, text);\n clipboard.setPrimaryClip(clip);\n }\n\n /**\n * Sets the navigation bar to have light icons on a light background.\n *\n * @param window The window for which the navigation bar color is set.\n * @param enable True if the light navigation bar should be enabled, false otherwise.\n */\n public static void setLightNavigationBar(Window window, boolean enable) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n final View decorView = window.getDecorView();\n int flags = decorView.getSystemUiVisibility();\n if (enable) {\n flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;\n } else {\n flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;\n }\n decorView.setSystemUiVisibility(flags);\n }\n }\n\n /**\n * Shows the soft keyboard for the specified view.\n *\n * @param view The view for which the soft keyboard is shown.\n */\n public static void showKeyboard(View view) {\n if (view == null) {\n return;\n }\n try {\n InputMethodManager inputManager = (InputMethodManager) ApplicationLoader.getAppContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);\n } catch (Exception ignored) {\n }\n }\n\n /**\n * Hides the soft keyboard for the specified view.\n *\n * @param view The view for which the soft keyboard is hidden.\n */\n public static void hideKeyboard(View view) {\n if (view == null) {\n return;\n }\n try {\n InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n if (!imm.isActive()) {\n return;\n }\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n } catch (Exception e) {\n Log.e(TAG, \"hideKeyboard: \", e);\n }\n }\n\n /**\n * Sets the navigation bar color to white for dialogs on API level 23 and above.\n *\n * @param dialog The dialog for which the navigation bar color is set to white.\n */\n public static void setWhiteNavigationBar(@NonNull Dialog dialog) {\n Window window = dialog.getWindow();\n if (window != null) {\n DisplayMetrics metrics = new DisplayMetrics();\n window.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n\n GradientDrawable dimDrawable = new GradientDrawable();\n\n GradientDrawable navigationBarDrawable = new GradientDrawable();\n navigationBarDrawable.setShape(GradientDrawable.RECTANGLE);\n navigationBarDrawable.setColor(Color.WHITE);\n\n Drawable[] layers = {dimDrawable, navigationBarDrawable};\n\n LayerDrawable windowBackground = new LayerDrawable(layers);\n windowBackground.setLayerInsetTop(1, metrics.heightPixels);\n\n window.setBackgroundDrawable(windowBackground);\n }\n }\n}" } ]
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResult; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import com.playsho.android.component.ActivityLauncher; import com.playsho.android.db.SessionStorage; import com.playsho.android.utils.NetworkListener; import com.playsho.android.utils.SystemUtilities;
4,880
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding; protected NetworkListener networkListener; // Activity launcher instance protected final ActivityLauncher<Intent, ActivityResult> activityLauncher = ActivityLauncher.registerActivityForResult(this); // Tag for logging protected String TAG = this.getClass().getSimpleName(); /** * Gets a String extra from the Intent. * * @param key The key of the extra. * @return The String extra value. */ protected String getIntentStringExtra(String key) { return getIntent().getStringExtra(key); } /** * Gets the name of the current activity. * * @return The name of the activity. */ protected String getClassName() { return this.getClass().getSimpleName(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); binding = DataBindingUtil.setContentView(this, getLayoutResourceId()); networkListener = new NetworkListener(); getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } @Override protected void onDestroy() { super.onDestroy(); onBackPressedCallback.remove(); } private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(isBackPressCallbackEnable) { @Override public void handleOnBackPressed() { // Call the abstract method for custom back press handling onBackPress(); } }; /** * Sets whether the custom back press callback is enabled or disabled. * * @param isBackPressCallbackEnable {@code true} to enable the callback, {@code false} to disable it. */ public void setBackPressedCallBackEnable(boolean isBackPressCallbackEnable) { this.isBackPressCallbackEnable = isBackPressCallbackEnable; } /** * Sets the status bar color using the SystemUtilities class. * * @param color The color resource ID. * @param isDark {@code true} if the status bar icons should be dark, {@code false} otherwise. */ protected void setStatusBarColor(@ColorRes int color, boolean isDark) {
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding; protected NetworkListener networkListener; // Activity launcher instance protected final ActivityLauncher<Intent, ActivityResult> activityLauncher = ActivityLauncher.registerActivityForResult(this); // Tag for logging protected String TAG = this.getClass().getSimpleName(); /** * Gets a String extra from the Intent. * * @param key The key of the extra. * @return The String extra value. */ protected String getIntentStringExtra(String key) { return getIntent().getStringExtra(key); } /** * Gets the name of the current activity. * * @return The name of the activity. */ protected String getClassName() { return this.getClass().getSimpleName(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); binding = DataBindingUtil.setContentView(this, getLayoutResourceId()); networkListener = new NetworkListener(); getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } @Override protected void onDestroy() { super.onDestroy(); onBackPressedCallback.remove(); } private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(isBackPressCallbackEnable) { @Override public void handleOnBackPressed() { // Call the abstract method for custom back press handling onBackPress(); } }; /** * Sets whether the custom back press callback is enabled or disabled. * * @param isBackPressCallbackEnable {@code true} to enable the callback, {@code false} to disable it. */ public void setBackPressedCallBackEnable(boolean isBackPressCallbackEnable) { this.isBackPressCallbackEnable = isBackPressCallbackEnable; } /** * Sets the status bar color using the SystemUtilities class. * * @param color The color resource ID. * @param isDark {@code true} if the status bar icons should be dark, {@code false} otherwise. */ protected void setStatusBarColor(@ColorRes int color, boolean isDark) {
SystemUtilities.changeStatusBarBackgroundColor(activity(), color, isDark);
3
2023-12-26 08:14:29+00:00
8k
lunasaw/voglander
voglander-service/src/main/java/io/github/lunasaw/voglander/service/login/DeviceRegisterServiceImpl.java
[ { "identifier": "DeviceChannelReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceChannelReq.java", "snippet": "@Data\npublic class DeviceChannelReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 通道Id\n */\n private String channelId;\n\n /**\n * 通道信息\n */\n private String channelInfo;\n\n /**\n * 通道名称\n */\n private String channelName;\n}" }, { "identifier": "DeviceInfoReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceInfoReq.java", "snippet": "@Data\npublic class DeviceInfoReq {\n\n private String deviceId;\n\n private String deviceInfo;\n}" }, { "identifier": "DeviceQueryReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceQueryReq.java", "snippet": "@Data\npublic class DeviceQueryReq {\n\n private String deviceId;\n\n}" }, { "identifier": "DeviceReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceReq.java", "snippet": "@Data\npublic class DeviceReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 注册时间\n */\n private Date registerTime;\n\n /**\n * 注册过期时间\n */\n private Integer expire;\n\n /**\n * 注册协议\n */\n private String transport;\n\n /**\n * 设备注册地址当前IP\n */\n private String localIp;\n\n /**\n * nat转换后看到的IP\n */\n private String remoteIp;\n\n /**\n * 经过rpotocol转换后的端口\n */\n private Integer remotePort;\n\n /**\n * 协议类型 {@link DeviceAgreementEnum}\n */\n private Integer type;\n\n}" }, { "identifier": "DeviceCommandService", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/service/DeviceCommandService.java", "snippet": "public interface DeviceCommandService {\n\n /**\n * 通道查询\n *\n * @param deviceQueryReq\n */\n void queryChannel(DeviceQueryReq deviceQueryReq);\n\n /**\n * 设备查询\n *\n * @param deviceQueryReq\n */\n void queryDevice(DeviceQueryReq deviceQueryReq);\n\n}" }, { "identifier": "DeviceRegisterService", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/service/DeviceRegisterService.java", "snippet": "public interface DeviceRegisterService {\n\n /**\n * 注册登陆\n *\n * @param device\n */\n void login(DeviceReq device);\n\n /**\n * 保持活跃\n * @param deviceId\n */\n void keepalive(String deviceId);\n\n /**\n * 更新设备地址\n * @param deviceId\n * @param ip\n * @param port\n */\n void updateRemoteAddress(String deviceId, String ip, Integer port);\n\n /**\n * 设备离线\n * @param userId\n */\n void offline(String userId);\n\n /**\n * 添加设备通道\n *\n * @param req\n */\n void addChannel(DeviceChannelReq req);\n\n /**\n * 更新设备信息\n *\n * @param req\n */\n void updateDeviceInfo(DeviceInfoReq req);\n}" }, { "identifier": "DeviceConstant", "path": "voglander-common/src/main/java/io/github/lunasaw/voglander/common/constant/DeviceConstant.java", "snippet": "public interface DeviceConstant {\n\n interface DeviceCommandService {\n String DEVICE_AGREEMENT_SERVICE_NAME_GB28181 = \"GbDeviceCommandService\";\n }\n\n interface Status {\n int OFFLINE = 0;\n int ONLINE = 1;\n }\n\n interface LocalConfig {\n String DEVICE_ID = \"0\";\n String DEVICE_NAME = \"voglander\";\n String DEVICE_GB_SIP = \"gb_sip\";\n String DEVICE_GB_SIP_DEFAULT = \"41010500002000000001\";\n\n String DEVICE_GB_PASSWORD = \"gb_password\";\n String DEVICE_GB_PASSWORD_DEFAULT = \"bajiuwulian1006\";\n\n }\n\n\n /**\n * 字符集, 支持 UTF-8 与 GB2312\n */\n\n String CHARSET = \"charset\";\n\n /**\n * 数据流传输模式\n * UDP:udp传输\n * TCP-ACTIVE:tcp主动模式\n * TCP-PASSIVE:tcp被动模式\n */\n String STREAM_MODE = \"streamMode\";\n\n /**\n * 目录订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_CATALOG = \"subscribeCycleForCatalog\";\n\n /**\n * 移动设备位置订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_MOBILE_POSITION = \"subscribeCycleForMobilePosition\";\n\n /**\n * 移动设备位置信息上报时间间隔,单位:秒,默认值5\n */\n String MOBILE_POSITION_SUBMISSION_INTERVAL = \"mobilePositionSubmissionInterval\";\n\n /**\n * 报警订阅周期,0为不订阅\n */\n String SUBSCRIBE_CYCLE_FOR_ALARM = \"subscribeCycleForAlarm\";\n\n /**\n * 是否开启ssrc校验,默认关闭,开启可以防止串流\n */\n String SSRC_CHECK = \"ssrcCheck\";\n\n /**\n * 地理坐标系, 目前支持 WGS84,GCJ02\n */\n String GEO_COORD_SYS = \"geoCoordSys\";\n\n /**\n * 设备使用的媒体id, 默认为null\n */\n String MEDIA_SERVER_ID = \"mediaServerId\";\n\n}" }, { "identifier": "DeviceChannelDTO", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/domaon/dto/DeviceChannelDTO.java", "snippet": "@Data\npublic class DeviceChannelDTO {\n\n private Long id;\n /**\n * 创建时间\n */\n private Date createTime;\n /**\n * 修改时间\n */\n private Date updateTime;\n /**\n * 状态 1在线 0离线\n */\n private Integer status;\n /**\n * 通道Id\n */\n private String channelId;\n /**\n * 设备ID\n */\n private String deviceId;\n /**\n * 通道名称\n */\n private String name;\n /**\n * 扩展字段\n */\n private String extend;\n\n\n private ExtendInfo extendInfo;\n\n public static DeviceChannelDTO convertDTO(DeviceChannelDO deviceChannelDO) {\n if (deviceChannelDO == null) {\n return null;\n }\n DeviceChannelDTO dto = new DeviceChannelDTO();\n dto.setId(deviceChannelDO.getId());\n dto.setCreateTime(deviceChannelDO.getCreateTime());\n dto.setUpdateTime(deviceChannelDO.getUpdateTime());\n dto.setStatus(deviceChannelDO.getStatus());\n dto.setChannelId(deviceChannelDO.getChannelId());\n dto.setDeviceId(deviceChannelDO.getDeviceId());\n dto.setName(deviceChannelDO.getName());\n dto.setExtend(deviceChannelDO.getExtend());\n dto.setExtendInfo(getExtendObj(deviceChannelDO.getExtend()));\n return dto;\n }\n\n public static DeviceChannelDO convertDO(DeviceChannelDTO dto) {\n if (dto == null) {\n return null;\n }\n DeviceChannelDO deviceChannelDO = new DeviceChannelDO();\n deviceChannelDO.setId(dto.getId());\n deviceChannelDO.setCreateTime(dto.getCreateTime());\n deviceChannelDO.setUpdateTime(dto.getUpdateTime());\n deviceChannelDO.setStatus(dto.getStatus());\n deviceChannelDO.setChannelId(dto.getChannelId());\n deviceChannelDO.setDeviceId(dto.getDeviceId());\n deviceChannelDO.setName(dto.getName());\n deviceChannelDO.setExtend(JSON.toJSONString(dto.getExtendInfo()));\n return deviceChannelDO;\n }\n\n public static DeviceChannelDTO req2dto(DeviceChannelReq req) {\n if (req == null) {\n return null;\n }\n DeviceChannelDTO dto = new DeviceChannelDTO();\n dto.setStatus(DeviceConstant.Status.ONLINE);\n dto.setDeviceId(req.getDeviceId());\n dto.setName(req.getChannelName());\n dto.setChannelId(req.getChannelId());\n ExtendInfo extendInfo = new ExtendInfo();\n extendInfo.setChannelInfo(req.getChannelInfo());\n dto.setExtendInfo(extendInfo);\n\n return dto;\n }\n\n private static ExtendInfo getExtendObj(String extentInfo) {\n if (StringUtils.isBlank(extentInfo)) {\n return new ExtendInfo();\n }\n String extend = Optional.of(extentInfo).orElse(StringUtils.EMPTY);\n return Optional.ofNullable(JSON.parseObject(extend, ExtendInfo.class)).orElse(new ExtendInfo());\n }\n\n @Data\n public static class ExtendInfo {\n /**\n * 设备通道信息\n */\n private String channelInfo;\n }\n}" }, { "identifier": "DeviceDTO", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/domaon/dto/DeviceDTO.java", "snippet": "@SuppressWarnings(\"serial\")\n@Data\npublic class DeviceDTO implements Serializable {\n\n @TableField(exist = false)\n private static final long serialVersionUID = 1L;\n private Long id;\n private Date createTime;\n private Date updateTime;\n //设备ID\n private String deviceId;\n //状态 1在线 0离线\n private Integer status;\n //自定义名称\n private String name;\n //IP\n private String ip;\n //端口\n private Integer port;\n //注册时间\n private Date registerTime;\n //心跳时间\n private Date keepaliveTime;\n //注册节点\n private String serverIp;\n /**\n * 协议类型 {@link DeviceAgreementEnum}\n */\n private Integer type;\n //扩展字段\n private String extend;\n\n private ExtendInfo extendInfo;\n\n public static DeviceDTO req2dto(DeviceReq deviceReq) {\n DeviceDTO dto = new DeviceDTO();\n\n dto.setDeviceId(deviceReq.getDeviceId());\n dto.setStatus(DeviceConstant.Status.ONLINE);\n dto.setIp(deviceReq.getRemoteIp());\n dto.setPort(deviceReq.getRemotePort());\n dto.setRegisterTime(deviceReq.getRegisterTime());\n dto.setKeepaliveTime(new Date());\n dto.setServerIp(deviceReq.getLocalIp());\n dto.setType(deviceReq.getType());\n ExtendInfo extendInfo = new ExtendInfo();\n extendInfo.setTransport(deviceReq.getTransport());\n extendInfo.setExpires(deviceReq.getExpire());\n dto.setExtendInfo(extendInfo);\n return dto;\n }\n\n public static DeviceDO convertDO(DeviceDTO dto) {\n if (dto == null) {\n return null;\n }\n DeviceDO deviceDO = new DeviceDO();\n deviceDO.setId(dto.getId());\n deviceDO.setCreateTime(dto.getCreateTime());\n deviceDO.setUpdateTime(dto.getUpdateTime());\n deviceDO.setDeviceId(dto.getDeviceId());\n deviceDO.setStatus(dto.getStatus());\n deviceDO.setName(dto.getName());\n deviceDO.setIp(dto.getIp());\n deviceDO.setPort(dto.getPort());\n deviceDO.setRegisterTime(dto.getRegisterTime());\n deviceDO.setKeepaliveTime(dto.getKeepaliveTime());\n deviceDO.setServerIp(dto.getServerIp());\n deviceDO.setType(dto.getType());\n deviceDO.setExtend(JSON.toJSONString(dto.getExtendInfo()));\n return deviceDO;\n }\n\n public static DeviceDTO convertDTO(DeviceDO deviceDO) {\n if (deviceDO == null) {\n return null;\n }\n DeviceDTO deviceDTO = new DeviceDTO();\n deviceDTO.setId(deviceDO.getId());\n deviceDTO.setCreateTime(deviceDO.getCreateTime());\n deviceDTO.setUpdateTime(deviceDO.getUpdateTime());\n deviceDTO.setDeviceId(deviceDO.getDeviceId());\n deviceDTO.setStatus(deviceDO.getStatus());\n deviceDTO.setName(deviceDO.getName());\n deviceDTO.setIp(deviceDO.getIp());\n deviceDTO.setPort(deviceDO.getPort());\n deviceDTO.setRegisterTime(deviceDO.getRegisterTime());\n deviceDTO.setKeepaliveTime(deviceDO.getKeepaliveTime());\n deviceDTO.setServerIp(deviceDO.getServerIp());\n deviceDTO.setType(deviceDTO.getType());\n deviceDTO.setExtend(deviceDO.getExtend());\n\n ExtendInfo extendObj = getExtendObj(deviceDO.getExtend());\n if (extendObj.getCharset() == null) {\n extendObj.setCharset(CharsetUtil.UTF_8);\n }\n if (extendObj.getStreamMode() == null) {\n extendObj.setStreamMode(StreamModeEnum.UDP.getType());\n }\n deviceDTO.setExtendInfo(extendObj);\n return deviceDTO;\n }\n\n private static ExtendInfo getExtendObj(String extentInfo) {\n if (StringUtils.isBlank(extentInfo)) {\n return new ExtendInfo();\n }\n String extend = Optional.of(extentInfo).orElse(StringUtils.EMPTY);\n return Optional.ofNullable(JSON.parseObject(extend, ExtendInfo.class)).orElse(new ExtendInfo());\n }\n\n @Data\n public static class ExtendInfo {\n\n /**\n * 设备序列号\n */\n private String serialNumber;\n\n /**\n * 传输协议\n * UDP/TCP\n */\n private String transport;\n\n /**\n * 注册有效期\n */\n private int expires;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 数据流传输模式\n * UDP:udp传输\n * TCP-ACTIVE:tcp主动模式\n * TCP-PASSIVE:tcp被动模式\n */\n private String streamMode;\n\n /**\n * 编码\n */\n private String charset;\n\n /**\n * 设备信息\n */\n private String deviceInfo;\n\n }\n\n}" }, { "identifier": "DeviceChannelManager", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/manager/DeviceChannelManager.java", "snippet": "@Component\npublic class DeviceChannelManager {\n\n @Autowired\n private DeviceChannelService deviceChannelService;\n\n @Autowired\n private DeviceManager deviceManager;\n\n public Long saveOrUpdate(DeviceChannelDTO dto) {\n Assert.notNull(dto, \"dto can not be null\");\n Assert.notNull(dto.getDeviceId(), \"deviceId can not be null\");\n\n DeviceDTO dtoByDeviceId = deviceManager.getDtoByDeviceId(dto.getDeviceId());\n if (dtoByDeviceId == null) {\n return null;\n }\n\n DeviceChannelDO deviceChannelDO = DeviceChannelDTO.convertDO(dto);\n DeviceChannelDO byDeviceId = getByDeviceId(dto.getDeviceId(), dto.getChannelId());\n if (byDeviceId != null) {\n deviceChannelDO.setId(byDeviceId.getId());\n deviceChannelService.updateById(deviceChannelDO);\n return byDeviceId.getId();\n }\n deviceChannelService.save(deviceChannelDO);\n return deviceChannelDO.getId();\n }\n\n public void method() {\n\n }\n\n public void updateStatus(String deviceId, String channelId, int status) {\n DeviceChannelDO DeviceChannelDO = getByDeviceId(deviceId, channelId);\n if (DeviceChannelDO == null) {\n return;\n }\n DeviceChannelDO.setStatus(status);\n deviceChannelService.updateById(DeviceChannelDO);\n }\n\n public DeviceChannelDO getByDeviceId(String deviceId, String channelId) {\n Assert.notNull(deviceId, \"userId can not be null\");\n QueryWrapper<DeviceChannelDO> queryWrapper = new QueryWrapper<DeviceChannelDO>().eq(\"device_id\", deviceId)\n .eq(\"channel_id\", channelId).last(\"limit 1\");\n return deviceChannelService.getOne(queryWrapper);\n }\n\n public DeviceChannelDTO getDtoByDeviceId(String deviceId, String channelId) {\n DeviceChannelDO byDeviceId = getByDeviceId(deviceId, channelId);\n return DeviceChannelDTO.convertDTO(byDeviceId);\n }\n}" }, { "identifier": "DeviceManager", "path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/manager/DeviceManager.java", "snippet": "@Component\npublic class DeviceManager {\n\n @Autowired\n private DeviceService deviceService;\n\n public Long saveOrUpdate(DeviceDTO dto) {\n Assert.notNull(dto, \"dto can not be null\");\n Assert.notNull(dto.getDeviceId(), \"deviceId can not be null\");\n DeviceDO deviceDO = DeviceDTO.convertDO(dto);\n\n DeviceDO byDeviceId = getByDeviceId(dto.getDeviceId());\n if (byDeviceId != null) {\n deviceDO.setId(byDeviceId.getId());\n deviceService.updateById(deviceDO);\n return byDeviceId.getId();\n }\n deviceService.save(deviceDO);\n return deviceDO.getId();\n }\n\n public void updateStatus(String deviceId, int status) {\n DeviceDO deviceDO = getByDeviceId(deviceId);\n if (deviceDO == null) {\n return;\n }\n deviceDO.setStatus(status);\n deviceService.updateById(deviceDO);\n }\n\n public DeviceDO getByDeviceId(String deviceId) {\n Assert.notNull(deviceId, \"userId can not be null\");\n QueryWrapper<DeviceDO> queryWrapper = new QueryWrapper<DeviceDO>().eq(\"device_id\", deviceId).last(\"limit 1\");\n return deviceService.getOne(queryWrapper);\n }\n\n public DeviceDTO getDtoByDeviceId(String deviceId) {\n DeviceDO byDeviceId = getByDeviceId(deviceId);\n return DeviceDTO.convertDTO(byDeviceId);\n }\n}" }, { "identifier": "DeviceAgreementService", "path": "voglander-service/src/main/java/io/github/lunasaw/voglander/service/command/DeviceAgreementService.java", "snippet": "@Service\npublic class DeviceAgreementService {\n\n public DeviceCommandService getCommandService(Integer type) {\n Assert.notNull(type, \"协议类型不能为空\");\n\n\n DeviceCommandService deviceCommandService = null;\n if (type.equals(DeviceAgreementEnum.GB28181.getType())) {\n deviceCommandService = SpringBeanFactory.getBean(DeviceConstant.DeviceCommandService.DEVICE_AGREEMENT_SERVICE_NAME_GB28181);\n }\n Assert.notNull(deviceCommandService, \"该协议没有对应的实现方法\");\n\n return deviceCommandService;\n }\n\n}" } ]
import io.github.lunasaw.voglander.client.domain.qo.DeviceChannelReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceInfoReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceQueryReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceReq; import io.github.lunasaw.voglander.client.service.DeviceCommandService; import io.github.lunasaw.voglander.client.service.DeviceRegisterService; import io.github.lunasaw.voglander.common.constant.DeviceConstant; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceChannelDTO; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceDTO; import io.github.lunasaw.voglander.manager.manager.DeviceChannelManager; import io.github.lunasaw.voglander.manager.manager.DeviceManager; import io.github.lunasaw.voglander.service.command.DeviceAgreementService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.util.Date;
4,736
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired
private DeviceAgreementService deviceAgreementService;
11
2023-12-27 07:28:18+00:00
8k
GrailStack/grail-codegen
src/main/java/com/itgrail/grail/codegen/custom/grailddd/GrailDddTemplate.java
[ { "identifier": "GrailFrameworkGenRequest", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/dto/GrailFrameworkGenRequest.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkGenRequest extends TemplateGenRequest {\n\n private String javaVersion;\n private String grailFrameworkVersion;\n\n private String groupId;\n private String artifactId;\n private String description;\n\n private String basePackage;\n\n private List<SubModuleDTO> subModules;\n\n private DbModelDTO dbModel;\n\n private DomainDTO domain;\n\n /**\n * 是否需要连接数据库,不需要连接数据库,就不添加Grail MyBatis\n */\n private Boolean dbConfigure;\n\n /**\n * 模块依赖\n */\n private List<ModuleDependencyModel> moduleDependencyModels;\n\n}" }, { "identifier": "SubModuleDTO", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/dto/SubModuleDTO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class SubModuleDTO implements Serializable {\n private String subModuleName;\n private String packaging;\n}" }, { "identifier": "GrailFrameworkMetadata", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/metadata/GrailFrameworkMetadata.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkMetadata extends TemplateMetaData {\n\n private List<GrailVersionMetaData> grailVersions;\n private List<ModuleMetaData> subModules;\n private List<String> dependencies;\n private List<DbMetaData> databases;\n private ModuleMetaData parentModule;\n}" }, { "identifier": "GrailVersionMetaData", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/metadata/GrailVersionMetaData.java", "snippet": "@Data\npublic class GrailVersionMetaData {\n private String grailFrameworkVersion;\n private String javaVersion;\n private String springBootVersion;\n private String springCloudVersion;\n}" }, { "identifier": "DomainDataModel", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/model/DomainDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DomainDataModel implements Serializable {\n\n /**\n * 当前应用所属域的唯一code\n */\n private String code;\n\n /**\n * 父域的唯一code\n */\n private String parentCode;\n\n /**\n * 当前域的名称\n */\n private String name;\n\n /**\n * 当前域的描述\n */\n private String desc;\n\n}" }, { "identifier": "GrailFrameworkDataModel", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/model/GrailFrameworkDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkDataModel extends CodeGenDataModel {\n private String grailFrameworkVersion;\n\n private DbDataModel db;\n\n private DomainDataModel domain;\n}" }, { "identifier": "CommonUtil", "path": "src/main/java/com/itgrail/grail/codegen/utils/CommonUtil.java", "snippet": "public class CommonUtil {\n\n public static void closeClosable(Closeable closeable) {\n try {\n if (closeable != null) {\n closeable.close();\n }\n } catch (Exception ex) {\n }\n }\n\n public static UUID genUUID() {\n ThreadLocalRandom random = ThreadLocalRandom.current();\n return new UUID(random.nextLong(), random.nextLong());\n }\n\n}" }, { "identifier": "PropertiesUtils", "path": "src/main/java/com/itgrail/grail/codegen/utils/PropertiesUtils.java", "snippet": "public class PropertiesUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);\n\n /**\n * 读取json文件,返回json字符串\n * @param fileName\n * @return\n */\n public static String readJsonFile(String fileName) {\n ClassPathResource classPathResource = new ClassPathResource(fileName);\n try {\n InputStream inputStream =classPathResource.getInputStream();\n return inputStreamToString(inputStream);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n private static String inputStreamToString(InputStream inputStream) {\n StringBuffer buffer = new StringBuffer();\n InputStreamReader inputStreamReader;\n try {\n inputStreamReader = new InputStreamReader(inputStream, \"utf-8\");\n BufferedReader bufferedReader = new BufferedReader(inputStreamReader);\n String str = null;\n while ((str = bufferedReader.readLine()) != null) {\n buffer.append(str);\n }\n // 释放资源\n bufferedReader.close();\n inputStreamReader.close();\n inputStream.close();\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return buffer.toString();\n }\n\n}" }, { "identifier": "DbDataModel", "path": "src/main/java/com/itgrail/grail/codegen/components/db/DbDataModel.java", "snippet": "@Data\npublic class DbDataModel {\n\n private List<Table> tables;\n\n private String dbName;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n private String dbDriver;\n\n //用于迭代\n private Table table;\n\n}" }, { "identifier": "DBProperties", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DBProperties.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DBProperties {\n\n private String dbType;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n\n}" }, { "identifier": "Database", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/Database.java", "snippet": "public interface Database extends Closeable {\n\n String getDbUrl();\n\n String getDbName();\n\n String getDbUserName();\n\n String getDbPassword();\n\n String getDriverClassName();\n\n Connection getConnection();\n\n DbTypeEnum getDbType();\n\n /**\n * 获取表名称列表\n *\n * @param tableNamePattern 获取表名时使用的表达式\n * @return 表名列表\n */\n List<String> getTableNames(String tableNamePattern);\n\n /**\n * 获取数据库所有表名称\n *\n * @return 所有表名称\n */\n List<String> getAllTableNames();\n\n /**\n * 查询表所有列\n *\n * @param tableName 表名\n * @return 所有列\n */\n List<Column> getColumns(String tableName);\n\n /**\n * 查询表主键列\n *\n * @param tableName 表名\n * @return 主键列\n */\n List<PrimaryKeyColumn> getPrimaryColumns(String tableName);\n\n\n /**\n * 查询数据库中所有表\n *\n * @return 数据表列表\n */\n List<Table> getAllTables();\n\n /**\n * 查询表\n *\n * @param tableNamePattern 表名称表达式过滤,如:sys_%,则仅仅查询出【sys_】开头的所有表\n * @return 数据表列表\n */\n List<Table> getTables(String tableNamePattern);\n\n /**\n * 查询表\n *\n * @param tableNames 表名称列表\n * @return 数据表列表\n */\n List<Table> getTables(List<String> tableNames);\n\n /**\n * 查询表\n *\n * @param tableName 表名\n * @return 表对象实例\n */\n Table getTable(String tableName);\n\n\n /**\n * 是否为主键列\n *\n * @param tableName 表名\n * @param columnName 列名\n * @return 是否为主键,true:主键,false:非主键\n */\n boolean isPrimaryKey(String tableName, String columnName);\n\n /**\n * 获取表备注信息\n *\n * @param tableName 表名\n * @return 表备注信息\n */\n String getTableComment(String tableName);\n\n}" }, { "identifier": "DatabaseFactory", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DatabaseFactory.java", "snippet": "@Slf4j\npublic class DatabaseFactory {\n\n private DatabaseFactory() {\n }\n\n public static Database create(DBProperties dbProperties) throws DbException {\n DbTypeEnum dbTypeEnum = DbTypeEnum.get(dbProperties.getDbType());\n if (dbTypeEnum == null) {\n throw new DbException(String.format(\"暂不支持该数据库类型, dbType=%s\", dbProperties.getDbType()));\n }\n try {\n Constructor<? extends Database> constructor = dbTypeEnum.getDataBaseImplClass().getConstructor(DBProperties.class);\n return constructor.newInstance(dbProperties);\n } catch (InvocationTargetException ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getCause().getMessage());\n } catch (Exception ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getMessage());\n }\n }\n\n}" }, { "identifier": "DbMetaData", "path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DbMetaData.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class DbMetaData {\n private String dbType;\n}" }, { "identifier": "Table", "path": "src/main/java/com/itgrail/grail/codegen/components/db/model/Table.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class Table {\n\n private String tableName;\n\n /**\n * 数据对象名称\n */\n private String doName;\n\n /**\n * 数据访问对象名称\n */\n private String daoName;\n\n /**\n * 表备注信息\n */\n private String comment;\n\n /**\n * 数据列列表\n */\n private List<Column> columns;\n\n /**\n * 主键列表\n */\n private List<PrimaryKeyColumn> primaryKeys;\n\n @Override\n public String toString() {\n return JSONObject.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.PrettyFormat);\n }\n\n}" }, { "identifier": "CustomizedTemplate", "path": "src/main/java/com/itgrail/grail/codegen/template/custom/CustomizedTemplate.java", "snippet": "public abstract class CustomizedTemplate {\n\n @Autowired\n private TemplateProcessor templateProcessor;\n\n private static final String TEMPLATE_LOCATE_BASE_PATH = \"templates/\";\n\n public GenResult gen(Map<String, Object> req) throws IllegalArgumentException {\n CodeGenDataModel dataModel = convert(req);\n byte[] fileBytes = templateProcessor.process(dataModel);\n return new GenResult().setFileBytes(fileBytes).setFileName(genFileName(dataModel));\n }\n\n public abstract String getTemplateName();\n\n public abstract List<ModuleMetaData> initSubModules();\n\n public abstract List<String> getSubModules();\n\n public abstract ModuleMetaData getParentModule();\n\n\n public abstract String getTemplateLocatePath();\n\n public String getDefaultGenFileName() {\n return \"init-\" + getTemplateName().toLowerCase();\n }\n\n public boolean hasSubModel(String subModel) {\n String subModelTmp = subModel.replaceFirst(\"-\", \"\");\n return Optional.ofNullable(getSubModules()).orElse(Lists.newArrayList())\n .stream().anyMatch(e -> e.equalsIgnoreCase(subModelTmp));\n }\n\n public String getBasePath() {\n return TEMPLATE_LOCATE_BASE_PATH;\n }\n\n public abstract TemplateMetaData getTemplateMetadata();\n\n public abstract CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException;\n\n public abstract String genFileName(CodeGenDataModel dataModel);\n\n}" }, { "identifier": "ModuleMetaData", "path": "src/main/java/com/itgrail/grail/codegen/template/custom/ModuleMetaData.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class ModuleMetaData implements Serializable {\n private String subModuleName;\n private List<String> packagingTypes;\n private List<DependencyModel> dependencys;\n}" }, { "identifier": "CodeGenDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/CodeGenDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class CodeGenDataModel {\n private String templateName;\n private String javaVersion;\n private MavenProjectDataModel project;\n}" }, { "identifier": "MavenModuleDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/MavenModuleDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class MavenModuleDataModel {\n private String groupId;\n private String artifactId;\n private String basePackage;\n private String packaging;\n\n /**\n * @see CustomizedTemplate#getSubModules()\n */\n private String moduleName;\n}" }, { "identifier": "MavenProjectDataModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/MavenProjectDataModel.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class MavenProjectDataModel {\n private String groupId;\n\n private String artifactId;\n\n private String basePackage;\n\n private String description;\n\n private Boolean dbConfigure=false;\n\n /**\n * key:\n *\n * @see MavenModuleDataModel#getModuleName()\n */\n private Map<String, MavenModuleDataModel> subModules;\n\n\n /**\n * 依赖\n */\n private List<ModuleDependencyModel> dependencies;\n\n /**\n * 用于判断某个 module 中是否包含了特定 dependency, 用于针对不同 dependency 生成对应的代码\n * @param moduleName\n * @param artifactId\n * @return\n */\n public boolean hasDependencyForModule(String moduleName, String artifactId) {\n Optional<ModuleDependencyModel> module = dependencies.stream()\n .filter(mod -> moduleName.equals(mod.getModulekey()))\n .findFirst();\n if (!module.isPresent()) {\n return false;\n }\n return module.get().getDependencyModels().stream().anyMatch(dep -> artifactId.equals(dep.getArtifactId()));\n }\n}" }, { "identifier": "ModuleDependencyModel", "path": "src/main/java/com/itgrail/grail/codegen/template/datamodel/ModuleDependencyModel.java", "snippet": "@Data\npublic class ModuleDependencyModel implements Serializable {\n\n /**\n * 模块唯一的key\n */\n private String modulekey;\n\n /**\n * 依赖\n */\n private List<DependencyModel> dependencyModels;\n\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.itgrail.grail.codegen.custom.grailframework.dto.GrailFrameworkGenRequest; import com.itgrail.grail.codegen.custom.grailframework.dto.SubModuleDTO; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailFrameworkMetadata; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailVersionMetaData; import com.itgrail.grail.codegen.custom.grailframework.model.DomainDataModel; import com.itgrail.grail.codegen.custom.grailframework.model.GrailFrameworkDataModel; import com.itgrail.grail.codegen.utils.CommonUtil; import com.itgrail.grail.codegen.utils.PropertiesUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.itgrail.grail.codegen.components.db.DbDataModel; import com.itgrail.grail.codegen.components.db.database.DBProperties; import com.itgrail.grail.codegen.components.db.database.Database; import com.itgrail.grail.codegen.components.db.database.DatabaseFactory; import com.itgrail.grail.codegen.components.db.database.DbMetaData; import com.itgrail.grail.codegen.components.db.model.Table; import com.itgrail.grail.codegen.template.custom.CustomizedTemplate; import com.itgrail.grail.codegen.template.custom.ModuleMetaData; import com.itgrail.grail.codegen.template.datamodel.CodeGenDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenModuleDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenProjectDataModel; import com.itgrail.grail.codegen.template.datamodel.ModuleDependencyModel; import java.util.List; import java.util.Map;
5,230
} } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("client","core","start"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
package com.itgrail.grail.codegen.custom.grailddd; /** * @author yage.luan * created at 2019/5/24 20:50 **/ @Component public class GrailDddTemplate extends CustomizedTemplate { @Override public String getTemplateName() { return "grailDdd"; } @Override public List<ModuleMetaData> initSubModules() { List<ModuleMetaData> subModules = Lists.newArrayList(); ModuleMetaData moduleMetaData1=new ModuleMetaData().setSubModuleName("client").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData2 = new ModuleMetaData().setSubModuleName("core").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData3= new ModuleMetaData().setSubModuleName("start").setPackagingTypes(Lists.newArrayList("jar", "war")); String json= PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("client".equals(mo.getModulekey())){ moduleMetaData1.setDependencys(mo.getDependencyModels()); } if("core".equals(mo.getModulekey())){ moduleMetaData2.setDependencys(mo.getDependencyModels()); } if("start".equals(mo.getModulekey())){ moduleMetaData3.setDependencys(mo.getDependencyModels()); } } } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("client","core","start"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
DbDataModel dbDataModel = new DbDataModel();
8
2023-12-30 15:32:55+00:00
8k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/urls/StandardCategoryURLGeneratorTest.java
[ { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}" }, { "identifier": "DefaultCategoryDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/category/DefaultCategoryDataset.java", "snippet": "public class DefaultCategoryDataset extends AbstractDataset\r\n implements CategoryDataset, PublicCloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -8168173757291644622L;\r\n\r\n /** A storage structure for the data. */\r\n private DefaultKeyedValues2D data;\r\n\r\n /**\r\n * Creates a new (empty) dataset.\r\n */\r\n public DefaultCategoryDataset() {\r\n this.data = new DefaultKeyedValues2D();\r\n }\r\n\r\n /**\r\n * Returns the number of rows in the table.\r\n *\r\n * @return The row count.\r\n *\r\n * @see #getColumnCount()\r\n */\r\n @Override\r\n public int getRowCount() {\r\n return this.data.getRowCount();\r\n }\r\n\r\n /**\r\n * Returns the number of columns in the table.\r\n *\r\n * @return The column count.\r\n *\r\n * @see #getRowCount()\r\n */\r\n @Override\r\n public int getColumnCount() {\r\n return this.data.getColumnCount();\r\n }\r\n\r\n /**\r\n * Returns a value from the table.\r\n *\r\n * @param row the row index (zero-based).\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n * @see #removeValue(Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getValue(int row, int column) {\r\n return this.data.getValue(row, column);\r\n }\r\n\r\n /**\r\n * Returns the key for the specified row.\r\n *\r\n * @param row the row index (zero-based).\r\n *\r\n * @return The row key.\r\n *\r\n * @see #getRowIndex(Comparable)\r\n * @see #getRowKeys()\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public Comparable getRowKey(int row) {\r\n return this.data.getRowKey(row);\r\n }\r\n\r\n /**\r\n * Returns the row index for a given key.\r\n *\r\n * @param key the row key (<code>null</code> not permitted).\r\n *\r\n * @return The row index.\r\n *\r\n * @see #getRowKey(int)\r\n */\r\n @Override\r\n public int getRowIndex(Comparable key) {\r\n // defer null argument check\r\n return this.data.getRowIndex(key);\r\n }\r\n\r\n /**\r\n * Returns the row keys.\r\n *\r\n * @return The keys.\r\n *\r\n * @see #getRowKey(int)\r\n */\r\n @Override\r\n public List getRowKeys() {\r\n return this.data.getRowKeys();\r\n }\r\n\r\n /**\r\n * Returns a column key.\r\n *\r\n * @param column the column index (zero-based).\r\n *\r\n * @return The column key.\r\n *\r\n * @see #getColumnIndex(Comparable)\r\n */\r\n @Override\r\n public Comparable getColumnKey(int column) {\r\n return this.data.getColumnKey(column);\r\n }\r\n\r\n /**\r\n * Returns the column index for a given key.\r\n *\r\n * @param key the column key (<code>null</code> not permitted).\r\n *\r\n * @return The column index.\r\n *\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public int getColumnIndex(Comparable key) {\r\n // defer null argument check\r\n return this.data.getColumnIndex(key);\r\n }\r\n\r\n /**\r\n * Returns the column keys.\r\n *\r\n * @return The keys.\r\n *\r\n * @see #getColumnKey(int)\r\n */\r\n @Override\r\n public List getColumnKeys() {\r\n return this.data.getColumnKeys();\r\n }\r\n\r\n /**\r\n * Returns the value for a pair of keys.\r\n *\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n *\r\n * @throws UnknownKeyException if either key is not defined in the dataset.\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n */\r\n @Override\r\n public Number getValue(Comparable rowKey, Comparable columnKey) {\r\n return this.data.getValue(rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds a value to the table. Performs the same function as setValue().\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n * @see #removeValue(Comparable, Comparable)\r\n */\r\n public void addValue(Number value, Comparable rowKey,\r\n Comparable columnKey) {\r\n this.data.addValue(value, rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds a value to the table.\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void addValue(double value, Comparable rowKey,\r\n Comparable columnKey) {\r\n addValue(new Double(value), rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds or updates a value in the table and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param value the value (<code>null</code> permitted).\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void setValue(Number value, Comparable rowKey,\r\n Comparable columnKey) {\r\n this.data.setValue(value, rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Adds or updates a value in the table and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #getValue(Comparable, Comparable)\r\n */\r\n public void setValue(double value, Comparable rowKey,\r\n Comparable columnKey) {\r\n setValue(new Double(value), rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Adds the specified value to an existing value in the dataset (if the\r\n * existing value is <code>null</code>, it is treated as if it were 0.0).\r\n *\r\n * @param value the value.\r\n * @param rowKey the row key (<code>null</code> not permitted).\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @throws UnknownKeyException if either key is not defined in the dataset.\r\n */\r\n public void incrementValue(double value,\r\n Comparable rowKey,\r\n Comparable columnKey) {\r\n double existing = 0.0;\r\n Number n = getValue(rowKey, columnKey);\r\n if (n != null) {\r\n existing = n.doubleValue();\r\n }\r\n setValue(existing + value, rowKey, columnKey);\r\n }\r\n\r\n /**\r\n * Removes a value from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowKey the row key.\r\n * @param columnKey the column key.\r\n *\r\n * @see #addValue(Number, Comparable, Comparable)\r\n */\r\n public void removeValue(Comparable rowKey, Comparable columnKey) {\r\n this.data.removeValue(rowKey, columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a row from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowIndex the row index.\r\n *\r\n * @see #removeColumn(int)\r\n */\r\n public void removeRow(int rowIndex) {\r\n this.data.removeRow(rowIndex);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a row from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param rowKey the row key.\r\n *\r\n * @see #removeColumn(Comparable)\r\n */\r\n public void removeRow(Comparable rowKey) {\r\n this.data.removeRow(rowKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a column from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param columnIndex the column index.\r\n *\r\n * @see #removeRow(int)\r\n */\r\n public void removeColumn(int columnIndex) {\r\n this.data.removeColumn(columnIndex);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a column from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n *\r\n * @param columnKey the column key (<code>null</code> not permitted).\r\n *\r\n * @see #removeRow(Comparable)\r\n *\r\n * @throws UnknownKeyException if <code>columnKey</code> is not defined\r\n * in the dataset.\r\n */\r\n public void removeColumn(Comparable columnKey) {\r\n this.data.removeColumn(columnKey);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Clears all data from the dataset and sends a {@link DatasetChangeEvent}\r\n * to all registered listeners.\r\n */\r\n public void clear() {\r\n this.data.clear();\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Tests this dataset for equality with an arbitrary object.\r\n *\r\n * @param obj the object (<code>null</code> permitted).\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof CategoryDataset)) {\r\n return false;\r\n }\r\n CategoryDataset that = (CategoryDataset) obj;\r\n if (!getRowKeys().equals(that.getRowKeys())) {\r\n return false;\r\n }\r\n if (!getColumnKeys().equals(that.getColumnKeys())) {\r\n return false;\r\n }\r\n int rowCount = getRowCount();\r\n int colCount = getColumnCount();\r\n for (int r = 0; r < rowCount; r++) {\r\n for (int c = 0; c < colCount; c++) {\r\n Number v1 = getValue(r, c);\r\n Number v2 = that.getValue(r, c);\r\n if (v1 == null) {\r\n if (v2 != null) {\r\n return false;\r\n }\r\n }\r\n else if (!v1.equals(v2)) {\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code for the dataset.\r\n *\r\n * @return A hash code.\r\n */\r\n @Override\r\n public int hashCode() {\r\n return this.data.hashCode();\r\n }\r\n\r\n /**\r\n * Returns a clone of the dataset.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws CloneNotSupportedException if there is a problem cloning the\r\n * dataset.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n DefaultCategoryDataset clone = (DefaultCategoryDataset) super.clone();\r\n clone.data = (DefaultKeyedValues2D) this.data.clone();\r\n return clone;\r\n }\r\n\r\n}\r" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.jfree.chart.TestUtilities; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.util.PublicCloneable; import org.junit.Test;
3,694
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardCategoryURLGeneratorTest.java * ------------------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 13-Dec-2007 : Added testGenerateURL() and testEquals() (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.urls; /** * Tests for the {@link StandardCategoryURLGenerator} class. */ public class StandardCategoryURLGeneratorTest { /** * Some tests for the generateURL() method. */ @Test public void testGenerateURL() { StandardCategoryURLGenerator g1 = new StandardCategoryURLGenerator();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardCategoryURLGeneratorTest.java * ------------------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 13-Dec-2007 : Added testGenerateURL() and testEquals() (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.urls; /** * Tests for the {@link StandardCategoryURLGenerator} class. */ public class StandardCategoryURLGeneratorTest { /** * Some tests for the generateURL() method. */ @Test public void testGenerateURL() { StandardCategoryURLGenerator g1 = new StandardCategoryURLGenerator();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
1
2023-12-24 12:36:47+00:00
8k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/util/EntityUtils.java
[ { "identifier": "RotationHandler", "path": "src/main/java/com/github/may2beez/mayobees/handler/RotationHandler.java", "snippet": "public class RotationHandler {\n private static RotationHandler instance;\n private final Minecraft mc = Minecraft.getMinecraft();\n private final Rotation startRotation = new Rotation(0f, 0f);\n private final Rotation targetRotation = new Rotation(0f, 0f);\n private final Clock dontRotate = new Clock();\n @Getter\n private boolean rotating;\n private long startTime;\n private long endTime;\n @Getter\n private float clientSideYaw = 0;\n @Getter\n private float clientSidePitch = 0;\n @Getter\n private float serverSideYaw = 0;\n @Getter\n private float serverSidePitch = 0;\n @Getter\n private RotationConfiguration configuration;\n\n private final Random random = new Random();\n\n public static RotationHandler getInstance() {\n if (instance == null) {\n instance = new RotationHandler();\n }\n return instance;\n }\n\n public void easeTo(RotationConfiguration configuration) {\n this.configuration = configuration;\n easingModifier = (random.nextFloat() * 0.5f - 0.25f);\n dontRotate.reset();\n startTime = System.currentTimeMillis();\n startRotation.setRotation(configuration.getFrom());\n Rotation neededChange;\n randomAddition = (Math.random() * 0.3 - 0.15);\n if (configuration.bowRotation()) {\n neededChange = getNeededChange(startRotation, getBowRotation(configuration.getTarget().get().getEntity()));\n } else if (configuration.getTarget().isPresent() && configuration.getTarget().get().getTarget().isPresent()) {\n neededChange = getNeededChange(startRotation, configuration.getTarget().get().getTarget().get());\n } else if (configuration.getTo().isPresent()) {\n neededChange = getNeededChange(startRotation, configuration.getTo().get());\n } else {\n throw new IllegalArgumentException(\"No target or rotation specified!\");\n }\n\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n\n LogUtils.debug(\"[Rotation] Needed change: \" + neededChange.getYaw() + \" \" + neededChange.getPitch());\n\n float absYaw = Math.max(Math.abs(neededChange.getYaw()), 1);\n float absPitch = Math.max(Math.abs(neededChange.getPitch()), 1);\n float pythagoras = pythagoras(absYaw, absPitch);\n float time = getTime(pythagoras, configuration.getTime());\n endTime = (long) (System.currentTimeMillis() + Math.max(time, 50 + Math.random() * 100));\n rotating = true;\n }\n\n private float getTime(float pythagoras, float time) {\n if (pythagoras < 25) {\n LogUtils.debug(\"[Rotation] Very close rotation, speeding up by 0.65\");\n return (long) (time * 0.65);\n }\n if (pythagoras < 45) {\n LogUtils.debug(\"[Rotation] Close rotation, speeding up by 0.77\");\n return (long) (time * 0.77);\n }\n if (pythagoras < 80) {\n LogUtils.debug(\"[Rotation] Not so close, but not that far rotation, speeding up by 0.9\");\n return (long) (time * 0.9);\n }\n if (pythagoras > 100) {\n LogUtils.debug(\"[Rotation] Far rotation, slowing down by 1.1\");\n return (long) (time * 1.1);\n }\n LogUtils.debug(\"[Rotation] Normal rotation\");\n return (long) (time * 1.0);\n }\n\n public void easeBackFromServerRotation() {\n if (configuration == null) return;\n LogUtils.debug(\"[Rotation] Easing back from server rotation\");\n configuration.goingBackToClientSide(true);\n startTime = System.currentTimeMillis();\n configuration.setTarget(Optional.empty());\n startRotation.setRotation(new Rotation(serverSideYaw, serverSidePitch));\n Rotation neededChange = getNeededChange(startRotation, new Rotation(clientSideYaw, clientSidePitch));\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n\n LogUtils.debug(\"[Rotation] Needed change: \" + neededChange.getYaw() + \" \" + neededChange.getPitch());\n\n float time = configuration.getTime();\n endTime = System.currentTimeMillis() + Math.max((long) time, 50);\n configuration.setCallback(Optional.of(this::reset));\n rotating = true;\n }\n\n private float pythagoras(float a, float b) {\n return (float) Math.sqrt(a * a + b * b);\n }\n\n public Rotation getNeededChange(Rotation target) {\n if (configuration != null && configuration.getRotationType() == RotationConfiguration.RotationType.SERVER) {\n return getNeededChange(new Rotation(serverSideYaw, serverSidePitch), target);\n } else {\n return getNeededChange(new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch), target);\n }\n }\n\n public Rotation getNeededChange(Rotation startRot, Vec3 target) {\n Rotation targetRot;\n if (configuration != null && random.nextGaussian() > 0.8) {\n targetRot = getRotation(target, configuration.randomness());\n } else {\n targetRot = getRotation(target);\n }\n return getNeededChange(startRot, targetRot);\n }\n\n public Rotation getNeededChange(Rotation startRot, Rotation endRot) {\n float yawDiff = (float) (wrapAngleTo180(endRot.getYaw()) - wrapAngleTo180(startRot.getYaw()));\n\n yawDiff = AngleUtils.normalizeAngle(yawDiff);\n\n return new Rotation(yawDiff, endRot.getPitch() - startRot.getPitch());\n }\n\n private double randomAddition = (Math.random() * 0.3 - 0.15);\n\n public Rotation getBowRotation(Entity entity) {\n System.out.println(\"Getting bow rotation\");\n double xDelta = (entity.posX - entity.lastTickPosX) * 0.4d;\n double zDelta = (entity.posZ - entity.lastTickPosZ) * 0.4d;\n double d = mc.thePlayer.getDistanceToEntity(entity);\n d -= d % 0.8d;\n double xMulti = d / 0.8 * xDelta;\n double zMulti = d / 0.8 * zDelta;\n double x = entity.posX + xMulti - mc.thePlayer.posX;\n double z = entity.posZ + zMulti - mc.thePlayer.posZ;\n double y = mc.thePlayer.posY + mc.thePlayer.getEyeHeight() - (entity.posY + entity.height / 2 + randomAddition);\n double dist = mc.thePlayer.getDistanceToEntity(entity);\n float yaw = (float) Math.toDegrees(Math.atan2(z, x)) - 90f;\n double d2 = Math.sqrt(x * x + z * z);\n float pitch = (float) (-(Math.atan2(y, d2) * 180.0 / Math.PI)) + (float) dist * 0.11f;\n return new Rotation(yaw, -pitch);\n }\n\n public Rotation getRotation(Vec3 to) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to, false);\n }\n\n public Rotation getRotation(Vec3 to, boolean randomness) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to, randomness);\n }\n\n public Rotation getRotation(Entity to) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), to.getPositionVector().addVector(0, Math.min(to.getEyeHeight() - 0.15, 1.5) + randomAddition, 0), false);\n }\n\n public Rotation getRotation(Vec3 from, Vec3 to) {\n if (configuration != null && random.nextGaussian() > 0.8) {\n return getRotation(from, to, configuration.randomness());\n }\n return getRotation(from, to, false);\n }\n\n public Rotation getRotation(BlockPos pos) {\n if (configuration != null && random.nextGaussian() > 0.8) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), configuration.randomness());\n }\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), false);\n }\n\n public Rotation getRotation(BlockPos pos, boolean randomness) {\n return getRotation(mc.thePlayer.getPositionEyes(((MinecraftAccessor) mc).getTimer().renderPartialTicks), new Vec3(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5), randomness);\n }\n\n public Rotation getRotation(Vec3 from, Vec3 to, boolean randomness) {\n double xDiff = to.xCoord - from.xCoord;\n double yDiff = to.yCoord - from.yCoord;\n double zDiff = to.zCoord - from.zCoord;\n\n double dist = Math.sqrt(xDiff * xDiff + zDiff * zDiff);\n\n float yaw = (float) Math.toDegrees(Math.atan2(zDiff, xDiff)) - 90F;\n float pitch = (float) -Math.toDegrees(Math.atan2(yDiff, dist));\n\n if (randomness) {\n yaw += (float) ((Math.random() - 1) * 4);\n pitch += (float) ((Math.random() - 1) * 4);\n }\n\n return new Rotation(yaw, pitch);\n }\n\n public boolean shouldRotate(Rotation to) {\n Rotation neededChange = getNeededChange(to);\n return Math.abs(neededChange.getYaw()) > 0.1 || Math.abs(neededChange.getPitch()) > 0.1;\n }\n\n public void reset() {\n LogUtils.debug(\"[Rotation] Resetting\");\n rotating = false;\n configuration = null;\n startTime = 0;\n endTime = 0;\n }\n\n private float interpolate(float start, float end, Function<Float, Float> function) {\n float t = (float) (System.currentTimeMillis() - startTime) / (endTime - startTime);\n return (end - start) * function.apply(t) + start;\n }\n\n private float easingModifier = 0;\n\n private float easeOutQuart(float x) {\n return (float) (1 - Math.pow(1 - x, 4));\n }\n\n private float easeOutExpo(float x) {\n return x == 1 ? 1 : 1 - (float) Math.pow(2, -10 * x);\n }\n\n private float easeOutBack(float x) {\n float c1 = 1.70158f + easingModifier;\n float c3 = c1 + 1;\n return 1 + c3 * (float) Math.pow(x - 1, 3) + c1 * (float) Math.pow(x - 1, 2);\n }\n\n @SubscribeEvent\n public void onRender(RenderWorldLastEvent event) {\n if (!rotating || configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.CLIENT)\n return;\n\n if (mc.currentScreen != null || dontRotate.isScheduled() && !dontRotate.passed()) {\n endTime = System.currentTimeMillis() + configuration.getTime();\n return;\n }\n\n if (System.currentTimeMillis() >= endTime) {\n // finish\n if (configuration.getCallback().isPresent()) {\n configuration.getCallback().get().run();\n } else { // No callback, just reset\n if (Math.abs(mc.thePlayer.rotationYaw - targetRotation.getYaw()) < 0.1 && Math.abs(mc.thePlayer.rotationPitch - targetRotation.getPitch()) < 0.1) {\n mc.thePlayer.rotationYaw = targetRotation.getYaw();\n mc.thePlayer.rotationPitch = targetRotation.getPitch();\n }\n reset();\n return;\n }\n if (configuration == null || !configuration.goingBackToClientSide()) { // Reset was called in callback\n return;\n }\n return;\n }\n\n if (configuration.followTarget() && configuration.getTarget().isPresent()) {\n Target target = configuration.getTarget().get();\n Rotation rot;\n if (target.getEntity() != null) {\n if (configuration.bowRotation()) {\n rot = getBowRotation(target.getEntity());\n } else {\n rot = getRotation(target.getEntity());\n }\n } else if (target.getBlockPos() != null) {\n rot = getRotation(target.getBlockPos());\n } else if (target.getTarget().isPresent()) {\n rot = getRotation(target.getTarget().get());\n } else {\n throw new IllegalArgumentException(\"No target specified!\");\n }\n Rotation neededChange = getNeededChange(startRotation, rot);\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n }\n mc.thePlayer.rotationYaw = interpolate(startRotation.getYaw(), targetRotation.getYaw(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n mc.thePlayer.rotationPitch = interpolate(startRotation.getPitch(), targetRotation.getPitch(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutQuart);\n }\n\n @SubscribeEvent(receiveCanceled = true)\n public void onUpdatePre(MotionUpdateEvent.Pre event) {\n if (!rotating || configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.SERVER)\n return;\n\n if (System.currentTimeMillis() >= endTime) {\n // finish\n if (configuration.getCallback().isPresent()) {\n configuration.getCallback().get().run();\n } else { // No callback, just reset\n reset();\n return;\n }\n if (configuration == null || !configuration.goingBackToClientSide()) { // Reset was called in callback\n return;\n }\n }\n clientSidePitch = mc.thePlayer.rotationPitch;\n clientSideYaw = mc.thePlayer.rotationYaw;\n // rotating\n if (configuration.followTarget() && configuration.getTarget().isPresent() && !configuration.goingBackToClientSide()) {\n Target target = configuration.getTarget().get();\n Rotation rot;\n if (target.getEntity() != null) {\n if (configuration.bowRotation()) {\n rot = getBowRotation(target.getEntity());\n } else {\n rot = getRotation(target.getEntity());\n }\n } else if (target.getBlockPos() != null) {\n rot = getRotation(target.getBlockPos());\n } else if (target.getTarget().isPresent()) {\n rot = getRotation(target.getTarget().get());\n } else {\n throw new IllegalArgumentException(\"No target specified!\");\n }\n// if (distanceTraveled > 180) {\n// distanceTraveled = 0;\n// startRotation.setRotation(new Rotation(mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch));\n// }\n Rotation neededChange = getNeededChange(startRotation, rot);\n targetRotation.setYaw(startRotation.getYaw() + neededChange.getYaw());\n targetRotation.setPitch(startRotation.getPitch() + neededChange.getPitch());\n// distanceTraveled += Math.abs(neededChange.getYaw());\n// long time = (long) getTime(pythagoras(Math.abs(neededChange.getYaw()), Math.abs(neededChange.getPitch())), configuration.getTime());\n// endTime = System.currentTimeMillis() + Math.max(time, (long) (50 + Math.random() * 100));\n }\n if (configuration.goingBackToClientSide()) {\n LogUtils.debug(\"Going back to client side\");\n targetRotation.setYaw(clientSideYaw);\n targetRotation.setPitch(clientSidePitch);\n }\n if (mc.currentScreen != null || dontRotate.isScheduled() && !dontRotate.passed()) {\n event.yaw = serverSideYaw;\n event.pitch = serverSidePitch;\n endTime = System.currentTimeMillis() + configuration.getTime();\n } else {\n float interX = interpolate(startRotation.getYaw(), targetRotation.getYaw(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n float interY = interpolate(startRotation.getPitch(), targetRotation.getPitch(), configuration.easeOutBack() ? this::easeOutBack : this::easeOutExpo);\n float absDiffX = Math.abs(interX - targetRotation.getYaw());\n float absDiffY = Math.abs(interY - targetRotation.getPitch());\n event.yaw = absDiffX < 0.1 ? targetRotation.getYaw() : interX;\n event.pitch = absDiffY < 0.1 ? targetRotation.getPitch() : interY;\n }\n serverSidePitch = event.pitch;\n serverSideYaw = event.yaw;\n mc.thePlayer.rotationYaw = serverSideYaw;\n mc.thePlayer.rotationPitch = serverSidePitch;\n }\n\n @SubscribeEvent(receiveCanceled = true)\n public void onUpdatePost(MotionUpdateEvent.Post event) {\n if (!rotating) return;\n if (configuration == null || configuration.getRotationType() != RotationConfiguration.RotationType.SERVER)\n return;\n\n mc.thePlayer.rotationYaw = clientSideYaw;\n mc.thePlayer.rotationPitch = clientSidePitch;\n }\n}" }, { "identifier": "Rotation", "path": "src/main/java/com/github/may2beez/mayobees/util/helper/Rotation.java", "snippet": "@Getter\n@Setter\npublic class Rotation {\n private float yaw;\n private float pitch;\n\n public Rotation(float yaw, float pitch) {\n this.yaw = yaw;\n this.pitch = pitch;\n }\n\n public void setRotation(Rotation rotation) {\n this.yaw = rotation.getYaw();\n this.pitch = rotation.getPitch();\n }\n\n public float getValue() {\n return Math.abs(this.yaw) + Math.abs(this.pitch);\n }\n\n @Override\n public String toString() {\n return \"Rotation{\" +\n \"yaw=\" + yaw +\n \", pitch=\" + pitch +\n '}';\n }\n}" } ]
import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.util.helper.Rotation; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.scoreboard.Score; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StringUtils; import net.minecraft.util.Vec3; import java.util.Collections; import java.util.Comparator; import java.util.List;
4,845
package com.github.may2beez.mayobees.util; public class EntityUtils { private final static Minecraft mc = Minecraft.getMinecraft(); public static boolean isPlayer(Entity entity, List<String> playerList) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } return playerList.stream().anyMatch(player -> player.toLowerCase().contains(entity.getName().toLowerCase())); } public static boolean isNPC(Entity entity) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } EntityLivingBase entityLivingBase = (EntityLivingBase) entity; if (StringUtils.stripControlCodes(entityLivingBase.getCustomNameTag()).startsWith("[NPC]")) { return true; } return entity.getUniqueID().version() == 2 && entityLivingBase.getHealth() == 20 && entityLivingBase.getMaxHealth() == 20; } private static boolean isOnTeam(EntityPlayer player) { for (Score score : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getScores()) { if (score.getObjective().getName().equals("health") && score.getPlayerName().contains(player.getName())) { return true; } } return false; } public static boolean isTeam(EntityLivingBase entity) { if (!(entity instanceof EntityPlayer) || entity.getDisplayName().getUnformattedText().length() < 4) { return false; } return isOnTeam((EntityPlayer) entity); } public static boolean isEntityInFOV(Entity entity, double fov) {
package com.github.may2beez.mayobees.util; public class EntityUtils { private final static Minecraft mc = Minecraft.getMinecraft(); public static boolean isPlayer(Entity entity, List<String> playerList) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } return playerList.stream().anyMatch(player -> player.toLowerCase().contains(entity.getName().toLowerCase())); } public static boolean isNPC(Entity entity) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } EntityLivingBase entityLivingBase = (EntityLivingBase) entity; if (StringUtils.stripControlCodes(entityLivingBase.getCustomNameTag()).startsWith("[NPC]")) { return true; } return entity.getUniqueID().version() == 2 && entityLivingBase.getHealth() == 20 && entityLivingBase.getMaxHealth() == 20; } private static boolean isOnTeam(EntityPlayer player) { for (Score score : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getScores()) { if (score.getObjective().getName().equals("health") && score.getPlayerName().contains(player.getName())) { return true; } } return false; } public static boolean isTeam(EntityLivingBase entity) { if (!(entity instanceof EntityPlayer) || entity.getDisplayName().getUnformattedText().length() < 4) { return false; } return isOnTeam((EntityPlayer) entity); } public static boolean isEntityInFOV(Entity entity, double fov) {
Rotation rotation = RotationHandler.getInstance().getRotation(entity);
1
2023-12-24 15:39:11+00:00
8k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/PictureImportActivity.java
[ { "identifier": "ConsumptionDataSource", "path": "app/src/main/java/de/anipe/verbrauchsapp/db/ConsumptionDataSource.java", "snippet": "public class ConsumptionDataSource implements Serializable {\n\n\tprivate static ConsumptionDataSource dataSouce;\n\n\tprivate static final long serialVersionUID = 368016508421825334L;\n\tprivate SQLiteDatabase database;\n\tprivate DBHelper dbHelper;\n\tprivate FileSystemAccessor accessor;\n\tprivate Context context;\n\n\tprivate ConsumptionDataSource(Context context) {\n\t\tdbHelper = new DBHelper(context);\n\t\taccessor = FileSystemAccessor.getInstance();\n\t\tthis.context = context;\n\t}\n\n\tpublic static ConsumptionDataSource getInstance(Context context) {\n\t\tif (dataSouce == null) {\n\t\t\tdataSouce = new ConsumptionDataSource(context);\n\t\t}\n\n\t\treturn dataSouce;\n\t}\n\n\tpublic void open() throws SQLException {\n\t\tdatabase = dbHelper.getWritableDatabase();\n\t}\n\n\tpublic void close() {\n\t\tdbHelper.close();\n\t}\n\n\tpublic List<Consumption> getConsumptionCycles(long carId) {\n\n\t\tList<Consumption> consumptionCyclestList = new LinkedList<>();\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS, null,\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null,\n\t\t\t\tDBHelper.CONSUMPTION_COLUMN_DATE + \" desc\");\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tConsumption cons = cursorToConsumption(cursor);\n\t\t\tconsumptionCyclestList.add(cons);\n\t\t}\n\t\tcursor.close();\n\n\t\treturn consumptionCyclestList;\n\t}\n\n\tpublic Car getCarForId(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS, null,\n\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\treturn cursorToCar(cursor);\n\t\t}\n\t\tcursor.close();\n\t\treturn null;\n\t}\n\n\tpublic int getMileageForCar(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] { \"MAX(\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELMILEAGE + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tint mileage = 0;\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tmileage = cursor.getInt(0);\n\t\t\tLog.d(\"ConsumptionDataSource\", \"Found mileage: \" + mileage);\n\t\t} else {\n\t\t\tcursor.close();\n\t\t\tcursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_STARTKM },\n\t\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null,\n\t\t\t\t\t\"1\");\n\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\tmileage = cursor.getInt(0);\n\t\t\t\tLog.d(\"ConsumptionDataSource\", \"Found start mileage: \"\n\t\t\t\t\t\t+ mileage);\n\t\t\t}\n\t\t}\n\t\tcursor.close();\n\t\treturn mileage;\n\t}\n\n\tpublic double getOverallConsumptionForCar(long carId) {\n\n\t\tdouble consumption = 0;\n\t\tint cycleCount = 0;\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] {\n\t\t\t\t\t\t\"SUM(\" + DBHelper.CONSUMPTION_COLUMN_CONSUMPTION + \")\",\n\t\t\t\t\t\t\"COUNT(\" + DBHelper.COLUMN_ID + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null);\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tconsumption = cursor.getDouble(0);\n\t\t\tcycleCount = cursor.getInt(1);\n\t\t}\n\t\tcursor.close();\n\t\treturn cycleCount == 0 ? 0 : (consumption / cycleCount);\n\t}\n\n\tpublic double getOverallCostsForCar(long carId) {\n\n\t\tdouble costs = 0;\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] { \"SUM(\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELLITERS + \"*\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELPRICE + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null);\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tcosts = cursor.getDouble(0);\n\t\t}\n\t\tcursor.close();\n\t\treturn costs;\n\t}\n\n\tpublic List<Car> getCarList() {\n\n\t\tList<Car> carList = new LinkedList<>();\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS, null, null, null,\n\t\t\t\tnull, null, DBHelper.CAR_COLUMN_TYPE);\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tCar car = cursorToCar(cursor);\n\t\t\tcarList.add(car);\n\t\t}\n\t\tcursor.close();\n\t\treturn carList;\n\t}\n\n\tpublic List<String> getCarTypesList() {\n\n\t\tList<String> carTypesList = new ArrayList<>();\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_TYPE }, null, null, null,\n\t\t\t\tnull, DBHelper.CAR_COLUMN_TYPE);\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tcarTypesList.add(cursor.getString(0));\n\t\t}\n\t\tcursor.close();\n\t\treturn carTypesList;\n\t}\n\n\tpublic long addCar(Car car) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_TYPE, car.getType());\n\t\tvalues.put(DBHelper.CAR_COLUMN_BRAND, car.getBrand().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_NUMBER, car.getNumberPlate());\n\t\tvalues.put(DBHelper.CAR_COLUMN_STARTKM, car.getStartKm());\n\t\tvalues.put(DBHelper.CAR_COLUMN_FUELTPE, car.getFuelType().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA,\n\t\t\t\tgetByteArrayForBitMap(car.getImage()));\n\n\t\ttry {\n\t\t\treturn database.insertOrThrow(DBHelper.TABLE_CARS, null, values);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic long updateCar(Car car) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_TYPE, car.getType());\n\t\tvalues.put(DBHelper.CAR_COLUMN_BRAND, car.getBrand().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_NUMBER, car.getNumberPlate());\n\t\tvalues.put(DBHelper.CAR_COLUMN_STARTKM, car.getStartKm());\n\t\tvalues.put(DBHelper.CAR_COLUMN_FUELTPE, car.getFuelType().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA,\n\t\t\t\tgetByteArrayForBitMap(car.getImage()));\n\n\t\treturn database.update(DBHelper.TABLE_CARS, values, DBHelper.COLUMN_ID\n\t\t\t\t+ \"=?\", new String[] { String.valueOf(car.getCarId()) });\n\t}\n\n\tpublic int deleteCar(Car car) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CARS, DBHelper.COLUMN_ID\n\t\t\t\t\t+ \"=?\", new String[] { String.valueOf(car.getCarId()) });\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic long storeImageForCar(long carId, Bitmap bitmap) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA, getByteArrayForBitMap(bitmap));\n\t\treturn database.update(DBHelper.TABLE_CARS, values, DBHelper.COLUMN_ID\n\t\t\t\t+ \"=?\", new String[] { String.valueOf(carId) });\n\t}\n\n\tpublic Bitmap getImageForCarId(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_IMAGEDATA },\n\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tBitmap bm = null;\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tbm = getBitMapForByteArray(cursor.getBlob(0));\n\t\t}\n\t\tcursor.close();\n\t\treturn bm;\n\t}\n\n\tpublic int deleteConsumption(long consumptionId) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\t\tDBHelper.COLUMN_ID + \"=\" + consumptionId, null);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic int deleteConsumptionsForCar(long carId) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=\" + carId, null);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic void addConsumptions(List<Consumption> consumptionCyclesList) {\n\t\tfor (Consumption cycle : consumptionCyclesList) {\n\t\t\taddConsumption(cycle);\n\t\t}\n\t}\n\n\tpublic long addConsumption(Consumption cycle) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CONSUMPTION_CAR_ID, cycle.getCarId());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_DATE, cycle.getDate().getTime());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELMILEAGE,\n\t\t\t\tcycle.getRefuelmileage());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELLITERS,\n\t\t\t\tcycle.getRefuelliters());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELPRICE,\n\t\t\t\tcycle.getRefuelprice());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_DRIVENMILEAGE,\n\t\t\t\tcycle.getDrivenmileage());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_CONSUMPTION,\n\t\t\t\tcycle.getConsumption());\n\n\t\ttry {\n\t\t\treturn database.insertOrThrow(DBHelper.TABLE_CONSUMPTIONS, null,\n\t\t\t\t\tvalues);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate Car cursorToCar(Cursor cursor) {\n\t\tCar car = new Car();\n\n\t\tcar.setCarId(cursor.getLong(0));\n\t\tcar.setType(cursor.getString(1));\n\t\tcar.setBrand(Brand.fromValue(cursor.getString(2)));\n\t\tcar.setNumberPlate(cursor.getString(3));\n\t\tcar.setStartKm(cursor.getInt(4));\n\t\tcar.setFuelType(Fueltype.fromValue(cursor.getString(5)));\n\t\tcar.setImage(getBitMapForByteArray(cursor.getBlob(6)));\n\t\tcar.setIcon(accessor.getBitmapForBrand(context, car.getBrand()));\n\n\t\treturn car;\n\t}\n\n\tprivate Consumption cursorToConsumption(Cursor cursor) {\n\t\tConsumption consumption = new Consumption();\n\n\t\tconsumption.setId(cursor.getLong(0));\n\t\tconsumption.setCarId(cursor.getLong(1));\n\t\tconsumption.setDate(new Date(cursor.getLong(2)));\n\t\tconsumption.setRefuelmileage(cursor.getInt(3));\n\t\tconsumption.setRefuelliters(cursor.getDouble(4));\n\t\tconsumption.setRefuelprice(cursor.getDouble(5));\n\t\tconsumption.setDrivenmileage(cursor.getInt(6));\n\t\tconsumption.setConsumption(cursor.getDouble(7));\n\n\t\treturn consumption;\n\t}\n\n\tprivate byte[] getByteArrayForBitMap(Bitmap image) {\n\t\tif (image == null) {\n\t\t\treturn new byte[0];\n\t\t}\n\n\t\tByteArrayOutputStream bos = new ByteArrayOutputStream();\n\t\timage.compress(Bitmap.CompressFormat.PNG, 100, bos);\n\t\treturn bos.toByteArray();\n\t}\n\n\tprivate Bitmap getBitMapForByteArray(byte[] blob) {\n\t\tByteArrayInputStream imageStream = new ByteArrayInputStream(blob);\n\t\treturn BitmapFactory.decodeStream(imageStream);\n\t}\n}" }, { "identifier": "FileSystemAccessor", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/FileSystemAccessor.java", "snippet": "public class FileSystemAccessor {\n\n\tprivate static FileSystemAccessor accessor;\n\n\tprivate FileSystemAccessor() {\n\t}\n\n\tpublic static FileSystemAccessor getInstance() {\n\t\tif (accessor == null) {\n\t\t\taccessor = new FileSystemAccessor();\n\t\t}\n\t\treturn accessor;\n\t}\n\n\t/* Checks if external storage is available for read and write */\n\tpublic boolean isExternalStorageWritable() {\n\t\tString state = Environment.getExternalStorageState();\n return Environment.MEDIA_MOUNTED.equals(state);\n }\n\n\t/* Checks if external storage is available to at least read */\n\tpublic boolean isExternalStorageReadable() {\n\t\tString state = Environment.getExternalStorageState();\n return Environment.MEDIA_MOUNTED.equals(state)\n || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);\n }\n\n\tpublic File createOrGetStorageDir(String folderName) {\n\t\tFile file = new File(Environment.getExternalStorageDirectory(),\n\t\t\t\tfolderName);\n\n\t\tif (file.exists() && file.isDirectory()) {\n\t\t\treturn file;\n\t\t}\n\t\tif (!file.mkdirs()) {\n\t\t\tLog.e(FileSystemAccessor.class.getCanonicalName(),\n\t\t\t\t\t\"Directory not created\");\n\t\t}\n\t\treturn file;\n\t}\n\n\tpublic File getFile() {\n\t\treturn Environment.getExternalStorageDirectory();\n\t}\n\n\tpublic File[] readFilesFromStorageDir(File folder) {\n\t\tif (isExternalStorageReadable()) {\n\t\t\tFile[] files = folder.listFiles();\n\t\t\t\n\t\t\tString[] temp = new String[files.length];\n\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\ttemp[i] = files[i].getAbsolutePath();\n\t\t\t}\n\t\t\tArrays.sort(temp);\n\t\t\tFile[] out = new File[files.length];\n\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\tout[i] = new File(temp[i]);\n\t\t\t}\n\t\t\treturn out;\n\t\t\t\n//\t\t\treturn folder.listFiles();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void writeFileToStorageDir(File file, String folderName) {\n\t\tif (isExternalStorageWritable()) {\n\t\t\ttry {\n\t\t\t\tFileOutputStream out = new FileOutputStream(new File(\n\t\t\t\t\t\tcreateOrGetStorageDir(folderName), file.getName()));\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<String> readCSVFileFromStorage(File csvFile) {\n\t\tList<String> res = new LinkedList<>();\n\n\t\ttry {\n\t\t\tBufferedReader in = new BufferedReader(new FileReader(csvFile));\n\t\t\tString zeile = null;\n\t\t\twhile ((zeile = in.readLine()) != null) {\n\t\t\t\tres.add(zeile);\n\t\t\t}\n\n\t\t\tin.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tpublic File writeXMLFileToStorage(Context context, Document doc,\n\t\t\tString folder, String name) throws Exception {\n\n\t\tXMLOutputter xmlOutput = new XMLOutputter();\n\t\txmlOutput.setFormat(Format.getPrettyFormat());\n\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\n\t\t\t\t\"yyyy.MM.dd-HH.mm.ss\", Locale.getDefault());\n\t\tString time = dateFormat.format(new Date());\n\n\t\tFile resultFile = new File(createOrGetStorageDir(folder),\n\t\t\t\tname.replaceAll(\" \", \"_\") + \"_\" + time + \".xml\");\n\t\tFileOutputStream stream = new FileOutputStream(resultFile);\n\n\t\txmlOutput.output(doc, stream);\n\n\t\treturn resultFile;\n\t}\n\n\tpublic Document readXMLDocumentFromFile(String folder, String name)\n\t\t\tthrows Exception {\n\t\tSAXBuilder builder = new SAXBuilder();\n\t\treturn builder.build(new File(folder, name));\n\t}\n\n\tpublic Bitmap getBitmapForBrand(Context context, Brand value) {\n\t\tAssetManager manager = context.getAssets();\n\n\t\tInputStream open = null;\n\t\ttry {\n\t\t\topen = manager.open(value.toString() + \".png\");\n\t\t\treturn BitmapFactory.decodeStream(open);\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tif (open != null) {\n\t\t\t\ttry {\n\t\t\t\t\topen.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Bitmap getBitmapForValue(File file) {\n\t\tFileInputStream streamIn = null;\n\t\ttry {\n\t\t\tstreamIn = new FileInputStream(file);\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBitmap bitmap = BitmapFactory.decodeStream(streamIn);\n\t\ttry {\n\t\t\tstreamIn.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn bitmap;\n\t}\n}" } ]
import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor;
4,172
package de.anipe.verbrauchsapp; public class PictureImportActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final int MAX_FILE_SIZE = 6000000; private ConsumptionDataSource dataSource;
package de.anipe.verbrauchsapp; public class PictureImportActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final int MAX_FILE_SIZE = 6000000; private ConsumptionDataSource dataSource;
private FileSystemAccessor accessor;
1
2023-12-28 12:33:52+00:00
8k
PSButlerII/SqlScriptGen
src/main/java/com/recondev/Main.java
[ { "identifier": "Enums", "path": "src/main/java/com/recondev/helpers/Enums.java", "snippet": "public class Enums {\n\n public enum DatabaseType {\n POSTGRESQL(\"PostgreSQL\"),\n MYSQL(\"MySQL\"),\n MONGODB(\"MongoDB\");\n\n private final String type;\n\n DatabaseType(String type) {\n this.type = type;\n }\n\n public static DatabaseType fromInt(int index) {\n return DatabaseType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n\n public int getValue() {\n return this.ordinal() + 1;\n }\n }\n\n public enum PostgreSQLDataType {\n SMALLINT(\"smallint\"),\n INTEGER(\"integer\"),\n BIGINT(\"bigint\"),\n DECIMAL(\"decimal\"),\n NUMERIC(\"numeric\"),\n REAL(\"real\"),\n DOUBLE_PRECISION(\"double precision\"),\n SERIAL(\"serial\"),\n BIGSERIAL(\"bigserial\"),\n MONEY(\"money\"),\n VARCHAR(\"varchar\"),\n CHAR(\"char\"),\n TEXT(\"text\"),\n BYTEA(\"bytea\"),\n TIMESTAMP(\"timestamp\"),\n DATE(\"date\"),\n TIME(\"time\"),\n INTERVAL(\"interval\"),\n BOOLEAN(\"boolean\"),\n BIT(\"bit\"),\n VARBIT(\"varbit\"),\n UUID(\"uuid\"),\n XML(\"xml\"),\n JSON(\"json\"),\n JSONB(\"jsonb\");\n\n private final String type;\n\n PostgreSQLDataType(String type) {\n this.type = type;\n }\n\n public static PostgreSQLDataType fromInt(int index) {\n return PostgreSQLDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum PostgreSQLComplexDataType {\n POINT(\"point\"),\n LINE(\"line\"),\n LSEG(\"lseg\"),\n BOX(\"box\"),\n PATH(\"path\"),\n POLYGON(\"polygon\"),\n CIRCLE(\"circle\"),\n CIDR(\"cidr\"),\n INET(\"inet\"),\n MACADDR(\"macaddr\"),\n ARRAY(\"array\"); // Note: Array is a more complex type\n\n private final String complexType;\n\n PostgreSQLComplexDataType(String complexType) {\n this.complexType = complexType;\n }\n\n public static PostgreSQLComplexDataType fromInt(int index) {\n return PostgreSQLComplexDataType.values()[index];\n }\n\n public String getComplexType() {\n return complexType;\n }\n }\n\n public enum MySQLDataType {\n TINYINT(\"TINYINT\"),\n SMALLINT(\"SMALLINT\"),\n MEDIUMINT(\"MEDIUMINT\"),\n INT(\"INT\"),\n BIGINT(\"BIGINT\"),\n DECIMAL(\"DECIMAL\"),\n FLOAT(\"FLOAT\"),\n DOUBLE(\"DOUBLE\"),\n BIT(\"BIT\"),\n CHAR(\"CHAR\"),\n VARCHAR(\"VARCHAR\"),\n TINYTEXT(\"TINYTEXT\"),\n TEXT(\"TEXT\"),\n MEDIUMTEXT(\"MEDIUMTEXT\"),\n LONGTEXT(\"LONGTEXT\"),\n DATE(\"DATE\"),\n DATETIME(\"DATETIME\"),\n TIMESTAMP(\"TIMESTAMP\"),\n TIME(\"TIME\"),\n YEAR(\"YEAR\"),\n BINARY(\"BINARY\"),\n VARBINARY(\"VARBINARY\"),\n TINYBLOB(\"TINYBLOB\"),\n BLOB(\"BLOB\"),\n MEDIUMBLOB(\"MEDIUMBLOB\"),\n LONGBLOB(\"LONGBLOB\"),\n ENUM(\"ENUM\"),\n SET(\"SET\");\n\n private final String type;\n\n MySQLDataType(String type) {\n this.type = type;\n }\n\n public static MySQLDataType fromInt(int index) {\n return MySQLDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum MongoDBDataType {\n DOUBLE(\"Double\"),\n STRING(\"String\"),\n BINARY_DATA(\"Binary data\"),\n OBJECT_ID(\"ObjectId\"),\n BOOLEAN(\"Boolean\"),\n DATE(\"Date\"),\n NULL(\"Null\"),\n JAVASCRIPT(\"JavaScript\"),\n INT(\"32-bit integer\"),\n TIMESTAMP(\"Timestamp\"),\n LONG(\"64-bit integer\"),\n DECIMAL128(\"Decimal128\");\n\n private final String type;\n\n MongoDBDataType(String type) {\n this.type = type;\n }\n\n public static MongoDBDataType fromInt(int index) {\n return MongoDBDataType.values()[index];\n }\n\n public String getType() {\n return type;\n }\n }\n\n public enum MongoDBComplexDataType {\n OBJECT(\"Object\"), // Object or embedded document\n ARRAY(\"Array\"), // Array type\n JAVASCRIPT_WITH_SCOPE(\"JavaScript (with scope)\"), // JavaScript code with scope\n DB_POINTER(\"DBPointer (Deprecated)\"), // Reference to another document\n REGEX(\"Regular Expression\"); // Regular expression type\n\n private final String complexType;\n\n MongoDBComplexDataType(String complexType) {\n this.complexType = complexType;\n }\n\n public static MongoDBComplexDataType fromInt(int index) {\n return MongoDBComplexDataType.values()[index];\n }\n\n public String getComplexType() {\n return complexType;\n }\n }\n\n // TODO: Add PostgreSQLConstraintType\n public enum PostgreSQLConstraintType implements DatabaseConstraintType {\n PRIMARY_KEY(\"PRIMARY KEY\"),\n UNIQUE(\"UNIQUE\"),\n CHECK(\"CHECK\"),\n FOREIGN_KEY(\"FOREIGN KEY\"),\n EXCLUSION(\"EXCLUSION\");\n\n private final String constraintType;\n private boolean requiresAdditionalInput;\n\n PostgreSQLConstraintType(String constraintType) {\n this.constraintType = constraintType;\n }\n\n public static PostgreSQLConstraintType fromInt(int index) {\n return PostgreSQLConstraintType.values()[index];\n }\n\n public static PostgreSQLConstraintType fromString(String constraintType) {\n for (PostgreSQLConstraintType type : PostgreSQLConstraintType.values()) {\n if (type.getConstraintType().equals(constraintType)) {\n return type;\n }\n }\n throw new IllegalArgumentException(\"Invalid constraint type\");\n }\n\n public String getConstraintType() {\n return constraintType;\n }\n\n public boolean requiresAdditionalInput() {\n if (this == CHECK || this == FOREIGN_KEY || this == fromString(\"CHECK\") || this == fromString(\"FOREIGN KEY\")) {\n return this.requiresAdditionalInput = true;\n }\n return this.requiresAdditionalInput;\n }\n\n public String getConstraintSQL(String columnName, String additionalInput) {\n switch (this) {\n case PRIMARY_KEY:\n return \"CONSTRAINT \" + columnName + \"_pk \" + this.getConstraintType() + \" (\" + columnName + \")\";\n case UNIQUE:\n return \"CONSTRAINT \" + columnName + \"_unique \" + this.getConstraintType() + \" (\" + columnName + \")\";\n case CHECK:\n return \"CONSTRAINT \" + columnName + \"_check \" + this.getConstraintType() + \" (\" + columnName + \" \" + additionalInput + \")\";\n case FOREIGN_KEY:\n return \"CONSTRAINT \" + columnName + \"_fk \" + this.getConstraintType() + \" (\" + columnName + \") REFERENCES \" + \"(\" + additionalInput + \")\";\n// case EXCLUSION:\n// return \"CONSTRAINT \" + columnName + \"_exclusion \" + this.getConstraintType() + \" USING gist (\" + columnName + \" WITH =)\";\n default:\n throw new IllegalArgumentException(\"Invalid constraint type\");\n }\n }\n }\n\n // TODO: Add MySQLConstraintType\n public enum MySQLConstraintType implements DatabaseConstraintType {\n PRIMARY_KEY(\"PRIMARY KEY\"),\n UNIQUE(\"UNIQUE\"),\n FOREIGN_KEY(\"FOREIGN KEY\"),\n CHECK(\"CHECK\");\n\n private final String constraintType;\n\n MySQLConstraintType(String constraintType) {\n this.constraintType = constraintType;\n }\n\n public static MySQLConstraintType fromInt(int index) {\n return MySQLConstraintType.values()[index];\n }\n\n public String getConstraintType() {\n return constraintType;\n }\n\n /**\n * @return\n */\n @Override\n public boolean requiresAdditionalInput() {\n return false;\n }\n\n /**\n * @param columnName\n * @param additionalInput\n * @return\n */\n @Override\n public String getConstraintSQL(String columnName, String additionalInput) {\n return null;\n }\n }\n\n // TODO: Add MongoDBConstraintType\n}" }, { "identifier": "DatabaseScriptGenerator", "path": "src/main/java/com/recondev/interfaces/DatabaseScriptGenerator.java", "snippet": "public interface DatabaseScriptGenerator {\n String generateCreateTableScript(String table, Map<String, String> columns, List<String> constraints);\n\n String generateCreateDatabaseScript(String name);\n}" }, { "identifier": "ScriptGeneratorFactory", "path": "src/main/java/com/recondev/service/ScriptGeneratorFactory.java", "snippet": "public class ScriptGeneratorFactory {\n public static DatabaseScriptGenerator getScriptGenerator(int dbType) {\n switch (dbType) {\n case 1:\n return new PostgreSQLScriptGenerator();\n case 2:\n return new MySQLScriptGenerator();\n // other cases will go here if i ever get that far\n default:\n throw new IllegalArgumentException(\"Invalid database type\");\n }\n }\n}" }, { "identifier": "UserInteraction", "path": "src/main/java/com/recondev/userinteraction/UserInteraction.java", "snippet": "public class UserInteraction {\n // private String getConstraintString(int constraintCount) {\n//\n// //TODO: Make this method more generic so it can be used for other databases\n// String constraintSQL = null;\n// for (int i = 0; i < constraintCount; i++) {\n// System.out.println(\"Choose constraint type:\");\n//\n// // print out the constraint types\n// for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {\n// System.out.println(j + \": \" + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());\n// }\n//\n// int constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n// Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);\n//\n// System.out.println(\"Enter column name for constraint:\");\n// String columnName = scanner.nextLine();\n//\n// String additionalInput = \"\";\n// if (constraintType.requiresAdditionalInput()) {\n// if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {\n// System.out.println(\"Enter table name for the constraint:\");\n// String tableName = scanner.nextLine();\n//\n// System.out.println(\"Enter column name for the constraint:\");\n// String foreignKeyColumnName = scanner.nextLine();\n//\n// additionalInput = tableName + \"(\" + foreignKeyColumnName + \")\";\n// } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {\n// System.out.println(\"Enter check condition (e.g., column_name > 5):\");\n// additionalInput = scanner.nextLine();\n// }\n//\n// // Assuming other constraint types might need a generic input\n// else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||\n// constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||\n// constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {\n// System.out.println(\"Enter additional input for the constraint:\");\n// additionalInput = scanner.nextLine();\n// }\n// // Handle any other constraints that might need additional input\n// else {\n// System.out.println(\"Enter additional input for the constraint:\");\n// additionalInput = scanner.nextLine();\n// }\n// }\n// constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);\n// }\n// return constraintSQL;\n// }\n private final Scanner scanner = new Scanner(System.in);\n\n public Enums.DatabaseType getDatabaseType() {\n System.out.println(\"Enter database type\\n (1)PostgreSQL\\n (2)MySQL\\n (3)MongoDB)[**Currently only PostgreSQL and MySQL are supported**]\");\n int dbType;\n try {\n try {\n dbType = Integer.parseInt(scanner.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getDatabaseType();\n }\n //get a map of the database types and their corresponding numbers\n Map<Integer, String> dbTypes = new HashMap<>();\n int index = 1;\n for (Enums.DatabaseType type : Enums.DatabaseType.values()) {\n dbTypes.put(index, String.valueOf(type));\n index++;\n }\n //if the user entered a valid number, return the corresponding database type\n if (dbTypes.containsKey(dbType)) {\n return Enums.DatabaseType.valueOf(dbTypes.get(dbType));\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getDatabaseType();\n } catch (IllegalArgumentException e) {\n System.out.println(e.getMessage());\n return getDatabaseType();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return getDatabaseType();\n }\n return null;\n }\n public String getTableName() {\n System.out.println(\"Enter table name:\");\n return scanner.nextLine();\n }\n public Map<String, String> getColumns(Enums.DatabaseType dbType) {\n System.out.println(\"Enter number of columns:\");\n int columnCount;\n Map<String, String> columns;\n\n try {\n try {\n columnCount = Integer.parseInt(scanner.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getColumns(dbType);\n }\n columns = new HashMap<>();\n\n for (int i = 0; i < columnCount; i++) {\n System.out.println(\"Enter column name for column \" + (i + 1) + \":\");\n String columnName = scanner.nextLine();\n System.out.println(\"Enter data type for column \" + columnName + \":\");\n String dataType = promptForDataType(dbType);\n columns.put(columnName, dataType);\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return getColumns(dbType);\n } catch (IllegalArgumentException e) {\n System.out.println(e.getMessage());\n return getColumns(dbType);\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return getColumns(dbType);\n }\n return columns;\n }\n\n public List<String> addSQLConstraints(Enums.DatabaseType dbType) {\n List<String> constraints = new ArrayList<>();\n System.out.println(\"Do you want to add constraints? (yes/no)\");\n String addConstraints;\n String constraintSQL;\n try {\n\n try {\n addConstraints = scanner.nextLine();\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter yes or no\");\n return addSQLConstraints(dbType);\n }\n\n if (addConstraints.equalsIgnoreCase(\"yes\") || addConstraints.equalsIgnoreCase(\"y\")) {\n System.out.println(\"Enter number of constraints:\");\n int constraintCount = Integer.parseInt(scanner.nextLine());\n\n //TODO: Make this method more generic so it can be used for other databases. Maybe pass in the database type?\n// constraintSQL = getConstraint(constraintCount,dbType);\n// constraints.add(constraintSQL);\n\n for (int i = 0; i < constraintCount; i++) {\n String constraint = getConstraint(dbType);\n constraints.add(constraint);\n }\n } else if (addConstraints.equalsIgnoreCase(\"no\") || addConstraints.equalsIgnoreCase(\"n\")) {\n System.out.println(\"No constraints added\");\n } else {\n System.out.println(\"Please enter yes or no\");\n return addSQLConstraints(dbType);\n }\n } catch (NumberFormatException e) {\n System.out.println(\"Please enter a valid number\");\n return addSQLConstraints(dbType);\n } catch (IllegalArgumentException e) {\n System.out.println(\"Input \" + e.getMessage() + \" is not valid\" + \"\\nPlease enter a valid input\");\n return addSQLConstraints(dbType);\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return addSQLConstraints(dbType);\n }\n return constraints;\n }\n\n private String getConstraint(Enums.DatabaseType dbType) {\n\n //TODO: Make this method more generic so it can be used for other databases\n String constraintSQL = null;\n int constraintTypeIndex;\n String columnName;\n System.out.println(\"Choose constraint type:\");\n\n constraintTypeIndex = getConstraintValues(dbType);\n\n //Should this be a method that takes in the database type and returns the appropriate constraint types?\n DatabaseConstraintType constraintType = getSelectedConstraintType(dbType, constraintTypeIndex);\n\n System.out.println(\"Enter column name for constraint:\");\n columnName = scanner.nextLine();\n\n String additionalInput = \"\";\n if (constraintType.requiresAdditionalInput()) {\n if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {\n System.out.println(\"Enter table name for the constraint:\");\n String tableName = scanner.nextLine();\n\n System.out.println(\"Enter column name for the constraint:\");\n String foreignKeyColumnName = scanner.nextLine();\n\n additionalInput = tableName + \"(\" + foreignKeyColumnName + \")\";\n } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {\n System.out.println(\"Enter check condition (e.g., column_name > 5):\");\n additionalInput = scanner.nextLine();\n }\n\n // Assuming other constraint types might need a generic input\n else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||\n constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||\n constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {\n System.out.println(\"Enter additional input for the constraint:\");\n additionalInput = scanner.nextLine();\n }\n // Handle any other constraints that might need additional input\n else {\n System.out.println(\"Enter additional input for the constraint:\");\n additionalInput = scanner.nextLine();\n }\n }\n constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);\n\n\n return constraintSQL;\n }\n\n public int getConstraintValues(Enums.DatabaseType dbType) {\n // Use the dbtype to print out the appropriate constraint types\n int constraintTypeIndex = 0;\n switch (dbType) {\n case POSTGRESQL:\n for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {\n System.out.println(j + \": \" + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());\n }\n constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n return constraintTypeIndex;\n case MYSQL:\n for (int j = 0; j < Enums.MySQLConstraintType.values().length; j++) {\n System.out.println(j + \": \" + Enums.MySQLConstraintType.values()[j].getConstraintType());\n }\n constraintTypeIndex = Integer.parseInt(scanner.nextLine());\n return constraintTypeIndex;\n// case MONGODB:\n// for (int j = 0; j < Enums.MongoDBConstraintType.values().length; j++) {\n// System.out.println(j + \": \" + Enums.MongoDBConstraintType.values()[j].getConstraintType());\n// }\n// break;\n }\n return constraintTypeIndex;\n }\n\n private DatabaseConstraintType getSelectedConstraintType(Enums.DatabaseType dbType, int constraintTypeIndex) {\n switch (dbType) {\n case POSTGRESQL:\n return Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);\n case MYSQL:\n return Enums.MySQLConstraintType.fromInt(constraintTypeIndex);\n // Add cases for other databases\n default:\n throw new IllegalArgumentException(\"Unsupported database type\");\n }\n }\n\n private String promptForDataType(Enums.DatabaseType dbType) {\n List<String> dataTypes = getDataTypesForDatabase(dbType);\n for (int i = 0; i < dataTypes.size(); i++) {\n System.out.println(i + \": \" + dataTypes.get(i));\n }\n System.out.println(\"Select the data type by number:\");\n int dataTypeIndex = scanner.nextInt();\n scanner.nextLine();\n return dataTypes.get(dataTypeIndex);\n }\n private List<String> getDataTypesForDatabase(Enums.DatabaseType dbType) {\n List<String> dataTypes = new ArrayList<>();\n switch (dbType) {\n case POSTGRESQL:\n for (Enums.PostgreSQLDataType type : Enums.PostgreSQLDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n case MYSQL:\n for (Enums.MySQLDataType type : Enums.MySQLDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n case MONGODB:\n for (Enums.MongoDBDataType type : Enums.MongoDBDataType.values()) {\n dataTypes.add(type.getType());\n }\n break;\n }\n return dataTypes;\n }\n\n}" } ]
import com.recondev.helpers.Enums; import com.recondev.interfaces.DatabaseScriptGenerator; import com.recondev.service.ScriptGeneratorFactory; import com.recondev.userinteraction.UserInteraction; import java.util.List; import java.util.Map;
4,959
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction();
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction();
Enums.DatabaseType dbType = ui.getDatabaseType();
0
2023-12-29 01:53:43+00:00
8k
drSolutions-OpenSource/Utilizar_JDBC
psql/src/main/java/Main.java
[ { "identifier": "TipoTelefone", "path": "psql/src/main/java/configuracoes/TipoTelefone.java", "snippet": "public class TipoTelefone {\n\tpublic static final String CELULAR = \"Celular\";\n\tpublic static final String FIXO = \"Fixo\";\n\tpublic static final String COMERCIAL = \"Comercial\";\n\tpublic static final String FAX = \"Fax\";\n}" }, { "identifier": "TelefonesDAO", "path": "psql/src/main/java/dao/TelefonesDAO.java", "snippet": "public class TelefonesDAO {\n\tprivate Connection connection;\n\tprivate String erro;\n\n\t/**\n\t * Construtor que realiza a conexão com o banco de dados\n\t */\n\tpublic TelefonesDAO() {\n\t\tconnection = SingleConnection.getConnection();\n\t}\n\n\t/**\n\t * Salvar um telefone de usuário no banco de dados\n\t * \n\t * @param Telefones sendo as informações do telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean salvar(Telefones telefone) {\n\t\tString sql = \"insert into telefones (tipo,telefone,usuariosid) values (?, ?, ?)\";\n\t\ttry {\n\t\t\tPreparedStatement insert = connection.prepareStatement(sql);\n\t\t\tinsert.setString(1, telefone.getTipo());\n\t\t\tinsert.setString(2, telefone.getTelefone());\n\t\t\tinsert.setLong(3, telefone.getUsuarioid());\n\n\t\t\tint retorno = insert.executeUpdate();\n\t\t\tconnection.commit();\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (PSQLException epsql) {\n\t\t\tepsql.printStackTrace();\n\t\t\tthis.erro = epsql.getMessage();\n\t\t\treturn false;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Alterar telefone no banco de dados\n\t * \n\t * @param Telefones sendo as informações dp telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean alterar(Telefones telefone) {\n\t\tString sql = \"update telefone set tipo = ? , telefone = ? , usuariosid = ? where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement update = connection.prepareStatement(sql);\n\t\t\tupdate.setString(1, telefone.getTipo());\n\t\t\tupdate.setString(2, telefone.getTelefone());\n\t\t\tupdate.setLong(3, telefone.getUsuarioid());\n\t\t\tupdate.setLong(4, telefone.getId());\n\t\t\tint retorno = update.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException esql) {\n\t\t\t\tesql.printStackTrace();\n\t\t\t\tthis.erro = esql.getMessage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Excluir um telefone do banco de dados\n\t * \n\t * @param Long id sendo o id do telefone\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean excluir(Long id) {\n\t\tString sql = \"delete from telefone where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement delete = connection.prepareStatement(sql);\n\t\t\tdelete.setLong(1, id);\n\t\t\tint retorno = delete.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException esql) {\n\t\t\t\tesql.printStackTrace();\n\t\t\t\tthis.erro = esql.getMessage();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os telefones do banco de dados\n\t * \n\t * @return List<Telefones> sendo a lista de telefones\n\t */\n\tpublic List<Telefones> listar() {\n\t\tList<Telefones> lista = new ArrayList<Telefones>();\n\n\t\tString sql = \"select * from telefones order by id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tTelefones telefone = new Telefones();\n\t\t\t\ttelefone.setId(resultado.getLong(\"id\"));\n\t\t\t\ttelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\ttelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\ttelefone.setUsuarioid(resultado.getLong(\"usuariosid\"));\n\t\t\t\tlista.add(telefone);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Lista um telefone do banco de dados\n\t * \n\t * @param Long sendo o id do telefone\n\t * @return Telefones sendo o telefone\n\t */\n\tpublic Telefones buscar(Long id) {\n\t\tTelefones telefone = new Telefones();\n\n\t\tString sql = \"select * from telefones where id = \" + id;\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\ttelefone.setId(resultado.getLong(\"id\"));\n\t\t\t\ttelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\ttelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\ttelefone.setUsuarioid(resultado.getLong(\"usuariosid\"));\n\t\t\t}\n\t\t\treturn telefone;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthis.erro = e.getMessage();\n\t\t\treturn telefone;\n\t\t}\n\t}\n\n\tpublic String getErro() {\n\t\treturn erro;\n\t}\n}" }, { "identifier": "UsuariosDAO", "path": "psql/src/main/java/dao/UsuariosDAO.java", "snippet": "public class UsuariosDAO {\n\tprivate Connection connection;\n\n\t/**\n\t * Construtor que realiza a conexão com o banco de dados\n\t */\n\tpublic UsuariosDAO() {\n\t\tconnection = SingleConnection.getConnection();\n\t}\n\n\t/**\n\t * Salvar um novo usuário no banco de dados\n\t * \n\t * @param Usuarios sendo as informações do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean salvar(Usuarios usuario) {\n\t\tString sql = \"insert into usuarios (nome,email,login,senha) values (?, ?, ?, ?)\";\n\t\ttry {\n\t\t\tPreparedStatement insert = connection.prepareStatement(sql);\n\t\t\tinsert.setString(1, usuario.getNome());\n\t\t\tinsert.setString(2, usuario.getEmail());\n\t\t\tinsert.setString(3, usuario.getLogin());\n\t\t\tinsert.setString(4, usuario.getSenha());\n\t\t\tint retorno = insert.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Alterar um usuário no banco de dados\n\t * \n\t * @param Usuarios sendo as informações do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean alterar(Usuarios usuario) {\n\t\tString sql = \"update usuarios set nome = ? , email = ? , login = ? , senha = ? where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement update = connection.prepareStatement(sql);\n\t\t\tupdate.setString(1, usuario.getNome());\n\t\t\tupdate.setString(2, usuario.getEmail());\n\t\t\tupdate.setString(3, usuario.getLogin());\n\t\t\tupdate.setString(4, usuario.getSenha());\n\t\t\tupdate.setLong(5, usuario.getId());\n\t\t\tint retorno = update.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Excluir um usuário do banco de dados\n\t * \n\t * @param Long id sendo o id do usuário\n\t * @return boolean sendo true no caso de sucesso, e false caso contrário\n\t */\n\tpublic boolean excluir(Long id) {\n\t\tString sql = \"delete from usuarios where id = ?\";\n\t\ttry {\n\t\t\tPreparedStatement delete = connection.prepareStatement(sql);\n\t\t\tdelete.setLong(1, id);\n\t\t\tint retorno = delete.executeUpdate();\n\t\t\tconnection.commit(); /* Salvar no banco de dados */\n\n\t\t\tif (retorno > 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\ttry {\n\t\t\t\tconnection.rollback(); /* Reverter a operação no BD */\n\t\t\t} catch (SQLException sqle) {\n\t\t\t\tsqle.printStackTrace();\n\t\t\t}\n\t\t\te.printStackTrace();\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os usuários do banco de dados\n\t * \n\t * @return List<Usuarios> sendo a lista de usuários\n\t */\n\tpublic List<Usuarios> listar() {\n\t\tList<Usuarios> lista = new ArrayList<Usuarios>();\n\n\t\tString sql = \"select * from usuarios order by id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tUsuarios usuario = new Usuarios();\n\t\t\t\tusuario.setId(resultado.getLong(\"id\"));\n\t\t\t\tusuario.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuario.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuario.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuario.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tlista.add(usuario);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Listar todos os usuários do banco de dados com seus telefones\n\t * \n\t * @return List<UsuarioTelefone> sendo a lista de usuários\n\t */\n\tpublic List<UsuarioTelefone> listarComTelefones() {\n\t\tList<UsuarioTelefone> lista = new ArrayList<UsuarioTelefone>();\n\n\t\tString sql = \"select usuario.nome, usuario.email, usuario.login, usuario.senha, telefone.tipo, telefone.telefone\"\n\t\t\t\t+ \"\tfrom telefones as telefone\" + \"\tinner join usuarios as usuario\"\n\t\t\t\t+ \"\ton telefone.usuariosid = usuario.id \" + \"\torder by telefone.id\";\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tUsuarioTelefone usuarioTelefone = new UsuarioTelefone();\n\t\t\t\tusuarioTelefone.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuarioTelefone.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuarioTelefone.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuarioTelefone.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tusuarioTelefone.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\tusuarioTelefone.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t\tlista.add(usuarioTelefone);\n\t\t\t}\n\t\t\treturn lista;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn lista;\n\t\t}\n\t}\n\n\t/**\n\t * Listar um usuário do banco de dados\n\t * \n\t * @param Long sendo o id do usuário\n\t * @return Usuarios sendo o usuário\n\t */\n\tpublic Usuarios buscar(Long id) {\n\t\tUsuarios retorno = new Usuarios();\n\t\tString sql = \"select * from usuarios where id = ?\";\n\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tselect.setLong(1, id);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tretorno.setId(resultado.getLong(\"id\"));\n\t\t\t\tretorno.setNome(resultado.getString(\"nome\"));\n\t\t\t\tretorno.setEmail(resultado.getString(\"email\"));\n\t\t\t\tretorno.setLogin(resultado.getString(\"login\"));\n\t\t\t\tretorno.setSenha(resultado.getString(\"senha\"));\n\t\t\t}\n\t\t\treturn retorno;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn retorno;\n\t\t}\n\t}\n\n\t/**\n\t * Listar um usuário do banco de dados com seu telefone\n\t * \n\t * @param Long sendo o id do usuário\n\t * @return UsuarioTelefone sendo o usuário\n\t */\n\tpublic UsuarioTelefone buscarComTelefone(Long id) {\n\t\tUsuarioTelefone usuario = new UsuarioTelefone();\n\n\t\tString sql = \"select usuario.nome, usuario.email, usuario.login, usuario.senha, telefone.tipo, telefone.telefone\"\n\t\t\t\t+ \"\tfrom telefones as telefone\" + \"\tinner join usuarios as usuario\"\n\t\t\t\t+ \"\ton telefone.usuariosid = usuario.id \" + \"\twhere usuario.id = \" + id;\n\t\ttry {\n\t\t\tPreparedStatement select = connection.prepareStatement(sql);\n\t\t\tResultSet resultado = select.executeQuery();\n\n\t\t\twhile (resultado.next()) {\n\t\t\t\tusuario.setNome(resultado.getString(\"nome\"));\n\t\t\t\tusuario.setEmail(resultado.getString(\"email\"));\n\t\t\t\tusuario.setLogin(resultado.getString(\"login\"));\n\t\t\t\tusuario.setSenha(resultado.getString(\"senha\"));\n\t\t\t\tusuario.setTipo(resultado.getString(\"tipo\"));\n\t\t\t\tusuario.setTelefone(resultado.getString(\"telefone\"));\n\t\t\t}\n\t\t\treturn usuario;\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn usuario;\n\t\t}\n\t}\n\n\t/**\n\t * Gerar um hash de senha\n\t * \n\t * @param senha String sendo a senha original\n\t * @return String sendo a senha com hash\n\t */\n\tpublic String gerarSenhaHash(String senha) {\n\t\tSecureRandom random = new SecureRandom();\n\t\tbyte[] salt = new byte[16];\n\t\trandom.nextBytes(salt);\n\t\tKeySpec spec = new PBEKeySpec(senha.toCharArray(), salt, 65536, 128);\n\t\tSecretKeyFactory f;\n\t\tbyte[] hash = null;\n\t\ttry {\n\t\t\tf = SecretKeyFactory.getInstance(\"PBKDF2WithHmacSHA1\");\n\t\t\thash = f.generateSecret(spec).getEncoded();\n\t\t} catch (NoSuchAlgorithmException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (InvalidKeySpecException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBase64.Encoder enc = Base64.getEncoder();\n\t\treturn enc.encodeToString(hash);\n\t}\n}" }, { "identifier": "Telefones", "path": "psql/src/main/java/model/Telefones.java", "snippet": "public class Telefones {\n\tprivate Long id;\n\tprivate String tipo;\n\tprivate String telefone;\n\tprivate Long usuarioid;\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 Long getUsuarioid() {\n\t\treturn usuarioid;\n\t}\n\n\tpublic void setUsuarioid(Long usuarioid) {\n\t\tthis.usuarioid = usuarioid;\n\t}\n\n\tpublic String getTipo() {\n\t\treturn tipo;\n\t}\n\n\tpublic void setTipo(String tipo) {\n\t\tthis.tipo = tipo;\n\t}\n\n\tpublic String getTelefone() {\n\t\treturn telefone;\n\t}\n\n\tpublic void setTelefone(String telefone) {\n\t\tthis.telefone = telefone;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Telefones [id=\" + id + \", tipo=\" + tipo + \", telefone=\" + telefone + \", usuarioid=\" + usuarioid + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(id, telefone, tipo, usuarioid);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tTelefones other = (Telefones) obj;\n\t\treturn Objects.equals(id, other.id) && Objects.equals(telefone, other.telefone)\n\t\t\t\t&& Objects.equals(tipo, other.tipo) && Objects.equals(usuarioid, other.usuarioid);\n\t}\n}" }, { "identifier": "UsuarioTelefone", "path": "psql/src/main/java/model/UsuarioTelefone.java", "snippet": "public class UsuarioTelefone {\n\tString nome;\n\tString email;\n\tString login;\n\tString senha;\n\tString tipo;\n\tString telefone;\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getTipo() {\n\t\treturn tipo;\n\t}\n\n\tpublic void setTipo(String tipo) {\n\t\tthis.tipo = tipo;\n\t}\n\n\tpublic String getTelefone() {\n\t\treturn telefone;\n\t}\n\n\tpublic void setTelefone(String telefone) {\n\t\tthis.telefone = telefone;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UsuarioTelefone [nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \", tipo=\" + tipo + \", telefone=\" + telefone + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(email, login, nome, senha, telefone, tipo);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUsuarioTelefone other = (UsuarioTelefone) obj;\n\t\treturn Objects.equals(email, other.email) && Objects.equals(login, other.login)\n\t\t\t\t&& Objects.equals(nome, other.nome) && Objects.equals(senha, other.senha)\n\t\t\t\t&& Objects.equals(telefone, other.telefone) && Objects.equals(tipo, other.tipo);\n\t}\n}" }, { "identifier": "Usuarios", "path": "psql/src/main/java/model/Usuarios.java", "snippet": "public class Usuarios {\n\tprivate Long id;\n\tprivate String nome;\n\tprivate String email;\n\tprivate String login;\n\tprivate String senha;\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 getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Usuarios [id=\" + id + \", nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \"]\";\n\t}\n}" } ]
import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.List; import configuracoes.TipoTelefone; import dao.TelefonesDAO; import dao.UsuariosDAO; import model.Telefones; import model.UsuarioTelefone; import model.Usuarios;
5,654
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("[email protected]"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO();
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("[email protected]"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("[email protected]"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO();
Telefones telefone = new Telefones();
3
2023-12-30 14:50:31+00:00
8k
JoshiCodes/NewLabyAPI
src/main/java/de/joshicodes/newlabyapi/api/LabyModAPI.java
[ { "identifier": "LabyModProtocol", "path": "src/main/java/de/joshicodes/newlabyapi/LabyModProtocol.java", "snippet": "public class LabyModProtocol {\n\n /**\n * Send a message to LabyMod\n * @param player Minecraft Client\n * @param key LabyMod message key\n * @param messageContent json object content\n */\n public static void sendLabyModMessage(Player player, String key, JsonElement messageContent ) {\n\n // Send Plugin Message to Player\n // a String consists of two components:\n // - varint: the string's length\n // - byte-array: the string's content\n //\n // The packet's data consists of two strings:\n // - the message's key\n // - the message's contents\n\n // Getting the bytes that should be sent\n byte[] bytes = getBytesToSend( key, messageContent.toString() );\n\n // Sending the bytes to the player\n player.sendPluginMessage( NewLabyPlugin.getInstance(), \"labymod3:main\", bytes );\n\n }\n\n /**\n * Gets the bytes that are required to send the given message\n *\n * @param messageKey the message's key\n * @param messageContents the message's contents\n * @return the byte array that should be the payload\n */\n public static byte[] getBytesToSend( String messageKey, String messageContents ) {\n // Getting an empty buffer\n ByteBuf byteBuf = Unpooled.buffer();\n\n // Writing the message-key to the buffer\n writeString( byteBuf, messageKey );\n\n // Writing the contents to the buffer\n writeString( byteBuf, messageContents );\n\n // Copying the buffer's bytes to the byte array\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes( bytes );\n\n // Release the buffer\n byteBuf.release();\n\n // Returning the byte array\n return bytes;\n }\n\n /**\n * Writes a varint to the given byte buffer\n *\n * @param buf the byte buffer the int should be written to\n * @param input the int that should be written to the buffer\n */\n private static void writeVarIntToBuffer( ByteBuf buf, int input ) {\n while ( (input & -128) != 0 ) {\n buf.writeByte( input & 127 | 128 );\n input >>>= 7;\n }\n\n buf.writeByte( input );\n }\n\n /**\n * Writes a string to the given byte buffer\n *\n * @param buf the byte buffer the string should be written to\n * @param string the string that should be written to the buffer\n */\n private static void writeString( ByteBuf buf, String string ) {\n byte[] abyte = string.getBytes(StandardCharsets.UTF_8);\n\n if ( abyte.length > Short.MAX_VALUE ) {\n throw new EncoderException( \"String too big (was \" + string.length() + \" bytes encoded, max \" + Short.MAX_VALUE + \")\" );\n } else {\n writeVarIntToBuffer( buf, abyte.length );\n buf.writeBytes( abyte );\n }\n }\n\n /**\n * Reads a varint from the given byte buffer\n *\n * @param buf the byte buffer the varint should be read from\n * @return the int read\n */\n public static int readVarIntFromBuffer( ByteBuf buf ) {\n int i = 0;\n int j = 0;\n\n byte b0;\n do {\n b0 = buf.readByte();\n i |= (b0 & 127) << j++ * 7;\n if ( j > 5 ) {\n throw new RuntimeException( \"VarInt too big\" );\n }\n } while ( (b0 & 128) == 128 );\n\n return i;\n }\n\n /**\n * Reads a string from the given byte buffer\n *\n * @param buf the byte buffer the string should be read from\n * @param maxLength the string's max-length\n * @return the string read\n */\n public static String readString( ByteBuf buf, int maxLength ) {\n int i = readVarIntFromBuffer( buf );\n\n if ( i > maxLength * 4 ) {\n throw new DecoderException( \"The received encoded string buffer length is longer than maximum allowed (\" + i + \" > \" + maxLength * 4 + \")\" );\n } else if ( i < 0 ) {\n throw new DecoderException( \"The received encoded string buffer length is less than zero! Weird string!\" );\n } else {\n byte[] bytes = new byte[i];\n buf.readBytes( bytes );\n\n String s = new String( bytes, StandardCharsets.UTF_8);\n if ( s.length() > maxLength ) {\n throw new DecoderException( \"The received string length is longer than maximum allowed (\" + i + \" > \" + maxLength + \")\" );\n } else {\n return s;\n }\n }\n }\n\n}" }, { "identifier": "NewLabyPlugin", "path": "src/main/java/de/joshicodes/newlabyapi/NewLabyPlugin.java", "snippet": "public final class NewLabyPlugin extends JavaPlugin {\n\n public static final Component PREFIX = MiniMessage.miniMessage().deserialize(\n \"<b><gradient:#227eb8:#53bbfb>NewLabyAPI</gradient></b> <gray>»</gray>\"\n );\n\n private static NewLabyPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n if (!getDataFolder().exists())\n getDataFolder().mkdir();\n saveDefaultConfig();\n\n LabyModAPI.init(this);\n\n getServer().getMessenger().registerIncomingPluginChannel(this, \"labymod3:main\", new LabyPluginMessageListener());\n getServer().getMessenger().registerOutgoingPluginChannel(this, \"labymod3:main\");\n\n PluginManager pluginManager = getServer().getPluginManager();\n pluginManager.registerEvents(new PlayerListener(), this);\n\n pluginManager.registerEvents(new ConfigListener(getConfig()), this);\n\n if (getConfig().getBoolean(\"updateChecks.enabled\", true)) {\n final NewLabyPlugin instance = this;\n new BukkitRunnable() {\n @Override\n public void run() {\n getLogger().info(\"Checking for updates...\");\n String version = getDescription().getVersion();\n if (version.contains(\"-dev\")) {\n // Don't check for updates if the version is a dev version\n getLogger().info(\"You are running a dev version, so no update check will be performed!\");\n return;\n }\n UpdateChecker updateChecker = new UpdateChecker(instance);\n try {\n updateChecker.checkForUpdate();\n } catch (IOException e) {\n getLogger().warning(\"Could not check for updates!\");\n return;\n }\n if (!updateChecker.isUpToDate()) {\n final String url = \"https://github.com/JoshiCodes/NewLabyAPI/releases/latest\";\n final String current = getDescription().getVersion();\n getLogger().info(\" \");\n getLogger().info(\" \");\n getLogger().info(\"There is a new version available! (\" + updateChecker.getLatestVersion() + \")\");\n getLogger().info(\"You are running:\" + current);\n getLogger().info(\"Download it here: \" + url);\n if (getConfig().getBoolean(\"updateChecks.joinNotify\", true)) {\n final String permission = getConfig().getString(\"updateChecks.joinNotifyPerm\", \"newlabyapi.update\");\n pluginManager.registerEvents(new Listener() {\n @EventHandler\n public void onJoin(PlayerJoinEvent e) {\n if (e.getPlayer().hasPermission(permission)) {\n e.getPlayer().sendMessage(Component.space());\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>There is a new version available! (\" + updateChecker.getLatestVersion() + \")</gradient>\"\n )\n )\n );\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>You are running:</gradient> <b><color:#53bbfb>\" + current + \"</color></b>\"\n )\n )\n );\n e.getPlayer().sendMessage(\n Component.join(\n JoinConfiguration.separator(Component.space()),\n PREFIX,\n MiniMessage.miniMessage().deserialize(\n \"<gradient:#227eb8:#53bbfb>Download it here:</gradient> <b><color:#53bbfb><click:open_url:'\" + url + \"'>\" + url + \"</click></color></b>\"\n )\n )\n );\n }\n }\n }, instance);\n }\n } else {\n getLogger().info(\"You are running the latest version!\");\n }\n }\n }.runTaskLater(this, 20);\n }\n\n }\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n\n public static NewLabyPlugin getInstance() {\n return instance;\n }\n\n public static void debug(String s) {\n NewLabyPlugin instance = NewLabyPlugin.getInstance();\n if (instance.getConfig().getBoolean(\"debug\")) {\n instance.getLogger().info(\"[DEBUG] \" + s);\n }\n }\n\n}" }, { "identifier": "LabyModPlayerJoinEvent", "path": "src/main/java/de/joshicodes/newlabyapi/api/event/player/LabyModPlayerJoinEvent.java", "snippet": "public class LabyModPlayerJoinEvent extends LabyModPlayerEvent {\n\n private final String rawJson;\n\n public LabyModPlayerJoinEvent(LabyModPlayer player, String json) {\n super(player);\n this.rawJson = json;\n }\n\n public String getRawJson() {\n return rawJson;\n }\n\n @Override\n public HandlerList getHandlers() {\n return super.getHandlers();\n }\n\n}" }, { "identifier": "InputPrompt", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/InputPrompt.java", "snippet": "public class InputPrompt implements LabyProtocolObject {\n\n private int id;\n private String message;\n private String value;\n private String placeholder;\n private int maxLength;\n\n /**\n * @param id A unique id for each packet, use a static number and increase it for each prompt request\n * @param message The message above the text field\n * @param value The value inside of the text field\n * @param placeholder A placeholder text inside of the text field if there is no value given\n * @param maxLength Max amount of characters of the text field value\n */\n public InputPrompt(final int id, String message, String value, String placeholder, int maxLength) {\n this.id = id;\n this.message = message;\n this.value = value;\n this.placeholder = placeholder;\n this.maxLength = maxLength;\n }\n\n /**\n * @param id A unique id for each packet, use a static number and increase it for each prompt request\n * @param message The message above the text field\n * @param value The value inside of the text field\n * @param placeholder A placeholder text inside of the text field if there is no value given\n */\n public InputPrompt(final int id, String message, String value, String placeholder) {\n this(id, message, value, placeholder, 0);\n }\n\n public InputPrompt setMessage(String message) {\n this.message = message;\n return this;\n }\n\n public InputPrompt setValue(String value) {\n this.value = value;\n return this;\n }\n\n public InputPrompt setPlaceholder(String placeholder) {\n this.placeholder = placeholder;\n return this;\n }\n\n public InputPrompt setMaxLength(int maxLength) {\n this.maxLength = maxLength;\n return this;\n }\n\n @Override\n public JsonObject toJson() {\n JsonObject object = new JsonObject();\n object.addProperty(\"id\", id);\n if(message != null)\n object.addProperty(\"message\", message);\n if(value != null)\n object.addProperty(\"value\", value);\n if(placeholder != null)\n object.addProperty(\"placeholder\", placeholder);\n if(maxLength > 0)\n object.addProperty(\"max_length\", maxLength);\n return object;\n }\n\n}" }, { "identifier": "LabyModPlayerSubtitle", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/LabyModPlayerSubtitle.java", "snippet": "public class LabyModPlayerSubtitle implements LabyProtocolObject {\n\n private final UUID uuid;\n private double size;\n private @Nullable String value;\n private @Nullable Component valueComponent;\n\n public LabyModPlayerSubtitle(final UUID uuid) {\n this.uuid = uuid;\n this.value = null;\n this.size = 0.8d;\n }\n\n public LabyModPlayerSubtitle(final UUID uuid, final double size, final @Nullable String value) {\n this.uuid = uuid;\n this.value = value;\n setSize(size);\n }\n\n public LabyModPlayerSubtitle(final UUID uuid, final double size, final @Nullable Component valueComponent) {\n this.uuid = uuid;\n this.valueComponent = valueComponent;\n setSize(size);\n }\n\n /**\n * Set the size of the subtitle<br>\n * This should be between 0.8 and 1.6.\n * @param size The size of the subtitle\n * @throws IllegalArgumentException if the size is not between 0.8 and 1.6\n * @return The current instance\n */\n public LabyModPlayerSubtitle setSize(double size) {\n if(size < 0.8 || size > 1.6) throw new IllegalArgumentException(\"Size must be between 0.8 and 1.6\");\n this.size = size;\n return this;\n }\n\n /**\n * Set the subtitle text. <br>\n * Set to null to remove the subtitle.\n * @param value The subtitle text or null\n * @return The current instance\n */\n public LabyModPlayerSubtitle setValue(@Nullable String value) {\n this.value = value;\n return this;\n }\n\n /**\n * Set the subtitle text. <br>\n * Set to null to remove the subtitle.\n * @param value The subtitle text or null\n * @return The current instance\n */\n public LabyModPlayerSubtitle setValue(@Nullable Component value) {\n this.valueComponent = value;\n return this;\n }\n\n public UUID getUUID() {\n return uuid;\n }\n\n public double getSize() {\n return size;\n }\n\n @Nullable\n public String getValue() {\n return value;\n }\n\n @Nullable\n public Component getValueComponent() {\n return valueComponent;\n }\n\n @Override\n public JsonElement toJson() {\n JsonObject object = new JsonObject();\n object.addProperty(\"uuid\", uuid.toString());\n object.addProperty(\"size\", size);\n if(valueComponent != null)\n object.addProperty(\"raw_json_text\", JSONComponentSerializer.json().serialize(valueComponent));\n else if(value != null)\n object.addProperty(\"value\", value);\n return object;\n }\n\n}" }, { "identifier": "LabyProtocolObject", "path": "src/main/java/de/joshicodes/newlabyapi/api/object/LabyProtocolObject.java", "snippet": "public interface LabyProtocolObject {\n\n JsonElement toJson();\n\n}" } ]
import com.google.gson.JsonObject; import de.joshicodes.newlabyapi.LabyModProtocol; import de.joshicodes.newlabyapi.NewLabyPlugin; import de.joshicodes.newlabyapi.api.event.player.LabyModPlayerJoinEvent; import de.joshicodes.newlabyapi.api.object.InputPrompt; import de.joshicodes.newlabyapi.api.object.LabyModPlayerSubtitle; import de.joshicodes.newlabyapi.api.object.LabyProtocolObject; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
3,973
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); }
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); }
public static void sendPrompt(Player player, InputPrompt prompt) {
3
2023-12-24 15:00:08+00:00
8k
1752597830/admin-common
qf-admin/back/admin-init-main/src/main/java/com/qf/server/Server.java
[ { "identifier": "Arith", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/server/util/Arith.java", "snippet": "public class Arith\n{\n\n /** 默认除法运算精度 */\n private static final int DEF_DIV_SCALE = 10;\n\n /** 这个类不能实例化 */\n private Arith()\n {\n }\n\n /**\n * 提供精确的加法运算。\n * @param v1 被加数\n * @param v2 加数\n * @return 两个参数的和\n */\n public static double add(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.add(b2).doubleValue();\n }\n\n /**\n * 提供精确的减法运算。\n * @param v1 被减数\n * @param v2 减数\n * @return 两个参数的差\n */\n public static double sub(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.subtract(b2).doubleValue();\n }\n\n /**\n * 提供精确的乘法运算。\n * @param v1 被乘数\n * @param v2 乘数\n * @return 两个参数的积\n */\n public static double mul(double v1, double v2)\n {\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n return b1.multiply(b2).doubleValue();\n }\n\n /**\n * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到\n * 小数点以后10位,以后的数字四舍五入。\n * @param v1 被除数\n * @param v2 除数\n * @return 两个参数的商\n */\n public static double div(double v1, double v2)\n {\n return div(v1, v2, DEF_DIV_SCALE);\n }\n\n /**\n * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指\n * 定精度,以后的数字四舍五入。\n * @param v1 被除数\n * @param v2 除数\n * @param scale 表示表示需要精确到小数点以后几位。\n * @return 两个参数的商\n */\n public static double div(double v1, double v2, int scale)\n {\n if (scale < 0)\n {\n throw new IllegalArgumentException(\n \"The scale must be a positive integer or zero\");\n }\n BigDecimal b1 = new BigDecimal(Double.toString(v1));\n BigDecimal b2 = new BigDecimal(Double.toString(v2));\n if (b1.compareTo(BigDecimal.ZERO) == 0)\n {\n return BigDecimal.ZERO.doubleValue();\n }\n return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();\n }\n\n /**\n * 提供精确的小数位四舍五入处理。\n * @param v 需要四舍五入的数字\n * @param scale 小数点后保留几位\n * @return 四舍五入后的结果\n */\n public static double round(double v, int scale)\n {\n if (scale < 0)\n {\n throw new IllegalArgumentException(\n \"The scale must be a positive integer or zero\");\n }\n BigDecimal b = new BigDecimal(Double.toString(v));\n BigDecimal one = BigDecimal.ONE;\n return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();\n }\n}" }, { "identifier": "IpUtils", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/server/util/IpUtils.java", "snippet": "public class IpUtils\n{\n public final static String REGX_0_255 = \"(25[0-5]|2[0-4]\\\\d|1\\\\d{2}|[1-9]\\\\d|\\\\d)\";\n // 匹配 ip\n public final static String REGX_IP = \"((\" + REGX_0_255 + \"\\\\.){3}\" + REGX_0_255 + \")\";\n public final static String REGX_IP_WILDCARD = \"(((\\\\*\\\\.){3}\\\\*)|(\" + REGX_0_255 + \"(\\\\.\\\\*){3})|(\" + REGX_0_255 + \"\\\\.\" + REGX_0_255 + \")(\\\\.\\\\*){2}\" + \"|((\" + REGX_0_255 + \"\\\\.){3}\\\\*))\";\n // 匹配网段\n public final static String REGX_IP_SEG = \"(\" + REGX_IP + \"\\\\-\" + REGX_IP + \")\";\n\n /**\n * 获取客户端IP\n * \n * @return IP地址\n */\n //public static String getIpAddr()\n //{\n // return getIpAddr(ServletUtils.getRequest());\n //}\n\n /**\n * 获取客户端IP\n * \n * @param request 请求对象\n * @return IP地址\n */\n public static String getIpAddr(HttpServletRequest request)\n {\n if (request == null)\n {\n return \"unknown\";\n }\n String ip = request.getHeader(\"x-forwarded-for\");\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"X-Forwarded-For\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getHeader(\"X-Real-IP\");\n }\n\n if (ip == null || ip.length() == 0 || \"unknown\".equalsIgnoreCase(ip))\n {\n ip = request.getRemoteAddr();\n }\n\n return \"0:0:0:0:0:0:0:1\".equals(ip) ? \"127.0.0.1\" : getMultistageReverseProxyIp(ip);\n }\n\n /**\n * 检查是否为内部IP地址\n * \n * @param ip IP地址\n * @return 结果\n */\n public static boolean internalIp(String ip)\n {\n byte[] addr = textToNumericFormatV4(ip);\n return internalIp(addr) || \"127.0.0.1\".equals(ip);\n }\n\n /**\n * 检查是否为内部IP地址\n * \n * @param addr byte地址\n * @return 结果\n */\n private static boolean internalIp(byte[] addr)\n {\n if (addr == null || addr.length < 2)\n {\n return true;\n }\n final byte b0 = addr[0];\n final byte b1 = addr[1];\n // 10.x.x.x/8\n final byte SECTION_1 = 0x0A;\n // 172.16.x.x/12\n final byte SECTION_2 = (byte) 0xAC;\n final byte SECTION_3 = (byte) 0x10;\n final byte SECTION_4 = (byte) 0x1F;\n // 192.168.x.x/16\n final byte SECTION_5 = (byte) 0xC0;\n final byte SECTION_6 = (byte) 0xA8;\n switch (b0)\n {\n case SECTION_1:\n return true;\n case SECTION_2:\n if (b1 >= SECTION_3 && b1 <= SECTION_4)\n {\n return true;\n }\n case SECTION_5:\n switch (b1)\n {\n case SECTION_6:\n return true;\n }\n default:\n return false;\n }\n }\n\n /**\n * 将IPv4地址转换成字节\n * \n * @param text IPv4地址\n * @return byte 字节\n */\n public static byte[] textToNumericFormatV4(String text)\n {\n if (text.length() == 0)\n {\n return null;\n }\n\n byte[] bytes = new byte[4];\n String[] elements = text.split(\"\\\\.\", -1);\n try\n {\n long l;\n int i;\n switch (elements.length)\n {\n case 1:\n l = Long.parseLong(elements[0]);\n if ((l < 0L) || (l > 4294967295L))\n {\n return null;\n }\n bytes[0] = (byte) (int) (l >> 24 & 0xFF);\n bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);\n bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 2:\n l = Integer.parseInt(elements[0]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[0] = (byte) (int) (l & 0xFF);\n l = Integer.parseInt(elements[1]);\n if ((l < 0L) || (l > 16777215L))\n {\n return null;\n }\n bytes[1] = (byte) (int) (l >> 16 & 0xFF);\n bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 3:\n for (i = 0; i < 2; ++i)\n {\n l = Integer.parseInt(elements[i]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[i] = (byte) (int) (l & 0xFF);\n }\n l = Integer.parseInt(elements[2]);\n if ((l < 0L) || (l > 65535L))\n {\n return null;\n }\n bytes[2] = (byte) (int) (l >> 8 & 0xFF);\n bytes[3] = (byte) (int) (l & 0xFF);\n break;\n case 4:\n for (i = 0; i < 4; ++i)\n {\n l = Integer.parseInt(elements[i]);\n if ((l < 0L) || (l > 255L))\n {\n return null;\n }\n bytes[i] = (byte) (int) (l & 0xFF);\n }\n break;\n default:\n return null;\n }\n }\n catch (NumberFormatException e)\n {\n return null;\n }\n return bytes;\n }\n\n /**\n * 获取IP地址\n * \n * @return 本地IP地址\n */\n public static String getHostIp()\n {\n try\n {\n return InetAddress.getLocalHost().getHostAddress();\n }\n catch (UnknownHostException e)\n {\n }\n return \"127.0.0.1\";\n }\n\n /**\n * 获取主机名\n * \n * @return 本地主机名\n */\n public static String getHostName()\n {\n try\n {\n return InetAddress.getLocalHost().getHostName();\n }\n catch (UnknownHostException e)\n {\n }\n return \"未知\";\n }\n\n /**\n * 从多级反向代理中获得第一个非unknown IP地址\n *\n * @param ip 获得的IP地址\n * @return 第一个非unknown IP地址\n */\n public static String getMultistageReverseProxyIp(String ip)\n {\n // 多级反向代理检测\n if (ip != null && ip.indexOf(\",\") > 0)\n {\n final String[] ips = ip.trim().split(\",\");\n for (String subIp : ips)\n {\n if (false == isUnknown(subIp))\n {\n ip = subIp;\n break;\n }\n }\n }\n return StringUtils.substring(ip, 0, 255);\n }\n\n /**\n * 检测给定字符串是否为未知,多用于检测HTTP请求相关\n *\n * @param checkString 被检测的字符串\n * @return 是否未知\n */\n public static boolean isUnknown(String checkString)\n {\n return StringUtils.isBlank(checkString) || \"unknown\".equalsIgnoreCase(checkString);\n }\n\n /**\n * 是否为IP\n */\n public static boolean isIP(String ip)\n {\n return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP);\n }\n\n /**\n * 是否为IP,或 *为间隔的通配符地址\n */\n public static boolean isIpWildCard(String ip)\n {\n return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD);\n }\n\n /**\n * 检测参数是否在ip通配符里\n */\n public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip)\n {\n String[] s1 = ipWildCard.split(\"\\\\.\");\n String[] s2 = ip.split(\"\\\\.\");\n boolean isMatchedSeg = true;\n for (int i = 0; i < s1.length && !s1[i].equals(\"*\"); i++)\n {\n if (!s1[i].equals(s2[i]))\n {\n isMatchedSeg = false;\n break;\n }\n }\n return isMatchedSeg;\n }\n\n /**\n * 是否为特定格式如:“10.10.10.1-10.10.10.99”的ip段字符串\n */\n public static boolean isIPSegment(String ipSeg)\n {\n return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG);\n }\n\n /**\n * 判断ip是否在指定网段中\n */\n public static boolean ipIsInNetNoCheck(String iparea, String ip)\n {\n int idx = iparea.indexOf('-');\n String[] sips = iparea.substring(0, idx).split(\"\\\\.\");\n String[] sipe = iparea.substring(idx + 1).split(\"\\\\.\");\n String[] sipt = ip.split(\"\\\\.\");\n long ips = 0L, ipe = 0L, ipt = 0L;\n for (int i = 0; i < 4; ++i)\n {\n ips = ips << 8 | Integer.parseInt(sips[i]);\n ipe = ipe << 8 | Integer.parseInt(sipe[i]);\n ipt = ipt << 8 | Integer.parseInt(sipt[i]);\n }\n if (ips > ipe)\n {\n long t = ips;\n ips = ipe;\n ipe = t;\n }\n return ips <= ipt && ipt <= ipe;\n }\n\n /**\n * 校验ip是否符合过滤串规则\n * \n * @param filter 过滤IP列表,支持后缀'*'通配,支持网段如:`10.10.10.1-10.10.10.99`\n * @param ip 校验IP地址\n * @return boolean 结果\n */\n public static boolean isMatchedIp(String filter, String ip)\n {\n if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip))\n {\n return false;\n }\n String[] ips = filter.split(\";\");\n for (String iStr : ips)\n {\n if (isIP(iStr) && iStr.equals(ip))\n {\n return true;\n }\n else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip))\n {\n return true;\n }\n else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip))\n {\n return true;\n }\n }\n return false;\n }\n}" } ]
import com.qf.server.util.Arith; import com.qf.server.util.IpUtils; import lombok.ToString; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.CentralProcessor.TickType; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.List; import java.util.Properties;
5,093
package com.qf.server; /** * 服务器相关信息 * * @author ruoyi */ @ToString public class Server { private static final int OSHI_WAIT_SECOND = 1000; /** * CPU相关信息 */ private Cpu cpu = new Cpu(); /** * 內存相关信息 */ private Mem mem = new Mem(); /** * JVM相关信息 */ private Jvm jvm = new Jvm(); /** * 服务器相关信息 */ private Sys sys = new Sys(); /** * 磁盘相关信息 */ private List<SysFile> sysFiles = new LinkedList<SysFile>(); public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Mem getMem() { return mem; } public void setMem(Mem mem) { this.mem = mem; } public Jvm getJvm() { return jvm; } public void setJvm(Jvm jvm) { this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties();
package com.qf.server; /** * 服务器相关信息 * * @author ruoyi */ @ToString public class Server { private static final int OSHI_WAIT_SECOND = 1000; /** * CPU相关信息 */ private Cpu cpu = new Cpu(); /** * 內存相关信息 */ private Mem mem = new Mem(); /** * JVM相关信息 */ private Jvm jvm = new Jvm(); /** * 服务器相关信息 */ private Sys sys = new Sys(); /** * 磁盘相关信息 */ private List<SysFile> sysFiles = new LinkedList<SysFile>(); public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Mem getMem() { return mem; } public void setMem(Mem mem) { this.mem = mem; } public Jvm getJvm() { return jvm; } public void setJvm(Jvm jvm) { this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties();
sys.setComputerName(IpUtils.getHostName());
1
2023-12-30 13:42:53+00:00
8k
JIGerss/Salus
salus-web/src/main/java/team/glhf/salus/service/Impl/GameServiceImpl.java
[ { "identifier": "ConfigReq", "path": "salus-pojo/src/main/java/team/glhf/salus/dto/game/ConfigReq.java", "snippet": "@Data\r\n@Builder\r\npublic class ConfigReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(message = \"param cannot be null\")\r\n private String key;\r\n\r\n @Range(min = 1200, max = 3600, message = \"param cannot be more than 3600 or less than 1200\")\r\n @NotNull(message = \"param cannot be null\")\r\n private Integer time;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "SelectReq", "path": "salus-pojo/src/main/java/team/glhf/salus/dto/game/SelectReq.java", "snippet": "@Data\r\n@Builder\r\npublic class SelectReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(message = \"param cannot be null\")\r\n private String key;\r\n\r\n @Range(min = 1, max = 2, message = \"param must be 1 or 2\")\r\n @NotNull(message = \"param cannot be null\")\r\n private Integer role;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "StartGameReq", "path": "salus-pojo/src/main/java/team/glhf/salus/dto/game/StartGameReq.java", "snippet": "@Data\r\n@Builder\r\npublic class StartGameReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(message = \"param cannot be null\")\r\n private String key;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "User", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/User.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"tb_user\")\r\npublic class User implements Serializable {\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"nickname\")\r\n private String nickname;\r\n\r\n @TableField(\"email\")\r\n private String email;\r\n\r\n @TableField(\"phone\")\r\n private String phone;\r\n\r\n @TableField(\"password\")\r\n private String password;\r\n\r\n @TableField(fill = FieldFill.INSERT)\r\n private String createTime;\r\n\r\n @TableField(fill = FieldFill.INSERT_UPDATE)\r\n private String updateTime;\r\n\r\n @TableField(\"gender\")\r\n private String gender;\r\n\r\n @TableField(\"birthday\")\r\n private String birthday;\r\n\r\n @TableField(\"height\")\r\n private Long height;\r\n\r\n @TableField(\"weight\")\r\n private Long weight;\r\n\r\n @TableField(\"signature\")\r\n private String signature;\r\n\r\n @TableField(\"avatar\")\r\n private String avatar;\r\n\r\n @TableField(\"fans\")\r\n private Long fans;\r\n\r\n @TableLogic()\r\n private String exist;\r\n\r\n @Version()\r\n private Long version;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r" }, { "identifier": "GameMessageType", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/GameMessageType.java", "snippet": "@Getter\r\n@ToString\r\n@JsonFormat(shape = JsonFormat.Shape.OBJECT)\r\npublic enum GameMessageType implements Serializable {\r\n NORMAL(1, \"消息1\"),\r\n MESSAGE(3, \"消息3\"),\r\n OVER(4, \"消息4\");\r\n\r\n private final Integer code;\r\n private final String name;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n\r\n GameMessageType(Integer code, String name) {\r\n this.code = code;\r\n this.name = name;\r\n }\r\n}\r" }, { "identifier": "GameRoleEnum", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/GameRoleEnum.java", "snippet": "@Getter\r\n@ToString\r\n@JsonFormat(shape = JsonFormat.Shape.OBJECT)\r\npublic enum GameRoleEnum implements Serializable {\r\n NULL(0, \"未选择角色\"),\r\n MOUSE(1, \"老鼠\"),\r\n CAT(2, \"猫\"),\r\n CAUGHT(999, \"被抓住的老鼠\");\r\n\r\n private final Integer code;\r\n private final String name;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n\r\n GameRoleEnum(Integer code, String name) {\r\n this.code = code;\r\n this.name = name;\r\n }\r\n\r\n public static GameRoleEnum getRoleByCode(Integer code) {\r\n for (GameRoleEnum value : GameRoleEnum.values()) {\r\n if (value.getCode().equals(code)) {\r\n return value;\r\n }\r\n }\r\n return NULL;\r\n }\r\n}\r" }, { "identifier": "GameStageEnum", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/GameStageEnum.java", "snippet": "@Getter\r\n@ToString\r\n@JsonFormat(shape = JsonFormat.Shape.OBJECT)\r\npublic enum GameStageEnum implements Serializable {\r\n INIT(0, \"初始化游戏\"),\r\n PREPARE(1, \"准备游戏\"),\r\n LOADING(2, \"加载游戏\"),\r\n PLAYING(3, \"正在游戏\"),\r\n OVER(999, \"游戏结束\");\r\n\r\n private final Integer status;\r\n private final String message;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n\r\n GameStageEnum(Integer status, String message) {\r\n this.status = status;\r\n this.message = message;\r\n }\r\n}\r" }, { "identifier": "HttpCodeEnum", "path": "salus-common/src/main/java/team/glhf/salus/enumeration/HttpCodeEnum.java", "snippet": "public enum HttpCodeEnum {\r\n // Success ==> 200\r\n SUCCESS(200, \"操作成功\"),\r\n\r\n // Timeout ==> 400\r\n TIME_OUT(400, \"系统超时\"),\r\n\r\n // Login Error ==> 1~50\r\n NEED_LOGIN_AFTER(1, \"需要登录后操作\"),\r\n LOGIN_PASSWORD_ERROR(2, \"密码错误\"),\r\n ACCOUNT_NOT_FOUND(3, \"账号不存在\"),\r\n ACCOUNT_DISABLED(4, \"账号被禁用\"),\r\n NUMBER_CODE_NOT_EQUAL(4, \"验证码不匹配\"),\r\n NUMBER_CODE_NOT_EXIST(5, \"请先发送验证码\"),\r\n ACCOUNT_PASSWORD_ERROR(6, \"账号或密码错误\"),\r\n\r\n // Token ==> 50~100\r\n TOKEN_INVALID(50, \"无效的TOKEN\"),\r\n TOKEN_REQUIRE(51, \"TOKEN是必须的\"),\r\n TOKEN_EXPIRED_TIME(52, \"TOKEN已过期\"),\r\n TOKEN_ALGORITHM_SIGNATURE_INVALID(53, \"TOKEN的算法或签名不对\"),\r\n TOKEN_CANT_EMPTY(54, \"TOKEN不能为空\"),\r\n\r\n // Sign Verification ==> 100~120\r\n SIGN_INVALID(100, \"无效的SIGN\"),\r\n SIG_TIMEOUT(101, \"SIGN已过期\"),\r\n\r\n // Args Error ==> 500~1000\r\n PARAM_REQUIRE(500, \"缺少参数\"),\r\n PARAM_INVALID(501, \"无效参数\"),\r\n PARAM_IMAGE_FORMAT_ERROR(502, \"图片格式有误\"),\r\n INVALID_ID(503, \"该ID查无数据\"),\r\n SERVER_ERROR(503, \"服务器内部错误\"),\r\n SERVER_BUSY(504, \"服务器繁忙\"),\r\n USER_NOT_REGISTERED(505, \"用户未注册\"),\r\n USER_REGISTERED(506, \"用户已注册\"),\r\n REQUEST_ERROR(507, \"请求出错\"),\r\n\r\n // Data Error ==> 1000~2000\r\n DATA_EXIST(1000, \"数据已经存在\"),\r\n DATA_PART_NOT_EXIST(1002, \"前端请求,部分必要数据不能为空\"),\r\n DATA_ALL_NOT_EXIST(1002, \"前端请求,数据完全为空\"),\r\n DATA_PART_ILLEGAL(1003, \"部分数据不合法\"),\r\n DATA_UPLOAD_ERROR(1004, \"服务器上传失败\"),\r\n PHONE_ILLEGAL(1005, \"手机号为空或者格式不合法\"),\r\n PASSWORD_ILLEGAL(1006, \"密码为空或者格式不合法\"),\r\n NUMBER_CODE_ILLEGAL(1007, \"未获取验证码或者格式不合法\"),\r\n TOKEN_DATA_INVALID(1008, \"token里的荷载数据有误\"),\r\n USERNAME_PASSWORD_ILLEGAL(1009, \"账号或密码为空或长度过长\"),\r\n EMAIL_SEND_ERROR(1010, \"发送邮件失败,请重试\"),\r\n SMS_SEND_ERROR(1011, \"发送短信失败,请重试\"),\r\n GET_LOCATION_ERROR(1012, \"获取地址失败,请检查参数是否正确\"),\r\n\r\n // Article Error\r\n ARTICLE_NOT_EXIST(1101, \"文章不存在,请检查参数是否正确\"),\r\n ARTICLE_ALREADY_LIKED(1102, \"文章已被点赞\"),\r\n ARTICLE_NOT_LIKED(1103, \"文章没有被点赞\"),\r\n ARTICLE_PERMISSION_ERROR(1104, \"你没有权限操作该文章\"),\r\n UPLOAD_ERROR(1105, \"上传文件失败,可能文件太大了,请重试\"),\r\n\r\n // User Error\r\n USER_ALREADY_SUBSCRIBED(1201, \"用户已被关注\"),\r\n USER_NOT_SUBSCRIBED(1202, \"用户没有被关注\"),\r\n USER_SUBSCRIBED_ITSELF(1203, \"用户不能关注自己\"),\r\n\r\n //Place Error\r\n PLACE_NOT_EXIST(1301,\"场所不存在,请检查参数是否正确\"),\r\n PLACE_ALREADY_POINTED(1302, \"场所已被该用户评分\"),\r\n PLACE_NOT_POINTED(1303, \"场所没有被该用户评分\"),\r\n\r\n // Game Error\r\n FAIL_TO_JOIN_GAME(1401, \"加入失败,请检查参数是否正确\"),\r\n SEND_MESSAGE_ERROR(1402, \"消息发送失败,请检查参数是否正确\"),\r\n GAME_NOT_EXIST(1403, \"游戏不存在,请检查参数是否正确\"),\r\n GAME_PERMISSION_ERROR(1404, \"你不是房主\"),\r\n GAME_ALREADY_STARTED(1405, \"游戏已经开始\"),\r\n USER_NOT_JOIN_GAME(1406, \"你尚未加入该游戏\"),\r\n GAME_CONFIGURATION_ERROR(1407, \"玩家尚未选择角色,或者游戏时间未配置\"),\r\n GAME_NO_BOTH_ROLES(1408, \"缺少至少一个猫或至少一个老鼠\"),\r\n GAME_STAGE_ERROR(1409, \"游戏还未开始或者已经结束\"),\r\n GAME_CAUGHT_MOUSE(1410, \"你已被抓住\");\r\n\r\n private final Integer code;\r\n private final String message;\r\n\r\n HttpCodeEnum(Integer code, String message) {\r\n this.code = code;\r\n this.message = message;\r\n }\r\n\r\n public Integer getCode() {\r\n return code;\r\n }\r\n\r\n public String getMessage() {\r\n return message;\r\n }\r\n}\r" }, { "identifier": "GameException", "path": "salus-common/src/main/java/team/glhf/salus/exception/GameException.java", "snippet": "public class GameException extends SalusException {\r\n public GameException(HttpCodeEnum enums) {\r\n super(enums);\r\n }\r\n}\r" }, { "identifier": "GameService", "path": "salus-web/src/main/java/team/glhf/salus/service/GameService.java", "snippet": "public interface GameService {\r\n void joinOrCreateGame(GameEndPoint gameEndPoint);\r\n\r\n void quitGame(GameEndPoint gameEndPoint, Game game);\r\n\r\n void handleMessage(GameEndPoint gameEndPoint, String message, Game game);\r\n\r\n void configureGame(ConfigReq configReq, Game game);\r\n\r\n void selectRole(SelectReq selectReq, Game game);\r\n\r\n void startGame(StartGameReq startGameReq, Game game);\r\n\r\n Game getGameByKey(String key);\r\n\r\n void checkGameStatus(Game game);\r\n\r\n void gameOver(Game game, boolean mouseWin);\r\n\r\n void sendGameInfo(Game game);\r\n\r\n boolean hasGame(String key);\r\n}\r" }, { "identifier": "PlaceService", "path": "salus-web/src/main/java/team/glhf/salus/service/PlaceService.java", "snippet": "public interface PlaceService {\r\n /**\r\n * 创建健身场所\r\n */\r\n CreateRes createPlace(CreateReq createReq);\r\n\r\n /**\r\n * 根据ID获取健身场所\r\n */\r\n PlaceVo getPlaceById(String placeId);\r\n\r\n /**\r\n * 获取最近的健身场所\r\n */\r\n List<PlaceVo> getNearbyPlaces(String position);\r\n\r\n /**\r\n * 使用半正矢函数公式(Haversine公式)计算两地距离\r\n */\r\n double countDistance(String positionA, String positionB);\r\n\r\n /**\r\n * 使用半正矢函数公式(Haversine公式)计算两地距离\r\n */\r\n double countDistance(double jA, double wA, double jB, double wB);\r\n\r\n /**\r\n * 对健身场所评分\r\n */\r\n void pointPlace(PointReq pointReq,boolean isPoint);\r\n\r\n /**\r\n * 评论场所\r\n */\r\n void commentPlace(CommentReq commentReq, boolean isComment);\r\n\r\n /**\r\n * 查询该场所是否存在,若orElseThrow为true则在不存在时抛出异常\r\n */\r\n boolean checkHasPlace(String placeId, boolean orElseThrow);\r\n\r\n /**\r\n * 查询用户是否评分该场所,若没评分时抛出异常\r\n */\r\n boolean checkPointPlace(String userId, String placeId);\r\n}\r" }, { "identifier": "UserService", "path": "salus-web/src/main/java/team/glhf/salus/service/UserService.java", "snippet": "public interface UserService extends IService<User> {\r\n\r\n /**\r\n * 用户登录\r\n */\r\n LoginRes loginUser(LoginReq loginUserDto);\r\n\r\n /**\r\n * 用户注册\r\n */\r\n RegisterRes registerUser(RegisterReq registerUserDto);\r\n\r\n /**\r\n * 用户忘记密码\r\n */\r\n ForgetRes forgetUser(ForgetReq forgetUserDto);\r\n\r\n /**\r\n * 根据ID查找用户\r\n */\r\n User getUserById(String userId);\r\n\r\n /**\r\n * 根据姓名查找用户\r\n */\r\n List<User> getUserByName(String nickname);\r\n\r\n /**\r\n * 获取关注的人的\r\n */\r\n List<User> getSubscribers(String userId);\r\n\r\n /**\r\n * 关注用户或取消关注用户\r\n */\r\n void subscribeUser(SubscribeReq subscribeReq, boolean isSubscribe);\r\n\r\n /**\r\n * 修改用户信息\r\n */\r\n void updateUser(UpdateReq updateDto);\r\n\r\n // -------------------------------------------------------------------------------------------\r\n\r\n /**\r\n * 用户是否存在\r\n */\r\n boolean checkHasUser(String userId, String email);\r\n\r\n /**\r\n * 用户是否关注某用户\r\n */\r\n boolean checkHasSubscribeUser(String fromUserId, String toUserId);\r\n}\r" }, { "identifier": "Game", "path": "salus-web/src/main/java/team/glhf/salus/websocket/Game.java", "snippet": "@SuppressWarnings({\"BooleanMethodIsAlwaysInverted\", \"BusyWait\"})\r\n@Getter\r\n@Setter\r\npublic class Game implements Runnable {\r\n private int flag;\r\n private String key;\r\n private Integer time;\r\n private GameStageEnum gameStageEnum;\r\n private List<GameEndPoint> players;\r\n private final GameService gameService;\r\n\r\n public Game(GameService gameService) {\r\n this.gameStageEnum = GameStageEnum.INIT;\r\n this.players = new CopyOnWriteArrayList<>();\r\n this.gameService = gameService;\r\n this.time = 0;\r\n this.flag = 0;\r\n }\r\n\r\n @Override\r\n public void run() {\r\n while (time > 0 && flag == 0) {\r\n try {\r\n for (int i = 0; i < 5 && flag == 0; i++) {\r\n Thread.sleep(200);\r\n gameService.checkGameStatus(this);\r\n }\r\n } catch (InterruptedException e) {\r\n throw new GameException(HttpCodeEnum.SERVER_ERROR);\r\n } finally {\r\n time -= 1;\r\n }\r\n }\r\n if (flag == 0) {\r\n gameService.gameOver(this, true);\r\n }\r\n }\r\n\r\n public void addPlayer(GameEndPoint gameEndPoint) {\r\n players.add(gameEndPoint);\r\n }\r\n\r\n public void removePlayer(GameEndPoint gameEndPoint) {\r\n players.remove(gameEndPoint);\r\n }\r\n\r\n public boolean isStarted() {\r\n return !GameStageEnum.PREPARE.equals(gameStageEnum);\r\n }\r\n\r\n public boolean isHost(String userId) {\r\n return userId.equals(players.get(0).getUserId());\r\n }\r\n}\r" }, { "identifier": "GameEndPoint", "path": "salus-web/src/main/java/team/glhf/salus/websocket/GameEndPoint.java", "snippet": "@Getter\r\n@Setter\r\n@Component\r\n@NoArgsConstructor\r\n@ServerEndpoint(\"/game/entry\")\r\n@SuppressWarnings(\"unused\")\r\npublic class GameEndPoint {\r\n private String userId;\r\n private String key;\r\n private Session session;\r\n private GameRoleEnum role;\r\n private Double longitude;\r\n private Double latitude;\r\n private int score;\r\n private int caught;\r\n private static GameService gameService;\r\n\r\n @Autowired\r\n public void addGameService(GameService gameService) {\r\n GameEndPoint.gameService = gameService;\r\n }\r\n\r\n @OnOpen\r\n public void onOpen(Session session) {\r\n this.session = session;\r\n Map<String, List<String>> parameterMap = session.getRequestParameterMap();\r\n if (null != parameterMap) {\r\n List<String> tokens = parameterMap.get(\"Authorization\");\r\n List<String> keys = parameterMap.get(\"key\");\r\n if (null == tokens || null == keys) {\r\n throw new GameException(HttpCodeEnum.TOKEN_REQUIRE);\r\n }\r\n String token = tokens.get(0);\r\n key = keys.get(0);\r\n role = GameRoleEnum.MOUSE;\r\n userId = JwtUtil.verifyAndGetUserId(token);\r\n gameService.joinOrCreateGame(this);\r\n }\r\n }\r\n\r\n @OnMessage\r\n public void onMessage(Session session, String message) {\r\n gameService.handleMessage(this, message, null);\r\n }\r\n\r\n @OnClose\r\n public void onClose(Session session) {\r\n gameService.quitGame(this, null);\r\n }\r\n\r\n @OnError\r\n public void onError(Session session, Throwable throwable){\r\n for (HttpCodeEnum value : HttpCodeEnum.values()) {\r\n if (value.getMessage().equals(throwable.getMessage())) {\r\n sendMessage(Result.errorResult(value));\r\n }\r\n }\r\n }\r\n\r\n public void sendMessage(Object message) {\r\n try {\r\n ObjectMapper objectMapper = new ObjectMapper();\r\n String text = objectMapper\r\n .setSerializationInclusion(JsonInclude.Include.NON_NULL)\r\n .writeValueAsString(Result.okResult(message));\r\n if (null != session) {\r\n session.getBasicRemote().sendText(text);\r\n }\r\n } catch (Exception e) {\r\n throw new GameException(HttpCodeEnum.SEND_MESSAGE_ERROR);\r\n }\r\n }\r\n}\r" } ]
import cn.hutool.core.thread.ThreadUtil; import org.springframework.stereotype.Service; import team.glhf.salus.annotation.AutoOperateGame; import team.glhf.salus.dto.game.ConfigReq; import team.glhf.salus.dto.game.SelectReq; import team.glhf.salus.dto.game.StartGameReq; import team.glhf.salus.entity.User; import team.glhf.salus.enumeration.GameMessageType; import team.glhf.salus.enumeration.GameRoleEnum; import team.glhf.salus.enumeration.GameStageEnum; import team.glhf.salus.enumeration.HttpCodeEnum; import team.glhf.salus.exception.GameException; import team.glhf.salus.service.GameService; import team.glhf.salus.service.PlaceService; import team.glhf.salus.service.UserService; import team.glhf.salus.vo.game.*; import team.glhf.salus.websocket.Game; import team.glhf.salus.websocket.GameEndPoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
4,897
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/12/11 */ @Service public class GameServiceImpl implements GameService { private final UserService userService; private final PlaceService placeService; private final Map<String, Game> games = new ConcurrentHashMap<>(); public GameServiceImpl(UserService userService, PlaceService placeService) { this.userService = userService; this.placeService = placeService; } @Override public void joinOrCreateGame(GameEndPoint gameEndPoint) { String key = gameEndPoint.getKey(); Game game; if (hasGame(key)) { game = getGameByKey(key); game.addPlayer(gameEndPoint); } else { game = new Game(this); game.setKey(key); game.addPlayer(gameEndPoint);
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/12/11 */ @Service public class GameServiceImpl implements GameService { private final UserService userService; private final PlaceService placeService; private final Map<String, Game> games = new ConcurrentHashMap<>(); public GameServiceImpl(UserService userService, PlaceService placeService) { this.userService = userService; this.placeService = placeService; } @Override public void joinOrCreateGame(GameEndPoint gameEndPoint) { String key = gameEndPoint.getKey(); Game game; if (hasGame(key)) { game = getGameByKey(key); game.addPlayer(gameEndPoint); } else { game = new Game(this); game.setKey(key); game.addPlayer(gameEndPoint);
game.setGameStageEnum(GameStageEnum.PREPARE);
6
2023-12-23 15:03:37+00:00
8k
swsm/proxynet
proxynet-client/src/main/java/com/swsm/proxynet/client/init/SpringInitRunner.java
[ { "identifier": "ProxyConfig", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/config/ProxyConfig.java", "snippet": "@Configuration\n@Data\npublic class ProxyConfig {\n\n @Value(\"${proxynet.client.id}\")\n private Integer clientId;\n\n @Value(\"${proxynet.client.serverIp}\")\n private String serverIp;\n @Value(\"${proxynet.client.serverPort}\")\n private Integer serverPort;\n \n \n}" }, { "identifier": "ClientServerChannelHandler", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/handler/ClientServerChannelHandler.java", "snippet": "@Slf4j\npublic class ClientServerChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> {\n \n @Override\n protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception {\n if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT) {\n executeConnect(proxyNetMessage, channelHandlerContext);\n } else if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) {\n executeCommand(proxyNetMessage, channelHandlerContext);\n }\n }\n\n private void executeCommand(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) {\n Channel clientChannel = channelHandlerContext.channel();\n CommandMessage commandMessage = JSON.parseObject(proxyNetMessage.getInfo(), CommandMessage.class);\n if (ProxyNetMessage.COMMAND_INFO.equals(commandMessage.getType())) {\n CommandInfoMessage commandInfoMessage = JSON.parseObject(commandMessage.getMessage(), CommandInfoMessage.class);\n Channel targetChannel = clientChannel.attr(Constants.NEXT_CHANNEL).get();\n if (targetChannel == null) {\n log.info(\"targetInfo={}的客户端还未和代理客户端建立连接\", commandInfoMessage.getTargetIp() + \":\" + commandInfoMessage.getTargetPort());\n return;\n }\n ByteBuf data = channelHandlerContext.alloc().buffer(proxyNetMessage.getData().length);\n data.writeBytes(proxyNetMessage.getData());\n targetChannel.writeAndFlush(data);\n }\n }\n\n private void executeConnect(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) {\n ConnectMessage connectMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectMessage.class);\n log.info(\"收到服务端发送的connect消息:{}\", proxyNetMessage);\n log.info(\"向目标服务={}发起连接...\", proxyNetMessage);\n try {\n SpringInitRunner.bootstrapForTarget.connect(connectMessage.getTargetIp(), connectMessage.getTargetPort())\n .addListener((ChannelFutureListener) future -> {\n Channel targetChannel = future.channel();\n if (future.isSuccess()) {\n targetChannel.config().setOption(ChannelOption.AUTO_READ, false);\n log.info(\"向目标服务={}发起连接 成功...\", proxyNetMessage);\n\n String serverIp = ConfigUtil.getServerIp();\n int serverPort = ConfigUtil.getServerPort();\n SpringInitRunner.bootstrapForServer.connect(serverIp, serverPort)\n .addListener((ChannelFutureListener) future2 -> {\n if (future2.isSuccess()) {\n Channel newClientChannel = future2.channel();\n log.info(\"监控--clinetChannelId={},newClientChannelId={},realServerChannelId={},visitorId={}\", channelHandlerContext.channel().id().asLongText(), newClientChannel.id().asLongText(),targetChannel.id().asLongText(), connectMessage.getUserId());\n newClientChannel.attr(Constants.NEXT_CHANNEL).set(targetChannel);\n targetChannel.attr(Constants.NEXT_CHANNEL).set(newClientChannel);\n ChannelRelationCache.putUserIdToTargetChannel(connectMessage.getUserId(), targetChannel);\n targetChannel.attr(Constants.VISITOR_ID).set(connectMessage.getUserId());\n newClientChannel.writeAndFlush(ProxyNetMessage.buildConnectRespMessage(\"连接目标服务端成功\", true, connectMessage.getUserId()));\n targetChannel.config().setOption(ChannelOption.AUTO_READ, true);\n } else {\n log.error(\"客户端向服务端发起新连接失败\");\n channelHandlerContext.close();\n }\n });\n \n ChannelRelationCache.putTargetChannel(connectMessage.getTargetIp(), connectMessage.getTargetPort(), targetChannel);\n ChannelRelationCache.putUserIdToTargetChannel(connectMessage.getUserId(), targetChannel);\n ChannelRelationCache.putTargetChannelToClientChannel(targetChannel, channelHandlerContext.channel());\n channelHandlerContext.writeAndFlush(ProxyNetMessage.buildConnectRespMessage(\"连接目标服务端成功\", true, connectMessage.getUserId()));\n } else {\n log.info(\"向目标服务={}发起连接 失败...\", proxyNetMessage);\n channelHandlerContext.writeAndFlush(ProxyNetMessage.buildConnectRespMessage(\"连接目标服务端异常\", false, connectMessage.getUserId()));\n }\n }).sync();\n } catch (InterruptedException e) {\n log.error(\"客户端连接目标服务器出现异常\", e);\n channelHandlerContext.writeAndFlush(ProxyNetMessage.buildConnectRespMessage(\"连接目标服务端异常\", false, connectMessage.getUserId()));\n }\n\n }\n\n @Override\n public void channelActive(ChannelHandlerContext ctx) throws Exception {\n \n }\n\n\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n \n }\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\n super.exceptionCaught(ctx, cause);\n if (ctx.channel().isActive()) {\n ctx.channel().close();\n }\n }\n}" }, { "identifier": "ClientTargetChannelHandler", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/handler/ClientTargetChannelHandler.java", "snippet": "@Slf4j\npublic class ClientTargetChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {\n \n @Override\n protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {\n Channel targetChannel = channelHandlerContext.channel();\n Channel clientChannel = targetChannel.attr(Constants.NEXT_CHANNEL).get();\n if (clientChannel == null) {\n log.warn(\"目的端返回给代理端信息,但代理端和服务端的channel已关闭\");\n targetChannel.close();\n return;\n }\n String userId = ChannelRelationCache.getUserIdByTargetChannel(targetChannel);\n if (userId == null) {\n log.warn(\"目的端返回给代理端信息,但用户端和服务端的channel已关闭\");\n targetChannel.close();\n return;\n }\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes(bytes);\n clientChannel.writeAndFlush(ProxyNetMessage.buildCommandMessage(\n ProxyNetMessage.COMMAND_RESP, JSON.toJSONString(new CommandRespMessage(userId, bytes))));\n }\n\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n ChannelRelationCache.removeTargetChannel(ctx.channel());\n ChannelRelationCache.removeTargetChannelToClientChannel(ctx.channel());\n ctx.close();\n }\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\n super.exceptionCaught(ctx, cause);\n ChannelRelationCache.removeTargetChannel(ctx.channel());\n ChannelRelationCache.removeTargetChannelToClientChannel(ctx.channel());\n ctx.close();\n }\n\n public static void main(String[] args) {\n String ss = \"SgAAAAo1LjcuMjYADAAAAE9DOh82DXx/AP/3CAIA/4EVAAAAAAAAAAAAAG4xGidPGBcfPgFbdABteXNxbF9uYXRpdmVfcGFzc3dvcmQA\";\n byte[] bytes = ss.getBytes(Charset.forName(\"utf-8\"));\n System.out.println(bytes);\n }\n \n}" }, { "identifier": "ProxyNetMessageDecoder", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/handler/ProxyNetMessageDecoder.java", "snippet": "public class ProxyNetMessageDecoder extends LengthFieldBasedFrameDecoder {\n public ProxyNetMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {\n super(maxFrameLength, lengthFieldOffset, lengthFieldLength);\n }\n\n @Override\n protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {\n ByteBuf newIn = (ByteBuf) super.decode(ctx, in);\n if (newIn == null) {\n return null;\n }\n\n if (newIn.readableBytes() < PROXY_MESSAGE_TOTAL_SIZE) {\n return null;\n }\n\n int frameLength = newIn.readInt();\n if (newIn.readableBytes() < frameLength) {\n return null;\n }\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n byte type = newIn.readByte();\n proxyNetMessage.setType(type);\n\n int infoLength = newIn.readInt();\n byte[] infoBytes = new byte[infoLength];\n newIn.readBytes(infoBytes);\n proxyNetMessage.setInfo(new String(infoBytes));\n\n byte[] data = new byte[frameLength - PROXY_MESSAGE_TYPE_SIZE - PROXY_MESSAGE_INFO_SIZE - infoLength];\n newIn.readBytes(data);\n proxyNetMessage.setData(data);\n\n newIn.release();\n\n return proxyNetMessage;\n }\n}" }, { "identifier": "ProxyNetMessageEncoder", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/handler/ProxyNetMessageEncoder.java", "snippet": "public class ProxyNetMessageEncoder extends MessageToByteEncoder<ProxyNetMessage> {\n\n @Override\n protected void encode(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage, ByteBuf byteBuf) throws Exception {\n int bodyLength = PROXY_MESSAGE_TYPE_SIZE + PROXY_MESSAGE_INFO_SIZE;\n byte[] infoBytes = null;\n if (proxyNetMessage.getInfo() != null) {\n infoBytes = proxyNetMessage.getInfo().getBytes();\n bodyLength += infoBytes.length;\n }\n\n if (proxyNetMessage.getData() != null) {\n bodyLength += proxyNetMessage.getData().length;\n }\n\n byteBuf.writeInt(bodyLength);\n\n byteBuf.writeByte(proxyNetMessage.getType());\n\n if (infoBytes != null) {\n byteBuf.writeInt(infoBytes.length);\n byteBuf.writeBytes(infoBytes);\n } else {\n byteBuf.writeInt(0x00);\n }\n\n if (proxyNetMessage.getData() != null) {\n byteBuf.writeBytes(proxyNetMessage.getData());\n }\n }\n}" }, { "identifier": "ProxyNetMessage", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/ProxyNetMessage.java", "snippet": "@Data\npublic class ProxyNetMessage {\n\n public static final byte CONNECT = 0x01;\n public static final byte CONNECT_RESP = 0x02;\n public static final byte COMMAND = 0x03;\n \n public static final String COMMAND_AUTH = \"AUTH\";\n public static final String COMMAND_INFO = \"INFO\";\n public static final String COMMAND_RESP = \"RESP\";\n\n // 类型\n private byte type;\n // 消息实际信息\n private String info;\n // 用户请求消息 及 目标服务响应消息 原始数据\n private byte[] data;\n \n \n \n public static ProxyNetMessage buildCommandMessage(String type, String message) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(COMMAND);\n if (COMMAND_AUTH.equals(type)) {\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_AUTH, message)));\n } else if (COMMAND_INFO.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_INFO, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandInfoMessage.class).getInfo());\n } else if (COMMAND_RESP.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_RESP, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandRespMessage.class).getRespInfo());\n } else {\n throw new RuntimeException(\"invalid command type:\" + type);\n }\n return proxyNetMessage;\n }\n \n public static ProxyNetMessage buildConnectMessage(String userId, String ip, Integer port) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectMessage(userId, ip, port)));\n return proxyNetMessage;\n }\n\n public static ProxyNetMessage buildConnectRespMessage(String message, Boolean result, String userId) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT_RESP);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectRespMessage(result, message, userId)));\n return proxyNetMessage;\n }\n \n \n \n}" }, { "identifier": "ALL_IDLE_SECOND_TIME", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer ALL_IDLE_SECOND_TIME = 3;" }, { "identifier": "PROXY_MESSAGE_LENGTH_FILED_LENGTH", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer PROXY_MESSAGE_LENGTH_FILED_LENGTH = 4;" }, { "identifier": "PROXY_MESSAGE_LENGTH_FILED_OFFSET", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer PROXY_MESSAGE_LENGTH_FILED_OFFSET = 0;" }, { "identifier": "PROXY_MESSAGE_MAX_SIZE", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer PROXY_MESSAGE_MAX_SIZE = Integer.MAX_VALUE;" }, { "identifier": "READ_IDLE_SECOND_TIME", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer READ_IDLE_SECOND_TIME = 3;" }, { "identifier": "WRITE_IDLE_SECOND_TIME", "path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java", "snippet": "public static final Integer WRITE_IDLE_SECOND_TIME = 3;" } ]
import com.swsm.proxynet.client.config.ProxyConfig; import com.swsm.proxynet.client.handler.ClientServerChannelHandler; import com.swsm.proxynet.client.handler.ClientTargetChannelHandler; import com.swsm.proxynet.common.handler.ProxyNetMessageDecoder; import com.swsm.proxynet.common.handler.ProxyNetMessageEncoder; import com.swsm.proxynet.common.model.ProxyNetMessage; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import static com.swsm.proxynet.common.Constants.ALL_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_LENGTH; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_OFFSET; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_MAX_SIZE; import static com.swsm.proxynet.common.Constants.READ_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.WRITE_IDLE_SECOND_TIME;
3,787
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH)); socketChannel.pipeline().addLast(new ProxyNetMessageEncoder()); socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECOND_TIME, WRITE_IDLE_SECOND_TIME, ALL_IDLE_SECOND_TIME)); socketChannel.pipeline().addLast(new ClientServerChannelHandler()); } }); bootstrapForServer.connect(proxyConfig.getServerIp(), proxyConfig.getServerPort()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { log.info("连接代理服务器的客户端 成功..."); // 向服务端发送 客户端id信息 future.channel().writeAndFlush( ProxyNetMessage.buildCommandMessage(ProxyNetMessage.COMMAND_AUTH, String.valueOf(proxyConfig.getClientId()))); } else { log.info("连接代理服务器的客户端 失败..."); System.exit(-1); } }).sync(); log.info("启动 连接代理服务器的客户端 成功..."); log.info("初始化 连接被代理服务器的客户端..."); bootstrapForTarget = new Bootstrap(); bootstrapForTarget.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception {
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH)); socketChannel.pipeline().addLast(new ProxyNetMessageEncoder()); socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECOND_TIME, WRITE_IDLE_SECOND_TIME, ALL_IDLE_SECOND_TIME)); socketChannel.pipeline().addLast(new ClientServerChannelHandler()); } }); bootstrapForServer.connect(proxyConfig.getServerIp(), proxyConfig.getServerPort()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { log.info("连接代理服务器的客户端 成功..."); // 向服务端发送 客户端id信息 future.channel().writeAndFlush( ProxyNetMessage.buildCommandMessage(ProxyNetMessage.COMMAND_AUTH, String.valueOf(proxyConfig.getClientId()))); } else { log.info("连接代理服务器的客户端 失败..."); System.exit(-1); } }).sync(); log.info("启动 连接代理服务器的客户端 成功..."); log.info("初始化 连接被代理服务器的客户端..."); bootstrapForTarget = new Bootstrap(); bootstrapForTarget.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ClientTargetChannelHandler());
2
2023-12-25 03:25:38+00:00
8k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/adapters/LocationAdapter.java
[ { "identifier": "EmailQrFullActivity", "path": "app/src/main/java/com/trodev/scanhub/detail_activity/EmailQrFullActivity.java", "snippet": "public class EmailQrFullActivity extends AppCompatActivity {\n\n TextView from_tv, to_tv, text_tv;\n String from, to, text;\n Button generate, qr_download, pdf_download;\n public final static int QRCodeWidth = 500;\n Bitmap card, qrimage;\n ImageView qr_image;\n LinearLayout infoLl;\n CardView cardView;\n final static int REQUEST_CODE = 1232;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_email_qr_full);\n\n /*init*/\n from_tv = findViewById(R.id.from_tv);\n to_tv = findViewById(R.id.recevier_tv);\n text_tv = findViewById(R.id.text_tv);\n\n from = getIntent().getStringExtra(\"mFrom\");\n to = getIntent().getStringExtra(\"mTo\");\n text = getIntent().getStringExtra(\"mText\");\n\n from_tv.setText(from);\n to_tv.setText(to);\n text_tv.setText(text);\n\n /*init buttons*/\n // generate = findViewById(R.id.generate);\n qr_download = findViewById(R.id.qr_download);\n pdf_download = findViewById(R.id.pdf_download);\n\n /*image*/\n qr_image = findViewById(R.id.qr_image);\n\n /*card view init*/\n infoLl = findViewById(R.id.infoLl);\n cardView = findViewById(R.id.cardView);\n\n askPermissions();\n\n /*call method*/\n create_qr();\n\n pdf_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n make_pdf();\n }\n });\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n card = null;\n card = getBitmapFromUiView(infoLl);\n saveBitmapImage(card);\n\n }\n });\n\n }\n\n private void askPermissions() {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);\n }\n\n private void create_qr() {\n if (from_tv.getText().toString().trim().length() + to_tv.getText().toString().length() + text_tv.getText().toString().length() == 0) {\n } else {\n try {\n qrimage = textToImageEncode(\n \"Manufacture Date: \" + from_tv.getText().toString() +\n \"\\nExpire Date: \" + to_tv.getText().toString().trim() +\n \"\\nProduct Name: \" + text_tv.getText().toString().trim());\n\n qr_image.setImageBitmap(qrimage);\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n MediaStore.Images.Media.insertImage(getContentResolver(), qrimage, \"product_qr_image\"\n , null);\n Toast.makeText(EmailQrFullActivity.this, \"Download Complete\", Toast.LENGTH_SHORT).show();\n }\n });\n } catch (WriterException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n private Bitmap textToImageEncode(String value) throws WriterException {\n BitMatrix bitMatrix;\n try {\n\n bitMatrix = new MultiFormatWriter().encode(value, BarcodeFormat.DATA_MATRIX.QR_CODE, QRCodeWidth, QRCodeWidth, null);\n\n } catch (IllegalArgumentException e) {\n return null;\n }\n\n int bitMatrixWidth = bitMatrix.getWidth();\n int bitMatrixHeight = bitMatrix.getHeight();\n\n int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];\n for (int y = 0; y < bitMatrixHeight; y++) {\n int offSet = y * bitMatrixWidth;\n for (int x = 0; x < bitMatrixWidth; x++) {\n pixels[offSet + x] = bitMatrix.get(x, y) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white);\n }\n }\n Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);\n bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);\n return bitmap;\n }\n\n /* ##################################################################### */\n /* ##################################################################### */\n /*method\n * qr image downloader*/\n private Bitmap getBitmapFromUiView(View view) {\n\n //Define a bitmap with the same size as the view\n Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);\n //Bind a canvas to it\n Canvas canvas = new Canvas(returnedBitmap);\n //Get the view's background\n Drawable bgDrawable = view.getBackground();\n if (bgDrawable != null) {\n //has background drawable, then draw it on the canvas\n bgDrawable.draw(canvas);\n } else {\n //does not have background drawable, then draw white background on the canvas\n canvas.drawColor(Color.WHITE);\n }\n // draw the view on the canvas\n view.draw(canvas);\n\n //return the bitmap\n return returnedBitmap;\n }\n\n private void saveBitmapImage(Bitmap card) {\n\n long timestamp = System.currentTimeMillis();\n\n //Tell the media scanner about the new file so that it is immediately available to the user.\n ContentValues values = new ContentValues();\n\n values.put(MediaStore.Images.Media.MIME_TYPE, \"image/png\");\n values.put(MediaStore.Images.Media.DATE_ADDED, timestamp);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n\n values.put(MediaStore.Images.Media.DATE_TAKEN, timestamp);\n values.put(MediaStore.Images.Media.RELATIVE_PATH, \"Pictures/\" + getString(R.string.app_name));\n values.put(MediaStore.Images.Media.IS_PENDING, true);\n Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n\n if (uri != null) {\n try {\n OutputStream outputStream = getContentResolver().openOutputStream(uri);\n if (outputStream != null) {\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n }\n\n values.put(MediaStore.Images.Media.IS_PENDING, false);\n getContentResolver().update(uri, values, null, null);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n\n } else {\n File imageFileFolder = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));\n if (!imageFileFolder.exists()) {\n imageFileFolder.mkdirs();\n }\n String mImageName = \"\" + timestamp + \".png\";\n\n File imageFile = new File(imageFileFolder, mImageName);\n try {\n OutputStream outputStream = new FileOutputStream(imageFile);\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());\n getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n private void make_pdf() {\n\n DisplayMetrics displayMetrics = new DisplayMetrics();\n\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n this.getDisplay().getRealMetrics(displayMetrics);\n } else\n this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);\n\n cardView.measure(View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY),\n View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY));\n\n Log.d(\"my log\", \"Width Now \" + cardView.getMeasuredWidth());\n\n // cardView.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);\n\n // Create a new PdfDocument instance\n PdfDocument document = new PdfDocument();\n\n // Obtain the width and height of the view\n int viewWidth = cardView.getMeasuredWidth();\n int viewHeight = cardView.getMeasuredHeight();\n\n\n // Create a PageInfo object specifying the page attributes\n PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(viewWidth, viewHeight, 1).create();\n\n // Start a new page\n PdfDocument.Page page = document.startPage(pageInfo);\n\n // Get the Canvas object to draw on the page\n Canvas canvas = page.getCanvas();\n\n // Create a Paint object for styling the view\n Paint paint = new Paint();\n paint.setColor(Color.WHITE);\n\n // Draw the view on the canvas\n cardView.draw(canvas);\n\n // Finish the page\n document.finishPage(page);\n\n // Specify the path and filename of the output PDF file\n File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);\n\n /*time wise print*/\n /*eikhane millisecond ta niye lopping vabe pdf banacche*/\n long timestamps = System.currentTimeMillis();\n String fileName = \"Email_\" + timestamps + \".pdf\";\n\n File filePath = new File(downloadsDir, fileName);\n\n try {\n // Save the document to a file\n FileOutputStream fos = new FileOutputStream(filePath);\n document.writeTo(fos);\n document.close();\n fos.close();\n // PDF conversion successful\n Toast.makeText(this, \"pdf download successful\", Toast.LENGTH_LONG).show();\n } catch (IOException e) {\n e.printStackTrace();\n Toast.makeText(this, \"pdf download un-successful\", Toast.LENGTH_SHORT).show();\n }\n\n }\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n\n}" }, { "identifier": "LocationQrFullActivity", "path": "app/src/main/java/com/trodev/scanhub/detail_activity/LocationQrFullActivity.java", "snippet": "public class LocationQrFullActivity extends AppCompatActivity {\n\n TextView from_tv, to_tv, text_tv;\n String from, to, text;\n Button generate, qr_download, pdf_download;\n public final static int QRCodeWidth = 500;\n Bitmap card, qrimage;\n ImageView qr_image;\n LinearLayout infoLl;\n CardView cardView;\n final static int REQUEST_CODE = 1232;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_location_qr_full);\n\n /*init*/\n from_tv = findViewById(R.id.from_tv);\n to_tv = findViewById(R.id.recevier_tv);\n text_tv = findViewById(R.id.text_tv);\n\n from = getIntent().getStringExtra(\"mFrom\");\n to = getIntent().getStringExtra(\"mTo\");\n text = getIntent().getStringExtra(\"mText\");\n\n from_tv.setText(from);\n to_tv.setText(to);\n text_tv.setText(text);\n\n /*init buttons*/\n // generate = findViewById(R.id.generate);\n qr_download = findViewById(R.id.qr_download);\n pdf_download = findViewById(R.id.pdf_download);\n\n /*image*/\n qr_image = findViewById(R.id.qr_image);\n\n /*card view init*/\n infoLl = findViewById(R.id.infoLl);\n cardView = findViewById(R.id.cardView);\n\n askPermissions();\n\n /*call method*/\n create_qr();\n\n pdf_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n make_pdf();\n }\n });\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n card = null;\n card = getBitmapFromUiView(infoLl);\n saveBitmapImage(card);\n\n }\n });\n\n }\n\n private void askPermissions() {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);\n }\n\n private void create_qr() {\n if (from_tv.getText().toString().trim().length() + to_tv.getText().toString().length() + text_tv.getText().toString().length() == 0) {\n } else {\n try {\n qrimage = textToImageEncode(\n \"Manufacture Date: \" + from_tv.getText().toString() +\n \"\\nExpire Date: \" + to_tv.getText().toString().trim() +\n \"\\nProduct Name: \" + text_tv.getText().toString().trim());\n\n qr_image.setImageBitmap(qrimage);\n\n qr_download.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n MediaStore.Images.Media.insertImage(getContentResolver(), qrimage, \"product_qr_image\"\n , null);\n Toast.makeText(LocationQrFullActivity.this, \"Download Complete\", Toast.LENGTH_SHORT).show();\n }\n });\n } catch (WriterException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n private Bitmap textToImageEncode(String value) throws WriterException {\n BitMatrix bitMatrix;\n try {\n\n bitMatrix = new MultiFormatWriter().encode(value, BarcodeFormat.DATA_MATRIX.QR_CODE, QRCodeWidth, QRCodeWidth, null);\n\n } catch (IllegalArgumentException e) {\n return null;\n }\n\n int bitMatrixWidth = bitMatrix.getWidth();\n int bitMatrixHeight = bitMatrix.getHeight();\n\n int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];\n for (int y = 0; y < bitMatrixHeight; y++) {\n int offSet = y * bitMatrixWidth;\n for (int x = 0; x < bitMatrixWidth; x++) {\n pixels[offSet + x] = bitMatrix.get(x, y) ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white);\n }\n }\n Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);\n bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);\n return bitmap;\n }\n\n /* ##################################################################### */\n /* ##################################################################### */\n /*method\n * qr image downloader*/\n private Bitmap getBitmapFromUiView(View view) {\n\n //Define a bitmap with the same size as the view\n Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);\n //Bind a canvas to it\n Canvas canvas = new Canvas(returnedBitmap);\n //Get the view's background\n Drawable bgDrawable = view.getBackground();\n if (bgDrawable != null) {\n //has background drawable, then draw it on the canvas\n bgDrawable.draw(canvas);\n } else {\n //does not have background drawable, then draw white background on the canvas\n canvas.drawColor(Color.WHITE);\n }\n // draw the view on the canvas\n view.draw(canvas);\n\n //return the bitmap\n return returnedBitmap;\n }\n\n private void saveBitmapImage(Bitmap card) {\n\n long timestamp = System.currentTimeMillis();\n\n //Tell the media scanner about the new file so that it is immediately available to the user.\n ContentValues values = new ContentValues();\n\n values.put(MediaStore.Images.Media.MIME_TYPE, \"image/png\");\n values.put(MediaStore.Images.Media.DATE_ADDED, timestamp);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n\n values.put(MediaStore.Images.Media.DATE_TAKEN, timestamp);\n values.put(MediaStore.Images.Media.RELATIVE_PATH, \"Pictures/\" + getString(R.string.app_name));\n values.put(MediaStore.Images.Media.IS_PENDING, true);\n Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n\n if (uri != null) {\n try {\n OutputStream outputStream = getContentResolver().openOutputStream(uri);\n if (outputStream != null) {\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n }\n\n values.put(MediaStore.Images.Media.IS_PENDING, false);\n getContentResolver().update(uri, values, null, null);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n\n } else {\n File imageFileFolder = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));\n if (!imageFileFolder.exists()) {\n imageFileFolder.mkdirs();\n }\n String mImageName = \"\" + timestamp + \".png\";\n\n File imageFile = new File(imageFileFolder, mImageName);\n try {\n OutputStream outputStream = new FileOutputStream(imageFile);\n try {\n card.compress(Bitmap.CompressFormat.PNG, 100, outputStream);\n outputStream.close();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n }\n values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());\n getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);\n\n Toast.makeText(this, \"card download successful...\", Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n Log.e(TAG, \"saveToGallery: \", e);\n Toast.makeText(this, \"card download un-successful...\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n private void make_pdf() {\n\n DisplayMetrics displayMetrics = new DisplayMetrics();\n\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n this.getDisplay().getRealMetrics(displayMetrics);\n } else\n this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);\n\n cardView.measure(View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, View.MeasureSpec.EXACTLY),\n View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, View.MeasureSpec.EXACTLY));\n\n Log.d(\"my log\", \"Width Now \" + cardView.getMeasuredWidth());\n\n // cardView.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);\n\n // Create a new PdfDocument instance\n PdfDocument document = new PdfDocument();\n\n // Obtain the width and height of the view\n int viewWidth = cardView.getMeasuredWidth();\n int viewHeight = cardView.getMeasuredHeight();\n\n\n // Create a PageInfo object specifying the page attributes\n PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(viewWidth, viewHeight, 1).create();\n\n // Start a new page\n PdfDocument.Page page = document.startPage(pageInfo);\n\n // Get the Canvas object to draw on the page\n Canvas canvas = page.getCanvas();\n\n // Create a Paint object for styling the view\n Paint paint = new Paint();\n paint.setColor(Color.WHITE);\n\n // Draw the view on the canvas\n cardView.draw(canvas);\n\n // Finish the page\n document.finishPage(page);\n\n // Specify the path and filename of the output PDF file\n File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);\n\n /*time wise print*/\n /*eikhane millisecond ta niye lopping vabe pdf banacche*/\n long timestamps = System.currentTimeMillis();\n String fileName = \"Email_\" + timestamps + \".pdf\";\n\n File filePath = new File(downloadsDir, fileName);\n\n try {\n // Save the document to a file\n FileOutputStream fos = new FileOutputStream(filePath);\n document.writeTo(fos);\n document.close();\n fos.close();\n // PDF conversion successful\n Toast.makeText(this, \"pdf download successful\", Toast.LENGTH_LONG).show();\n } catch (IOException e) {\n e.printStackTrace();\n Toast.makeText(this, \"pdf download un-successful\", Toast.LENGTH_SHORT).show();\n }\n\n }\n\n /* ##################################################################### */\n /*qr pdf file*/\n /* ##################################################################### */\n}" }, { "identifier": "EmailModel", "path": "app/src/main/java/com/trodev/scanhub/models/EmailModel.java", "snippet": "public class EmailModel {\n\n public String email_from, email_to, email_sms, date, time, uid;\n\n public EmailModel() {\n }\n\n public EmailModel(String email_from, String email_to, String email_sms, String date, String time, String uid) {\n this.email_from = email_from;\n this.email_to = email_to;\n this.email_sms = email_sms;\n this.date = date;\n this.time = time;\n this.uid = uid;\n }\n\n public String getEmail_from() {\n return email_from;\n }\n\n public void setEmail_from(String email_from) {\n this.email_from = email_from;\n }\n\n public String getEmail_to() {\n return email_to;\n }\n\n public void setEmail_to(String email_to) {\n this.email_to = email_to;\n }\n\n public String getEmail_sms() {\n return email_sms;\n }\n\n public void setEmail_sms(String email_sms) {\n this.email_sms = email_sms;\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 getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n}" }, { "identifier": "LocationModel", "path": "app/src/main/java/com/trodev/scanhub/models/LocationModel.java", "snippet": "public class LocationModel {\n\n String loc_from, loc_to, loc_sms, date, time, uid;\n\n public LocationModel() {\n }\n\n public LocationModel(String loc_from, String loc_to, String loc_sms, String date, String time, String uid) {\n this.loc_from = loc_from;\n this.loc_to = loc_to;\n this.loc_sms = loc_sms;\n this.date = date;\n this.time = time;\n this.uid = uid;\n }\n\n public String getLoc_from() {\n return loc_from;\n }\n\n public void setLoc_from(String loc_from) {\n this.loc_from = loc_from;\n }\n\n public String getLoc_to() {\n return loc_to;\n }\n\n public void setLoc_to(String loc_to) {\n this.loc_to = loc_to;\n }\n\n public String getLoc_sms() {\n return loc_sms;\n }\n\n public void setLoc_sms(String loc_sms) {\n this.loc_sms = loc_sms;\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 getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n}" } ]
import android.content.Context; import android.content.Intent; 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.trodev.scanhub.R; import com.trodev.scanhub.detail_activity.EmailQrFullActivity; import com.trodev.scanhub.detail_activity.LocationQrFullActivity; import com.trodev.scanhub.models.EmailModel; import com.trodev.scanhub.models.LocationModel; import java.util.ArrayList;
6,067
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context; private ArrayList<LocationModel> list; private String category; public LocationAdapter(Context context, ArrayList<LocationModel> list, String category) { this.context = context; this.list = list; this.category = category; } @NonNull @Override public LocationAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.location_qr_item, parent, false); return new LocationAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull LocationAdapter.MyViewHolder holder, int position) { /*get data from database model*/ LocationModel models = list.get(position); holder.from.setText(models.getLoc_from()); holder.to.setText(models.getLoc_to()); holder.time.setText(models.getTime()); holder.date.setText(models.getDate()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context; private ArrayList<LocationModel> list; private String category; public LocationAdapter(Context context, ArrayList<LocationModel> list, String category) { this.context = context; this.list = list; this.category = category; } @NonNull @Override public LocationAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.location_qr_item, parent, false); return new LocationAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull LocationAdapter.MyViewHolder holder, int position) { /*get data from database model*/ LocationModel models = list.get(position); holder.from.setText(models.getLoc_from()); holder.to.setText(models.getLoc_to()); holder.time.setText(models.getTime()); holder.date.setText(models.getDate()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
Intent intent = new Intent(context, LocationQrFullActivity.class);
1
2023-12-26 05:10:38+00:00
8k
Deepennn/NetAPP
src/main/java/com/netapp/device/host/Host.java
[ { "identifier": "Iface", "path": "src/main/java/com/netapp/device/Iface.java", "snippet": "public class Iface\n{\n protected String iName; // 接口名称\n protected String macAddress; // MAC地址\n protected BlockingQueue<Ethernet> inputQueue; // 输入队列\n protected BlockingQueue<Ethernet> outputQueue; // 输出队列\n\n public Iface(String iName, String macAddress) {\n this.iName = iName;\n this.macAddress = macAddress;\n this.inputQueue = new LinkedBlockingQueue<>();\n this.outputQueue = new LinkedBlockingQueue<>();\n }\n\n /**---------------------------------putters:放入(阻塞)-------------------------------------*/\n\n // 由 Net 放入数据包\n public void putInputPacket(Ethernet etherPacket) {\n System.out.println(this.iName + \" is receiving Ether packet: \" + etherPacket);\n try {\n inputQueue.put(etherPacket);\n } catch (InterruptedException e) {\n// System.out.println(this.iName + \" blocked a receiving Ether packet: \" + etherPacket);\n e.printStackTrace();\n }\n }\n\n // 由 Device 放入数据包\n public void putOutputPacket(Ethernet etherPacket) {\n System.out.println(this.iName + \" is sending Ether packet: \" + etherPacket);\n try {\n// System.out.println(this.iName + \" blocked a sending Ether packet: \" + etherPacket);\n outputQueue.put(etherPacket);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**---------------------------------putters:放入(不阻塞)-------------------------------------*/\n\n\n // 由 Net 放入数据包\n public void offerInputPacket(Ethernet etherPacket) {\n if(inputQueue.offer(etherPacket)){\n System.out.println(this.iName + \" succeed in receiving Ether packet: \" + etherPacket);\n }else{\n System.out.println(this.iName + \" failed in receiving Ether packet: \" + etherPacket);\n }\n }\n\n // 由 Device 放入数据包\n public void offerOutputPacket(Ethernet etherPacket) {\n if(outputQueue.offer(etherPacket)){\n System.out.println(this.iName + \" succeed in sending Ether packet: \" + etherPacket);\n }else{\n System.out.println(this.iName + \" failed in sending Ether packet: \" + etherPacket);\n }\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**----------------------------------peekers:查看--------------------------------------------*/\n\n // 由 Device 查看数据包\n public Ethernet peekInputPacket() {\n return inputQueue.peek();\n }\n\n // 由 Net 查看数据包\n public Ethernet peekOutputPacket() {\n return outputQueue.peek();\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n /**---------------------------------pollers:取出(不阻塞)-------------------------------------*/\n\n // 由 Device 取出数据包\n public Ethernet pollInputPacket() {\n return inputQueue.poll();\n }\n\n // 由 Net 取出数据包\n public Ethernet pollOutputPacket() {\n return outputQueue.poll();\n }\n\n /**------------------------------------------------------------------------------------------*/\n\n public String getiName()\n { return this.iName; }\n\n public void setiName(String iName) {\n this.iName = iName;\n }\n\n public String getMacAddress() {\n return macAddress;\n }\n\n public void setMacAddress(String macAddress) {\n this.macAddress = macAddress;\n }\n\n public BlockingQueue<Ethernet> getInputQueue() {\n return inputQueue;\n }\n\n public void setInputQueue(BlockingQueue<Ethernet> inputQueue) {\n this.inputQueue = inputQueue;\n }\n\n public BlockingQueue<Ethernet> getOutputQueue() {\n return outputQueue;\n }\n\n public void setOutputQueue(BlockingQueue<Ethernet> outputQueue) {\n this.outputQueue = outputQueue;\n }\n\n}" }, { "identifier": "NetDevice", "path": "src/main/java/com/netapp/device/NetDevice.java", "snippet": "public abstract class NetDevice extends Device\n{\n\n /** ARP 缓存 */\n protected AtomicReference<ArpCache> atomicCache;\n\n /** 为ARP设置的输出缓存区 (不知道目的 MAC 的目的 IP) --> (对应数据包队列) */\n protected HashMap<String, BlockingQueue<Ethernet>> outputQueueMap;\n\n /**\n * 创建设备。\n * @param hostname 设备的主机名\n * @param interfaces 接口映射\n */\n public NetDevice(String hostname, Map<String, Iface> interfaces)\n {\n super(hostname, interfaces);\n this.atomicCache = new AtomicReference<>(new ArpCache());\n this.outputQueueMap = new HashMap<>();\n this.loadArpCache(ARP_CACHE_PREFFIX + this.hostname + ARP_CACHE_SUFFIX);\n }\n\n /**\n * 处理在特定接口接收到的以太网数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n public void handlePacket(Ethernet etherPacket, Iface inIface) {\n System.out.println(this.hostname + \" is receiving Ether packet: \" + etherPacket.toString());\n\n /********************************************************************/\n\n /* 检验 MAC */\n if(!inIface.getMacAddress().equals(etherPacket.getDestinationMAC()) &&\n !etherPacket.isBroadcast()){\n return;\n }\n\n /* 检验校验和 */\n int origCksum = etherPacket.getChecksum();\n etherPacket.updateChecksum();\n int calcCksum = etherPacket.getChecksum();\n if (origCksum != calcCksum) {\n System.out.println(this.hostname + \" found Ether packet's checksum is wrong: \");\n return;\n }\n /* 处理数据包 */\n switch (etherPacket.getEtherType()) {\n case Ethernet.TYPE_IPv4:\n this.handleIPPacket(etherPacket, inIface);\n break;\n case Ethernet.TYPE_ARP:\n this.handleARPPacket(etherPacket, inIface);\n break;\n // 暂时忽略其他数据包类型\n }\n\n /********************************************************************/\n }\n\n\n /**\n * 处理 IP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n protected abstract void handleIPPacket(Ethernet etherPacket, Iface inIface);\n\n\n /**\n * 发送 ICMP 数据包。(错误响应)\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n * @param type ICMP 类型\n * @param code ICMP 代码\n * @param echo 是否回显\n */\n protected abstract void sendICMPPacket(Ethernet etherPacket, Iface inIface, int type, int code, boolean echo);\n\n\n /**\n * 处理 ARP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param inIface 接收数据包的接口\n */\n protected void handleARPPacket(Ethernet etherPacket, Iface inIface) {\n if (etherPacket.getEtherType() != Ethernet.TYPE_ARP) {\n return;\n }\n\n ARP arpPacket = (ARP) etherPacket.getPayload();\n System.out.println(this.hostname + \" is handling ARP packet: \" + arpPacket);\n\n if (arpPacket.getOpCode() != ARP.OP_REQUEST) {\n if (arpPacket.getOpCode() == ARP.OP_REPLY) { // 收到的是 ARP 响应数据包\n\n // 放入 ARP 缓存\n String srcIp = arpPacket.getSenderProtocolAddress();\n atomicCache.get().insert(srcIp, arpPacket.getSenderHardwareAddress());\n\n Queue<Ethernet> packetsToSend = outputQueueMap.get(srcIp); // outputQueueMap 中目的 IP 是响应源 IP 的数据包队列\n while(packetsToSend != null && packetsToSend.peek() != null){\n Ethernet packet = packetsToSend.poll();\n packet.setDestinationMAC(arpPacket.getSenderHardwareAddress());\n packet.updateChecksum();\n this.sendPacket(packet, inIface);\n }\n }\n return;\n }\n\n // ARP 请求数据包\n\n String targetIp = arpPacket.getTargetProtocolAddress();\n if (!Objects.equals(targetIp, ((NetIface) inIface).getIpAddress())) // 不是对应接口 IP 则不处理\n return;\n\n Ethernet ether = new Ethernet();\n ether.setEtherType(Ethernet.TYPE_ARP);\n ether.setSourceMAC(inIface.getMacAddress());\n ether.setDestinationMAC(etherPacket.getSourceMAC());\n\n ARP arp = new ARP();\n arp.setHardwareType(ARP.HW_TYPE_ETHERNET);\n arp.setProtocolType(ARP.PROTO_TYPE_IP);\n arp.setOpCode(ARP.OP_REPLY);\n arp.setSenderHardwareAddress(inIface.getMacAddress());\n arp.setSenderProtocolAddress(((NetIface)inIface).getIpAddress());\n arp.setTargetHardwareAddress(arpPacket.getSenderHardwareAddress());\n arp.setTargetProtocolAddress(arpPacket.getSenderProtocolAddress());\n\n ether.setPayload(arp);\n\n System.out.println(this.hostname + \" is sending ARP packet:\" + ether);\n\n ether.updateChecksum();\n this.sendPacket(ether, inIface);\n return;\n }\n\n /**\n * 发送 ARP 数据包。\n * @param etherPacket 接收到的以太网数据包\n * @param dstIp ICMP 类型\n * @param outIface 发送数据包的接口\n */\n protected void sendARPPacket(Ethernet etherPacket, String dstIp, Iface outIface){\n ARP arp = new ARP();\n arp.setHardwareType(ARP.HW_TYPE_ETHERNET);\n arp.setProtocolType(ARP.PROTO_TYPE_IP);\n arp.setOpCode(ARP.OP_REQUEST);\n arp.setSenderHardwareAddress(outIface.getMacAddress());\n arp.setSenderProtocolAddress(((NetIface)outIface).getIpAddress());\n arp.setTargetHardwareAddress(null);\n arp.setTargetProtocolAddress(dstIp);\n\n final AtomicReference<Ethernet> atomicEtherPacket = new AtomicReference<>(new Ethernet());\n final AtomicReference<Iface> atomicIface = new AtomicReference<>(outIface);\n final AtomicReference<Ethernet> atomicInPacket = new AtomicReference<>(etherPacket);\n\n atomicEtherPacket.get().setEtherType(Ethernet.TYPE_ARP);\n atomicEtherPacket.get().setSourceMAC(outIface.getMacAddress());\n\n atomicEtherPacket.get().setPayload(arp);\n atomicEtherPacket.get().setDestinationMAC(Ethernet.BROADCAST_MAC); // 广播 ARP 请求数据包\n atomicEtherPacket.get().updateChecksum();\n\n\n if (!outputQueueMap.containsKey(dstIp)) {\n outputQueueMap.put(dstIp, new LinkedBlockingQueue<>());\n System.out.println(hostname + \" is making a new buffer queue for: \" + dstIp);\n }\n BlockingQueue<Ethernet> nextHopQueue = outputQueueMap.get(dstIp);\n\n // 放入(不阻塞)\n try {\n nextHopQueue.put(etherPacket);\n } catch (InterruptedException e) {\n// System.out.println(this.hostname + \" blocked a sending Ether packet: \" + etherPacket);\n e.printStackTrace();\n }\n\n final AtomicReference<BlockingQueue<Ethernet>> atomicQueue = new AtomicReference<BlockingQueue<Ethernet>>(nextHopQueue); // 线程安全\n\n Thread waitForReply = new Thread(new Runnable() {\n\n public void run() {\n\n try {\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n System.out.println(hostname + \" is sending ARP packet:\" + atomicEtherPacket.get());\n sendPacket(atomicEtherPacket.get(), atomicIface.get());\n Thread.sleep(1000);\n if (atomicCache.get().lookup(dstIp) != null) {\n System.out.println(hostname + \": Found it: \" + atomicCache.get().lookup(dstIp));\n return;\n }\n\n // 都发了 3 次了,实在是真的是找不着 MAC,那就放弃吧,发送一个`目的主机不可达`的 ICMP\n System.out.println(hostname + \": Not found: \" + dstIp);\n\n while (atomicQueue.get() != null && atomicQueue.get().peek() != null) {\n atomicQueue.get().poll();\n }\n sendICMPPacket(atomicInPacket.get(), atomicIface.get(), 3, 1, false);\n return;\n } catch (InterruptedException e) {\n System.out.println(e);\n }\n }\n });\n waitForReply.start();\n return;\n }\n\n\n /**\n * 从文件加载 ARP 缓存。\n * @param arpCacheFile 包含 ARP 缓存的文件名\n */\n public void loadArpCache(String arpCacheFile) {\n if (!atomicCache.get().load(arpCacheFile)) {\n System.err.println(\"Error setting up ARP cache from file \" + arpCacheFile);\n System.exit(1);\n }\n\n System.out.println(this.hostname + \" loaded static ARP cache\");\n System.out.println(\"----------------------------------\");\n System.out.print(this.atomicCache.get().toString());\n System.out.println(\"----------------------------------\");\n }\n\n public AtomicReference<ArpCache> getAtomicCache() {\n return atomicCache;\n }\n\n public void setAtomicCache(AtomicReference<ArpCache> atomicCache) {\n this.atomicCache = atomicCache;\n }\n\n}" }, { "identifier": "NetIface", "path": "src/main/java/com/netapp/device/NetIface.java", "snippet": "public class NetIface extends Iface {\n\n protected String ipAddress; // IP地址\n protected String subnetMask; // 所在子网子网掩码\n\n public NetIface(String name, String ipAddress, String macAddress, String subnetMask) {\n super(name, macAddress);\n this.ipAddress = ipAddress;\n this.subnetMask = subnetMask;\n }\n\n public String getIpAddress() {\n return ipAddress;\n }\n\n public void setIpAddress(String ipAddress) {\n this.ipAddress = ipAddress;\n }\n\n public String getSubnetMask()\n { return this.subnetMask; }\n\n public void setSubnetMask(String subnetMask)\n { this.subnetMask = subnetMask; }\n\n}" }, { "identifier": "ArpEntry", "path": "src/main/java/com/netapp/device/ArpEntry.java", "snippet": "public class ArpEntry\n{\n\n /** 对应于MAC地址的IP地址 */\n private String ip;\n\n /** 对应于IP地址的MAC地址 */\n private String mac;\n\n /** 映射创建时的时间 */\n private long timeAdded;\n\n /**\n * 创建一个将IP地址映射到MAC地址的ARP表条目。\n * @param ip 对应于MAC地址的IP地址\n * @param mac 对应于IP地址的MAC地址\n */\n public ArpEntry(String ip, String mac)\n {\n this.ip = ip;\n this.mac = mac;\n this.timeAdded = System.currentTimeMillis();\n }\n\n /**\n * @return 对应于MAC地址的IP地址\n */\n public String getIp()\n { return this.ip; }\n\n /**\n * @return 对应于IP地址的MAC地址\n */\n public String getMac()\n { return this.mac; }\n\n\n /**\n * @return 映射创建时的时间(自纪元以来的毫秒数)\n */\n public long getTimeAdded()\n { return this.timeAdded; }\n\n public String toString()\n {\n return String.format(\"%s \\t%s\", this.ip,\n this.mac);\n }\n}" } ]
import com.netapp.device.Iface; import com.netapp.device.NetDevice; import com.netapp.device.NetIface; import com.netapp.device.ArpEntry; import com.netapp.packet.*; import java.util.Map;
4,178
package com.netapp.device.host; public class Host extends NetDevice { protected String gatewayAddress; // 网关IP地址
package com.netapp.device.host; public class Host extends NetDevice { protected String gatewayAddress; // 网关IP地址
protected boolean isInSubnet(String dstIp, Iface outIface){
0
2023-12-23 13:03:07+00:00
8k
strokegmd/StrokeClient
stroke/client/modules/render/Hud.java
[ { "identifier": "StrokeClient", "path": "stroke/client/StrokeClient.java", "snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpublic static String name = \"[stroke] client ・ \";\r\n\tpublic static String version = \"v1.0.00\";\r\n\t\r\n\tpublic static StrokeClient instance;\r\n\tpublic static ClickGuiScreen clickGui;\r\n\t\r\n\tpublic static SettingsManager settingsManager;\r\n\t\r\n\tpublic static boolean destructed = false;\r\n\t\r\n\tpublic StrokeClient()\r\n\t{\r\n\t\tinstance = this;\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t}\r\n\t\r\n\tpublic static void launchClient() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\t\r\n\t\tViaMCP.getInstance().start();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Launching Stroke Client \" + version + \"!\");\r\n\t\t\r\n\t\tModuleManager.loadModules();\r\n\t\tCommandManager.loadCommands();\r\n\t\t\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.autoenable) {\r\n\t\t\t\tmodule.toggle(); module.toggle(); // bugfix lmao\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] All done!\");\r\n\t}\r\n\t\r\n\tpublic static void onKeyPress(int key) {\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.keybind == key && !(mc.currentScreen instanceof GuiChat) && !(mc.currentScreen instanceof GuiContainer) && !(mc.currentScreen instanceof GuiEditSign)) {\r\n\t\t\t\tmodule.toggle();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static int getScaledWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledWidth();\r\n\t}\r\n\t\r\n\tpublic static int getScaledHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledHeight();\r\n\t}\r\n\t\r\n\tpublic static int getDisplayWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayWidth / 2;\r\n\t}\r\n\t\r\n\tpublic static int getDisplayHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayHeight / 2;\r\n\t}\r\n\t\r\n\tpublic static String getUsername() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.getSession().getUsername();\r\n\t}\r\n\t\r\n\tpublic static void sendChatMessage(String message) {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tTextComponentString component = new TextComponentString(\"[\\2479Stroke§r] \" + message);\r\n\t\tmc.ingameGUI.getChatGUI().printChatMessage(component);\r\n\t}\r\n}" }, { "identifier": "Setting", "path": "stroke/client/clickgui/Setting.java", "snippet": "public class Setting {\n\t\n\tprivate String name;\n\tprivate BaseModule parent;\n\tprivate String mode;\n\t\n\tprivate String sval;\n\tprivate ArrayList<String> options;\n\tprivate String title;\n\t\n\tprivate boolean bval;\n\t\n\tprivate double dval;\n\tprivate double min;\n\tprivate double max;\n\tprivate boolean onlyint = false;\n\t\n\tprivate String text;\n\t\n\tprivate int color;\n\t\n\tpublic Setting(String name, BaseModule parent, ArrayList<String> options, String title){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.options = options;\n\t\tthis.title = title;\n\t\tthis.mode = \"Combo\";\n\t}\n\t\n\tpublic Setting(String name, BaseModule parent, boolean bval){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.bval = bval;\n\t\tthis.mode = \"Check\";\n\t}\n\t\n\tpublic Setting(String name, BaseModule parent, double dval, double min, double max, boolean onlyint){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.dval = dval;\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t\tthis.onlyint = onlyint;\n\t\tthis.mode = \"Slider\";\n\t}\n\n\t\n\tpublic String getName(){\n\t\treturn name;\n\t}\n\t\n\tpublic BaseModule getParentMod(){\n\t\treturn parent;\n\t}\n\t\n\tpublic String getValString(){\n\t\treturn this.sval;\n\t}\n\t\n\tpublic void setValString(String in){\n\t\tthis.sval = in;\n\t}\n\t\n\tpublic ArrayList<String> getOptions(){\n\t\treturn this.options;\n\t}\n\t\n\tpublic String getTitle(){\n\t\treturn this.title;\n\t}\n\t\n\tpublic boolean getValBoolean(){\n\t\treturn this.bval;\n\t}\n\t\n\tpublic void setValBoolean(boolean in){\n\t\tthis.bval = in;\n\t}\n\t\n\tpublic double getValDouble(){\n\t\tif(this.onlyint){\n\t\t\tthis.dval = (int)dval;\n\t\t}\n\t\treturn this.dval;\n\t}\n\n\tpublic void setValDouble(double in){\n\t\tthis.dval = in;\n\t}\n\t\n\tpublic double getMin(){\n\t\treturn this.min;\n\t}\n\t\n\tpublic double getMax(){\n\t\treturn this.max;\n\t}\n\t\n\tpublic int getColor(){\n\t\treturn this.color;\n\t}\n\t\n\tpublic String getString(){\n\t\treturn this.text;\n\t}\n\t\n\tpublic boolean isCombo(){\n\t\treturn this.mode.equalsIgnoreCase(\"Combo\") ? true : false;\n\t}\n\t\n\tpublic boolean isCheck(){\n\t\treturn this.mode.equalsIgnoreCase(\"Check\") ? true : false;\n\t}\n\t\n\tpublic boolean isSlider(){\n\t\treturn this.mode.equalsIgnoreCase(\"Slider\") ? true : false;\n\t}\n\t\n\tpublic boolean isMode(){\n\t\treturn this.mode.equalsIgnoreCase(\"ModeButton\") ? true : false;\n\t}\n\t\n\tpublic boolean onlyInt(){\n\t\treturn this.onlyint;\n\t}\n}" }, { "identifier": "BaseModule", "path": "stroke/client/modules/BaseModule.java", "snippet": "public class BaseModule {\r\n\tpublic static Minecraft mc = Minecraft.getMinecraft();\r\n\t\r\n\tpublic String name;\r\n\tpublic String tooltip;\r\n\t\r\n\tpublic ModuleCategory category;\r\n\tpublic int keybind;\r\n\t\r\n\tpublic boolean autoenable;\r\n\tpublic boolean enabled;\r\n\t\r\n\tpublic Map<String, Integer> settings = new HashMap();\r\n\t\r\n\tpublic int posX;\r\n\tpublic int posY;\r\n\t\r\n\tpublic BaseModule(String name, String tooltip, int keybind, ModuleCategory category, boolean autoenable) {\r\n\t\tthis.name = name;\r\n\t\tthis.tooltip = tooltip;\r\n\t\tthis.category = category;\r\n\t\tthis.keybind = keybind;\r\n\t\tthis.autoenable = autoenable;\r\n\t\tthis.enabled = autoenable;\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Loaded \" + this.name + \"!\");\r\n\t}\r\n\t\r\n\tpublic void toggle() {\r\n\t\tthis.enabled = !this.enabled;\r\n\t\tif(this.enabled) {\r\n\t\t\tthis.onEnable();\r\n\t\t} else {\r\n\t\t\tthis.onDisable();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setKey(int key)\r\n\t{\r\n\t\tthis.keybind = key;\r\n\t}\r\n\t\r\n\tpublic void onEnable() {}\r\n\tpublic void onUpdate() {}\r\n\tpublic void onRender() {}\r\n\tpublic void onRender3D() {}\r\n\tpublic void onDisable() {}\r\n}" }, { "identifier": "ModuleCategory", "path": "stroke/client/modules/ModuleCategory.java", "snippet": "public enum ModuleCategory {\r\n\tCombat, Movement, Player, Render, Fun, Misc\r\n}\r" }, { "identifier": "ModuleManager", "path": "stroke/client/modules/ModuleManager.java", "snippet": "public class ModuleManager {\r\n\tpublic static Minecraft mc = Minecraft.getMinecraft();\r\n\t\r\n\tpublic static ArrayList<BaseModule> modules = new ArrayList<BaseModule>();\r\n\t\r\n\tpublic static void addModule(BaseModule module) {\r\n\t\tmodules.add(module);\r\n\t}\r\n\r\n\tpublic static void sortModules() {\r\n\t\tmodules.sort(Comparator.comparingInt(module -> mc.fontRendererObj.getStringWidth(((BaseModule)module).name)).reversed());\r\n\t}\r\n\t\r\n\tpublic static void loadModules() {\r\n\t\tModuleManager.addModule(new AntiKnockback());\r\n\t\tModuleManager.addModule(new AutoArmor());\r\n\t\tModuleManager.addModule(new AutoGApple());\r\n\t\tModuleManager.addModule(new AutoTotem());\r\n\t\tModuleManager.addModule(new Criticals());\r\n\t\tModuleManager.addModule(new CrystalAura());\r\n\t\tModuleManager.addModule(new KillAura());\r\n\t\t\r\n\t\tModuleManager.addModule(new AirJump());\r\n\t\tModuleManager.addModule(new AutoJump());\r\n\t\tModuleManager.addModule(new EntitySpeed());\r\n\t\tModuleManager.addModule(new Flight());\r\n\t\tModuleManager.addModule(new InventoryMove());\r\n\t\tModuleManager.addModule(new NoSlowDown());\r\n\t\tModuleManager.addModule(new SafeWalk());\r\n\t\tModuleManager.addModule(new Sprint());\r\n\t\tModuleManager.addModule(new Step());\r\n\t\r\n\t\tModuleManager.addModule(new Blink());\r\n\t\tModuleManager.addModule(new ChestStealer());\r\n\t\tModuleManager.addModule(new FastPlace());\r\n\t\tModuleManager.addModule(new Freecam());\r\n\t\tModuleManager.addModule(new NoFall());\r\n\t\tModuleManager.addModule(new Portals());\r\n\t\tModuleManager.addModule(new Timer());\r\n\t\t\r\n\t\tModuleManager.addModule(new AntiOverlay());\r\n\t\tModuleManager.addModule(new BlockHitAnim());\r\n\t\tModuleManager.addModule(new ClickGui());\r\n\t\tModuleManager.addModule(new FullBright());\r\n\t\tModuleManager.addModule(new Hud());\r\n\t\tModuleManager.addModule(new NameTags());\r\n\t\tModuleManager.addModule(new NoScoreBoard());\r\n\t\tModuleManager.addModule(new NoWeather());\r\n\t\tModuleManager.addModule(new PlayerESP());\r\n\t\tModuleManager.addModule(new StorageESP());\r\n\t\tModuleManager.addModule(new TargetHUD());\r\n\t\tModuleManager.addModule(new Tracers());\r\n\t\tModuleManager.addModule(new ViewModel());\r\n\t\tModuleManager.addModule(new Wallhack());\r\n\t\tModuleManager.addModule(new XRay());\r\n\t\t\r\n\t\tModuleManager.addModule(new DiscordRPCModule());\r\n\t\tModuleManager.addModule(new MCF());\r\n\t\tModuleManager.addModule(new MigrationCape());\r\n\t\tModuleManager.addModule(new SelfDestruct());\r\n\t\tModuleManager.addModule(new Spammer());\r\n\t\tModuleManager.addModule(new StashLogger());\r\n\t\t\r\n\t\tModuleManager.addModule(new HalalMode());\r\n\t}\r\n\t\r\n\tpublic static BaseModule getModuleByName(String name) {\r\n\t\tfor(BaseModule module : modules) {\r\n\t\t\tif(module.name.equalsIgnoreCase(name)) {\r\n\t\t\t\treturn module;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic static ArrayList<BaseModule> getModulesInCategory(ModuleCategory category)\r\n\t{\r\n\t\tArrayList<BaseModule> modules = new ArrayList<BaseModule>();\r\n\t\tfor (BaseModule module : ModuleManager.modules)\r\n\t\t{\r\n\t\t\tif (module.category == category)\r\n\t\t\t{\r\n\t\t\t\tmodules.add(module);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn modules;\r\n\t}\r\n}\r" }, { "identifier": "ColorUtils", "path": "stroke/client/util/ColorUtils.java", "snippet": "public class ColorUtils {\r\n\tpublic static int primaryColor = 0xffffff;\r\n\tpublic static int secondaryColor = 0x9b90ff;\r\n\tpublic static int settingColor = 0x999999;\r\n\t\r\n\tpublic static int primaryObjectColor = new Color(primaryColor).hashCode();\r\n\tpublic static int secondaryObjectColor = new Color(secondaryColor).hashCode();\r\n\t\r\n\t// stolen again lol kekw xd lmao lmfao))))))\r\n\t// best c0d3r ever\r\n\tpublic static int getRainbow(float seconds, float saturation, float brightness, int index) {\r\n\t\tfloat hue = ((System.currentTimeMillis() + index) % (int)(seconds * 1000)) / (float)(seconds * 1000);\r\n\t\tint color = Color.HSBtoRGB(hue, saturation, brightness);\r\n\t\treturn color;\r\n\t}\r\n}\r" } ]
import java.awt.Color; import net.minecraft.client.gui.Gui; import net.stroke.client.StrokeClient; import net.stroke.client.clickgui.Setting; import net.stroke.client.modules.BaseModule; import net.stroke.client.modules.ModuleCategory; import net.stroke.client.modules.ModuleManager; import net.stroke.client.util.ColorUtils;
3,848
package net.stroke.client.modules.render; public class Hud extends BaseModule { public StrokeClient client; public Hud() { super("Hud", "Shows enabled modules and important information", 0x00, ModuleCategory.Render, true); // totally not stolen from kami StrokeClient.instance.settingsManager.rSetting(new Setting("Coordinates", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Module List", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Username", this, true)); } public void onRender() { boolean coordinates = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Coordinates").getValBoolean(); boolean moduleList = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Module List").getValBoolean(); boolean username = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Username").getValBoolean(); int xBorder = StrokeClient.getScaledWidth() - 2; int yBorder = StrokeClient.getScaledHeight() - 10; int versionX = mc.fontRendererObj.getStringWidth(client.name); int usernameX = mc.fontRendererObj.getStringWidth("Hello, ") + 2; int markX = mc.fontRendererObj.getStringWidth("Hello, " + StrokeClient.getUsername()) + 2; double playerX = Math.round(mc.player.posX * 10.0) / 10.0; double playerY = Math.round(mc.player.posY * 10.0) / 10.0; double playerZ = Math.round(mc.player.posZ * 10.0) / 10.0; double playerNetherX = playerX / 8.0f; double playerNetherY = playerY; double playerNetherZ = playerZ / 8.0f; playerNetherX = Math.round(playerNetherX * 10.0) / 10.0; playerNetherZ = Math.round(playerNetherZ * 10.0) / 10.0; String coords = Double.toString(playerX) + ", " + Double.toString(playerY) + ", " + Double.toString(playerZ); String netherCoords = Double.toString(playerNetherX) + ", " + Double.toString(playerNetherY) + ", " + Double.toString(playerNetherZ); int xyzX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords); int coordsX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords) + mc.fontRendererObj.getStringWidth("XYZ "); int xyzY = yBorder - 10; int coordsY = xyzY; int netherX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords); int netherCoordsX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords) + mc.fontRendererObj.getStringWidth("Nether "); int netherY = yBorder; int netherCoordsY = netherY; int rainbowColor = ColorUtils.getRainbow(2.0f, 0.8f, 1.0f, 100); Gui.drawRect(3, 2, 124, 1, rainbowColor); Gui.drawRect(3, 2, 124, 14, Color.black.hashCode() * 100); mc.fontRendererObj.drawStringWithShadow(client.name, 4, 4, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(client.version, versionX, 4, ColorUtils.secondaryColor); if(username) { mc.fontRendererObj.drawStringWithShadow("Hello, ", 2, yBorder, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(StrokeClient.getUsername(), usernameX, yBorder, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow("!", markX, yBorder, ColorUtils. primaryColor); } if(coordinates) { mc.fontRendererObj.drawStringWithShadow("XYZ", xyzX, xyzY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(coords, coordsX, coordsY, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow("Nether ", netherX, netherY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(netherCoords, netherCoordsX, netherCoordsY, ColorUtils.primaryColor); } int moduleNumber = 0;
package net.stroke.client.modules.render; public class Hud extends BaseModule { public StrokeClient client; public Hud() { super("Hud", "Shows enabled modules and important information", 0x00, ModuleCategory.Render, true); // totally not stolen from kami StrokeClient.instance.settingsManager.rSetting(new Setting("Coordinates", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Module List", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Username", this, true)); } public void onRender() { boolean coordinates = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Coordinates").getValBoolean(); boolean moduleList = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Module List").getValBoolean(); boolean username = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Username").getValBoolean(); int xBorder = StrokeClient.getScaledWidth() - 2; int yBorder = StrokeClient.getScaledHeight() - 10; int versionX = mc.fontRendererObj.getStringWidth(client.name); int usernameX = mc.fontRendererObj.getStringWidth("Hello, ") + 2; int markX = mc.fontRendererObj.getStringWidth("Hello, " + StrokeClient.getUsername()) + 2; double playerX = Math.round(mc.player.posX * 10.0) / 10.0; double playerY = Math.round(mc.player.posY * 10.0) / 10.0; double playerZ = Math.round(mc.player.posZ * 10.0) / 10.0; double playerNetherX = playerX / 8.0f; double playerNetherY = playerY; double playerNetherZ = playerZ / 8.0f; playerNetherX = Math.round(playerNetherX * 10.0) / 10.0; playerNetherZ = Math.round(playerNetherZ * 10.0) / 10.0; String coords = Double.toString(playerX) + ", " + Double.toString(playerY) + ", " + Double.toString(playerZ); String netherCoords = Double.toString(playerNetherX) + ", " + Double.toString(playerNetherY) + ", " + Double.toString(playerNetherZ); int xyzX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords); int coordsX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords) + mc.fontRendererObj.getStringWidth("XYZ "); int xyzY = yBorder - 10; int coordsY = xyzY; int netherX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords); int netherCoordsX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords) + mc.fontRendererObj.getStringWidth("Nether "); int netherY = yBorder; int netherCoordsY = netherY; int rainbowColor = ColorUtils.getRainbow(2.0f, 0.8f, 1.0f, 100); Gui.drawRect(3, 2, 124, 1, rainbowColor); Gui.drawRect(3, 2, 124, 14, Color.black.hashCode() * 100); mc.fontRendererObj.drawStringWithShadow(client.name, 4, 4, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(client.version, versionX, 4, ColorUtils.secondaryColor); if(username) { mc.fontRendererObj.drawStringWithShadow("Hello, ", 2, yBorder, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(StrokeClient.getUsername(), usernameX, yBorder, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow("!", markX, yBorder, ColorUtils. primaryColor); } if(coordinates) { mc.fontRendererObj.drawStringWithShadow("XYZ", xyzX, xyzY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(coords, coordsX, coordsY, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow("Nether ", netherX, netherY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(netherCoords, netherCoordsX, netherCoordsY, ColorUtils.primaryColor); } int moduleNumber = 0;
for (BaseModule module : ModuleManager.modules) {
4
2023-12-31 10:56:59+00:00
8k
piovas-lu/condominio
src/main/java/app/condominio/controller/CobrancaController.java
[ { "identifier": "Cobranca", "path": "src/main/java/app/condominio/domain/Cobranca.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"cobrancas\")\r\npublic class Cobranca implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idcobranca\")\r\n\tprivate Long idCobranca;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivoemissao\")\r\n\tprivate MotivoEmissao motivoEmissao;\r\n\r\n\t@Size(max = 10)\r\n\t@NotBlank\r\n\tprivate String numero;\r\n\r\n\t@Size(max = 3)\r\n\tprivate String parcela;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"dataemissao\")\r\n\tprivate LocalDate dataEmissao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datavencimento\")\r\n\tprivate LocalDate dataVencimento;\r\n\r\n\t@NotNull\r\n\t@Min(0)\r\n\tprivate BigDecimal valor;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal desconto;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal abatimento;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrasdeducoes\")\r\n\tprivate BigDecimal outrasDeducoes;\r\n\r\n\t// Juros tem atualização no banco de dados\r\n\t@Min(0)\r\n\t@Column(name = \"jurosmora\")\r\n\tprivate BigDecimal jurosMora;\r\n\r\n\t// Multa tem atualização no banco de dados\r\n\t@Min(0)\r\n\tprivate BigDecimal multa;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrosacrescimos\")\r\n\tprivate BigDecimal outrosAcrescimos;\r\n\r\n\t// Total é atualizado no banco de dados quando Juros e Multa são atualizados\r\n\t@Min(0)\r\n\t@NotNull\r\n\tprivate BigDecimal total;\r\n\r\n\t@Size(max = 255)\r\n\tprivate String descricao;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualjurosmes\")\r\n\tprivate Float percentualJurosMes;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualmulta\")\r\n\tprivate Float percentualMulta;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate SituacaoCobranca situacao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datarecebimento\")\r\n\tprivate LocalDate dataRecebimento;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivobaixa\")\r\n\tprivate MotivoBaixa motivoBaixa;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idmoradia\")\r\n\tprivate Moradia moradia;\r\n\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic Long getIdCobranca() {\r\n\t\treturn idCobranca;\r\n\t}\r\n\r\n\tpublic void setIdCobranca(Long idCobranca) {\r\n\t\tthis.idCobranca = idCobranca;\r\n\t}\r\n\r\n\tpublic Moradia getMoradia() {\r\n\t\treturn moradia;\r\n\t}\r\n\r\n\tpublic void setMoradia(Moradia moradia) {\r\n\t\tthis.moradia = moradia;\r\n\t}\r\n\r\n\tpublic MotivoEmissao getMotivoEmissao() {\r\n\t\treturn motivoEmissao;\r\n\t}\r\n\r\n\tpublic void setMotivoEmissao(MotivoEmissao motivoEmissao) {\r\n\t\tthis.motivoEmissao = motivoEmissao;\r\n\t}\r\n\r\n\tpublic String getNumero() {\r\n\t\treturn numero;\r\n\t}\r\n\r\n\tpublic void setNumero(String numero) {\r\n\t\tthis.numero = numero;\r\n\t}\r\n\r\n\tpublic String getParcela() {\r\n\t\treturn parcela;\r\n\t}\r\n\r\n\tpublic void setParcela(String parcela) {\r\n\t\tthis.parcela = parcela;\r\n\t}\r\n\r\n\tpublic LocalDate getDataEmissao() {\r\n\t\treturn dataEmissao;\r\n\t}\r\n\r\n\tpublic void setDataEmissao(LocalDate dataEmissao) {\r\n\t\tthis.dataEmissao = dataEmissao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataVencimento() {\r\n\t\treturn dataVencimento;\r\n\t}\r\n\r\n\tpublic void setDataVencimento(LocalDate dataVencimento) {\r\n\t\tthis.dataVencimento = dataVencimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getValor() {\r\n\t\treturn valor;\r\n\t}\r\n\r\n\tpublic void setValor(BigDecimal valor) {\r\n\t\tthis.valor = valor;\r\n\t}\r\n\r\n\tpublic BigDecimal getDesconto() {\r\n\t\treturn desconto;\r\n\t}\r\n\r\n\tpublic void setDesconto(BigDecimal desconto) {\r\n\t\tthis.desconto = desconto;\r\n\t}\r\n\r\n\tpublic BigDecimal getAbatimento() {\r\n\t\treturn abatimento;\r\n\t}\r\n\r\n\tpublic void setAbatimento(BigDecimal abatimento) {\r\n\t\tthis.abatimento = abatimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrasDeducoes() {\r\n\t\treturn outrasDeducoes;\r\n\t}\r\n\r\n\tpublic void setOutrasDeducoes(BigDecimal outrasDeducoes) {\r\n\t\tthis.outrasDeducoes = outrasDeducoes;\r\n\t}\r\n\r\n\tpublic BigDecimal getJurosMora() {\r\n\t\treturn jurosMora;\r\n\t}\r\n\r\n\tpublic void setJurosMora(BigDecimal jurosMora) {\r\n\t\tthis.jurosMora = jurosMora;\r\n\t}\r\n\r\n\tpublic BigDecimal getMulta() {\r\n\t\treturn multa;\r\n\t}\r\n\r\n\tpublic void setMulta(BigDecimal multa) {\r\n\t\tthis.multa = multa;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrosAcrescimos() {\r\n\t\treturn outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic void setOutrosAcrescimos(BigDecimal outrosAcrescimos) {\r\n\t\tthis.outrosAcrescimos = outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic BigDecimal getTotal() {\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void setTotal(BigDecimal total) {\r\n\t\tthis.total = total;\r\n\t}\r\n\r\n\tpublic String getDescricao() {\r\n\t\treturn descricao;\r\n\t}\r\n\r\n\tpublic void setDescricao(String descricao) {\r\n\t\tthis.descricao = descricao;\r\n\t}\r\n\r\n\tpublic Float getPercentualJurosMes() {\r\n\t\treturn percentualJurosMes;\r\n\t}\r\n\r\n\tpublic void setPercentualJurosMes(Float percentualJurosMes) {\r\n\t\tthis.percentualJurosMes = percentualJurosMes;\r\n\t}\r\n\r\n\tpublic Float getPercentualMulta() {\r\n\t\treturn percentualMulta;\r\n\t}\r\n\r\n\tpublic void setPercentualMulta(Float percentualMulta) {\r\n\t\tthis.percentualMulta = percentualMulta;\r\n\t}\r\n\r\n\tpublic SituacaoCobranca getSituacao() {\r\n\t\treturn situacao;\r\n\t}\r\n\r\n\tpublic void setSituacao(SituacaoCobranca situacao) {\r\n\t\tthis.situacao = situacao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataRecebimento() {\r\n\t\treturn dataRecebimento;\r\n\t}\r\n\r\n\tpublic void setDataRecebimento(LocalDate dataRecebimento) {\r\n\t\tthis.dataRecebimento = dataRecebimento;\r\n\t}\r\n\r\n\tpublic MotivoBaixa getMotivoBaixa() {\r\n\t\treturn motivoBaixa;\r\n\t}\r\n\r\n\tpublic void setMotivoBaixa(MotivoBaixa motivoBaixa) {\r\n\t\tthis.motivoBaixa = motivoBaixa;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tString s = numero;\r\n\t\tif (parcela != null) {\r\n\t\t\ts += \" - \" + parcela;\r\n\t\t}\r\n\t\treturn s;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idCobranca == null) ? 0 : idCobranca.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tCobranca other = (Cobranca) obj;\r\n\t\tif (idCobranca == null) {\r\n\t\t\tif (other.idCobranca != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idCobranca.equals(other.idCobranca)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r" }, { "identifier": "Moradia", "path": "src/main/java/app/condominio/domain/Moradia.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"moradias\")\r\npublic class Moradia implements Serializable, Comparable<Moradia> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idmoradia\")\r\n\tprivate Long idMoradia;\r\n\r\n\t@Size(min = 1, max = 10)\r\n\t@NotBlank\r\n\tprivate String sigla;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate TipoMoradia tipo;\r\n\r\n\tprivate Float area;\r\n\r\n\t@Max(100)\r\n\t@Min(0)\r\n\t@Column(name = \"fracaoideal\")\r\n\tprivate Float fracaoIdeal;\r\n\r\n\t@Size(max = 30)\r\n\tprivate String matricula;\r\n\r\n\tprivate Integer vagas;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idbloco\")\r\n\tprivate Bloco bloco;\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)\r\n\t@OrderBy(value = \"dataEntrada\")\r\n\t@Valid\r\n\tprivate List<Relacao> relacoes = new ArrayList<>();\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@OrderBy(value = \"numero, parcela\")\r\n\tprivate List<Cobranca> cobrancas = new ArrayList<>();\r\n\r\n\tpublic Long getIdMoradia() {\r\n\t\treturn idMoradia;\r\n\t}\r\n\r\n\tpublic void setIdMoradia(Long idMoradia) {\r\n\t\tthis.idMoradia = idMoradia;\r\n\t}\r\n\r\n\tpublic String getSigla() {\r\n\t\treturn sigla;\r\n\t}\r\n\r\n\tpublic void setSigla(String sigla) {\r\n\t\tthis.sigla = sigla;\r\n\t}\r\n\r\n\tpublic TipoMoradia getTipo() {\r\n\t\treturn tipo;\r\n\t}\r\n\r\n\tpublic void setTipo(TipoMoradia tipo) {\r\n\t\tthis.tipo = tipo;\r\n\t}\r\n\r\n\tpublic Float getArea() {\r\n\t\treturn area;\r\n\t}\r\n\r\n\tpublic void setArea(Float area) {\r\n\t\tthis.area = area;\r\n\t}\r\n\r\n\tpublic Float getFracaoIdeal() {\r\n\t\treturn fracaoIdeal;\r\n\t}\r\n\r\n\tpublic void setFracaoIdeal(Float fracaoIdeal) {\r\n\t\tthis.fracaoIdeal = fracaoIdeal;\r\n\t}\r\n\r\n\tpublic String getMatricula() {\r\n\t\treturn matricula;\r\n\t}\r\n\r\n\tpublic void setMatricula(String matricula) {\r\n\t\tthis.matricula = matricula;\r\n\t}\r\n\r\n\tpublic Integer getVagas() {\r\n\t\treturn vagas;\r\n\t}\r\n\r\n\tpublic void setVagas(Integer vagas) {\r\n\t\tthis.vagas = vagas;\r\n\t}\r\n\r\n\tpublic Bloco getBloco() {\r\n\t\treturn bloco;\r\n\t}\r\n\r\n\tpublic void setBloco(Bloco bloco) {\r\n\t\tthis.bloco = bloco;\r\n\t}\r\n\r\n\tpublic List<Relacao> getRelacoes() {\r\n\t\treturn relacoes;\r\n\t}\r\n\r\n\tpublic void setRelacoes(List<Relacao> relacoes) {\r\n\t\tthis.relacoes = relacoes;\r\n\t}\r\n\r\n\tpublic List<Cobranca> getCobrancas() {\r\n\t\treturn cobrancas;\r\n\t}\r\n\r\n\tpublic void setCobrancas(List<Cobranca> cobrancas) {\r\n\t\tthis.cobrancas = cobrancas;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn bloco.toString() + \" - \" + sigla;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idMoradia == null) ? 0 : idMoradia.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tMoradia other = (Moradia) obj;\r\n\t\tif (idMoradia == null) {\r\n\t\t\tif (other.idMoradia != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idMoradia.equals(other.idMoradia)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Moradia arg0) {\r\n\t\treturn this.toString().compareTo(arg0.toString());\r\n\t}\r\n}\r" }, { "identifier": "MotivoBaixa", "path": "src/main/java/app/condominio/domain/enums/MotivoBaixa.java", "snippet": "public enum MotivoBaixa {\r\n\r\n\t// @formatter:off\r\n\tN(\"Recebimento normal\"),\r\n\tR(\"Renegociação de dívida\"),\r\n\tP(\"Prescrição\"),\r\n\tO(\"Outras\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate MotivoBaixa(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n}\r" }, { "identifier": "MotivoEmissao", "path": "src/main/java/app/condominio/domain/enums/MotivoEmissao.java", "snippet": "public enum MotivoEmissao {\r\n\r\n\t// @formatter:off\r\n\tO(\"Normal\"),\r\n\tE(\"Extra\"),\r\n\tA(\"Avulsa\"),\r\n\tR(\"Renegociação\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate MotivoEmissao(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n}\r" }, { "identifier": "SituacaoCobranca", "path": "src/main/java/app/condominio/domain/enums/SituacaoCobranca.java", "snippet": "public enum SituacaoCobranca {\r\n\r\n\t// @formatter:off\r\n\tN(\"Normal\"),\r\n\tA(\"Notificado\"),\r\n\tP(\"Protestado\"),\r\n\tJ(\"Ação Judicial\"),\r\n\tO(\"Outras\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\r\n\tprivate SituacaoCobranca(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n}\r" }, { "identifier": "CobrancaService", "path": "src/main/java/app/condominio/service/CobrancaService.java", "snippet": "public interface CobrancaService extends CrudService<Cobranca, Long> {\r\n\r\n\t/**\r\n\t * @return Retorna um BigDecimal com o valor total da inadimplência do\r\n\t * Condomínio na data atual (considera o valor total da Cobrança, com\r\n\t * acréscimos e deduções). Nunca retorna nulo, se não houver\r\n\t * inadimplência, retorna BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal inadimplencia();\r\n\r\n\t/**\r\n\t * @return Retorna uma lista do tipo List{@literal <}Cobranca{@literal >} com\r\n\t * todas as Cobrancas do Condomínio vencidas na data atual (considera o\r\n\t * valor total da Cobrança, com acréscimos e deduções). Nunca retorna\r\n\t * nulo, se não houver inadimplência, retorna uma lista vazia.\r\n\t */\r\n\tpublic List<Cobranca> listarInadimplencia();\r\n\r\n}\r" }, { "identifier": "MoradiaService", "path": "src/main/java/app/condominio/service/MoradiaService.java", "snippet": "public interface MoradiaService extends CrudService<Moradia, Long> {\r\n\r\n}\r" } ]
import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import app.condominio.domain.Cobranca; import app.condominio.domain.Moradia; import app.condominio.domain.enums.MotivoBaixa; import app.condominio.domain.enums.MotivoEmissao; import app.condominio.domain.enums.SituacaoCobranca; import app.condominio.service.CobrancaService; import app.condominio.service.MoradiaService;
4,513
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao")
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao")
public MotivoEmissao[] motivosEmissao() {
3
2023-12-29 22:19:42+00:00
8k
HuXin0817/shop_api
buyer-api/src/test/java/cn/lili/buyer/test/cart/CartTest.java
[ { "identifier": "CategoryVO", "path": "framework/src/main/java/cn/lili/modules/goods/entity/vos/CategoryVO.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class CategoryVO extends Category {\n\n private static final long serialVersionUID = 3775766246075838410L;\n\n @ApiModelProperty(value = \"父节点名称\")\n private String parentTitle;\n\n @ApiModelProperty(\"子分类列表\")\n private List<CategoryVO> children;\n\n @ApiModelProperty(\"分类关联的品牌列表\")\n private List<Brand> brandList;\n\n public CategoryVO(Category category) {\n BeanUtil.copyProperties(category, this);\n }\n\n public CategoryVO(String id, String createBy, Date createTime, String updateBy, Date updateTime, Boolean deleteFlag, String name, String parentId, Integer level, BigDecimal sortOrder, Double commissionRate, String image, Boolean supportChannel) {\n super(id, createBy, createTime, updateBy, updateTime, deleteFlag, name, parentId, level, sortOrder, commissionRate, image, supportChannel);\n }\n\n public List<CategoryVO> getChildren() {\n\n if (children != null) {\n children.sort(new Comparator<CategoryVO>() {\n @Override\n public int compare(CategoryVO o1, CategoryVO o2) {\n return o1.getSortOrder().compareTo(o2.getSortOrder());\n }\n });\n return children;\n }\n return null;\n }\n}" }, { "identifier": "CategoryService", "path": "framework/src/main/java/cn/lili/modules/goods/service/CategoryService.java", "snippet": "public interface CategoryService extends IService<Category> {\n\n\n /**\n * 管理端获取所有分类\n * 即获取的对象不管是否删除,都要展示,而且不从缓存获取,保证内容是最新的\n *\n * @param parentId 分类父ID\n * @return 商品分类列表\n */\n List<Category> dbList(String parentId);\n\n /**\n * 获取分类\n *\n * @param id\n * @return\n */\n Category getCategoryById(String id);\n\n /**\n * 根据分类id集合获取所有分类根据层级排序\n *\n * @param ids 分类ID集合\n * @return 商品分类列表\n */\n List<Category> listByIdsOrderByLevel(List<String> ids);\n\n /**\n * 根据分类id集合获取所有分类根据层级排序\n *\n * @param ids 分类ID集合\n * @return 商品分类列表\n */\n List<Map<String, Object>> listMapsByIdsOrderByLevel(List<String> ids, String columns);\n\n /**\n * 获取分类树\n *\n * @return 分类树\n */\n List<CategoryVO> categoryTree();\n\n /**\n * 查询所有的分类,父子关系\n *\n * @param parentId 分类父ID\n * @return 所有的分类,父子关系\n */\n List<CategoryVO> listAllChildren(String parentId);\n\n /**\n * 查询所有的分类,父子关系\n * 数据库获取\n *\n * @param categorySearchParams 查询参数\n * @return 所有的分类,父子关系\n */\n List<CategoryVO> listAllChildren(CategorySearchParams categorySearchParams);\n\n /**\n * 获取指定分类的分类名称\n *\n * @param ids 指定分类id集合\n * @return 分类名称集合\n */\n List<String> getCategoryNameByIds(List<String> ids);\n\n /**\n * 获取商品分类list\n *\n * @param category 分类\n * @return 商品分类list\n */\n List<Category> findByAllBySortOrder(Category category);\n\n /**\n * 添加商品分类\n *\n * @param category 商品分类信息\n * @return 添加结果\n */\n boolean saveCategory(Category category);\n\n /**\n * 修改商品分类\n *\n * @param category 商品分类信息\n * @return 修改结果\n */\n void updateCategory(Category category);\n\n /**\n * 批量删除分类\n *\n * @param id 分类ID\n */\n void delete(String id);\n\n /**\n * 分类状态的更改\n *\n * @param categoryId 商品分类ID\n * @param enableOperations 是否可用\n */\n void updateCategoryStatus(String categoryId, Boolean enableOperations);\n\n /**\n * 获取商家经营类目\n *\n * @param categories 经营范围\n * @return 分类VO列表\n */\n List<CategoryVO> getStoreCategory(String[] categories);\n\n /**\n * 获取一级分类列表\n * 用于商家入驻选择\n *\n * @return 分类列表\n */\n List<Category> firstCategory();\n\n}" }, { "identifier": "TradeDTO", "path": "framework/src/main/java/cn/lili/modules/order/cart/entity/dto/TradeDTO.java", "snippet": "@Data\npublic class TradeDTO implements Serializable {\n\n private static final long serialVersionUID = -3137165707807057810L;\n\n @ApiModelProperty(value = \"sn\")\n private String sn;\n\n @ApiModelProperty(value = \"是否为其他订单下的订单,如果是则为依赖订单的sn,否则为空\")\n private String parentOrderSn;\n\n @ApiModelProperty(value = \"购物车列表\")\n private List<CartVO> cartList;\n\n @ApiModelProperty(value = \"整笔交易中所有的规格商品\")\n private List<CartSkuVO> skuList;\n\n @ApiModelProperty(value = \"购物车车计算后的总价\")\n private PriceDetailVO priceDetailVO;\n\n @ApiModelProperty(value = \"购物车车计算后的总价\")\n private PriceDetailDTO priceDetailDTO;\n\n @ApiModelProperty(value = \"发票信息\")\n private ReceiptVO receiptVO;\n\n @ApiModelProperty(value = \"是否需要发票\")\n private Boolean needReceipt;\n\n\n @ApiModelProperty(value = \"不支持配送方式\")\n private List<CartSkuVO> notSupportFreight;\n\n /**\n * 购物车类型\n */\n private CartTypeEnum cartTypeEnum;\n /**\n * 店铺备注\n */\n private List<StoreRemarkDTO> storeRemark;\n\n /**\n * sku促销连线 包含满优惠\n * <p>\n * KEY值为 sku_id+\"_\"+SuperpositionPromotionEnum\n * VALUE值为 对应的活动ID\n *\n * @see SuperpositionPromotionEnum\n */\n private Map<String, String> skuPromotionDetail;\n\n /**\n * 使用平台优惠券,一笔订单只能使用一个平台优惠券\n */\n private MemberCouponDTO platformCoupon;\n\n /**\n * key 为商家id\n * value 为商家优惠券\n * 店铺优惠券\n */\n private Map<String, MemberCouponDTO> storeCoupons;\n\n /**\n * 可用优惠券列表\n */\n private List<MemberCoupon> canUseCoupons;\n\n /**\n * 无法使用优惠券无法使用的原因\n */\n private List<MemberCouponVO> cantUseCoupons;\n\n /**\n * 收货地址\n */\n private MemberAddress memberAddress;\n\n /**\n * 自提地址\n */\n private StoreAddress storeAddress;\n\n /**\n * 客户端类型\n */\n private String clientType;\n\n /**\n * 买家名称\n */\n private String memberName;\n\n /**\n * 买家id\n */\n private String memberId;\n\n /**\n * 分销商id\n */\n private String distributionId;\n\n /**\n * 订单vo\n */\n private List<OrderVO> orderVO;\n\n public TradeDTO(CartTypeEnum cartTypeEnum) {\n this.cartTypeEnum = cartTypeEnum;\n\n this.skuList = new ArrayList<>();\n this.cartList = new ArrayList<>();\n this.skuPromotionDetail = new HashMap<>();\n this.storeCoupons = new HashMap<>();\n this.priceDetailDTO = new PriceDetailDTO();\n this.cantUseCoupons = new ArrayList<>();\n this.canUseCoupons = new ArrayList<>();\n this.needReceipt = false;\n }\n\n public TradeDTO() {\n this(CartTypeEnum.CART);\n }\n\n /**\n * 过滤购物车中已选择的sku\n *\n * @return\n */\n public List<CartSkuVO> getCheckedSkuList() {\n if (skuList != null && !skuList.isEmpty()) {\n return skuList.stream().filter(CartSkuVO::getChecked).collect(Collectors.toList());\n }\n return skuList;\n }\n\n public void removeCoupon() {\n this.canUseCoupons = new ArrayList<>();\n this.cantUseCoupons = new ArrayList<>();\n }\n}" }, { "identifier": "CartTypeEnum", "path": "framework/src/main/java/cn/lili/modules/order/cart/entity/enums/CartTypeEnum.java", "snippet": "public enum CartTypeEnum {\n\n /**\n * 购物车\n */\n CART,\n /**\n * 立即购买\n */\n BUY_NOW,\n /**\n * 虚拟商品\n */\n VIRTUAL,\n /**\n * 拼团\n */\n PINTUAN,\n /**\n * 积分\n */\n POINTS,\n /**\n * 砍价商品\n */\n KANJIA;\n\n public String getPrefix() {\n return \"{\" + this.name() + \"}_\";\n }\n\n}" }, { "identifier": "TradeParams", "path": "framework/src/main/java/cn/lili/modules/order/cart/entity/vo/TradeParams.java", "snippet": "@Data\npublic class TradeParams implements Serializable {\n\n private static final long serialVersionUID = -8383072817737513063L;\n\n @ApiModelProperty(value = \"购物车购买:CART/立即购买:BUY_NOW/拼团购买:PINTUAN / 积分购买:POINT\")\n private String way;\n\n /**\n * @see ClientTypeEnum\n */\n @ApiModelProperty(value = \"客户端:H5/移动端 PC/PC端,WECHAT_MP/小程序端,APP/移动应用端\")\n private String client;\n\n @ApiModelProperty(value = \"店铺备注\")\n private List<StoreRemarkDTO> remark;\n\n @ApiModelProperty(value = \"是否为其他订单下的订单,如果是则为依赖订单的sn,否则为空\")\n private String parentOrderSn;\n\n\n}" }, { "identifier": "CartService", "path": "framework/src/main/java/cn/lili/modules/order/cart/service/CartService.java", "snippet": "public interface CartService {\n\n /**\n * 获取整笔交易\n *\n * @param checkedWay 购物车类型\n * @return 购物车视图\n */\n TradeDTO readDTO(CartTypeEnum checkedWay);\n\n /**\n * 获取整个交易中勾选的购物车和商品\n *\n * @param way 获取方式\n * @return 交易信息\n */\n TradeDTO getCheckedTradeDTO(CartTypeEnum way);\n\n /**\n * 获取可使用的优惠券数量\n *\n * @param checkedWay 购物车类型\n * @return 可使用的优惠券数量\n */\n Long getCanUseCoupon(CartTypeEnum checkedWay);\n\n /**\n * 获取整个交易中勾选的购物车和商品\n *\n * @return 交易信息\n */\n TradeDTO getAllTradeDTO();\n\n /**\n * 购物车加入一个商品\n *\n * @param skuId 要写入的skuId\n * @param num 要加入购物车的数量\n * @param cartType 购物车类型\n * @param cover 是否覆盖购物车的数量,如果为否则累加,否则直接覆盖\n */\n void add(String skuId, Integer num, String cartType, Boolean cover);\n\n\n /**\n * 更新选中状态\n *\n * @param skuId 要写入的skuId\n * @param checked 是否选中\n */\n void checked(String skuId, boolean checked);\n\n\n /**\n * 更新某个店铺的所有商品的选中状态\n *\n * @param storeId 店铺Id\n * @param checked 是否选中\n */\n void checkedStore(String storeId, boolean checked);\n\n\n /**\n * 更新全部的选中状态\n *\n * @param checked 是否选中\n */\n void checkedAll(boolean checked);\n\n\n /**\n * 批量删除\n *\n * @param skuIds 要写入的skuIds\n */\n void delete(String[] skuIds);\n\n /**\n * 清空购物车\n */\n void clean();\n\n /**\n * 重新写入\n *\n * @param tradeDTO 购物车构建器最终要构建的成品\n */\n void resetTradeDTO(TradeDTO tradeDTO);\n\n\n /**\n * 选择收货地址\n *\n * @param shippingAddressId 收货地址id\n * @param way 购物车类型\n */\n void shippingAddress(String shippingAddressId, String way);\n\n /**\n * 选择自提地址\n *\n * @param shopAddressId 收货地址id\n * @param way 购物车类型\n */\n void shippingSelfAddress(String shopAddressId, String way);\n\n /**\n * 选择发票\n *\n * @param receiptVO 发票信息\n * @param way 购物车类型\n */\n void shippingReceipt(ReceiptVO receiptVO, String way);\n\n\n /**\n * 选择配送方式\n *\n * @param deliveryMethod 配送方式\n * @param way 购物车类型\n */\n void shippingMethod(String deliveryMethod, String way);\n\n /**\n * 获取购物车商品数量\n *\n * @param checked 是否选择\n * @return 购物车商品数量\n */\n Long getCartNum(Boolean checked);\n\n /**\n * 选择优惠券\n *\n * @param couponId 优惠券id\n * @param way 购物车类型\n * @param use true使用 false 弃用\n */\n void selectCoupon(String couponId, String way, boolean use);\n\n /**\n * 创建交易\n * 1.获取购物车类型,不同的购物车类型有不同的订单逻辑\n * 购物车类型:购物车、立即购买、虚拟商品、拼团、积分\n * 2.校验用户的收件人信息\n * 3.设置交易的基础参数\n * 4.交易信息存储到缓存中\n * 5.创建交易\n * 6.清除购物车选择数据\n *\n * @param tradeParams 创建交易参数\n * @return 交易信息\n */\n Trade createTrade(TradeParams tradeParams);\n\n /***\n * 获取可使用的配送方式\n * @param way\n * @return\n */\n List<String> shippingMethodList(String way);\n}" }, { "identifier": "PaymentService", "path": "framework/src/main/java/cn/lili/modules/payment/service/PaymentService.java", "snippet": "public interface PaymentService {\n\n /**\n * 支付成功通知\n *\n * @param paymentSuccessParams 支付成功回调参数\n */\n void success(PaymentSuccessParams paymentSuccessParams);\n\n\n /**\n * 平台支付成功\n *\n * @param paymentSuccessParams 支付成功回调参数\n */\n void adminPaySuccess(PaymentSuccessParams paymentSuccessParams);\n\n}" } ]
import cn.hutool.json.JSONUtil; import cn.lili.modules.goods.entity.vos.CategoryVO; import cn.lili.modules.goods.service.CategoryService; import cn.lili.modules.order.cart.entity.dto.TradeDTO; import cn.lili.modules.order.cart.entity.enums.CartTypeEnum; import cn.lili.modules.order.cart.entity.vo.TradeParams; import cn.lili.modules.order.cart.service.CartService; import cn.lili.modules.payment.service.PaymentService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List;
4,562
package cn.lili.buyer.test.cart; /** * @author paulG * @since 2020/11/14 **/ @ExtendWith(SpringExtension.class) @SpringBootTest class CartTest { @Autowired private CartService cartService; @Autowired private CategoryService categoryService; @Autowired private PaymentService paymentService; @Test void getAll() { TradeDTO allTradeDTO = cartService.getAllTradeDTO(); Assertions.assertNotNull(allTradeDTO); System.out.println(JSONUtil.toJsonStr(allTradeDTO)); } @Test void deleteAll() { cartService.delete(new String[]{"1344220459059404800"}); Assertions.assertTrue(true); } @Test void createTrade() { // TradeDTO allTradeDTO = cartService.getAllTradeDTO(); // Assert.assertNotNull(allTradeDTO); // System.out.println(JsonUtil.objectToJson(allTradeDTO)); cartService.createTrade(new TradeParams()); } @Test void getAllCategory() { List<CategoryVO> allCategory = categoryService.categoryTree(); for (CategoryVO categoryVO : allCategory) { System.out.println(categoryVO); } Assertions.assertTrue(true); } @Test void storeCoupon() {
package cn.lili.buyer.test.cart; /** * @author paulG * @since 2020/11/14 **/ @ExtendWith(SpringExtension.class) @SpringBootTest class CartTest { @Autowired private CartService cartService; @Autowired private CategoryService categoryService; @Autowired private PaymentService paymentService; @Test void getAll() { TradeDTO allTradeDTO = cartService.getAllTradeDTO(); Assertions.assertNotNull(allTradeDTO); System.out.println(JSONUtil.toJsonStr(allTradeDTO)); } @Test void deleteAll() { cartService.delete(new String[]{"1344220459059404800"}); Assertions.assertTrue(true); } @Test void createTrade() { // TradeDTO allTradeDTO = cartService.getAllTradeDTO(); // Assert.assertNotNull(allTradeDTO); // System.out.println(JsonUtil.objectToJson(allTradeDTO)); cartService.createTrade(new TradeParams()); } @Test void getAllCategory() { List<CategoryVO> allCategory = categoryService.categoryTree(); for (CategoryVO categoryVO : allCategory) { System.out.println(categoryVO); } Assertions.assertTrue(true); } @Test void storeCoupon() {
cartService.selectCoupon("1333318596239843328", CartTypeEnum.CART.name(), true);
3
2023-12-24 19:45:18+00:00
8k
SocialPanda3578/OnlineShop
shop/src/shop/Panel/MainPanel.java
[ { "identifier": "Admin", "path": "shop/src/shop/Admin.java", "snippet": "public class Admin extends User{\n public Admin(){\n\n }\n public Admin(String name,String pass){\n setUsername(name);\n setPassword(pass);\n }\n \n public void login(){\n if (isLogin()) {\n System.out.println(getUsername()+\"已登录,不能重复登录!\");\n } else {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n System.out.print(\"请输入密码:\");\n Console console = System.console();\n char[] pass = console.readPassword();\n password = String.valueOf(pass);\n if (password == null || username == null) {\n System.out.println(\"用户名或密码不能为空\");\n continue;\n }\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n String sql = \"select * from admins where ad_name=? and ad_password=?\";\n ResultSet rs = db.select(sql, obj);\n try {\n if (!rs.next()) {\n System.out.println(\"用户名或密码错误!请重试!\");\n continue;\n } else {\n setUsername(username);\n setPassword(password);\n setStatus(true);\n System.out.println(\"管理员\" + username + \" 登录成功!\");\n AdminPanel ap = new AdminPanel();\n ap.FirstMenu();\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n break;\n }\n }\n }\n }\n\n public void printUsers(){\n DBUtil db=new DBUtil();\n Object[] objs={};\n ResultSet set = db.select(\"select * from users\", objs);\n System.out.println(\"用户名\"+\"\\t\\t密码\");\n try {\n while (set.next()){\n String u_name=set.getString(\"u_username\");\n String u_pass=set.getString(\"u_password\");\n System.out.println(String.format(\"%-16s\", u_name)+String.format(\"%-16s\",u_pass));\n }\n }\n catch (SQLException e1) {\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n public void updateUser() throws SQLException {\n DBUtil db=new DBUtil();\n System.out.println(\"***************************\");\n System.out.print(\"请输入需修改的用户名:\");\n String targetUser = Main.sc.next();\n if(checkUser(targetUser)) {\n System.out.print(\"请输入新用户名:\");\n String newName = Main.sc.next();\n System.out.print(\"请输入新的密码:\");\n String newPassword = Main.sc.next();\n\n Object[] obj = {newName, newPassword, targetUser};\n int i=db.update(\"update users set u_username=?,u_password=? where u_username=?\", obj);\n if(i!=0) System.out.println(\"用户修改成功\");\n else\n System.out.println(\"用户修改失败\");\n db.closeConnection();\n }\n else{\n System.out.println(\"用户不存在,请检查输入!\");\n }\n }\n public void addUser() throws SQLException {\n System.out.print(\"请输入用户名:\");\n String newName = Main.sc.next();\n DBUtil db=new DBUtil();\n if(checkUser(newName)) System.out.println(\"用户名已存在\");\n else\n {\n System.out.print(\"请输入密码:\");\n String newPassword=Main.sc.next();\n Object[] objs={newName,newPassword};\n int i=db.update(\"insert into users values(?,?)\",objs);\n if(i==0) System.out.println(\"用户创建失败\");\n else {\n System.out.println(\"用户创建成功\");\n String sql = \"CREATE TABLE \" + newName + \"_cart\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n sql = \"CREATE TABLE \" + newName + \"_history\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n }\n db.closeConnection();\n }\n }\n public void deleteUser() throws SQLException {\n System.out.print(\"请输入用户名:\");\n String newName = Main.sc.next();\n DBUtil db=new DBUtil();\n if(!checkUser(newName)) System.out.println(\"用户名不存在\");\n else\n {\n Object[] obj={newName};\n int i=db.update(\"delete from users where u_username=?\",obj);\n if(i==0) System.out.println(\"用户删除失败\");\n else {\n db.update(\"drop table \" + newName + \"_cart\", null);\n db.update(\"drop table \" + newName + \"_history\", null);\n System.out.println(\"用户删除成功\");\n }\n db.closeConnection();\n }\n }\n public void updateItems() throws SQLException {\n DBUtil db = new DBUtil();\n System.out.print(\"请输入需修改的商品编号:\");\n String targetItems = Main.sc.next();\n if (checkItems(targetItems)) {\n System.out.print(\"请输入新的商品名称\");\n String newName = Main.sc.next();\n System.out.print(\"请输入新的商品价格\");\n String newPrice = Main.sc.next();\n System.out.print(\"请输入新的商品数量\");\n String newNums = Main.sc.next();\n Object[] obj = { newName, newPrice, newNums ,targetItems};\n int i = db.update(\"update items set it_name=?,it_price=?,it_nums=? where it_id=?\", obj);\n if (i != 0)\n System.out.println(\"商品修改成功\");\n else\n System.out.println(\"商品修改失败\");\n db.closeConnection();\n }\n else {\n System.out.println(\"商品不存在,请检查输入!\");\n }\n }\n public void addItems() {\n System.out.println(\"请依次输入 编号 名称 价格 数量\");\n String id = Main.sc.next();\n String name = Main.sc.next();\n Double price = Main.sc.nextDouble();\n int nums = Main.sc.nextInt();\n DBUtil db = new DBUtil();\n Object obj[] = { id, name, price, nums };\n int i = db.update(\"insert into items values(?,?,?,?)\", obj);\n if (i == 1)\n System.out.println(\"商品上架成功\");\n else\n System.out.println(\"商品上架失败\");\n db.closeConnection();\n }\n public void deleteItems() {\n System.out.println(\"输入 要删除商品的编号\");\n String id = Main.sc.next();\n DBUtil db = new DBUtil();\n Object[] obj = { id };\n int i = db.update(\"delete from items where it_id=?\", obj);\n if (i == 0)\n System.out.println(\"商品删除失败\");\n else\n System.out.println(\"商品删除成功\");\n db.closeConnection();\n }\n public boolean checkUser(String name) throws SQLException {\n DBUtil db = new DBUtil();\n Object[] obj = { name };\n ResultSet rs = db.select(\"select * from users where u_username=?\", obj);\n if (rs.next())\n return true;\n else\n return false;\n }\n public boolean checkItems(String id) throws SQLException {\n DBUtil db = new DBUtil();\n Object[] obj = { id };\n ResultSet rs = db.select(\"select * from items where it_id=?\", obj);\n if (rs.next()) {\n return true;\n }\n else {\n return false;\n }\n }\n}" }, { "identifier": "History", "path": "shop/src/shop/History.java", "snippet": "public class History {\r\n public void PrintHistoryItems(User user) {\r\n if (user.isLogin()) {\r\n DBUtil db = new DBUtil();\r\n Object obj[] = {};\r\n String username = user.getUsername();\r\n ResultSet rs = db.select(\"select * from \" + username + \"_history\", obj);\r\n try {\r\n while (rs.next()) {\r\n String id = rs.getString(\"id\");\r\n String na = rs.getString(\"name\");\r\n Double price = rs.getDouble(\"price\");\r\n Integer num = rs.getInt(\"nums\");\r\n System.out.println(id + \"\\t\\t\" + na + \"\\t\\t\\t\" + price + \"\\t\\t\\t\" + num);\r\n }\r\n } catch (SQLException e1) {\r\n e1.printStackTrace();\r\n } finally {\r\n db.closeConnection();\r\n }\r\n } else {\r\n System.out.println(\"用户未登录\");\r\n }\r\n }\r\n\r\n public void addHistory(User user,Object obj[]/*id name price nums*/) {\r\n DBUtil db = new DBUtil();\r\n db.update(\"insert into \" + user.getUsername() + \"_history\", obj);\r\n }\r\n}\r" }, { "identifier": "Main", "path": "shop/src/shop/Main.java", "snippet": "public class Main\r\n{\r\n public static Scanner sc=new Scanner(System.in);\r\n\r\n public static void main(String[] args) throws SQLException, InterruptedException {\r\n MainPanel mainPanel = new MainPanel();\r\n mainPanel.showMainMenu();\r\n }\r\n}\r" }, { "identifier": "Shop", "path": "shop/src/shop/Shop.java", "snippet": "public class Shop {\n\n public void PrintItems()\n {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs=db.select(\"select * from items\",objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void ID_ASC_Order() {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs = db.select(\"select * from items order by it_id asc\", objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void Price_ASC_Order() {\n System.out.println(\"商品编号\\t名称\\t\\t价格\\t\\t数量\");\n DBUtil db=new DBUtil();\n Object objs[]={};\n ResultSet rs=db.select(\"select * from items order by it_price asc\",objs);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(String.format(\"%-16s\",id)+String.format(\"%-16s\",na)+String.format(\"%-16s\", price)+String.format(\"%-16s\", num));\n }\n }\n catch(SQLException e1){\n e1.printStackTrace();\n }\n finally {\n db.closeConnection();\n }\n }\n\n public void Find(String s) {\n DBUtil db = new DBUtil();\n Object obj[] = { s };\n ResultSet rs = db.select(\"select * from items where ca_id=? or ca_name=?\", obj);\n try {\n while (rs.next()) {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n Integer num = rs.getInt(\"it_nums\");\n System.out.println(id + ' ' + na + ' ' + price + ' ' + num);\n }\n } catch (SQLException e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n }\n // i = new Items(null, null, null, null);\n //return i;\n }\n\n public void buy(User user) throws SQLException {\n if (user.isLogin()) {\n System.out.println(\"想买点什么\");\n String name = Main.sc.next();\n System.out.println(\"想买多少\");\n int n = Main.sc.nextInt();\n\n Object obj[] = { name, name };\n DBUtil db = new DBUtil();\n ResultSet rs = db.select(\"select * from items where it_name=? or it_id=?\", obj);\n if (rs.next()) {\n if (rs.getInt(\"it_nums\") < n) {\n System.out.println(\"库存不够\");\n } else {\n String id = rs.getString(\"it_id\");\n String na = rs.getString(\"it_name\");\n Double price = rs.getDouble(\"it_price\");\n db.update(\"insert into \" + user.getUsername() + \"_history values(?,?,?,?)\",\n new Object[] { id, na, price, n });\n db.update(\"update items set it_nums=it_nums-? where it_id=?\", new Object[] { n, id });\n db.update(\"delete from items where it_nums<=0\", new Object[] {});\n System.out.println(n+\"件 商品\" + na + \"购买成功\");\n }\n } else {\n System.out.println(\"商品不存在\");\n }\n db.closeConnection();\n }\n else {\n System.out.println(\"请登录后使用\");\n } \n }\n}" }, { "identifier": "User", "path": "shop/src/shop/User.java", "snippet": "public class User\n{\n private static String user_name;\n private static String pass_word;\n private static boolean status=false;\n\n public String getUsername()\n {\n return user_name;\n }\n public String getPassword()\n {\n return pass_word;\n }\n public void setPassword(String password)\n {\n pass_word = password;\n }\n public void setUsername(String username){user_name=username;}\n public static boolean isLogin()\n {\n return status;\n }\n public static void setStatus(boolean status) {\n User.status = status;\n }\n\n public void reg() //用户注册\n {\n if (!status) {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n boolean fg = true;\n\n DBUtil db = new DBUtil();\n Object[] objs = { username };\n String sql = \"select * from users where u_username=?\";\n ResultSet rs = db.select(sql, objs);\n try {\n if (rs.next()) {\n System.out.println(\"用户名重复\");\n continue;\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n }\n\n if (fg == false)\n continue;\n else if (username.length() < 3) {\n System.out.println(\"用户名长度至少大于3位!\");\n continue;\n } else\n break;\n }\n while (true) {\n System.out.print(\"请输入登录密码:\");\n password = Main.sc.next();\n if (password.length() < 6) {\n System.out.println(\"密码长度至少大于6位!\");\n continue;\n }\n int digit = 0;\n int letter = 0;\n for (int i = 0; i < password.length(); i++) {\n if (Character.isDigit(password.charAt(i)))\n digit++;\n if (Character.isLetter(password.charAt(i)))\n letter++;\n }\n if (digit == 0 || letter == 0) {\n System.out.println(\"密码至少含有一个字符和一个数字!\");\n continue;\n }\n System.out.print(\"请再次确认您的密码\");\n Console console = System.console();\n char[] repassword = console.readPassword();\n //String repassword = Main.sc.next();\n if (password.equals(String.valueOf(repassword)))//插入用户数据\n {\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n //ResultSet set=db.select(\"select * from users\",obj);\n int i = db.update(\"insert into users values(?,?)\", obj);\n if (i != 0) {\n System.out.println(\"用户创建成功,已为您自动登录\");\n String sql = \"CREATE TABLE \" + username + \"_cart\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n sql = \"CREATE TABLE \" + username + \"_history\"\n + \" (id VARCHAR(30), name VARCHAR(40), price DOUBLE,nums INT)\";\n db.update(sql, null);\n user_name = username;\n pass_word = password;\n status = true;\n System.out.println(\"普通用户\" + username + \" 登录成功!\");\n } else\n System.out.println(\"用户创建失败\");\n db.closeConnection();\n break;\n } else {\n System.out.println(\"两次输入的密码不一致!\");\n }\n }\n }\n else {\n System.out.println(\"您已登录!请退出登录后尝试注册\");\n }\n }\n\n public void login()\n {\n if (status) {\n System.out.println(user_name+\"已登录,不能重复登录!\");\n } else {\n String username = \"\";\n String password = \"\";\n while (true) {\n System.out.print(\"请输入用户名:\");\n username = Main.sc.next();\n System.out.print(\"请输入密码:\");\n Console console = System.console();\n char[] pass = console.readPassword();\n password = String.valueOf(pass);\n if (password == null || username == null) {\n System.out.println(\"用户名或密码不能为空\");\n continue;\n }\n DBUtil db = new DBUtil();\n Object[] obj = { username, password };\n String sql = \"select * from users where u_username=? and u_password=?\";\n ResultSet rs = db.select(sql, obj);\n try {\n if (!rs.next()) {\n System.out.println(\"用户名或密码错误!请重试!\");\n continue;\n } else {\n user_name = username;\n pass_word = password;\n status = true;\n System.out.println(\"普通用户\" + username + \" 登录成功!\");\n }\n } catch (Exception e1) {\n e1.printStackTrace();\n } finally {\n db.closeConnection();\n break;\n }\n }\n }\n }\n\n public void exit() {\n if (status) {\n status = false;\n System.out.println(\"再见\" + user_name + \"!\");\n }\n }\n}" } ]
import shop.Admin; import shop.History; import shop.Main; import shop.Shop; import shop.User; import java.io.IOException; import java.sql.SQLException;
4,780
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:"); int choice = Main.sc.nextInt();
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:"); int choice = Main.sc.nextInt();
Admin admin = new Admin();
0
2023-12-28 04:26:15+00:00
8k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/factory/BarChartFactory.java
[ { "identifier": "Legend", "path": "src/main/java/com/github/muskstark/echart/attribute/Legend.java", "snippet": "@Getter\npublic class Legend {\n\n private String type;\n private String id;\n private Boolean show;\n private Double zLevel;\n private Double z;\n private Object left;\n private Object top;\n private Object right;\n private Object bottom;\n private Object width;\n private Object height;\n private String orient;\n private String align;\n private Integer[] padding;\n private Double itemGap;\n private Double itemWidth;\n private Double itemHeight;\n// private ItemStyle itemStyle;\n private LineStyle lineStyle;\n private Object symbolRotate;\n private String formatter;\n private Boolean selectedMode;\n private String inactiveColor;\n private String inactiveBorderColor;\n private String inactiveBorderWidth;\n private Object selected;\n private TextStyle textStyle;\n private ToolTip tooltip;\n private String icon;\n private List<Object> data;\n private String backgroundColor;\n private String borderColor;\n private Double borderWidth;\n private Integer[] borderRadius;\n private Double shadowBlur;\n private String shadowColor;\n private Double shadowOffsetX;\n private Double shadowOffsetY;\n private Double scrollDataIndex;\n private Double pageButtonItemGap;\n private Double pageButtonGap;\n private String pageButtonPosition;\n private String pageFormatter;\n// private PageIcons pageIcons;\n private String pageIconColor;\n private String pageIconInactiveColor;\n private Integer[] pageIconSize;\n// private TextStyle pageTextStyle;\n private Boolean animation;\n private Double animationDurationUpdate;\n// private Object emphasis;\n private Boolean[] selector;\n// private SelectorLabel selectorLabel;\n private String selectorPosition;\n private Integer selectorItemGap;\n private Integer selectorButtonGap;\n\n public Legend type(String type){\n this.type = type;\n return this;\n }\n\n public Legend id(String id){\n this.id = id;\n return this;\n }\n\n public Legend show(Boolean show){\n this.show = show;\n return this;\n }\n\n public Legend zLevel(Double zLevel){\n this.zLevel = zLevel;\n return this;\n }\n\n public Legend z(Double z){\n this.z = z;\n return this;\n }\n\n public Legend left(Object left){\n if(left instanceof String || left instanceof Double){\n this.left = left;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend top(Object top){\n if(top instanceof String || top instanceof Double){\n this.top = top;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend right(Object right){\n if(right instanceof String || right instanceof Double){\n this.right = right;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend bottom(Object bottom){\n if(bottom instanceof String || bottom instanceof Double){\n this.bottom = bottom;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend width(Object width){\n if(width instanceof String || width instanceof Double){\n this.width = width;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend height(Object height){\n if(height instanceof String || height instanceof Double){\n this.height = height;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Legend orient(String orient){\n this.orient = orient;\n return this;\n }\n\n\n\n}" }, { "identifier": "Title", "path": "src/main/java/com/github/muskstark/echart/attribute/Title.java", "snippet": "@Getter\npublic class Title implements Serializable {\n private String id;\n private Boolean show;\n private String text;\n private String link;\n private String target;\n private TextStyle textStyle;\n private String subtext;\n private String subLink;\n private String subTarget;\n private TextStyle subtextStyle;\n private String textAlign;\n private String textVerticalAlign;\n private Boolean triggerEvent;\n private Integer[] padding;\n private Integer itemGap;\n private Integer zLevel;\n private Integer z;\n private String left;\n private String top;\n private String right;\n private String bottom;\n private String backgroundColor;\n private String borderColor;\n private Integer borderWidth;\n private Integer[] borderRadius;\n private Integer shadowBlur;\n private String shadowColor;\n private Integer shadowOffsetX;\n private Integer shadowOffsetY;\n\n public Title id(String id){\n this.id = id;\n return this;\n }\n\n public Title show(Boolean show){\n this.show = show;\n return this;\n }\n\n public Title text(String text){\n this.text = text;\n return this;\n }\n\n public Title link(String link){\n this.link = link;\n return this;\n }\n\n public Title target(String target){\n this.target = target;\n return this;\n }\n\n public Title textStyle(TextStyle textStyle){\n this.textStyle = textStyle;\n return this;\n }\n\n public Title subtext(String subtext){\n this.subtext = subtext;\n return this;\n }\n\n public Title subLink(String subLink){\n this.subLink = subLink;\n return this;\n }\n\n public Title subTarget(String subTarget){\n this.subTarget = subTarget;\n return this;\n }\n\n public Title subtextStyle(TextStyle subtextStyle){\n this.subtextStyle = subtextStyle;\n return this;\n }\n\n public Title textAlign(String textAlign){\n this.textAlign = textAlign;\n return this;\n }\n\n public Title textVerticalAlign(String textVerticalAlign){\n this.textVerticalAlign = textVerticalAlign;\n return this;\n }\n\n public Title triggerEvent(Boolean triggerEvent){\n this.triggerEvent = triggerEvent;\n return this;\n }\n\n public Title padding(Integer[] padding){\n this.padding = padding;\n return this;\n }\n\n public Title itemGap(Integer itemGap){\n this.itemGap = itemGap;\n return this;\n }\n\n public Title zLevel(Integer zLevel){\n this.zLevel = zLevel;\n return this;\n }\n\n public Title z(Integer z){\n this.z = z;\n return this;\n }\n\n public Title left(String left){\n this.left = left;\n return this;\n }\n\n public Title top(String top){\n this.top = top;\n return this;\n }\n\n public Title right(String right){\n this.right = right;\n return this;\n }\n\n public Title bottom(String bottom){\n this.bottom = bottom;\n return this;\n }\n\n public Title backgroundColor(String backgroundColor){\n this.backgroundColor = backgroundColor;\n return this;\n }\n\n public Title borderColor(String borderColor){\n this.borderColor = borderColor;\n return this;\n }\n\n public Title borderWidth(Integer borderWidth){\n this.borderWidth = borderWidth;\n return this;\n }\n\n public Title borderRadius(Integer[] borderRadius){\n this.borderRadius = borderRadius;\n return this;\n }\n\n public Title shadowBlur(Integer shadowBlur){\n this.shadowBlur = shadowBlur;\n return this;\n }\n\n public Title shadowColor(String shadowColor){\n this.shadowColor = shadowColor;\n return this;\n }\n\n public Title shadowOffsetX(Integer shadowOffsetX){\n this.shadowOffsetX = shadowOffsetX;\n return this;\n }\n\n public Title shadowOffsetY(Integer shadowOffsetY){\n this.shadowOffsetY = shadowOffsetY;\n return this;\n }\n\n\n}" }, { "identifier": "XAxis", "path": "src/main/java/com/github/muskstark/echart/attribute/axis/XAxis.java", "snippet": "@Getter\npublic class XAxis extends Axis {\n\n\n}" }, { "identifier": "YAxis", "path": "src/main/java/com/github/muskstark/echart/attribute/axis/YAxis.java", "snippet": "@Getter\npublic class YAxis extends Axis {\n\n\n}" }, { "identifier": "BarSeries", "path": "src/main/java/com/github/muskstark/echart/attribute/series/BarSeries.java", "snippet": "@Getter\npublic class BarSeries extends Series {\n\n private String barWidth;\n private String barMaxWidth;\n private Integer barMinWidth;\n private Integer barMinHeight;\n private Integer barMinAngle;\n private String barGap;\n private String barCategoryGap;\n\n public BarSeries defineBarWidth(String barWidth){\n this.barWidth = barWidth;\n return this;\n }\n\n public BarSeries defineBarMaxWidth(String barMaxWidth){\n this.barMaxWidth = barMaxWidth;\n return this;\n }\n public BarSeries defineBarMinWidth(Integer barMinWidth){\n this.barMinWidth = barMinWidth;\n return this;\n }\n\n public BarSeries defineBarMinHeight(Integer barMinHeight){\n this.barMinHeight = barMinHeight;\n return this;\n }\n\n public BarSeries defineBarMinAngle(Integer barMinAngle){\n this.barMinAngle = barMinAngle;\n return this;\n }\n\n public BarSeries defineBarGap(String barGap){\n this.barGap = barGap;\n return this;\n }\n\n public BarSeries defineBarCategoryGap(String barCategoryGap){\n this.barCategoryGap = barCategoryGap;\n return this;\n }\n\n\n\n\n\n\n\n}" }, { "identifier": "StyleOfBarChart", "path": "src/main/java/com/github/muskstark/echart/enums/StyleOfBarChart.java", "snippet": "@Getter\npublic enum StyleOfBarChart {\n /**\n * 基础类图表\n */\n BAR_CHART(null)\n ,BAR_CHART_BASE(\"base\")\n ,BAR_CHART_AXIS_ALIGN_WITH_TICK(\"Axis Align with Tick\")\n ,BAR_CHART_WITH_BACKGROUND(\"background\");\n\n private final String styleOfChart;\n\n\n StyleOfBarChart(String styleOfChart) {\n this.styleOfChart = styleOfChart;\n }\n\n}" }, { "identifier": "BarChart", "path": "src/main/java/com/github/muskstark/echart/model/bar/BarChart.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class BarChart extends Charts {\n\n @JSONField(name = \"xAxis\")\n private XAxis xAxis;\n @JSONField(name = \"yAxis\")\n private YAxis yAxis;\n private List<BarSeries> series;\n\n\n public Title defineTitle() {\n return this.getTitle();\n }\n\n public XAxis defineXAxis() {\n return this.getXAxis();\n }\n\n public YAxis defineYAxis() {\n return this.getYAxis();\n }\n\n public ToolTip defineToolTip() {\n if (this.getToolTip() == null) {\n this.setToolTip(new ToolTip());\n }\n return this.getToolTip();\n }\n\n public BarSeries defineDefaultSeries() {\n return this.getSeries().get(0);\n }\n\n public Legend defineLegend() {\n return this.getLegend();\n }\n\n public void addSeries(BarSeries series) {\n this.getSeries().add(series);\n }\n}" }, { "identifier": "AxisPointer", "path": "src/main/java/com/github/muskstark/echart/style/asix/AxisPointer.java", "snippet": "@Getter\npublic class AxisPointer {\n\n private Boolean show;\n private String type;\n private Boolean snap;\n private Number z;\n private AxisPointerLabel label;\n private LineStyle lineStyle;\n\n public AxisPointer show(boolean show) {\n this.show = show;\n return this;\n }\n\n public AxisPointer type(String type) {\n this.type = type;\n return this;\n }\n\n public AxisPointer snap(boolean snap) {\n this.snap = snap;\n return this;\n }\n\n public AxisPointer z(Number z) {\n this.z = z;\n return this;\n }\n\n public AxisPointer label(AxisPointerLabel label) {\n this.label = label;\n return this;\n }\n\n public AxisPointer lineStyle(LineStyle lineStyle) {\n this.lineStyle = lineStyle;\n return this;\n }\n\n }" }, { "identifier": "BackgroundStyle", "path": "src/main/java/com/github/muskstark/echart/style/background/BackgroundStyle.java", "snippet": "@Getter\npublic class BackgroundStyle {\n\n private String color;\n private String borderColor;\n private String borderWidth;\n private String borderType;\n private Integer[] borderRadius;\n private Integer shadowBlur;\n private Color shadowColor;\n private Integer shadowOffsetX;\n private Integer shadowOffsetY;\n private Integer opacity;\n\n public BackgroundStyle defineColor(String color) {\n this.color = color;\n return this;\n }\n\n public BackgroundStyle defineBorderColor(String borderColor) {\n this.borderColor = borderColor;\n return this;\n }\n\n public BackgroundStyle defineBorderWidth(String borderWidth) {\n this.borderWidth = borderWidth;\n return this;\n }\n\n public BackgroundStyle defineBorderType(String borderType) {\n this.borderType = borderType;\n return this;\n }\n\n public BackgroundStyle defineBorderRadius(Integer leftUp, Integer rightUp, Integer rightDown, Integer leftDown) {\n this.borderRadius = new Integer[]{leftUp, rightUp, rightDown, leftDown};\n return this;\n }\n public BackgroundStyle defineBorderRadius(Integer allRadius) {\n this.borderRadius = new Integer[]{allRadius, allRadius, allRadius, allRadius};\n return this;\n }\n\n public BackgroundStyle defineShadowBlur(Integer shadowBlur) {\n this.shadowBlur = shadowBlur;\n return this;\n }\n\n public BackgroundStyle defineShadowColor(Color shadowColor) {\n this.shadowColor = shadowColor;\n return this;\n }\n\n public BackgroundStyle defineShadowOffsetX(Integer shadowOffsetX) {\n this.shadowOffsetX = shadowOffsetX;\n return this;\n }\n\n public BackgroundStyle defineShadowOffsetY(Integer shadowOffsetY) {\n this.shadowOffsetY = shadowOffsetY;\n return this;\n }\n\n public BackgroundStyle defineOpacity(Integer opacity) {\n this.opacity = opacity;\n return this;\n }\n\n\n\n}" } ]
import com.github.muskstark.echart.attribute.Legend; import com.github.muskstark.echart.attribute.Title; import com.github.muskstark.echart.attribute.axis.XAxis; import com.github.muskstark.echart.attribute.axis.YAxis; import com.github.muskstark.echart.attribute.series.BarSeries; import com.github.muskstark.echart.enums.StyleOfBarChart; import com.github.muskstark.echart.model.bar.BarChart; import com.github.muskstark.echart.style.asix.AxisPointer; import com.github.muskstark.echart.style.background.BackgroundStyle; import java.util.ArrayList;
3,913
package com.github.muskstark.echart.factory; public abstract class BarChartFactory { private static final String TYPE = "bar"; public static BarChart createChart(){ return createBaseBarChart(); } public static BarChart createChart(StyleOfBarChart chartStyle) { BarChart chart = null; String styleOfChart = chartStyle.getStyleOfChart(); if(styleOfChart == null){ chart = createBaseBarChart(); return chart; } switch (styleOfChart) { case "base" -> { chart = createBaseBarChart(); chart.defineTitle().show(false); chart.defineXAxis().type("category"); chart.defineYAxis().type("value"); } case "Axis Align with Tick" -> { chart = createBaseBarChart(); chart.defineToolTip() .trigger("axis") .axisPointer(
package com.github.muskstark.echart.factory; public abstract class BarChartFactory { private static final String TYPE = "bar"; public static BarChart createChart(){ return createBaseBarChart(); } public static BarChart createChart(StyleOfBarChart chartStyle) { BarChart chart = null; String styleOfChart = chartStyle.getStyleOfChart(); if(styleOfChart == null){ chart = createBaseBarChart(); return chart; } switch (styleOfChart) { case "base" -> { chart = createBaseBarChart(); chart.defineTitle().show(false); chart.defineXAxis().type("category"); chart.defineYAxis().type("value"); } case "Axis Align with Tick" -> { chart = createBaseBarChart(); chart.defineToolTip() .trigger("axis") .axisPointer(
new AxisPointer()
7
2023-12-25 08:03:42+00:00
8k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/LoginForm.java
[ { "identifier": "PanelCover", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/panel/PanelCover.java", "snippet": "public class PanelCover extends javax.swing.JPanel {\n\n private final DecimalFormat df = new DecimalFormat(\"##0.###\", DecimalFormatSymbols.getInstance(Locale.US));\n private ActionListener event;\n private MigLayout layout;\n private JLabel judul;\n private JLabel deskripsi;\n private JLabel deskripsi1;\n private ButtonOutLine button;\n private Boolean isLogin;\n \n public PanelCover() {\n initComponents();\n setOpaque(false);\n layout = new MigLayout(\"wrap, fill\", \"[center]\", \"push[]10[]5[]25[]push\");\n setLayout(layout);\n init();\n }\n \n private void init() {\n judul = new JLabel (\"Selamat Datang!\");\n judul.setFont(new Font(\"sansserif\", 1, 30));\n judul.setForeground(new Color(245,245,245));\n add(judul);\n deskripsi = new JLabel(\"Daftarkan dirimu\");\n deskripsi.setForeground(new Color(245, 245, 245));\n add(deskripsi);\n deskripsi1 = new JLabel(\"dan pesan kamar sekarang!\");\n deskripsi1.setForeground(new Color(245, 245, 245));\n add(deskripsi1);\n button = new ButtonOutLine();\n button.setBackground(new Color(255, 255, 255));\n button.setForeground(new Color(255, 255, 255));\n button.setText(\"SIGN UP\");\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent ae) {\n event.actionPerformed(ae);\n }\n });\n add(button, \"w 60%, h 40\");\n }\n \n \n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 292, Short.MAX_VALUE)\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, 260, Short.MAX_VALUE)\n );\n }// </editor-fold>//GEN-END:initComponents\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n GradientPaint gra = new GradientPaint (0, 0, new Color(173, 151, 79), 0, getHeight(), new Color(48, 45, 35));\n g2.setPaint(gra);\n g2.fillRect(0, 0, getWidth(), getHeight());\n super.paintComponent(grphcs);\n }\n \n public void addEvent(ActionListener event) {\n this.event = event;\n }\n\n public void registerLeft(double v) {\n v = Double.valueOf(df.format(v));\n login(false);\n layout.setComponentConstraints(judul, \"pad 0 -\" + v + \"% 0 0\");\n layout.setComponentConstraints(deskripsi, \"pad 0 -\" + v + \"% 0 0\");\n layout.setComponentConstraints(deskripsi1, \"pad 0 -\" + v + \"% 0 0\");\n\n }\n \n public void registerRight(double v) {\n v = Double.valueOf(df.format(v));\n login(false);\n layout.setComponentConstraints(judul, \"pad 0 -\" + v + \"% 0 0\");\n layout.setComponentConstraints(deskripsi, \"pad 0 -\" + v + \"% 0 0\");\n layout.setComponentConstraints(deskripsi1, \"pad 0 -\" + v + \"% 0 0\");\n }\n\n public void loginLeft(double v) {\n v = Double.valueOf(df.format(v));\n login(true);\n layout.setComponentConstraints(judul, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n layout.setComponentConstraints(deskripsi, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n layout.setComponentConstraints(deskripsi1, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n }\n\n public void loginRight(double v) {\n v = Double.valueOf(df.format(v));\n login(true);\n layout.setComponentConstraints(judul, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n layout.setComponentConstraints(deskripsi, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n layout.setComponentConstraints(deskripsi1, \"pad 0 \" + v + \"% 0 \" + v + \"%\");\n }\n\n private void login(Boolean l) {\n if (this.isLogin != l) {\n if (l) {\n judul.setText(\"Selamat Datang!\");\n deskripsi.setText(\"Untuk terhubung dengan kami\");\n deskripsi1.setText(\"login dengan akunmu!\");\n button.setText(\"SIGN IN\");\n } else {\n judul.setText(\"Selamat Datang!\");\n deskripsi.setText(\"Daftarkan dirimu\");\n deskripsi1.setText(\"dan pesan kamar sekarang!\");\n button.setText(\"SIGN UP\");\n }\n this.isLogin = l ;\n }\n }\n \n\n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n // End of variables declaration//GEN-END:variables\n}" }, { "identifier": "PanelLoading", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/panel/PanelLoading.java", "snippet": "public class PanelLoading extends javax.swing.JPanel {\n\n \n public PanelLoading() {\n initComponents();\n setOpaque(false);\n setFocusCycleRoot(true);\n setVisible(false);\n \n }\n\n /**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */\n @SuppressWarnings(\"unchecked\")\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n private void initComponents() {\n\n jLabel1 = new javax.swing.JLabel();\n\n jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);\n jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(\"/images/Ellipsis-1s-200px.gif\"))); // NOI18N\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);\n this.setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)\n );\n }// </editor-fold>//GEN-END:initComponents\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n Graphics2D g2 = (Graphics2D) grphcs;\n g2.setColor(new Color(255, 255,255));\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));\n g2.fillRect(0, 0, getWidth(), getHeight());\n g2.setComposite(AlphaComposite.SrcOver);\n }\n\n \n\n // Variables declaration - do not modify//GEN-BEGIN:variables\n private javax.swing.JLabel jLabel1;\n // End of variables declaration//GEN-END:variables\n}" }, { "identifier": "PanelLoginDanRegister", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/panel/PanelLoginDanRegister.java", "snippet": "public class PanelLoginDanRegister extends javax.swing.JLayeredPane {\r\n GuestServiceLoginImpl guestAcc;\r\n GuestServiceImpl guestDetail;\r\n Guest guest;\r\n Timer timer;\r\n \r\n\r\n public PanelLoginDanRegister(ActionListener eventRegister) {\r\n initComponents();\r\n initRegister(eventRegister);\r\n initLogin();\r\n login.setVisible(true);\r\n register.setVisible(false);\r\n }\r\n \r\n private void initRegister(ActionListener eventRegister) {\r\n register.setLayout(new MigLayout (\"wrap\", \"push[center]push\", \"110[]25[]10[]10[]70[]push\"));\r\n JLabel label = new JLabel(\"Register\");\r\n label.setFont(new Font(\"sansserif\", 1, 30));\r\n label.setForeground(new Color(48, 45, 35));\r\n register.add(label);\r\n \r\n // Kolom Nama - Password\r\n MyTextField txtUser = new MyTextField();\r\n txtUser.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/user.png\")));\r\n txtUser.setHint(\"Your Name\");\r\n register.add(txtUser, \"w 60%\");\r\n \r\n MyTextField txtEmail = new MyTextField();\r\n txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/mail.png\")));\r\n txtEmail.setHint((\"Your Email\"));\r\n register.add(txtEmail, \"w 60%\");\r\n \r\n MyPassField txtPass = new MyPassField();\r\n txtPass.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/pass.png\")));\r\n txtPass.setHint((\"Password\"));\r\n register.add(txtPass, \"w 60%\");\r\n \r\n MyTextField txtNumber = new MyTextField();\r\n txtNumber.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/telephone.png\")));\r\n txtNumber.setHint(\"Phone Number\");\r\n register.add(txtNumber, \"w 40%, pos 100 318 n n\");\r\n \r\n MyTextField txtAge = new MyTextField();\r\n txtAge.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/age-group.png\")));\r\n txtAge.setHint(\"Age\");\r\n register.add(txtAge, \"w 18%, pos 306 318 n n\");\r\n \r\n // kolom button\r\n Button cmd = new Button();\r\n cmd.setBackground(new Color (48, 45, 35));\r\n cmd.setForeground(new Color (250, 250, 250));\r\n cmd.addActionListener(eventRegister);\r\n cmd.setText(\"Register\");\r\n register.add(cmd, \"w 40%, h 40\");\r\n \r\n ShowPasswordCheckBox registerPassShow = new ShowPasswordCheckBox();\r\n register.add(registerPassShow, \"pos 405 277 n n\");\r\n showPassword(registerPassShow, txtPass);\r\n \r\n guestAcc = new GuestServiceLoginImpl();\r\n guestDetail = new GuestServiceImpl();\r\n guest = new Guest();\r\n \r\n JLabel registerConfirm = new JLabel();\r\n register.add(registerConfirm, \"pos 193 430 15% 10%\");\r\n \r\n //Register\r\n cmd.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n try{\r\n Long.valueOf(txtNumber.getText());\r\n int x = Integer.parseInt(txtAge.getText());\r\n \r\n guestAcc.register(txtUser.getText(), txtEmail.getText(), String.valueOf(txtPass.getPassword()));\r\n guest.setGuest_pnumber(txtNumber.getText());\r\n guest.setGuest_age(x);\r\n guestDetail.create(guest);\r\n \r\n registerConfirm.setText(\"Register Successful!\");\r\n new Timer(4_000, (e) -> {registerConfirm.setText(null);}).start();\r\n \r\n } catch (NumberFormatException e) {\r\n if(txtNumber.getText().isEmpty() || txtAge.getText().isEmpty()){\r\n System.out.println(\"Test\");\r\n } else {\r\n ErrorString error = new ErrorString();\r\n error.setVisible(true);\r\n error.setLocationRelativeTo(null);\r\n System.out.println(e);\r\n }\r\n \r\n }\r\n }\r\n });\r\n } \r\n \r\n private void initLogin() {\r\n login.setLayout(new MigLayout(\"wrap \", \"push[center]push\", \"push[]25[]10[]10[]15[]push\"));\r\n JLabel label = new JLabel(\"Masuk\");\r\n label.setFont(new Font(\"sansserif\", 1, 30));\r\n label.setForeground(new Color(48, 45, 35));\r\n login.add(label);\r\n \r\n // Kolom Email - Sandi\r\n MyTextField txtEmail = new MyTextField();\r\n txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/mail.png\")));\r\n txtEmail.setHint((\"Your Email\"));\r\n login.add(txtEmail, \"w 60%\");\r\n \r\n MyPassField txtPass = new MyPassField();\r\n txtPass.setPrefixIcon(new ImageIcon(getClass().getResource(\"/images/pass.png\")));\r\n txtPass.setHint((\"Password\"));\r\n login.add(txtPass, \"w 60%\");\r\n \r\n JButton cmdLupa = new JButton(\"Forget Password?\");\r\n cmdLupa.setForeground(new Color(100,100,100));\r\n cmdLupa.setFont(new Font(\"sansserif\", 1, 12));\r\n cmdLupa.setContentAreaFilled(false);\r\n cmdLupa.setCursor(new Cursor(Cursor.HAND_CURSOR));\r\n login.add(cmdLupa);\r\n\r\n // Tombol Sign In\r\n Button cmd = new Button();\r\n cmd.setBackground(new Color (48, 45, 35));\r\n cmd.setForeground(new Color (250, 250, 250));\r\n cmd.setText(\"Login\");\r\n login.add(cmd, \"w 40%, h 40\");\r\n \r\n cmd.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n login(txtEmail, txtPass);\r\n }\r\n });\r\n \r\n ShowPasswordCheckBox loginPassShow = new ShowPasswordCheckBox();\r\n login.add(loginPassShow, \"pos 405 255 n n\");\r\n showPassword(loginPassShow, txtPass);\r\n }\r\n \r\n public void login(JTextField txtEmail, JPasswordField txtPass){\r\n String email = txtEmail.getText();\r\n String pass = String.valueOf(txtPass.getPassword());\r\n System.out.println(email);\r\n System.out.println(pass);\r\n }\r\n \r\n public void showPassword(JCheckBox show, JPasswordField pass){\r\n show.addActionListener(new ActionListener() {\r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n if (show.isSelected()) {\r\n pass.setEchoChar((char)0);\r\n } else {\r\n pass.setEchoChar('*');\r\n }\r\n }\r\n });\r\n }\r\n \r\n public void showRegister (boolean show) {\r\n if (show) {\r\n register.setVisible(false);\r\n login.setVisible(true);\r\n } else {\r\n register.setVisible(true);\r\n login.setVisible(false);\r\n }\r\n \r\n }\r\n\r\n /**\r\n * This method is called from within the constructor to initialize the form.\r\n * WARNING: Do NOT modify this code. The content of this method is always\r\n * regenerated by the Form Editor.\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\r\n private void initComponents() {\r\n\r\n login = new javax.swing.JPanel();\r\n register = new javax.swing.JPanel();\r\n\r\n setLayout(new java.awt.CardLayout());\r\n\r\n login.setBackground(new java.awt.Color(255, 255, 255));\r\n\r\n javax.swing.GroupLayout loginLayout = new javax.swing.GroupLayout(login);\r\n login.setLayout(loginLayout);\r\n loginLayout.setHorizontalGroup(\r\n loginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\r\n .addGap(0, 292, Short.MAX_VALUE)\r\n );\r\n loginLayout.setVerticalGroup(\r\n loginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\r\n .addGap(0, 260, Short.MAX_VALUE)\r\n );\r\n\r\n add(login, \"card3\");\r\n\r\n register.setBackground(new java.awt.Color(255, 255, 255));\r\n\r\n javax.swing.GroupLayout registerLayout = new javax.swing.GroupLayout(register);\r\n register.setLayout(registerLayout);\r\n registerLayout.setHorizontalGroup(\r\n registerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\r\n .addGap(0, 292, Short.MAX_VALUE)\r\n );\r\n registerLayout.setVerticalGroup(\r\n registerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\r\n .addGap(0, 260, Short.MAX_VALUE)\r\n );\r\n\r\n add(register, \"card2\");\r\n }// </editor-fold>//GEN-END:initComponents\r\n\r\n \r\n\r\n // Variables declaration - do not modify//GEN-BEGIN:variables\r\n private javax.swing.JPanel login;\r\n private javax.swing.JPanel register;\r\n // End of variables declaration//GEN-END:variables\r\n}\r" }, { "identifier": "ExitButton", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/component/ExitButton.java", "snippet": "public class ExitButton extends JButton{\n ExitConfirmation exit;\n\n public ExitButton(){\n setBorder(BorderFactory.createEmptyBorder());\n setContentAreaFilled(false);\n setCursor(new Cursor(Cursor.HAND_CURSOR));\n exit = new ExitConfirmation();\n addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent me) { \n exit.setVisible(true);\n exit.setLocationRelativeTo(null);\n }\n \n });\n }\n}" } ]
import com.itenas.oop.org.uashotel.swing.panel.PanelCover; import com.itenas.oop.org.uashotel.swing.panel.PanelLoading; import com.itenas.oop.org.uashotel.swing.panel.PanelLoginDanRegister; import com.itenas.oop.org.uashotel.swing.component.ExitButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.ImageIcon; import net.miginfocom.swing.MigLayout; import org.jdesktop.animation.timing.Animator; import org.jdesktop.animation.timing.TimingTarget; import org.jdesktop.animation.timing.TimingTargetAdapter;
4,100
package com.itenas.oop.org.uashotel.swing; public class LoginForm extends javax.swing.JFrame { private MigLayout layout;
package com.itenas.oop.org.uashotel.swing; public class LoginForm extends javax.swing.JFrame { private MigLayout layout;
private PanelCover cover;
0
2023-12-24 11:39:51+00:00
8k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/global/initData/NotProd.java
[ { "identifier": "Book", "path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n @ManyToOne\n private Member author;\n @OneToOne\n private Product product;\n private String title;\n private String body;\n private int price;\n private boolean published;\n}" }, { "identifier": "BookService", "path": "src/main/java/com/multibook/bookorder/domain/book/book/service/BookService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class BookService {\n private final BookRepository bookRepository;\n\n @Transactional\n public Book createBook(Member author, String title, String body, int price, boolean published) {\n Book book = Book.builder()\n .author(author)\n .title(title)\n .body(body)\n .price(price)\n .published(published)\n .build();\n\n bookRepository.save(book);\n\n return book;\n }\n\n public Page<Book> search(Member author, Boolean published, List<String> kwTypes, String kw, Pageable pageable) {\n return bookRepository.search(author, published, kwTypes, kw, pageable);\n }\n}" }, { "identifier": "CashLog", "path": "src/main/java/com/multibook/bookorder/domain/cash/cash/entity/CashLog.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class CashLog extends BaseTime {\n @Enumerated(EnumType.STRING)\n private EvenType eventType;\n private String relTypeCode;\n private Long relId;\n @ManyToOne\n private Member member;\n private long price;\n\n public enum EvenType {\n 충전__무통장입금,\n 충전__토스페이먼츠,\n 출금__통장입금,\n 사용__토스페이먼츠_주문결제,\n 사용__예치금_주문결제,\n 환불__예치금_주문결제,\n 작가정산__예치금;\n }\n}" }, { "identifier": "WithdrawService", "path": "src/main/java/com/multibook/bookorder/domain/cash/withdraw/service/WithdrawService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class WithdrawService {\n private final WithdrawApplyRepository withdrawApplyRepository;\n private final MemberService memberService;\n\n public boolean canApply(Member actor, long cash) {\n return actor.getRestCash() >= cash;\n }\n\n @Transactional\n public void apply(Member applicant, long cash, String bankName, String bankAccountNo) {\n WithdrawApply apply = WithdrawApply.builder()\n .applicant(applicant)\n .cash(cash)\n .bankName(bankName)\n .bankAccountNo(bankAccountNo)\n .build();\n\n withdrawApplyRepository.save(apply);\n }\n\n public List<WithdrawApply> findByApplicant(Member applicant) {\n return withdrawApplyRepository.findByApplicantOrderByIdDesc(applicant);\n }\n\n public Optional<WithdrawApply> findById(long id) {\n return withdrawApplyRepository.findById(id);\n }\n\n public boolean canDelete(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (actor.isAdmin()) return true;\n\n if (!withdrawApply.getApplicant().equals(actor)) return false;\n\n return true;\n }\n\n @Transactional\n public void delete(WithdrawApply withdrawApply) {\n withdrawApplyRepository.delete(withdrawApply);\n }\n\n public List<WithdrawApply> findAll() {\n return withdrawApplyRepository.findAllByOrderByIdDesc();\n }\n\n public boolean canCancel(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (!actor.isAdmin()) return false;\n\n if (withdrawApply.getApplicant().getRestCash() >= withdrawApply.getCash()) return false;\n\n return true;\n }\n\n public boolean canWithdraw(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (!actor.isAdmin()) return false;\n\n if (withdrawApply.getApplicant().getRestCash() < withdrawApply.getCash()) return false;\n\n return true;\n }\n\n @Transactional\n public void withdraw(WithdrawApply withdrawApply) {\n withdrawApply.setWithdrawDone();\n\n memberService.addCash(withdrawApply.getApplicant(), withdrawApply.getCash() * -1, CashLog.EvenType.출금__통장입금, withdrawApply);\n }\n\n @Transactional\n public void cancel(WithdrawApply withdrawApply) {\n withdrawApply.setCancelDone(\"관리자에 의해 취소됨, 잔액부족\");\n }\n}" }, { "identifier": "Member", "path": "src/main/java/com/multibook/bookorder/domain/member/member/entity/Member.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true, exclude = {\"myBooks\", \"owner\"})\npublic class Member extends BaseTime {\n private String username;\n private String password;\n private String nickname;\n private long restCash;\n\n @OneToMany(mappedBy = \"owner\", cascade = ALL, orphanRemoval = true)\n @Builder.Default\n private List<MyBook> myBooks = new ArrayList<>();\n\n public void addMyBook(Book book) {\n MyBook myBook = MyBook.builder()\n .owner(this)\n .book(book)\n .build();\n\n myBooks.add(myBook);\n }\n\n public void removeMyBook(Book book) {\n myBooks.removeIf(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean hasBook(Book book) {\n return myBooks\n .stream()\n .anyMatch(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean has(Product product) {\n return switch (product.getRelTypeCode()) {\n case \"book\" -> hasBook(product.getBook());\n default -> false;\n };\n }\n\n @Transient\n public Collection<? extends GrantedAuthority> getAuthorities() {\n List<GrantedAuthority> authorities = new ArrayList<>();\n\n authorities.add(new SimpleGrantedAuthority(\"ROLE_MEMBER\"));\n\n if (List.of(\"system\", \"admin\").contains(username)) {\n authorities.add(new SimpleGrantedAuthority(\"ROLE_ADMIN\"));\n }\n\n return authorities;\n }\n\n public boolean isAdmin() {\n return getAuthorities().stream()\n .anyMatch(a -> a.getAuthority().equals(\"ROLE_ADMIN\"));\n }\n}" }, { "identifier": "MemberService", "path": "src/main/java/com/multibook/bookorder/domain/member/member/service/MemberService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class MemberService {\n private final MemberRepository memberRepository;\n private final PasswordEncoder passwordEncoder;\n private final CashService cashService;\n private final GenFileService genFileService;\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname) {\n return join(username, password, nickname, \"\");\n }\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) {\n String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath());\n return join(username, password, nickname, profileImgFilePath);\n }\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) {\n if (findByUsername(username).isPresent()) {\n return RsData.of(\"400-2\", \"이미 존재하는 회원입니다.\");\n }\n\n Member member = Member.builder()\n .username(username)\n .password(passwordEncoder.encode(password))\n .nickname(nickname)\n .build();\n memberRepository.save(member);\n\n if (UtZip.str.hasLength(profileImgFilePath)) {\n saveProfileImg(member, profileImgFilePath);\n }\n\n return RsData.of(\"200\", \"%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.\".formatted(member.getUsername()), member);\n }\n\n private void saveProfileImg(Member member, String profileImgFilePath) {\n genFileService.save(member.getModelName(), member.getId(), \"common\", \"profileImg\", 1, profileImgFilePath);\n }\n\n public Optional<Member> findByUsername(String username) {\n return memberRepository.findByUsername(username);\n }\n\n @Transactional\n public void addCash(Member member, long price, CashLog.EvenType eventType, BaseEntity relEntity) {\n CashLog cashLog = cashService.addCash(member, price, eventType, relEntity);\n\n long newRestCash = member.getRestCash() + cashLog.getPrice();\n member.setRestCash(newRestCash);\n }\n\n @Transactional\n public RsData<Member> whenSocialLogin(String providerTypeCode, String username, String nickname, String profileImgUrl) {\n Optional<Member> opMember = findByUsername(username);\n\n if (opMember.isPresent()) return RsData.of(\"200\", \"이미 존재합니다.\", opMember.get());\n\n String filePath = UtZip.str.hasLength(profileImgUrl) ? UtZip.file.downloadFileByHttp(profileImgUrl, AppConfig.getTempDirPath()) : \"\";\n\n return join(username, \"\", nickname, filePath);\n }\n\n public String getProfileImgUrl(Member member) {\n return Optional.ofNullable(member)\n .flatMap(this::findProfileImgUrl)\n .orElse(\"https://placehold.co/30x30?text=UU\");\n }\n\n private Optional<String> findProfileImgUrl(Member member) {\n return genFileService.findBy(\n member.getModelName(), member.getId(), \"common\", \"profileImg\", 1\n )\n .map(GenFile::getUrl);\n }\n}" }, { "identifier": "CartService", "path": "src/main/java/com/multibook/bookorder/domain/product/cart/service/CartService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class CartService {\n private final CartItemRepository cartItemRepository;\n\n @Transactional\n public CartItem addItem(Member buyer, Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n CartItem cartItem = CartItem.builder()\n .buyer(buyer)\n .product(product)\n .build();\n\n cartItemRepository.save(cartItem);\n\n return cartItem;\n }\n\n @Transactional\n public void removeItem(Member buyer, Product product) {\n cartItemRepository.deleteByBuyerAndProduct(buyer, product);\n }\n\n public List<CartItem> findByBuyerOrderByIdDesc(Member buyer) {\n return cartItemRepository.findByBuyer(buyer);\n }\n\n public void delete(CartItem cartItem) {\n cartItemRepository.delete(cartItem);\n }\n\n public boolean canAdd(Member buyer, Product product) {\n if (buyer == null) return false;\n\n return !cartItemRepository.existsByBuyerAndProduct(buyer, product);\n }\n\n public boolean canRemove(Member buyer, Product product) {\n if (buyer == null) return false;\n\n return cartItemRepository.existsByBuyerAndProduct(buyer, product);\n }\n\n public boolean canDirectMakeOrder(Member buyer, Product product) {\n return canAdd(buyer, product);\n }\n}" }, { "identifier": "Order", "path": "src/main/java/com/multibook/bookorder/domain/product/order/entity/Order.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\n@Table(name = \"order_\")\npublic class Order extends BaseTime {\n @ManyToOne\n private Member buyer;\n\n @Builder.Default\n @OneToMany(mappedBy = \"order\", cascade = ALL, orphanRemoval = true)\n @ToString.Exclude\n private List<OrderItem> orderItems = new ArrayList<>();\n\n private LocalDateTime payDate; // 결제일\n private LocalDateTime cancelDate; // 취소일\n private LocalDateTime refundDate; // 환불일\n\n public void addItem(CartItem cartItem) {\n addItem(cartItem.getProduct());\n }\n\n public void addItem(Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n OrderItem orderItem = OrderItem.builder()\n .order(this)\n .product(product)\n .build();\n\n orderItems.add(orderItem);\n }\n\n public long calcPayPrice() {\n return orderItems.stream()\n .mapToLong(OrderItem::getPayPrice)\n .sum();\n }\n\n public void setPaymentDone() {\n payDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setPaymentDone);\n }\n\n public void setCancelDone() {\n cancelDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setCancelDone);\n }\n\n public void setRefundDone() {\n refundDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setRefundDone);\n }\n\n public String getName() {\n String name = orderItems.get(0).getProduct().getName();\n\n if (orderItems.size() > 1) {\n name += \" 외 %d건\".formatted(orderItems.size() - 1);\n }\n\n return name;\n }\n\n public String getCode() {\n // yyyy-MM-dd 형식의 DateTimeFormatter 생성\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n\n // LocalDateTime 객체를 문자열로 변환\n return getCreateDate().format(formatter) + (AppConfig.isNotProd() ? \"-test-\" + UUID.randomUUID().toString() : \"\") + \"__\" + getId();\n }\n\n public boolean isPayable() {\n if (payDate != null) return false;\n if (cancelDate != null) return false;\n\n return true;\n }\n\n public String getForPrintPayStatus() {\n if (payDate != null)\n return \"결제완료(\" + payDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (cancelDate != null) return \"-\";\n\n return \"결제대기\";\n }\n\n public String getForPrintCancelStatus() {\n if (cancelDate != null)\n return \"취소완료(\" + cancelDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (!isCancelable()) return \"취소불가능\";\n\n return \"취소가능\";\n }\n\n public String getForPrintRefundStatus() {\n if (refundDate != null)\n return \"환불완료(\" + refundDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (payDate == null) return \"-\";\n if (!isCancelable()) return \"-\";\n\n return \"환불가능\";\n }\n\n public boolean isPayDone() {\n return payDate != null;\n }\n\n public boolean isCancelable() {\n if (cancelDate != null) return false;\n\n // 결제일자로부터 1시간 지나면 취소 불가능\n if (payDate != null && payDate.plusHours(1).isBefore(LocalDateTime.now())) return false;\n\n return true;\n }\n}" }, { "identifier": "OrderService", "path": "src/main/java/com/multibook/bookorder/domain/product/order/service/OrderService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class OrderService {\n private final OrderRepository orderRepository;\n private final CartService cartService;\n private final MemberService memberService;\n\n @Transactional\n public Order createFromProduct(Member buyer, Product product) {\n Order order = Order.builder()\n .buyer(buyer)\n .build();\n\n order.addItem(product);\n\n orderRepository.save(order);\n\n return order;\n }\n\n @Transactional\n public Order createFromCart(Member buyer) {\n List<CartItem> cartItems = cartService.findByBuyerOrderByIdDesc(buyer);\n\n Order order = Order.builder()\n .buyer(buyer)\n .build();\n\n cartItems.stream()\n .forEach(order::addItem);\n\n orderRepository.save(order);\n\n cartItems.stream()\n .forEach(cartService::delete);\n\n return order;\n }\n\n @Transactional\n public void payByCashOnly(Order order) {\n Member buyer = order.getBuyer();\n long restCash = buyer.getRestCash();\n long payPrice = order.calcPayPrice();\n\n if (payPrice > restCash) {\n throw new GlobalException(\"400-1\", \"예치금이 부족합니다.\");\n }\n\n memberService.addCash(buyer, payPrice * -1, CashLog.EvenType.사용__예치금_주문결제, order);\n\n payDone(order);\n }\n\n @Transactional\n public void payByTossPayments(Order order, long pgPayPrice) {\n Member buyer = order.getBuyer();\n long restCash = buyer.getRestCash();\n long payPrice = order.calcPayPrice();\n\n long useRestCash = payPrice - pgPayPrice;\n\n memberService.addCash(buyer, pgPayPrice, CashLog.EvenType.충전__토스페이먼츠, order);\n memberService.addCash(buyer, pgPayPrice * -1, CashLog.EvenType.사용__토스페이먼츠_주문결제, order);\n\n if (useRestCash > 0) {\n if (useRestCash > restCash) {\n throw new RuntimeException(\"예치금이 부족합니다.\");\n }\n\n memberService.addCash(buyer, useRestCash * -1, CashLog.EvenType.사용__예치금_주문결제, order);\n }\n\n payDone(order);\n }\n\n private void payDone(Order order) {\n order.setPaymentDone();\n }\n\n private void refund(Order order) {\n long payPrice = order.calcPayPrice();\n\n memberService.addCash(order.getBuyer(), payPrice, CashLog.EvenType.환불__예치금_주문결제, order);\n\n order.setRefundDone();\n }\n\n public void checkCanPay(String orderCode, long pgPayPrice) {\n Order order = findByCode(orderCode).orElse(null);\n\n if (order == null)\n throw new GlobalException(\"400-1\", \"존재하지 않는 주문입니다.\");\n\n checkCanPay(order, pgPayPrice);\n }\n\n public void checkCanPay(Order order, long pgPayPrice) {\n if (!canPay(order, pgPayPrice))\n throw new GlobalException(\"400-2\", \"PG결제금액 혹은 예치금이 부족하여 결제할 수 없습니다.\");\n }\n\n public boolean canPay(Order order, long pgPayPrice) {\n if (!order.isPayable()) return false;\n\n long restCash = order.getBuyer().getRestCash();\n\n return order.calcPayPrice() <= restCash + pgPayPrice;\n }\n\n public Optional<Order> findById(long id) {\n return orderRepository.findById(id);\n }\n\n public boolean actorCanSee(Member actor, Order order) {\n return order.getBuyer().equals(actor);\n }\n\n public Optional<Order> findByCode(String code) {\n long id = Long.parseLong(code.split(\"__\", 2)[1]);\n\n return findById(id);\n }\n\n public void payDone(String code) {\n Order order = findByCode(code).orElse(null);\n\n if (order == null)\n throw new GlobalException(\"400-1\", \"존재하지 않는 주문입니다.\");\n\n payDone(order);\n }\n\n public Page<Order> search(Member buyer, Boolean payStatus, Boolean cancelStatus, Boolean refundStatus, Pageable pageable) {\n return orderRepository.search(buyer, payStatus, cancelStatus, refundStatus, pageable);\n }\n\n @Transactional\n public void cancel(Order order) {\n if (!order.isCancelable())\n throw new GlobalException(\"400-1\", \"취소할 수 없는 주문입니다.\");\n\n order.setCancelDone();\n\n if (order.isPayDone())\n refund(order);\n }\n\n public boolean canCancel(Member actor, Order order) {\n return actor.equals(order.getBuyer()) && order.isCancelable();\n }\n}" }, { "identifier": "Product", "path": "src/main/java/com/multibook/bookorder/domain/product/product/entity/Product.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Product extends BaseTime {\n @ManyToOne\n private Member maker;\n private String relTypeCode;\n private long relId;\n private String name;\n private int price;\n private boolean published;\n\n public Book getBook() {\n return AppConfig.getEntityManager().getReference(Book.class, relId);\n }\n}" }, { "identifier": "ProductService", "path": "src/main/java/com/multibook/bookorder/domain/product/product/service/ProductService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class ProductService {\n private final ProductRepository productRepository;\n private final ProductBookmarkService productBookmarkService;\n\n @Transactional\n public Product createProduct(Book book, boolean published) {\n if (book.getProduct() != null) return book.getProduct();\n\n Product product = Product.builder()\n .maker(book.getAuthor())\n .relTypeCode(book.getModelName())\n .relId(book.getId())\n .name(book.getTitle())\n .price(book.getPrice())\n .published(published)\n .build();\n\n productRepository.save(product);\n\n book.setProduct(product);\n\n return product;\n }\n\n public Optional<Product> findById(long id) {\n return productRepository.findById(id);\n }\n\n public Page<Product> search(Member maker, Boolean published, List<String> kwTypes, String kw, Pageable pageable) {\n return productRepository.search(maker, published, kwTypes, kw, pageable);\n }\n\n public boolean canBookmark(Member actor, Product product) {\n if (actor == null) return false;\n\n return productBookmarkService.canBookmark(actor, product);\n }\n\n public boolean canCancelBookmark(Member actor, Product product) {\n if (actor == null) return false;\n\n return productBookmarkService.canCancelBookmark(actor, product);\n }\n\n @Transactional\n public void bookmark(Member member, Product product) {\n productBookmarkService.bookmark(member, product);\n }\n\n @Transactional\n public void cancelBookmark(Member member, Product product) {\n productBookmarkService.cancelBookmark(member, product);\n }\n}" }, { "identifier": "Order", "path": "src/main/java/com/multibook/bookorder/domain/product/order/entity/Order.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\n@Table(name = \"order_\")\npublic class Order extends BaseTime {\n @ManyToOne\n private Member buyer;\n\n @Builder.Default\n @OneToMany(mappedBy = \"order\", cascade = ALL, orphanRemoval = true)\n @ToString.Exclude\n private List<OrderItem> orderItems = new ArrayList<>();\n\n private LocalDateTime payDate; // 결제일\n private LocalDateTime cancelDate; // 취소일\n private LocalDateTime refundDate; // 환불일\n\n public void addItem(CartItem cartItem) {\n addItem(cartItem.getProduct());\n }\n\n public void addItem(Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n OrderItem orderItem = OrderItem.builder()\n .order(this)\n .product(product)\n .build();\n\n orderItems.add(orderItem);\n }\n\n public long calcPayPrice() {\n return orderItems.stream()\n .mapToLong(OrderItem::getPayPrice)\n .sum();\n }\n\n public void setPaymentDone() {\n payDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setPaymentDone);\n }\n\n public void setCancelDone() {\n cancelDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setCancelDone);\n }\n\n public void setRefundDone() {\n refundDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setRefundDone);\n }\n\n public String getName() {\n String name = orderItems.get(0).getProduct().getName();\n\n if (orderItems.size() > 1) {\n name += \" 외 %d건\".formatted(orderItems.size() - 1);\n }\n\n return name;\n }\n\n public String getCode() {\n // yyyy-MM-dd 형식의 DateTimeFormatter 생성\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n\n // LocalDateTime 객체를 문자열로 변환\n return getCreateDate().format(formatter) + (AppConfig.isNotProd() ? \"-test-\" + UUID.randomUUID().toString() : \"\") + \"__\" + getId();\n }\n\n public boolean isPayable() {\n if (payDate != null) return false;\n if (cancelDate != null) return false;\n\n return true;\n }\n\n public String getForPrintPayStatus() {\n if (payDate != null)\n return \"결제완료(\" + payDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (cancelDate != null) return \"-\";\n\n return \"결제대기\";\n }\n\n public String getForPrintCancelStatus() {\n if (cancelDate != null)\n return \"취소완료(\" + cancelDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (!isCancelable()) return \"취소불가능\";\n\n return \"취소가능\";\n }\n\n public String getForPrintRefundStatus() {\n if (refundDate != null)\n return \"환불완료(\" + refundDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (payDate == null) return \"-\";\n if (!isCancelable()) return \"-\";\n\n return \"환불가능\";\n }\n\n public boolean isPayDone() {\n return payDate != null;\n }\n\n public boolean isCancelable() {\n if (cancelDate != null) return false;\n\n // 결제일자로부터 1시간 지나면 취소 불가능\n if (payDate != null && payDate.plusHours(1).isBefore(LocalDateTime.now())) return false;\n\n return true;\n }\n}" } ]
import com.multibook.bookorder.domain.book.book.entity.Book; import com.multibook.bookorder.domain.book.book.service.BookService; import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.cash.withdraw.service.WithdrawService; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.service.MemberService; import com.multibook.bookorder.domain.product.cart.service.CartService; import com.multibook.bookorder.domain.product.order.entity.Order; import com.multibook.bookorder.domain.product.order.service.OrderService; import com.multibook.bookorder.domain.product.product.entity.Product; import com.multibook.bookorder.domain.product.product.service.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import com.multibook.bookorder.domain.product.order.entity.Order; import org.springframework.transaction.annotation.Transactional;
7,074
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService;
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService;
private final ProductService productService;
10
2023-12-26 14:58:59+00:00
8k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/clients/ClusterConnectionStates.java
[ { "identifier": "AuthenticationException", "path": "clients/src/main/java/org/apache/kafka/common/errors/AuthenticationException.java", "snippet": "public class AuthenticationException extends ApiException {\n\n private static final long serialVersionUID = 1L;\n\n public AuthenticationException(String message) {\n super(message);\n }\n\n public AuthenticationException(Throwable cause) {\n super(cause);\n }\n\n public AuthenticationException(String message, Throwable cause) {\n super(message, cause);\n }\n\n}" }, { "identifier": "ExponentialBackoff", "path": "clients/src/main/java/org/apache/kafka/common/utils/ExponentialBackoff.java", "snippet": "public class ExponentialBackoff {\n private final int multiplier;\n private final double expMax;\n private final long initialInterval;\n private final double jitter;\n\n public ExponentialBackoff(long initialInterval, int multiplier, long maxInterval, double jitter) {\n this.initialInterval = initialInterval;\n this.multiplier = multiplier;\n this.jitter = jitter;\n this.expMax = maxInterval > initialInterval ?\n Math.log(maxInterval / (double) Math.max(initialInterval, 1)) / Math.log(multiplier) : 0;\n }\n\n public long backoff(long attempts) {\n if (expMax == 0) {\n return initialInterval;\n }\n double exp = Math.min(attempts, this.expMax);\n double term = initialInterval * Math.pow(multiplier, exp);\n double randomFactor = ThreadLocalRandom.current().nextDouble(1 - jitter, 1 + jitter);\n return (long) (randomFactor * term);\n }\n}" }, { "identifier": "LogContext", "path": "clients/src/main/java/org/apache/kafka/common/utils/LogContext.java", "snippet": "public class LogContext {\n\n private final String logPrefix;\n\n public LogContext(String logPrefix) {\n this.logPrefix = logPrefix == null ? \"\" : logPrefix;\n }\n\n public LogContext() {\n this(\"\");\n }\n\n public Logger logger(Class<?> clazz) {\n Logger logger = LoggerFactory.getLogger(clazz);\n if (logger instanceof LocationAwareLogger) {\n return new LocationAwareKafkaLogger(logPrefix, (LocationAwareLogger) logger);\n } else {\n return new LocationIgnorantKafkaLogger(logPrefix, logger);\n }\n }\n\n public String logPrefix() {\n return logPrefix;\n }\n\n private static abstract class AbstractKafkaLogger implements Logger {\n private final String prefix;\n\n protected AbstractKafkaLogger(final String prefix) {\n this.prefix = prefix;\n }\n\n protected String addPrefix(final String message) {\n return prefix + message;\n }\n }\n\n private static class LocationAwareKafkaLogger extends AbstractKafkaLogger {\n private final LocationAwareLogger logger;\n private final String fqcn;\n\n LocationAwareKafkaLogger(String logPrefix, LocationAwareLogger logger) {\n super(logPrefix);\n this.logger = logger;\n this.fqcn = LocationAwareKafkaLogger.class.getName();\n }\n\n @Override\n public String getName() {\n return logger.getName();\n }\n\n @Override\n public boolean isTraceEnabled() {\n return logger.isTraceEnabled();\n }\n\n @Override\n public boolean isTraceEnabled(Marker marker) {\n return logger.isTraceEnabled(marker);\n }\n\n @Override\n public boolean isDebugEnabled() {\n return logger.isDebugEnabled();\n }\n\n @Override\n public boolean isDebugEnabled(Marker marker) {\n return logger.isDebugEnabled(marker);\n }\n\n @Override\n public boolean isInfoEnabled() {\n return logger.isInfoEnabled();\n }\n\n @Override\n public boolean isInfoEnabled(Marker marker) {\n return logger.isInfoEnabled(marker);\n }\n\n @Override\n public boolean isWarnEnabled() {\n return logger.isWarnEnabled();\n }\n\n @Override\n public boolean isWarnEnabled(Marker marker) {\n return logger.isWarnEnabled(marker);\n }\n\n @Override\n public boolean isErrorEnabled() {\n return logger.isErrorEnabled();\n }\n\n @Override\n public boolean isErrorEnabled(Marker marker) {\n return logger.isErrorEnabled(marker);\n }\n\n @Override\n public void trace(String message) {\n if (logger.isTraceEnabled()) {\n writeLog(null, LocationAwareLogger.TRACE_INT, message, null, null);\n }\n }\n\n @Override\n public void trace(String format, Object arg) {\n if (logger.isTraceEnabled()) {\n writeLog(null, LocationAwareLogger.TRACE_INT, format, new Object[]{arg}, null);\n }\n }\n\n @Override\n public void trace(String format, Object arg1, Object arg2) {\n if (logger.isTraceEnabled()) {\n writeLog(null, LocationAwareLogger.TRACE_INT, format, new Object[]{arg1, arg2}, null);\n }\n }\n\n @Override\n public void trace(String format, Object... args) {\n if (logger.isTraceEnabled()) {\n writeLog(null, LocationAwareLogger.TRACE_INT, format, args, null);\n }\n }\n\n @Override\n public void trace(String msg, Throwable t) {\n if (logger.isTraceEnabled()) {\n writeLog(null, LocationAwareLogger.TRACE_INT, msg, null, t);\n }\n }\n\n @Override\n public void trace(Marker marker, String msg) {\n if (logger.isTraceEnabled()) {\n writeLog(marker, LocationAwareLogger.TRACE_INT, msg, null, null);\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg) {\n if (logger.isTraceEnabled()) {\n writeLog(marker, LocationAwareLogger.TRACE_INT, format, new Object[]{arg}, null);\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg1, Object arg2) {\n if (logger.isTraceEnabled()) {\n writeLog(marker, LocationAwareLogger.TRACE_INT, format, new Object[]{arg1, arg2}, null);\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object... argArray) {\n if (logger.isTraceEnabled()) {\n writeLog(marker, LocationAwareLogger.TRACE_INT, format, argArray, null);\n }\n }\n\n @Override\n public void trace(Marker marker, String msg, Throwable t) {\n if (logger.isTraceEnabled()) {\n writeLog(marker, LocationAwareLogger.TRACE_INT, msg, null, t);\n }\n }\n\n @Override\n public void debug(String message) {\n if (logger.isDebugEnabled()) {\n writeLog(null, LocationAwareLogger.DEBUG_INT, message, null, null);\n }\n }\n\n @Override\n public void debug(String format, Object arg) {\n if (logger.isDebugEnabled()) {\n writeLog(null, LocationAwareLogger.DEBUG_INT, format, new Object[]{arg}, null);\n }\n }\n\n @Override\n public void debug(String format, Object arg1, Object arg2) {\n if (logger.isDebugEnabled()) {\n writeLog(null, LocationAwareLogger.DEBUG_INT, format, new Object[]{arg1, arg2}, null);\n }\n }\n\n @Override\n public void debug(String format, Object... args) {\n if (logger.isDebugEnabled()) {\n writeLog(null, LocationAwareLogger.DEBUG_INT, format, args, null);\n }\n }\n\n @Override\n public void debug(String msg, Throwable t) {\n if (logger.isDebugEnabled()) {\n writeLog(null, LocationAwareLogger.DEBUG_INT, msg, null, t);\n }\n }\n\n @Override\n public void debug(Marker marker, String msg) {\n if (logger.isDebugEnabled()) {\n writeLog(marker, LocationAwareLogger.DEBUG_INT, msg, null, null);\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg) {\n if (logger.isDebugEnabled()) {\n writeLog(marker, LocationAwareLogger.DEBUG_INT, format, new Object[]{arg}, null);\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg1, Object arg2) {\n if (logger.isDebugEnabled()) {\n writeLog(marker, LocationAwareLogger.DEBUG_INT, format, new Object[]{arg1, arg2}, null);\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object... arguments) {\n if (logger.isDebugEnabled()) {\n writeLog(marker, LocationAwareLogger.DEBUG_INT, format, arguments, null);\n }\n }\n\n @Override\n public void debug(Marker marker, String msg, Throwable t) {\n if (logger.isDebugEnabled()) {\n writeLog(marker, LocationAwareLogger.DEBUG_INT, msg, null, t);\n }\n }\n\n @Override\n public void warn(String message) {\n writeLog(null, LocationAwareLogger.WARN_INT, message, null, null);\n }\n\n @Override\n public void warn(String format, Object arg) {\n writeLog(null, LocationAwareLogger.WARN_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void warn(String message, Object arg1, Object arg2) {\n writeLog(null, LocationAwareLogger.WARN_INT, message, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void warn(String format, Object... args) {\n writeLog(null, LocationAwareLogger.WARN_INT, format, args, null);\n }\n\n @Override\n public void warn(String msg, Throwable t) {\n writeLog(null, LocationAwareLogger.WARN_INT, msg, null, t);\n }\n\n @Override\n public void warn(Marker marker, String msg) {\n writeLog(marker, LocationAwareLogger.WARN_INT, msg, null, null);\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg) {\n writeLog(marker, LocationAwareLogger.WARN_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg1, Object arg2) {\n writeLog(marker, LocationAwareLogger.WARN_INT, format, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void warn(Marker marker, String format, Object... arguments) {\n writeLog(marker, LocationAwareLogger.WARN_INT, format, arguments, null);\n }\n\n @Override\n public void warn(Marker marker, String msg, Throwable t) {\n writeLog(marker, LocationAwareLogger.WARN_INT, msg, null, t);\n }\n\n @Override\n public void error(String message) {\n writeLog(null, LocationAwareLogger.ERROR_INT, message, null, null);\n }\n\n @Override\n public void error(String format, Object arg) {\n writeLog(null, LocationAwareLogger.ERROR_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void error(String format, Object arg1, Object arg2) {\n writeLog(null, LocationAwareLogger.ERROR_INT, format, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void error(String format, Object... args) {\n writeLog(null, LocationAwareLogger.ERROR_INT, format, args, null);\n }\n\n @Override\n public void error(String msg, Throwable t) {\n writeLog(null, LocationAwareLogger.ERROR_INT, msg, null, t);\n }\n\n @Override\n public void error(Marker marker, String msg) {\n writeLog(marker, LocationAwareLogger.ERROR_INT, msg, null, null);\n }\n\n @Override\n public void error(Marker marker, String format, Object arg) {\n writeLog(marker, LocationAwareLogger.ERROR_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void error(Marker marker, String format, Object arg1, Object arg2) {\n writeLog(marker, LocationAwareLogger.ERROR_INT, format, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void error(Marker marker, String format, Object... arguments) {\n writeLog(marker, LocationAwareLogger.ERROR_INT, format, arguments, null);\n }\n\n @Override\n public void error(Marker marker, String msg, Throwable t) {\n writeLog(marker, LocationAwareLogger.ERROR_INT, msg, null, t);\n }\n\n @Override\n public void info(String msg) {\n writeLog(null, LocationAwareLogger.INFO_INT, msg, null, null);\n }\n\n @Override\n public void info(String format, Object arg) {\n writeLog(null, LocationAwareLogger.INFO_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void info(String format, Object arg1, Object arg2) {\n writeLog(null, LocationAwareLogger.INFO_INT, format, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void info(String format, Object... args) {\n writeLog(null, LocationAwareLogger.INFO_INT, format, args, null);\n }\n\n @Override\n public void info(String msg, Throwable t) {\n writeLog(null, LocationAwareLogger.INFO_INT, msg, null, t);\n }\n\n @Override\n public void info(Marker marker, String msg) {\n writeLog(marker, LocationAwareLogger.INFO_INT, msg, null, null);\n }\n\n @Override\n public void info(Marker marker, String format, Object arg) {\n writeLog(marker, LocationAwareLogger.INFO_INT, format, new Object[]{arg}, null);\n }\n\n @Override\n public void info(Marker marker, String format, Object arg1, Object arg2) {\n writeLog(marker, LocationAwareLogger.INFO_INT, format, new Object[]{arg1, arg2}, null);\n }\n\n @Override\n public void info(Marker marker, String format, Object... arguments) {\n writeLog(marker, LocationAwareLogger.INFO_INT, format, arguments, null);\n }\n\n @Override\n public void info(Marker marker, String msg, Throwable t) {\n writeLog(marker, LocationAwareLogger.INFO_INT, msg, null, t);\n }\n\n private void writeLog(Marker marker, int level, String format, Object[] args, Throwable exception) {\n String message = format;\n if (args != null && args.length > 0) {\n FormattingTuple formatted = MessageFormatter.arrayFormat(format, args);\n if (exception == null && formatted.getThrowable() != null) {\n exception = formatted.getThrowable();\n }\n message = formatted.getMessage();\n }\n logger.log(marker, fqcn, level, addPrefix(message), null, exception);\n }\n }\n\n private static class LocationIgnorantKafkaLogger extends AbstractKafkaLogger {\n private final Logger logger;\n\n LocationIgnorantKafkaLogger(String logPrefix, Logger logger) {\n super(logPrefix);\n this.logger = logger;\n }\n\n @Override\n public String getName() {\n return logger.getName();\n }\n\n @Override\n public boolean isTraceEnabled() {\n return logger.isTraceEnabled();\n }\n\n @Override\n public boolean isTraceEnabled(Marker marker) {\n return logger.isTraceEnabled(marker);\n }\n\n @Override\n public boolean isDebugEnabled() {\n return logger.isDebugEnabled();\n }\n\n @Override\n public boolean isDebugEnabled(Marker marker) {\n return logger.isDebugEnabled(marker);\n }\n\n @Override\n public boolean isInfoEnabled() {\n return logger.isInfoEnabled();\n }\n\n @Override\n public boolean isInfoEnabled(Marker marker) {\n return logger.isInfoEnabled(marker);\n }\n\n @Override\n public boolean isWarnEnabled() {\n return logger.isWarnEnabled();\n }\n\n @Override\n public boolean isWarnEnabled(Marker marker) {\n return logger.isWarnEnabled(marker);\n }\n\n @Override\n public boolean isErrorEnabled() {\n return logger.isErrorEnabled();\n }\n\n @Override\n public boolean isErrorEnabled(Marker marker) {\n return logger.isErrorEnabled(marker);\n }\n\n @Override\n public void trace(String message) {\n if (logger.isTraceEnabled()) {\n logger.trace(addPrefix(message));\n }\n }\n\n @Override\n public void trace(String message, Object arg) {\n if (logger.isTraceEnabled()) {\n logger.trace(addPrefix(message), arg);\n }\n }\n\n @Override\n public void trace(String message, Object arg1, Object arg2) {\n if (logger.isTraceEnabled()) {\n logger.trace(addPrefix(message), arg1, arg2);\n }\n }\n\n @Override\n public void trace(String message, Object... args) {\n if (logger.isTraceEnabled()) {\n logger.trace(addPrefix(message), args);\n }\n }\n\n @Override\n public void trace(String msg, Throwable t) {\n if (logger.isTraceEnabled()) {\n logger.trace(addPrefix(msg), t);\n }\n }\n\n @Override\n public void trace(Marker marker, String msg) {\n if (logger.isTraceEnabled()) {\n logger.trace(marker, addPrefix(msg));\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg) {\n if (logger.isTraceEnabled()) {\n logger.trace(marker, addPrefix(format), arg);\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg1, Object arg2) {\n if (logger.isTraceEnabled()) {\n logger.trace(marker, addPrefix(format), arg1, arg2);\n }\n }\n\n @Override\n public void trace(Marker marker, String format, Object... argArray) {\n if (logger.isTraceEnabled()) {\n logger.trace(marker, addPrefix(format), argArray);\n }\n }\n\n @Override\n public void trace(Marker marker, String msg, Throwable t) {\n if (logger.isTraceEnabled()) {\n logger.trace(marker, addPrefix(msg), t);\n }\n }\n\n @Override\n public void debug(String message) {\n if (logger.isDebugEnabled()) {\n logger.debug(addPrefix(message));\n }\n }\n\n @Override\n public void debug(String message, Object arg) {\n if (logger.isDebugEnabled()) {\n logger.debug(addPrefix(message), arg);\n }\n }\n\n @Override\n public void debug(String message, Object arg1, Object arg2) {\n if (logger.isDebugEnabled()) {\n logger.debug(addPrefix(message), arg1, arg2);\n }\n }\n\n @Override\n public void debug(String message, Object... args) {\n if (logger.isDebugEnabled()) {\n logger.debug(addPrefix(message), args);\n }\n }\n\n @Override\n public void debug(String msg, Throwable t) {\n if (logger.isDebugEnabled()) {\n logger.debug(addPrefix(msg), t);\n }\n }\n\n @Override\n public void debug(Marker marker, String msg) {\n if (logger.isDebugEnabled()) {\n logger.debug(marker, addPrefix(msg));\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg) {\n if (logger.isDebugEnabled()) {\n logger.debug(marker, addPrefix(format), arg);\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg1, Object arg2) {\n if (logger.isDebugEnabled()) {\n logger.debug(marker, addPrefix(format), arg1, arg2);\n }\n }\n\n @Override\n public void debug(Marker marker, String format, Object... arguments) {\n if (logger.isDebugEnabled()) {\n logger.debug(marker, addPrefix(format), arguments);\n }\n }\n\n @Override\n public void debug(Marker marker, String msg, Throwable t) {\n if (logger.isDebugEnabled()) {\n logger.debug(marker, addPrefix(msg), t);\n }\n }\n\n @Override\n public void warn(String message) {\n logger.warn(addPrefix(message));\n }\n\n @Override\n public void warn(String message, Object arg) {\n logger.warn(addPrefix(message), arg);\n }\n\n @Override\n public void warn(String message, Object arg1, Object arg2) {\n logger.warn(addPrefix(message), arg1, arg2);\n }\n\n @Override\n public void warn(String message, Object... args) {\n logger.warn(addPrefix(message), args);\n }\n\n @Override\n public void warn(String msg, Throwable t) {\n logger.warn(addPrefix(msg), t);\n }\n\n @Override\n public void warn(Marker marker, String msg) {\n logger.warn(marker, addPrefix(msg));\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg) {\n logger.warn(marker, addPrefix(format), arg);\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg1, Object arg2) {\n logger.warn(marker, addPrefix(format), arg1, arg2);\n }\n\n @Override\n public void warn(Marker marker, String format, Object... arguments) {\n logger.warn(marker, addPrefix(format), arguments);\n }\n\n @Override\n public void warn(Marker marker, String msg, Throwable t) {\n logger.warn(marker, addPrefix(msg), t);\n }\n\n @Override\n public void error(String message) {\n logger.error(addPrefix(message));\n }\n\n @Override\n public void error(String message, Object arg) {\n logger.error(addPrefix(message), arg);\n }\n\n @Override\n public void error(String message, Object arg1, Object arg2) {\n logger.error(addPrefix(message), arg1, arg2);\n }\n\n @Override\n public void error(String message, Object... args) {\n logger.error(addPrefix(message), args);\n }\n\n @Override\n public void error(String msg, Throwable t) {\n logger.error(addPrefix(msg), t);\n }\n\n @Override\n public void error(Marker marker, String msg) {\n logger.error(marker, addPrefix(msg));\n }\n\n @Override\n public void error(Marker marker, String format, Object arg) {\n logger.error(marker, addPrefix(format), arg);\n }\n\n @Override\n public void error(Marker marker, String format, Object arg1, Object arg2) {\n logger.error(marker, addPrefix(format), arg1, arg2);\n }\n\n @Override\n public void error(Marker marker, String format, Object... arguments) {\n logger.error(marker, addPrefix(format), arguments);\n }\n\n @Override\n public void error(Marker marker, String msg, Throwable t) {\n logger.error(marker, addPrefix(msg), t);\n }\n\n @Override\n public void info(String message) {\n logger.info(addPrefix(message));\n }\n\n @Override\n public void info(String message, Object arg) {\n logger.info(addPrefix(message), arg);\n }\n\n @Override\n public void info(String message, Object arg1, Object arg2) {\n logger.info(addPrefix(message), arg1, arg2);\n }\n\n @Override\n public void info(String message, Object... args) {\n logger.info(addPrefix(message), args);\n }\n\n @Override\n public void info(String msg, Throwable t) {\n logger.info(addPrefix(msg), t);\n }\n\n @Override\n public void info(Marker marker, String msg) {\n logger.info(marker, addPrefix(msg));\n }\n\n @Override\n public void info(Marker marker, String format, Object arg) {\n logger.info(marker, addPrefix(format), arg);\n }\n\n @Override\n public void info(Marker marker, String format, Object arg1, Object arg2) {\n logger.info(marker, addPrefix(format), arg1, arg2);\n }\n\n @Override\n public void info(Marker marker, String format, Object... arguments) {\n logger.info(marker, addPrefix(format), arguments);\n }\n\n @Override\n public void info(Marker marker, String msg, Throwable t) {\n logger.info(marker, addPrefix(msg), t);\n }\n\n }\n\n}" } ]
import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.utils.ExponentialBackoff; import org.apache.kafka.common.utils.LogContext; import org.slf4j.Logger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.List;
6,476
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients; /** * The state of our connection to each node in the cluster. * */ final class ClusterConnectionStates { final static int RECONNECT_BACKOFF_EXP_BASE = 2; final static double RECONNECT_BACKOFF_JITTER = 0.2; final static int CONNECTION_SETUP_TIMEOUT_EXP_BASE = 2; final static double CONNECTION_SETUP_TIMEOUT_JITTER = 0.2; private final Map<String, NodeConnectionState> nodeState; private final Logger log; private final HostResolver hostResolver; private Set<String> connectingNodes; private ExponentialBackoff reconnectBackoff; private ExponentialBackoff connectionSetupTimeout; public ClusterConnectionStates(long reconnectBackoffMs, long reconnectBackoffMaxMs, long connectionSetupTimeoutMs, long connectionSetupTimeoutMaxMs,
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients; /** * The state of our connection to each node in the cluster. * */ final class ClusterConnectionStates { final static int RECONNECT_BACKOFF_EXP_BASE = 2; final static double RECONNECT_BACKOFF_JITTER = 0.2; final static int CONNECTION_SETUP_TIMEOUT_EXP_BASE = 2; final static double CONNECTION_SETUP_TIMEOUT_JITTER = 0.2; private final Map<String, NodeConnectionState> nodeState; private final Logger log; private final HostResolver hostResolver; private Set<String> connectingNodes; private ExponentialBackoff reconnectBackoff; private ExponentialBackoff connectionSetupTimeout; public ClusterConnectionStates(long reconnectBackoffMs, long reconnectBackoffMaxMs, long connectionSetupTimeoutMs, long connectionSetupTimeoutMaxMs,
LogContext logContext, HostResolver hostResolver) {
2
2023-12-23 07:12:18+00:00
8k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/event/ModEventBusClientEvents.java
[ { "identifier": "PingysWaddles", "path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java", "snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n // Directly reference a slf4j logger\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public PingysWaddles()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // register Creative Tab\n ModCreativeModTabs.register(modEventBus);\n // register items\n ModItems.register(modEventBus);\n // register blocks\n ModBlocks.register(modEventBus);\n //register entities\n ModEntities.register(modEventBus);\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Register the item to a creative tab\n modEventBus.addListener(this::addCreative);\n\n }\n\n private void commonSetup(final FMLCommonSetupEvent event)\n {\n\n }\n\n // Add the example block item to the building blocks tab\n private void addCreative(BuildCreativeModeTabContentsEvent event)\n {\n\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n EntityRenderers.register(ModEntities.EMPEROR_PENGUIN.get(), EmperorPenguinRenderer::new);\n EntityRenderers.register(ModEntities.SURFBOARD.get(), SurfboardRenderer::new);\n }\n }\n}" }, { "identifier": "BabyEmperorPenguinModel", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/client/BabyEmperorPenguinModel.java", "snippet": "public class BabyEmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> {\n\n private final ModelPart root;\n private final ModelPart head;\n\n public BabyEmperorPenguinModel(ModelPart root) {\n this.root = root;\n this.head = root.getChild(\"bone\").getChild(\"top\");\n }\n\n public static LayerDefinition createBodyLayer() {\n MeshDefinition meshdefinition = new MeshDefinition();\n PartDefinition partdefinition = meshdefinition.getRoot();\n\n PartDefinition bone = partdefinition.addOrReplaceChild(\"bone\", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F));\n\n PartDefinition body = bone.addOrReplaceChild(\"body\", CubeListBuilder.create().texOffs(0, 0).addBox(-4.0F, -10.0F, -4.0F, 8.0F, 10.0F, 8.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition top = bone.addOrReplaceChild(\"top\", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition head = top.addOrReplaceChild(\"head\", CubeListBuilder.create().texOffs(0, 18).addBox(-3.0F, -14.0F, -3.0F, 6.0F, 4.0F, 6.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition beak = top.addOrReplaceChild(\"beak\", CubeListBuilder.create().texOffs(0, 0).addBox(-0.5F, -11.5F, 2.3F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition wings = bone.addOrReplaceChild(\"wings\", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition rightwing = wings.addOrReplaceChild(\"rightwing\", CubeListBuilder.create(), PartPose.offset(4.0F, -9.0F, 0.0F));\n\n PartDefinition cube_r1 = rightwing.addOrReplaceChild(\"cube_r1\", CubeListBuilder.create().texOffs(0, 27).addBox(0.5F, 0.75F, -1.0F, 1.0F, 8.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.042F, -1.1456F, 0.0F, 0.0F, 0.0F, -0.1745F));\n\n PartDefinition leftwing = wings.addOrReplaceChild(\"leftwing\", CubeListBuilder.create(), PartPose.offset(-4.2558F, -9.3605F, 0.0F));\n\n PartDefinition cube_r2 = leftwing.addOrReplaceChild(\"cube_r2\", CubeListBuilder.create().texOffs(0, 27).mirror().addBox(-1.5F, 0.75F, -1.0F, 1.0F, 8.0F, 2.0F, new CubeDeformation(0.0F)).mirror(false), PartPose.offsetAndRotation(1.2978F, -0.7851F, 0.0F, 0.0F, 0.0F, 0.1745F));\n\n PartDefinition feet = bone.addOrReplaceChild(\"feet\", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition rightfoot = feet.addOrReplaceChild(\"rightfoot\", CubeListBuilder.create().texOffs(0, 18).addBox(1.0F, -1.0F, 3.425F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition leftfoot = feet.addOrReplaceChild(\"leftfoot\", CubeListBuilder.create().texOffs(0, 3).addBox(-2.0F, -1.0F, 3.425F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition tail = bone.addOrReplaceChild(\"tail\", CubeListBuilder.create(), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition part1 = tail.addOrReplaceChild(\"part1\", CubeListBuilder.create().texOffs(18, 18).addBox(-0.5F, -1.0F, -5.075F, 1.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n return LayerDefinition.create(meshdefinition, 64, 64);\n }\n\n @Override\n public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n this.root().getAllParts().forEach(ModelPart::resetPose);\n this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks);\n\n this.animateWalk(BabyEmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);\n this.animate(((EmperorPenguinEntity) entity).idleAnimationState, BabyEmperorPenguinAnimationDefinitions.WINGING, ageInTicks, 1f);\n this.animate(((EmperorPenguinEntity) entity).fallingAnimationState, BabyEmperorPenguinAnimationDefinitions.FALLING, ageInTicks, 1f);\n }\n\n @Override\n public void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) {\n root.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);\n }\n\n private void applyHeadRotation(T pEntity, float pNetHeadYaw, float pHeadPitch, float pAgeInTicks) {\n pNetHeadYaw = Mth.clamp(pNetHeadYaw, -25.0F, 25.0F);\n pHeadPitch = Mth.clamp(pHeadPitch, -5.0F, 15.0F);\n\n this.head.yRot = pNetHeadYaw * 0.017453292F;\n this.head.xRot = pHeadPitch * -0.017453292F;\n }\n\n @Override\n public ModelPart root() {\n return root;\n }\n}" }, { "identifier": "EmperorPenguinModel", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/client/EmperorPenguinModel.java", "snippet": "public class EmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> {\n private final ModelPart root;\n private final ModelPart head;\n\n public EmperorPenguinModel(ModelPart root) {\n this.root = root;\n this.head = root.getChild(\"emperor_penguin\").getChild(\"top\");\n }\n\n public static LayerDefinition createBodyLayer() {\n MeshDefinition meshdefinition = new MeshDefinition();\n PartDefinition partdefinition = meshdefinition.getRoot();\n\n PartDefinition emperor_penguin = partdefinition.addOrReplaceChild(\"emperor_penguin\", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F));\n\n PartDefinition top = emperor_penguin.addOrReplaceChild(\"top\", CubeListBuilder.create(), PartPose.offsetAndRotation(2.0F, -11.5F, 0.0F, -0.0349F, 0.0F, 0.0F));\n\n PartDefinition head = top.addOrReplaceChild(\"head\", CubeListBuilder.create().texOffs(2, 38).addBox(-7.0F, -18.5009F, -6.9477F, 14.0F, 10.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition beak = top.addOrReplaceChild(\"beak\", CubeListBuilder.create().texOffs(50, 2).addBox(-1.0F, -12.5009F, 6.0523F, 2.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition body = emperor_penguin.addOrReplaceChild(\"body\", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -20.0F, -8.0F, 16.0F, 20.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(2.0F, 0.0F, 0.0F));\n\n PartDefinition wings = emperor_penguin.addOrReplaceChild(\"wings\", CubeListBuilder.create(), PartPose.offset(2.0F, -1.5F, 0.0F));\n\n PartDefinition rightwing = wings.addOrReplaceChild(\"rightwing\", CubeListBuilder.create(), PartPose.offset(7.0F, -17.0F, 0.0F));\n\n PartDefinition cube_r1 = rightwing.addOrReplaceChild(\"cube_r1\", CubeListBuilder.create().texOffs(60, 58).addBox(15.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-12.7747F, 14.9515F, -13.0F, 0.0F, 0.0F, -0.1309F));\n\n PartDefinition leftwing = wings.addOrReplaceChild(\"leftwing\", CubeListBuilder.create(), PartPose.offset(-7.0F, -17.0F, 0.0F));\n\n PartDefinition cube_r2 = leftwing.addOrReplaceChild(\"cube_r2\", CubeListBuilder.create().texOffs(60, 32).addBox(-17.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(12.2192F, 15.1698F, -13.0F, 0.0F, 0.0F, 0.1309F));\n\n PartDefinition feet = emperor_penguin.addOrReplaceChild(\"feet\", CubeListBuilder.create(), PartPose.offset(2.0F, -2.0F, 0.0F));\n\n PartDefinition rightfoot = feet.addOrReplaceChild(\"rightfoot\", CubeListBuilder.create().texOffs(0, 7).addBox(2.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition leftfoot = feet.addOrReplaceChild(\"leftfoot\", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition tail = emperor_penguin.addOrReplaceChild(\"tail\", CubeListBuilder.create(), PartPose.offset(8.25F, -1.75F, 0.75F));\n\n PartDefinition part1 = tail.addOrReplaceChild(\"part1\", CubeListBuilder.create().texOffs(0, 36).addBox(-7.25F, 0.5F, -10.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F));\n\n PartDefinition part2 = tail.addOrReplaceChild(\"part2\", CubeListBuilder.create(), PartPose.offset(-6.25F, 0.25F, -0.75F));\n\n PartDefinition cube_r3 = part2.addOrReplaceChild(\"cube_r3\", CubeListBuilder.create().texOffs(0, 0).addBox(0.5F, -1.0F, -13.0F, 1.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 1.25F, 2.75F, 0.0349F, 0.0F, 0.0F));\n\n return LayerDefinition.create(meshdefinition, 128, 128);\n }\n\n @Override\n public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n this.root().getAllParts().forEach(ModelPart::resetPose);\n this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks);\n\n this.animateWalk(EmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);\n\n this.animate(((EmperorPenguinEntity) entity).idleAnimationState, EmperorPenguinAnimationDefinitions.WINGING, ageInTicks, 1f);\n this.animate(((EmperorPenguinEntity) entity).fallingAnimationState, EmperorPenguinAnimationDefinitions.FALLING, ageInTicks, 1f);\n\n }\n\n @Override\n public void renderToBuffer(PoseStack poseStack, VertexConsumer vertexConsumer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha) {\n root.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);\n }\n\n private void applyHeadRotation(T pEntity, float pNetHeadYaw, float pHeadPitch, float pAgeInTicks) {\n pNetHeadYaw = Mth.clamp(pNetHeadYaw, -25.0F, 25.0F);\n pHeadPitch = Mth.clamp(pHeadPitch, -5.0F, 15.0F);\n\n this.head.yRot = pNetHeadYaw * 0.017453292F;\n this.head.xRot = pHeadPitch * -0.017453292F;\n }\n\n @Override\n public ModelPart root() {\n return root;\n }\n}" }, { "identifier": "ModModelLayers", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/client/ModModelLayers.java", "snippet": "public class ModModelLayers\n{\n public static final ModelLayerLocation EMPEROR_PENGUIN_LAYER = new ModelLayerLocation(\n new ResourceLocation(PingysWaddles.MOD_ID, \"emperor_penguin_layer\"), \"main\"\n );\n\n public static final ModelLayerLocation BABY_EMPEROR_PENGUIN_LAYER = new ModelLayerLocation(\n new ResourceLocation(PingysWaddles.MOD_ID, \"baby_emperor_penguin_layer\"), \"main\"\n );\n\n public static final ModelLayerLocation OAK_SURFBOARD_LAYER = new ModelLayerLocation(\n new ResourceLocation(PingysWaddles.MOD_ID, \"surfboard_layer\"), \"main\"\n );\n}" }, { "identifier": "SurfboardModel", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/client/SurfboardModel.java", "snippet": "@OnlyIn(Dist.CLIENT)\npublic class SurfboardModel<T extends Entity> extends HierarchicalModel<T> {\n\n private final ModelPart root;\n\n\n public SurfboardModel(ModelPart root) {\n this.root = root;\n }\n\n public static LayerDefinition createBodyLayer() {\n MeshDefinition meshdefinition = new MeshDefinition();\n PartDefinition partdefinition = meshdefinition.getRoot();\n\n PartDefinition board = partdefinition.addOrReplaceChild(\"board\", CubeListBuilder.create()\n .texOffs(0, 4).addBox(-41.0F, -1.0F, 0.0F, 47.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 0).addBox(-41.0F, -1.0F, -1.0F, 47.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 2).addBox(-41.0F, -1.0F, 1.0F, 47.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 8).addBox(-39.0F, -1.0F, -2.0F, 45.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 6).addBox(-39.0F, -1.0F, 2.0F, 45.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 12).addBox(-35.0F, -1.0F, 3.0F, 40.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 10).addBox(-35.0F, -1.0F, -3.0F, 40.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 16).addBox(-33.0F, -1.0F, -4.0F, 35.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n .texOffs(0, 14).addBox(-33.0F, -1.0F, 4.0F, 35.0F, 1.0F, 1.0F, new CubeDeformation(0.0F))\n , PartPose.offsetAndRotation(0, 1, 0, 0, 135F, 0));\n return LayerDefinition.create(meshdefinition, 128, 128);\n }\n\n @Override\n public ModelPart root() {\n return this.root;\n }\n\n @Override\n public void setupAnim(T t, float v, float v1, float v2, float v3, float v4) {\n\n }\n}" } ]
import com.sdevuyst.pingyswaddles.PingysWaddles; import com.sdevuyst.pingyswaddles.entity.client.BabyEmperorPenguinModel; import com.sdevuyst.pingyswaddles.entity.client.EmperorPenguinModel; import com.sdevuyst.pingyswaddles.entity.client.ModModelLayers; import com.sdevuyst.pingyswaddles.entity.client.SurfboardModel; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod;
5,516
package com.sdevuyst.pingyswaddles.event; @Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public class ModEventBusClientEvents { @SubscribeEvent public static void registerLayer(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition(ModModelLayers.EMPEROR_PENGUIN_LAYER, EmperorPenguinModel::createBodyLayer); event.registerLayerDefinition(ModModelLayers.BABY_EMPEROR_PENGUIN_LAYER, BabyEmperorPenguinModel::createBodyLayer);
package com.sdevuyst.pingyswaddles.event; @Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public class ModEventBusClientEvents { @SubscribeEvent public static void registerLayer(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition(ModModelLayers.EMPEROR_PENGUIN_LAYER, EmperorPenguinModel::createBodyLayer); event.registerLayerDefinition(ModModelLayers.BABY_EMPEROR_PENGUIN_LAYER, BabyEmperorPenguinModel::createBodyLayer);
event.registerLayerDefinition(ModModelLayers.OAK_SURFBOARD_LAYER, SurfboardModel::createBodyLayer);
4
2023-12-31 09:54:03+00:00
8k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/ParquetFileReader.java
[ { "identifier": "ColumnChunkPageReader", "path": "src/main/java/org/apache/parquet/local/ColumnChunkPageReadStore.java", "snippet": "static final class ColumnChunkPageReader implements PageReader {\n\n private final BytesInputDecompressor decompressor;\n private final long valueCount;\n private final Queue<DataPage> compressedPages;\n private final DictionaryPage compressedDictionaryPage;\n // null means no page synchronization is required; firstRowIndex will not be returned by the\n // pages\n private final OffsetIndex offsetIndex;\n private final long rowCount;\n private int pageIndex = 0;\n\n private final BlockCipher.Decryptor blockDecryptor;\n private final byte[] dataPageAAD;\n private final byte[] dictionaryPageAAD;\n\n ColumnChunkPageReader(\n BytesInputDecompressor decompressor,\n List<DataPage> compressedPages,\n DictionaryPage compressedDictionaryPage,\n OffsetIndex offsetIndex,\n long rowCount,\n BlockCipher.Decryptor blockDecryptor,\n byte[] fileAAD,\n int rowGroupOrdinal,\n int columnOrdinal) {\n this.decompressor = decompressor;\n this.compressedPages = new ArrayDeque<DataPage>(compressedPages);\n this.compressedDictionaryPage = compressedDictionaryPage;\n long count = 0;\n for (DataPage p : compressedPages) {\n count += p.getValueCount();\n }\n this.valueCount = count;\n this.offsetIndex = offsetIndex;\n this.rowCount = rowCount;\n\n this.blockDecryptor = blockDecryptor;\n\n if (null != blockDecryptor) {\n dataPageAAD =\n AesCipher.createModuleAAD(\n fileAAD, ModuleType.DataPage, rowGroupOrdinal, columnOrdinal, 0);\n dictionaryPageAAD =\n AesCipher.createModuleAAD(\n fileAAD, ModuleType.DictionaryPage, rowGroupOrdinal, columnOrdinal, -1);\n } else {\n dataPageAAD = null;\n dictionaryPageAAD = null;\n }\n }\n\n private int getPageOrdinal(int currentPageIndex) {\n if (null == offsetIndex) {\n return currentPageIndex;\n }\n\n return offsetIndex.getPageOrdinal(currentPageIndex);\n }\n\n @Override\n public long getTotalValueCount() {\n return valueCount;\n }\n\n @Override\n public DataPage readPage() {\n final DataPage compressedPage = compressedPages.poll();\n if (compressedPage == null) {\n return null;\n }\n final int currentPageIndex = pageIndex++;\n\n if (null != blockDecryptor) {\n AesCipher.quickUpdatePageAAD(dataPageAAD, getPageOrdinal(currentPageIndex));\n }\n\n return compressedPage.accept(\n new DataPage.Visitor<DataPage>() {\n @Override\n public DataPage visit(DataPageV1 dataPageV1) {\n try {\n BytesInput bytes = dataPageV1.getBytes();\n if (null != blockDecryptor) {\n bytes = BytesInput.from(blockDecryptor.decrypt(bytes.toByteArray(), dataPageAAD));\n }\n BytesInput decompressed =\n decompressor.decompress(bytes, dataPageV1.getUncompressedSize());\n\n final DataPageV1 decompressedPage;\n if (offsetIndex == null) {\n decompressedPage =\n new DataPageV1(\n decompressed,\n dataPageV1.getValueCount(),\n dataPageV1.getUncompressedSize(),\n dataPageV1.getStatistics(),\n dataPageV1.getRlEncoding(),\n dataPageV1.getDlEncoding(),\n dataPageV1.getValueEncoding());\n } else {\n long firstRowIndex = offsetIndex.getFirstRowIndex(currentPageIndex);\n decompressedPage =\n new DataPageV1(\n decompressed,\n dataPageV1.getValueCount(),\n dataPageV1.getUncompressedSize(),\n firstRowIndex,\n Math.toIntExact(\n offsetIndex.getLastRowIndex(currentPageIndex, rowCount)\n - firstRowIndex\n + 1),\n dataPageV1.getStatistics(),\n dataPageV1.getRlEncoding(),\n dataPageV1.getDlEncoding(),\n dataPageV1.getValueEncoding());\n }\n if (dataPageV1.getCrc().isPresent()) {\n decompressedPage.setCrc(dataPageV1.getCrc().getAsInt());\n }\n return decompressedPage;\n } catch (IOException e) {\n throw new ParquetDecodingException(\"could not decompress page\", e);\n }\n }\n\n @Override\n public DataPage visit(DataPageV2 dataPageV2) {\n if (!dataPageV2.isCompressed() && offsetIndex == null && null == blockDecryptor) {\n return dataPageV2;\n }\n BytesInput pageBytes = dataPageV2.getData();\n\n if (null != blockDecryptor) {\n try {\n pageBytes =\n BytesInput.from(blockDecryptor.decrypt(pageBytes.toByteArray(), dataPageAAD));\n } catch (IOException e) {\n throw new ParquetDecodingException(\n \"could not convert page ByteInput to byte array\", e);\n }\n }\n if (dataPageV2.isCompressed()) {\n int uncompressedSize =\n Math.toIntExact(\n dataPageV2.getUncompressedSize()\n - dataPageV2.getDefinitionLevels().size()\n - dataPageV2.getRepetitionLevels().size());\n try {\n pageBytes = decompressor.decompress(pageBytes, uncompressedSize);\n } catch (IOException e) {\n throw new ParquetDecodingException(\"could not decompress page\", e);\n }\n }\n\n if (offsetIndex == null) {\n return DataPageV2.uncompressed(\n dataPageV2.getRowCount(),\n dataPageV2.getNullCount(),\n dataPageV2.getValueCount(),\n dataPageV2.getRepetitionLevels(),\n dataPageV2.getDefinitionLevels(),\n dataPageV2.getDataEncoding(),\n pageBytes,\n dataPageV2.getStatistics());\n } else {\n return DataPageV2.uncompressed(\n dataPageV2.getRowCount(),\n dataPageV2.getNullCount(),\n dataPageV2.getValueCount(),\n offsetIndex.getFirstRowIndex(currentPageIndex),\n dataPageV2.getRepetitionLevels(),\n dataPageV2.getDefinitionLevels(),\n dataPageV2.getDataEncoding(),\n pageBytes,\n dataPageV2.getStatistics());\n }\n }\n });\n }\n\n @Override\n public DictionaryPage readDictionaryPage() {\n if (compressedDictionaryPage == null) {\n return null;\n }\n try {\n BytesInput bytes = compressedDictionaryPage.getBytes();\n if (null != blockDecryptor) {\n bytes = BytesInput.from(blockDecryptor.decrypt(bytes.toByteArray(), dictionaryPageAAD));\n }\n DictionaryPage decompressedPage =\n new DictionaryPage(\n decompressor.decompress(bytes, compressedDictionaryPage.getUncompressedSize()),\n compressedDictionaryPage.getDictionarySize(),\n compressedDictionaryPage.getEncoding());\n if (compressedDictionaryPage.getCrc().isPresent()) {\n decompressedPage.setCrc(compressedDictionaryPage.getCrc().getAsInt());\n }\n return decompressedPage;\n } catch (IOException e) {\n throw new ParquetDecodingException(\"Could not decompress dictionary page\", e);\n }\n }\n}" }, { "identifier": "OffsetRange", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static class OffsetRange {\n private final long offset;\n private long length;\n\n private OffsetRange(long offset, int length) {\n this.offset = offset;\n this.length = length;\n }\n\n long getOffset() {\n return offset;\n }\n\n long getLength() {\n return length;\n }\n\n private boolean extend(long offset, int length) {\n if (this.offset + this.length == offset) {\n this.length += length;\n return true;\n } else {\n return false;\n }\n }\n}" }, { "identifier": "RowGroupFilter", "path": "src/main/java/org/apache/parquet/local/filter2/compat/RowGroupFilter.java", "snippet": "public class RowGroupFilter implements Visitor<List<BlockMetaData>> {\n private final List<BlockMetaData> blocks;\n private final MessageType schema;\n private final List<FilterLevel> levels;\n private final ParquetFileReader reader;\n\n public enum FilterLevel {\n STATISTICS,\n DICTIONARY,\n BLOOMFILTER\n }\n\n public static List<BlockMetaData> filterRowGroups(\n List<FilterLevel> levels,\n Filter filter,\n List<BlockMetaData> blocks,\n ParquetFileReader reader) {\n Objects.requireNonNull(filter, \"filter cannot be null\");\n return filter.accept(new RowGroupFilter(levels, blocks, reader));\n }\n\n private RowGroupFilter(\n List<FilterLevel> levels, List<BlockMetaData> blocks, ParquetFileReader reader) {\n this.blocks = Objects.requireNonNull(blocks, \"blocks cannnot be null\");\n this.reader = Objects.requireNonNull(reader, \"reader cannnot be null\");\n this.schema = reader.getFileMetaData().getSchema();\n this.levels = levels;\n }\n\n @Override\n public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) {\n FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate();\n\n // check that the schema of the filter matches the schema of the file\n SchemaCompatibilityValidator.validate(filterPredicate, schema);\n\n List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>();\n\n for (BlockMetaData block : blocks) {\n boolean drop = false;\n\n if (levels.contains(FilterLevel.STATISTICS)) {\n drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns());\n }\n\n if (!drop && levels.contains(FilterLevel.DICTIONARY)) {\n drop =\n DictionaryFilter.canDrop(\n filterPredicate, block.getColumns(), reader.getDictionaryReader(block));\n }\n\n if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) {\n drop =\n BloomFilterImpl.canDrop(\n filterPredicate, block.getColumns(), reader.getBloomFilterDataReader(block));\n }\n\n if (!drop) {\n filteredBlocks.add(block);\n }\n }\n\n return filteredBlocks;\n }\n\n @Override\n public List<BlockMetaData> visit(\n FilterCompat.UnboundRecordFilterCompat unboundRecordFilterCompat) {\n return blocks;\n }\n\n @Override\n public List<BlockMetaData> visit(NoOpFilter noOpFilter) {\n return blocks;\n }\n}" }, { "identifier": "calculateOffsetRanges", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static List<OffsetRange> calculateOffsetRanges(\n OffsetIndex offsetIndex, ColumnChunkMetaData cm, long firstPageOffset) {\n List<OffsetRange> ranges = new ArrayList<>();\n int n = offsetIndex.getPageCount();\n if (n > 0) {\n OffsetRange currentRange = null;\n\n // Add a range for the dictionary page if required\n long rowGroupOffset = cm.getStartingPos();\n if (rowGroupOffset < firstPageOffset) {\n currentRange = new OffsetRange(rowGroupOffset, (int) (firstPageOffset - rowGroupOffset));\n ranges.add(currentRange);\n }\n\n for (int i = 0; i < n; ++i) {\n long offset = offsetIndex.getOffset(i);\n int length = offsetIndex.getCompressedPageSize(i);\n if (currentRange == null || !currentRange.extend(offset, length)) {\n currentRange = new OffsetRange(offset, length);\n ranges.add(currentRange);\n }\n }\n }\n return ranges;\n}" }, { "identifier": "filterOffsetIndex", "path": "src/main/java/org/apache/parquet/local/ColumnIndexFilterUtils.java", "snippet": "static OffsetIndex filterOffsetIndex(\n OffsetIndex offsetIndex, RowRanges rowRanges, long totalRowCount) {\n int[] result = new int[offsetIndex.getPageCount()];\n int count = 0;\n for (int i = 0, n = offsetIndex.getPageCount(); i < n; ++i) {\n long from = offsetIndex.getFirstRowIndex(i);\n if (rowRanges.isOverlapping(from, offsetIndex.getLastRowIndex(i, totalRowCount))) {\n result[count++] = i;\n }\n }\n return new FilteredOffsetIndex(offsetIndex, Arrays.copyOfRange(result, 0, count));\n}" }, { "identifier": "EFMAGIC", "path": "src/main/java/org/apache/parquet/local/ParquetFileWriter.java", "snippet": "public static final byte[] EFMAGIC = EF_MAGIC_STR.getBytes(StandardCharsets.US_ASCII);" }, { "identifier": "MAGIC", "path": "src/main/java/org/apache/parquet/local/ParquetFileWriter.java", "snippet": "public static final byte[] MAGIC = MAGIC_STR.getBytes(StandardCharsets.US_ASCII);" } ]
import org.apache.parquet.bytes.ByteBufferInputStream; import org.apache.parquet.bytes.BytesInput; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.page.*; import org.apache.parquet.column.values.bloomfilter.BlockSplitBloomFilter; import org.apache.parquet.column.values.bloomfilter.BloomFilter; import org.apache.parquet.compression.CompressionCodecFactory.BytesInputDecompressor; import org.apache.parquet.crypto.*; import org.apache.parquet.crypto.ModuleCipherFactory.ModuleType; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.format.*; import org.apache.parquet.hadoop.ParquetEmptyBlockException; import org.apache.parquet.hadoop.metadata.*; import org.apache.parquet.hadoop.metadata.FileMetaData; import org.apache.parquet.internal.column.columnindex.ColumnIndex; import org.apache.parquet.internal.column.columnindex.OffsetIndex; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexFilter; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexStore; import org.apache.parquet.internal.filter2.columnindex.RowRanges; import org.apache.parquet.internal.hadoop.metadata.IndexReference; import org.apache.parquet.io.InputFile; import org.apache.parquet.io.ParquetDecodingException; import org.apache.parquet.io.SeekableInputStream; import org.apache.parquet.local.ColumnChunkPageReadStore.ColumnChunkPageReader; import org.apache.parquet.local.ColumnIndexFilterUtils.OffsetRange; import org.apache.parquet.local.filter2.compat.RowGroupFilter; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.PrimitiveType; import org.apache.yetus.audience.InterfaceAudience.Private; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.nio.ByteBuffer; import java.util.*; import java.util.Map.Entry; import java.util.zip.CRC32; import static org.apache.parquet.bytes.BytesUtils.readIntLittleEndian; import static org.apache.parquet.format.Util.readFileCryptoMetaData; import static org.apache.parquet.local.ColumnIndexFilterUtils.calculateOffsetRanges; import static org.apache.parquet.local.ColumnIndexFilterUtils.filterOffsetIndex; import static org.apache.parquet.local.ParquetFileWriter.EFMAGIC; import static org.apache.parquet.local.ParquetFileWriter.MAGIC;
5,912
throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } RowRanges rowRanges = getRowRanges(blockIndex); return readFilteredRowGroup(blockIndex, rowRanges); } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the {@code rowRanges} passed in. As the rows are not aligned among the pages of the * different columns row synchronization might be required. See the documentation of the class * SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @param rowRanges the row ranges to be read from the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading * @throws IllegalArgumentException if the {@code blockIndex} is invalid or the {@code rowRanges} * is null */ public ColumnChunkPageReadStore readFilteredRowGroup(int blockIndex, RowRanges rowRanges) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { throw new IllegalArgumentException( String.format( "Invalid block index %s, the valid block index range are: " + "[%s, %s]", blockIndex, 0, blocks.size() - 1)); } if (Objects.isNull(rowRanges)) { throw new IllegalArgumentException("RowRanges must not be null"); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0L) { return null; } long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> returning null return null; } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return internalReadRowGroup(blockIndex); } return internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(blockIndex)); } /** * Reads all the columns requested from the row group at the current file position. It may skip * specific pages based on the column indexes according to the actual filter. As the rows are not * aligned among the pages of the different columns row synchronization might be required. See the * documentation of the class SynchronizingColumnReader for details. * * @return the PageReadStore which can provide PageReaders for each column * @throws IOException if an error occurs while reading */ public PageReadStore readNextFilteredRowGroup() throws IOException { if (currentBlock == blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return readNextRowGroup(); } BlockMetaData block = blocks.get(currentBlock); if (block.getRowCount() == 0L) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); // Skip the empty block advanceToNextBlock(); return readNextFilteredRowGroup(); } RowRanges rowRanges = getRowRanges(currentBlock); long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> skipping this row-group advanceToNextBlock(); return readNextFilteredRowGroup(); } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup(); } this.currentRowGroup = internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(currentBlock)); // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return this.currentRowGroup; } private ColumnChunkPageReadStore internalReadFilteredRowGroup( BlockMetaData block, RowRanges rowRanges, ColumnIndexStore ciStore) throws IOException { ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(rowRanges, block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); List<ConsecutivePartList> allParts = new ArrayList<>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { OffsetIndex offsetIndex = ciStore.getOffsetIndex(mc.getPath()); OffsetIndex filteredOffsetIndex = filterOffsetIndex(offsetIndex, rowRanges, block.getRowCount()); for (OffsetRange range :
/* * 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. */ /* * copied from parquet-mr, updated by An Qi */ package org.apache.parquet.local; /** Internal implementation of the Parquet file reader as a block container */ public class ParquetFileReader implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ParquetFileReader.class); private final ParquetMetadataConverter converter; private final CRC32 crc; public static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f) throws IOException { ParquetMetadataConverter converter = new ParquetMetadataConverter(options); return readFooter(file, options, f, converter); } private static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f, ParquetMetadataConverter converter) throws IOException { long fileLen = file.getLength(); String filePath = file.toString(); LOG.debug("File length {}", fileLen); int FOOTER_LENGTH_SIZE = 4; if (fileLen < MAGIC.length + FOOTER_LENGTH_SIZE + MAGIC.length) { // MAGIC + data + footer + footerIndex + MAGIC throw new RuntimeException( filePath + " is not a Parquet file (length is too low: " + fileLen + ")"); } // Read footer length and magic string - with a single seek byte[] magic = new byte[MAGIC.length]; long fileMetadataLengthIndex = fileLen - magic.length - FOOTER_LENGTH_SIZE; LOG.debug("reading footer index at {}", fileMetadataLengthIndex); f.seek(fileMetadataLengthIndex); int fileMetadataLength = readIntLittleEndian(f); f.readFully(magic); boolean encryptedFooterMode; if (Arrays.equals(MAGIC, magic)) { encryptedFooterMode = false; } else if (Arrays.equals(EFMAGIC, magic)) { encryptedFooterMode = true; } else { throw new RuntimeException( filePath + " is not a Parquet file. Expected magic number at tail, but found " + Arrays.toString(magic)); } long fileMetadataIndex = fileMetadataLengthIndex - fileMetadataLength; LOG.debug("read footer length: {}, footer index: {}", fileMetadataLength, fileMetadataIndex); if (fileMetadataIndex < magic.length || fileMetadataIndex >= fileMetadataLengthIndex) { throw new RuntimeException( "corrupted file: the footer index is not within the file: " + fileMetadataIndex); } f.seek(fileMetadataIndex); FileDecryptionProperties fileDecryptionProperties = options.getDecryptionProperties(); InternalFileDecryptor fileDecryptor = null; if (null != fileDecryptionProperties) { fileDecryptor = new InternalFileDecryptor(fileDecryptionProperties); } // Read all the footer bytes in one time to avoid multiple read operations, // since it can be pretty time consuming for a single read operation in HDFS. ByteBuffer footerBytesBuffer = ByteBuffer.allocate(fileMetadataLength); f.readFully(footerBytesBuffer); LOG.debug("Finished to read all footer bytes."); footerBytesBuffer.flip(); InputStream footerBytesStream = ByteBufferInputStream.wrap(footerBytesBuffer); // Regular file, or encrypted file with plaintext footer if (!encryptedFooterMode) { return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, false, fileMetadataLength); } // Encrypted file with encrypted footer if (null == fileDecryptor) { throw new ParquetCryptoRuntimeException( "Trying to read file with encrypted footer. No keys available"); } FileCryptoMetaData fileCryptoMetaData = readFileCryptoMetaData(footerBytesStream); fileDecryptor.setFileCryptoMetaData( fileCryptoMetaData.getEncryption_algorithm(), true, fileCryptoMetaData.getKey_metadata()); // footer length is required only for signed plaintext footers return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, true, 0); } protected final SeekableInputStream f; private final InputFile file; private final ParquetReadOptions options; private final Map<ColumnPath, ColumnDescriptor> paths = new HashMap<>(); private final FileMetaData fileMetaData; // may be null private final List<BlockMetaData> blocks; private final List<ColumnIndexStore> blockIndexStores; private final List<RowRanges> blockRowRanges; // not final. in some cases, this may be lazily loaded for backward-compat. private final ParquetMetadata footer; private int currentBlock = 0; private ColumnChunkPageReadStore currentRowGroup = null; private DictionaryPageReader nextDictionaryReader = null; private InternalFileDecryptor fileDecryptor = null; public ParquetFileReader(InputFile file, ParquetMetadata footer, ParquetReadOptions options) throws IOException { this.converter = new ParquetMetadataConverter(options); this.file = file; this.options = options; this.f = file.newStream(); try { this.footer = footer; this.fileMetaData = footer.getFileMetaData(); this.fileDecryptor = fileMetaData.getFileDecryptor(); // must be called before filterRowGroups! if (null != fileDecryptor && fileDecryptor.plaintextFile()) { this.fileDecryptor = null; // Plaintext file. No need in decryptor } this.blocks = filterRowGroups(footer.getBlocks()); this.blockIndexStores = listWithNulls(this.blocks.size()); this.blockRowRanges = listWithNulls(this.blocks.size()); for (ColumnDescriptor col : footer.getFileMetaData().getSchema().getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } this.crc = options.usePageChecksumVerification() ? new CRC32() : null; } catch (Exception e) { f.close(); throw e; } } private static <T> List<T> listWithNulls(int size) { return new ArrayList<>(Collections.nCopies(size, null)); } public FileMetaData getFileMetaData() { return fileMetaData; } public long getRecordCount() { long total = 0L; for (BlockMetaData block : blocks) { total += block.getRowCount(); } return total; } public long getFilteredRecordCount() { if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return getRecordCount(); } long total = 0L; for (int i = 0, n = blocks.size(); i < n; ++i) { total += getRowRanges(i).rowCount(); } return total; } public String getFile() { return file.toString(); } public List<BlockMetaData> filterRowGroups(List<BlockMetaData> blocks) throws IOException { FilterCompat.Filter recordFilter = options.getRecordFilter(); if (FilterCompat.isFilteringRequired(recordFilter)) { // set up data filters based on configured levels List<RowGroupFilter.FilterLevel> levels = new ArrayList<>(); if (options.useStatsFilter()) { levels.add(RowGroupFilter.FilterLevel.STATISTICS); } if (options.useDictionaryFilter()) { levels.add(RowGroupFilter.FilterLevel.DICTIONARY); } if (options.useBloomFilter()) { levels.add(RowGroupFilter.FilterLevel.BLOOMFILTER); } return RowGroupFilter.filterRowGroups(levels, recordFilter, blocks, this); } return blocks; } public List<BlockMetaData> getRowGroups() { return blocks; } private MessageType requestedSchema = null; public void setRequestedSchema(MessageType projection) { requestedSchema = projection; paths.clear(); for (ColumnDescriptor col : projection.getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } } public MessageType getRequestedSchema() { if (requestedSchema == null) { return fileMetaData.getSchema(); } return requestedSchema; } /** * Reads all the columns requested from the row group at the specified block. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readRowGroup(int blockIndex) throws IOException { return internalReadRowGroup(blockIndex); } /** * Reads all the columns requested from the row group at the current file position. * * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readNextRowGroup() throws IOException { ColumnChunkPageReadStore rowGroup = null; try { rowGroup = internalReadRowGroup(currentBlock); } catch (ParquetEmptyBlockException e) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); advanceToNextBlock(); return readNextRowGroup(); } if (rowGroup == null) { return null; } this.currentRowGroup = rowGroup; // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return currentRowGroup; } private ColumnChunkPageReadStore internalReadRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } org.apache.parquet.local.ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(block.getRowCount(), block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan List<ConsecutivePartList> allParts = new ArrayList<ConsecutivePartList>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { long startingPos = mc.getStartingPos(); // first part or not consecutive => new list if (currentParts == null || currentParts.endPos() != startingPos) { currentParts = new ConsecutivePartList(startingPos); allParts.add(currentParts); } currentParts.addChunk( new ChunkDescriptor(columnDescriptor, mc, startingPos, mc.getTotalSize())); } } // actually read all the chunks ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); for (ConsecutivePartList consecutiveChunks : allParts) { consecutiveChunks.readAll(f, builder); } for (Chunk chunk : builder.build()) { readChunkPages(chunk, block, rowGroup); } return rowGroup; } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the column indexes according to the actual filter. As the rows are not aligned among the * pages of the different columns row synchronization might be required. See the documentation of * the class SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading */ public PageReadStore readFilteredRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return internalReadRowGroup(blockIndex); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } RowRanges rowRanges = getRowRanges(blockIndex); return readFilteredRowGroup(blockIndex, rowRanges); } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the {@code rowRanges} passed in. As the rows are not aligned among the pages of the * different columns row synchronization might be required. See the documentation of the class * SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @param rowRanges the row ranges to be read from the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading * @throws IllegalArgumentException if the {@code blockIndex} is invalid or the {@code rowRanges} * is null */ public ColumnChunkPageReadStore readFilteredRowGroup(int blockIndex, RowRanges rowRanges) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { throw new IllegalArgumentException( String.format( "Invalid block index %s, the valid block index range are: " + "[%s, %s]", blockIndex, 0, blocks.size() - 1)); } if (Objects.isNull(rowRanges)) { throw new IllegalArgumentException("RowRanges must not be null"); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0L) { return null; } long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> returning null return null; } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return internalReadRowGroup(blockIndex); } return internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(blockIndex)); } /** * Reads all the columns requested from the row group at the current file position. It may skip * specific pages based on the column indexes according to the actual filter. As the rows are not * aligned among the pages of the different columns row synchronization might be required. See the * documentation of the class SynchronizingColumnReader for details. * * @return the PageReadStore which can provide PageReaders for each column * @throws IOException if an error occurs while reading */ public PageReadStore readNextFilteredRowGroup() throws IOException { if (currentBlock == blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return readNextRowGroup(); } BlockMetaData block = blocks.get(currentBlock); if (block.getRowCount() == 0L) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); // Skip the empty block advanceToNextBlock(); return readNextFilteredRowGroup(); } RowRanges rowRanges = getRowRanges(currentBlock); long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> skipping this row-group advanceToNextBlock(); return readNextFilteredRowGroup(); } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup(); } this.currentRowGroup = internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(currentBlock)); // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return this.currentRowGroup; } private ColumnChunkPageReadStore internalReadFilteredRowGroup( BlockMetaData block, RowRanges rowRanges, ColumnIndexStore ciStore) throws IOException { ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(rowRanges, block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); List<ConsecutivePartList> allParts = new ArrayList<>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { OffsetIndex offsetIndex = ciStore.getOffsetIndex(mc.getPath()); OffsetIndex filteredOffsetIndex = filterOffsetIndex(offsetIndex, rowRanges, block.getRowCount()); for (OffsetRange range :
calculateOffsetRanges(filteredOffsetIndex, mc, offsetIndex.getOffset(0))) {
3
2023-12-29 01:48:28+00:00
8k
iamamritpalrandhawa/JChess
Engines/InitEngine.java
[ { "identifier": "ChessBoard", "path": "Chess/ChessBoard.java", "snippet": "public class ChessBoard {\r\n private JFrame frame;\r\n DbEngine db = new DbEngine();\r\n private BoardPanel boardPanel;\r\n private ChessEngine gameState;\r\n private static final int SQ_SIZE = 90;\r\n private Pair<Integer, Integer> selectedTile;\r\n private List<Pair<Integer, Integer>> playerClicks;\r\n private boolean GameOver = false, inProgress = true;\r\n private boolean playerone, playertwo;\r\n InfoBoard info;\r\n String whitePlayer, blackPlayer;\r\n\r\n public ChessBoard(boolean p1, boolean p2, InfoBoard info, String whitePlayer, String blackPlayer) {\r\n frame = new JFrame(\"Chess Game\");\r\n frame.setLayout(new BorderLayout());\r\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n frame.setSize(736, 758);\r\n frame.setResizable(false);\r\n gameState = new ChessEngine();\r\n boardPanel = new BoardPanel();\r\n selectedTile = null;\r\n playerClicks = new ArrayList<>();\r\n // boolean playerone = p1, playertwo = p2;\r\n this.playerone = p1;\r\n this.playertwo = p2;\r\n this.info = info;\r\n this.whitePlayer = whitePlayer;\r\n this.blackPlayer = blackPlayer;\r\n frame.add(boardPanel, BorderLayout.CENTER);\r\n frame.setVisible(true);\r\n\r\n frame.addKeyListener(new KeyListener() {\r\n\r\n @Override\r\n public void keyPressed(KeyEvent e) {\r\n if (e.getKeyChar() == 'z') {\r\n gameState.undoMove();\r\n info.UpdateMoves(gameState.moveLog);\r\n boardPanel.repaint();\r\n } else if (e.getKeyChar() == 'r') {\r\n inProgress = false;\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n }\r\n }\r\n\r\n @Override\r\n public void keyTyped(KeyEvent e) {\r\n if (e.getKeyChar() == 'z') {\r\n gameState.undoMove();\r\n info.UpdateMoves(gameState.moveLog);\r\n boardPanel.repaint();\r\n } else if (e.getKeyChar() == 'r') {\r\n new Thread(() -> {\r\n info.dispose();\r\n frame.dispose();\r\n }).start();\r\n new Thread(() -> {\r\n new InitEngine();\r\n }).start();\r\n }\r\n }\r\n\r\n @Override\r\n public void keyReleased(KeyEvent e) {\r\n }\r\n\r\n });\r\n\r\n boardPanel.addMouseListener(new MouseListener() {\r\n\r\n @Override\r\n public void mouseClicked(MouseEvent e) {\r\n handleMouseClick(e);\r\n }\r\n\r\n @Override\r\n public void mousePressed(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseReleased(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseEntered(MouseEvent e) {\r\n }\r\n\r\n @Override\r\n public void mouseExited(MouseEvent e) {\r\n }\r\n });\r\n startGame();\r\n }\r\n\r\n private void handleMouseClick(MouseEvent e) {\r\n boolean humanTurn = (gameState.whiteToMove && playerone) || (!gameState.whiteToMove && playertwo);\r\n\r\n // Ensure it's the player's turn and the game isn't over\r\n if (!GameOver && humanTurn) {\r\n int x = e.getY() / (758 / 8);\r\n int y = e.getX() / (736 / 8);\r\n\r\n // If no tile is selected, select the current tile\r\n if (selectedTile == null) {\r\n selectedTile = new Pair<>(x, y);\r\n playerClicks.add(selectedTile);\r\n } else {\r\n // If a tile is already selected, make the move\r\n playerClicks.add(new Pair<>(x, y));\r\n Pair<Integer, Integer> startTile = playerClicks.get(0);\r\n Pair<Integer, Integer> endTile = playerClicks.get(1);\r\n Move move = new Move(startTile.getFirst(), startTile.getSecond(), endTile.getFirst(),\r\n endTile.getSecond(), gameState.board, false);\r\n\r\n if (gameState.getValidMoves().contains(move)) {\r\n gameState.makeMove(move, true);\r\n info.UpdateMoves(gameState.moveLog);\r\n\r\n // Print the board state after the move\r\n for (int i = 0; i < 8; i++) {\r\n for (int j = 0; j < 8; j++) {\r\n System.out.print(gameState.board[i][j] + \" \");\r\n }\r\n System.out.println(); // Move to the next row\r\n }\r\n System.out.println(\"################################################\");\r\n }\r\n\r\n // Reset selected tile and clicks\r\n selectedTile = null;\r\n playerClicks.clear();\r\n }\r\n }\r\n\r\n // Check for game over conditions and repaint the board\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boardPanel.repaint();\r\n\r\n // Highlight valid moves after a short delay for better visualization\r\n new Thread(() -> {\r\n try {\r\n Thread.sleep(40);\r\n } catch (InterruptedException ex) {\r\n ex.printStackTrace();\r\n }\r\n boardPanel.highlightSquares(gameState, gameState.getValidMoves(), selectedTile);\r\n }).start();\r\n }\r\n\r\n private void makeAIMove() {\r\n Move aiMove = AiEngine.bestMove(gameState, gameState.getValidMoves());\r\n if (aiMove == null)\r\n aiMove = AiEngine.randomMove(gameState.getValidMoves());\r\n gameState.makeMove(aiMove, true);\r\n info.UpdateMoves(gameState.moveLog);\r\n\r\n // Check for game over conditions and repaint the board after AI's move\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boardPanel.repaint();\r\n }\r\n\r\n public void startGame() {\r\n // Start a new thread to continuously check and make AI moves\r\n new Thread(() -> {\r\n while (!GameOver && inProgress) {\r\n decide(info, gameState, whitePlayer, blackPlayer);\r\n boolean humanTurn = (gameState.whiteToMove && playerone) || (!gameState.whiteToMove && playertwo);\r\n if (!GameOver && !humanTurn) {\r\n makeAIMove();\r\n }\r\n try {\r\n // Adjust the delay between AI moves (in milliseconds) as needed\r\n Thread.sleep(1000);\r\n } catch (InterruptedException ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n }).start();\r\n }\r\n\r\n void decide(InfoBoard info, ChessEngine gameState, String whitePlayer, String blackPlayer) {\r\n String s = new String();\r\n for (Move move : gameState.moveLog) {\r\n s += move.getChessNotation() + \",\";\r\n }\r\n if (gameState.checkMate) {\r\n GameOver = true;\r\n String winner = gameState.whiteToMove ? \"Black\" : \"White\";\r\n JOptionPane.showMessageDialog(null, winner + \" Wins\", \"Game Over\",\r\n JOptionPane.INFORMATION_MESSAGE);\r\n db.run(\"INSERT INTO `matches`( `Player1Name`, `Player2Name`, `Result`, `MoveLogs`) VALUES ('\"\r\n + whitePlayer + \"','\" + blackPlayer + \"','\" + winner + \" wins','\" + s + \"')\");\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n } else if (gameState.staleMate) {\r\n GameOver = true;\r\n JOptionPane.showMessageDialog(null, \"Stalemate\", \"Game Over\", JOptionPane.INFORMATION_MESSAGE);\r\n db.run(\"INSERT INTO `matches`( `Player1Name`, `Player2Name`, `Result`, `MoveLogs`) VALUES ('\"\r\n + whitePlayer + \"','\" + blackPlayer + \"','Stalemate','\" + s + \"')\");\r\n info.dispose();\r\n frame.dispose();\r\n new InitEngine();\r\n }\r\n }\r\n\r\n private class BoardPanel extends JPanel {\r\n private static final int TILE_SIZE = 90;\r\n private static final int BOARD_SIZE = 8;\r\n\r\n private HashMap<String, ImageIcon> images;\r\n\r\n private void loadImages() {\r\n images = new HashMap<>();\r\n\r\n String[] pieces = { \"wp\", \"wR\", \"wN\", \"wB\", \"wK\", \"wQ\", \"bp\", \"bR\", \"bN\", \"bB\", \"bK\", \"bQ\" };\r\n\r\n for (String piece : pieces) {\r\n ImageIcon imageIcon = new ImageIcon(\"Resources/Images/\" + piece + \".png\");\r\n Image image = imageIcon.getImage().getScaledInstance(SQ_SIZE, SQ_SIZE, Image.SCALE_SMOOTH);\r\n images.put(piece, new ImageIcon(image));\r\n }\r\n }\r\n\r\n @Override\r\n protected void paintComponent(Graphics g) {\r\n super.paintComponent(g);\r\n Graphics2D g2d = (Graphics2D) g;\r\n loadImages();\r\n for (int row = 0; row < BOARD_SIZE; row++) {\r\n for (int col = 0; col < BOARD_SIZE; col++) {\r\n Color color = (row + col) % 2 == 0 ? new Color(183, 152, 115) : new Color(115, 83, 58);\r\n g.setColor(color);\r\n g.fillRect(col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE);\r\n String piece = gameState.board[row][col];\r\n if (!piece.equals(\"--\")) {\r\n ImageIcon pieceImage = images.get(piece);\r\n pieceImage.paintIcon(this, g, col * TILE_SIZE, row * TILE_SIZE);\r\n }\r\n }\r\n }\r\n\r\n if (selectedTile != null) {\r\n g2d.setColor(Color.BLUE);\r\n Stroke oldStroke = g2d.getStroke();\r\n float borderWidth = 4.0f;\r\n g2d.setStroke(new BasicStroke(borderWidth));\r\n int x = selectedTile.getSecond() * TILE_SIZE;\r\n int y = selectedTile.getFirst() * TILE_SIZE;\r\n g2d.drawRect(x, y, TILE_SIZE, TILE_SIZE);\r\n g2d.setStroke(oldStroke);\r\n }\r\n\r\n }\r\n\r\n private void highlightSquares(ChessEngine gs, List<Move> validMoves,\r\n Pair<Integer, Integer> sqSelected) {\r\n Graphics g = getGraphics();\r\n if (sqSelected != null) {\r\n int r = sqSelected.getFirst();\r\n int c = sqSelected.getSecond();\r\n\r\n if (gs.board[r][c].charAt(0) == (gs.whiteToMove ? 'w' : 'b')) {\r\n\r\n g.setColor(new Color(0, 0, 255, 100));\r\n g.fillRect(c * SQ_SIZE, r * SQ_SIZE, SQ_SIZE, SQ_SIZE);\r\n\r\n g.setColor(new Color(255, 255, 0, 100));\r\n for (Move move : validMoves) {\r\n if (move.startRow == r && move.startCol == c) {\r\n g.fillRect(move.endCol * SQ_SIZE, move.endRow * SQ_SIZE, SQ_SIZE, SQ_SIZE);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r" }, { "identifier": "InfoBoard", "path": "Chess/InfoBoard.java", "snippet": "public class InfoBoard extends JFrame {\r\n static JScrollPane scrollPane1;\r\n static JScrollPane scrollPane2;\r\n\r\n public InfoBoard(String p1, String p2) {\r\n setTitle(\"Chess\");\r\n setSize(400, 700);\r\n setResizable(false);\r\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n setLocationRelativeTo(null); // Center the window\r\n setLocation(1000, 0); // Set the location to the top right corner\r\n\r\n setLayout(new GridLayout(2, 1)); // Use a 1x2 grid layout\r\n setVisible(true);\r\n\r\n JPanel mp1 = new JPanel();\r\n mp1.setLayout(new GridLayout(1, 2)); // 2 rows, 1 column for mp1\r\n\r\n JLabel p1_label = new JLabel(p1, JLabel.CENTER);\r\n p1_label.setHorizontalAlignment(SwingConstants.CENTER);\r\n p1_label.setFont(new Font(\"New Times Roman\", Font.BOLD, 20));\r\n p1_label.setSize(200, 100);\r\n mp1.add(p1_label);\r\n\r\n JLabel p2_label = new JLabel(p2, JLabel.CENTER);\r\n p2_label.setHorizontalAlignment(SwingConstants.CENTER);\r\n p2_label.setFont(new Font(\"New Times Roman\", Font.BOLD, 20));\r\n p2_label.setForeground(Color.WHITE);\r\n p2_label.setBackground(Color.BLACK);\r\n p2_label.setSize(200, 100);\r\n p2_label.setOpaque(true);\r\n\r\n mp1.add(p2_label);\r\n\r\n JPanel mp2 = new JPanel();\r\n mp2.setLayout(new GridLayout(1, 2));\r\n\r\n String[] data = {};\r\n\r\n JList<String> list1 = new JList<String>(data);\r\n scrollPane1 = new JScrollPane(list1);\r\n scrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\r\n\r\n mp2.add(scrollPane1);\r\n\r\n JList<String> list2 = new JList<String>(data);\r\n scrollPane2 = new JScrollPane(list2);\r\n mp2.add(scrollPane2);\r\n scrollPane1.getVerticalScrollBar().setModel(scrollPane2.getVerticalScrollBar().getModel());\r\n\r\n add(mp1);\r\n add(mp2);\r\n\r\n }\r\n\r\n public void UpdateMoves(List<Move> moves) {\r\n DefaultListModel<String> listModel1 = new DefaultListModel<String>();\r\n DefaultListModel<String> listModel2 = new DefaultListModel<String>();\r\n\r\n for (int i = 0; i < moves.size(); i++) {\r\n Move move = moves.get(i);\r\n String moveString = move.getChessNotation();\r\n\r\n if (i % 2 == 0) {\r\n listModel1.addElement(moveString);\r\n } else {\r\n listModel2.addElement(moveString);\r\n }\r\n }\r\n\r\n JList<String> list1 = new JList<>(listModel1);\r\n JList<String> list2 = new JList<>(listModel2);\r\n\r\n scrollPane1.setViewportView(list1);\r\n scrollPane2.setViewportView(list2);\r\n\r\n // Sync both scrollable lists together with one scrollable\r\n scrollPane1.getVerticalScrollBar().setModel(scrollPane2.getVerticalScrollBar().getModel());\r\n }\r\n}\r" } ]
import Chess.ChessBoard; import Chess.InfoBoard; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane;
4,435
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; } InfoBoard info = null; if (p1 && p2) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(p1Name, p2Name); } else if (p1) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } info = new InfoBoard(p1Name, blackPlayer); } else if (p2) { String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(whitePlayer, p2Name); } else { info = new InfoBoard(whitePlayer, blackPlayer); }
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; } InfoBoard info = null; if (p1 && p2) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(p1Name, p2Name); } else if (p1) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } info = new InfoBoard(p1Name, blackPlayer); } else if (p2) { String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(whitePlayer, p2Name); } else { info = new InfoBoard(whitePlayer, blackPlayer); }
new ChessBoard(p1, p2, info, whitePlayer, blackPlayer);
0
2023-12-28 13:53:01+00:00
8k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/taskController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n private String msg;\n /**\n * 返回的数据\n */\n private Object data;\n\n /**\n * 增删改 成功响应\n */\n public static Result success() {\n return new Result(1, \"success\", null);\n }\n\n /**\n * 查询 成功响应\n */\n public static Result success(Object data) {\n return new Result(1, \"success\", data);\n }\n\n /**\n * 失败响应\n */\n public static Result error(String msg) {\n return new Result(0, msg, null);\n }\n}" }, { "identifier": "systemSetting", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}" }, { "identifier": "systemServiceImpl", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/systemServiceImpl.java", "snippet": "@Slf4j\n@Service\npublic class systemServiceImpl implements systemService {\n @Value(\"${deployPosition}\")\n private String deployPosition;\n private String deploy = \"default\";\n\n\n public String selectFile() {\n String projectRoot;\n if (deploy.equals(deployPosition)) {\n projectRoot = System.getProperty(\"user.dir\");\n } else {\n projectRoot = deployPosition;\n }\n String parent = projectRoot + File.separator + \"config.json\";\n File jsonFile = new File(parent);\n Path jsonFilePath = Paths.get(parent);\n // 如果 JSON 文件不存在,创建一个新的 JSON 对象\n if (!jsonFile.exists()) {\n try {\n // 创建文件config.json\n Files.createFile(jsonFilePath);\n // 往 config.json 文件中添加一个空数组,防止重启报错\n Files.writeString(jsonFilePath, \"{}\");\n log.info(\"空数组添加完成\");\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n log.info(\"config.json创建完成: \" + jsonFilePath);\n }\n return parent;\n }\n\n /**\n * 初始化config.json文件\n */\n public void initializeConfigJson() {\n String parent = selectFile();\n try {\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 定义一个 Map,其中键是 JSON 属性的名称,值是默认值\n Map<String, Object> keysAndDefaults = new HashMap<>();\n keysAndDefaults.put(\"loginUsername\", \"root\");\n keysAndDefaults.put(\"loginPassword\", \"123456\");\n keysAndDefaults.put(\"license_id\", \"\");\n keysAndDefaults.put(\"autoToken_url\", \"default\");\n keysAndDefaults.put(\"isGetToken\", \"false\");\n keysAndDefaults.put(\"getTokenPassword\", \"\");\n keysAndDefaults.put(\"containerName\", \"PandoraNext\");\n keysAndDefaults.put(\"isolated_conv_title\", \"*\");\n keysAndDefaults.put(\"proxy_api_prefix\", \"\");\n keysAndDefaults.put(\"disable_signup\", false);\n keysAndDefaults.put(\"auto_conv_arkose\", false);\n keysAndDefaults.put(\"proxy_file_service\", false);\n keysAndDefaults.put(\"custom_doh_host\", \"\");\n\n // 0.4.9.3\n keysAndDefaults.put(\"auto_updateSession\", false);\n keysAndDefaults.put(\"auto_updateTime\", 5);\n keysAndDefaults.put(\"auto_updateNumber\", 1);\n keysAndDefaults.put(\"pandoraNext_outUrl\", \"\");\n\n // 0.5.0\n\n keysAndDefaults.put(\"oneAPi_outUrl\", \"\");\n keysAndDefaults.put(\"oneAPi_intoToken\", \"\");\n\n boolean exist = checkAndSetDefaults(jsonObject, keysAndDefaults);\n\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n\n if (tlsJson.length() == 0) {\n jsonObject.put(\"tls\", tlsSetting.toJSONObject());\n exist = false;\n }\n if (captchaJson.length() == 0) {\n jsonObject.put(\"captcha\", captchaSetting.toJSONObject());\n exist = false;\n }\n if (!exist) {\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n }\n log.info(\"初始化config.json成功!\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n // 通用方法,检查和设置默认值\n private boolean checkAndSetDefaults(JSONObject jsonObject, Map<String, Object> keysAndDefaults) throws JSONException {\n boolean exist = true;\n for (Map.Entry<String, Object> entry : keysAndDefaults.entrySet()) {\n try {\n jsonObject.get(entry.getKey());\n } catch (JSONException e) {\n jsonObject.put(entry.getKey(), entry.getValue());\n log.info(\"config.json没有新增\" + entry.getKey() + \"参数,现已增加!\");\n exist = false;\n }\n }\n return exist;\n }\n\n /**\n * 修改config.json里的系统值\n *\n * @return \"修改成功!\"or\"修改失败\"\n */\n @Override\n public String requiredSetting(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n JSONObject jsonObject = new JSONObject(jsonContent);\n updateJsonValue(jsonObject, \"bind\", tem.getBing());\n updateJsonValue(jsonObject, \"timeout\", tem.getTimeout());\n updateJsonValue(jsonObject, \"proxy_url\", tem.getProxy_url());\n updateJsonValue(jsonObject, \"public_share\", tem.getPublic_share());\n updateJsonValue(jsonObject, \"site_password\", tem.getSite_password());\n updateJsonValue(jsonObject, \"setup_password\", tem.getSetup_password());\n JSONArray jsonArray = null;\n if (tem.getWhitelist() != null && tem.getWhitelist().length() > 0 && tem.getWhitelist() != \"null\") {\n String numbersString = tem.getWhitelist().replaceAll(\"[\\\\[\\\\]]\", \"\");\n String[] numbersArray = numbersString.split(\",\");\n // 将数组转换为 List<String>\n List<String> numbersList = new ArrayList<>(Arrays.asList(numbersArray));\n jsonArray = new JSONArray(numbersList);\n jsonObject.put(\"whitelist\", jsonArray);\n } else {\n jsonObject.put(\"whitelist\", JSONObject.NULL);\n }\n\n //4.7.2\n if (!tem.getLoginPassword().equals(jsonObject.optString(\"loginPassword\"))\n || !tem.getLoginUsername().equals(jsonObject.optString(\"loginUsername\"))) {\n Instant instant = Instant.now();\n //时间戳\n String key = String.valueOf(instant.toEpochMilli());\n JwtUtils.setSignKey(key);\n }\n\n updateJsonValue(jsonObject, \"loginUsername\", tem.getLoginUsername());\n updateJsonValue(jsonObject, \"loginPassword\", tem.getLoginPassword());\n\n updateJsonValue(jsonObject, \"license_id\", tem.getLicense_id());\n updateJsonValue(jsonObject, \"autoToken_url\", tem.getAutoToken_url());\n updateJsonValue(jsonObject, \"isGetToken\", tem.getIsGetToken());\n updateJsonValue(jsonObject, \"getTokenPassword\", tem.getGetTokenPassword());\n updateJsonValue(jsonObject, \"containerName\", tem.getContainerName());\n\n updateJsonValue(jsonObject, \"isolated_conv_title\", tem.getIsolated_conv_title());\n updateJsonValue(jsonObject, \"proxy_api_prefix\", tem.getProxy_api_prefix());\n\n // 4,9\n updateJsonValue(jsonObject, \"disable_signup\", tem.getDisable_signup());\n updateJsonValue(jsonObject, \"auto_conv_arkose\", tem.getAuto_conv_arkose());\n updateJsonValue(jsonObject, \"proxy_file_service\", tem.getProxy_file_service());\n updateJsonValue(jsonObject, \"custom_doh_host\", tem.getCustom_doh_host());\n\n // validation\n validation validation = tem.getValidation();\n JSONObject captchaJson = jsonObject.getJSONObject(\"captcha\");\n updateJsonValue(captchaJson, \"provider\", validation.getProvider());\n updateJsonValue(captchaJson, \"site_key\", validation.getSite_key());\n updateJsonValue(captchaJson, \"site_secret\", validation.getSite_secret());\n updateJsonValue(captchaJson, \"site_login\", validation.isSite_login());\n updateJsonValue(captchaJson, \"setup_login\", validation.isSetup_login());\n updateJsonValue(captchaJson, \"oai_username\", validation.isOai_username());\n updateJsonValue(captchaJson, \"oai_password\", validation.isOai_password());\n\n // tls\n tls tls = tem.getTls();\n JSONObject tlsJson = jsonObject.getJSONObject(\"tls\");\n updateJsonValue(tlsJson, \"enabled\", tls.isEnabled());\n updateJsonValue(tlsJson, \"cert_file\", tls.getCert_file());\n updateJsonValue(tlsJson, \"key_file\", tls.getKey_file());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改config.json成功,快去重启PandoraNext吧!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改config.json失败\";\n }\n\n private void updateJsonValue(JSONObject jsonObject, String key, Object value) {\n if (value == null) {\n return;\n }\n try {\n if (value != null && value.toString().length() > 0) {\n jsonObject.put(key, value);\n } else if (value.toString().length() == 0) {\n jsonObject.put(key, \"\");\n }\n } catch (JSONException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * 查询config.json里的系统值\n *\n * @return systemSettings类\n */\n public systemSetting selectSetting() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setSite_password(jsonObject.optString(\"site_password\"));\n config.setSetup_password(jsonObject.optString(\"setup_password\"));\n config.setBing(jsonObject.optString(\"bind\"));\n config.setPublic_share(jsonObject.optBoolean(\"public_share\"));\n config.setProxy_url(jsonObject.optString(\"proxy_url\"));\n config.setWhitelist(jsonObject.isNull(\"whitelist\") ? null : jsonObject.optString(\"whitelist\"));\n config.setTimeout(jsonObject.optInt(\"timeout\"));\n\n config.setLoginUsername(jsonObject.optString(\"loginUsername\"));\n config.setLoginPassword(jsonObject.optString(\"loginPassword\"));\n\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setIsGetToken(jsonObject.optBoolean(\"isGetToken\"));\n config.setGetTokenPassword(jsonObject.optString(\"getTokenPassword\"));\n config.setContainerName(jsonObject.optString(\"containerName\"));\n\n // 4.0\n config.setIsolated_conv_title(jsonObject.optString(\"isolated_conv_title\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n\n // 4.9\n config.setDisable_signup(jsonObject.optBoolean(\"disable_signup\"));\n config.setAuto_conv_arkose(jsonObject.optBoolean(\"auto_conv_arkose\"));\n config.setProxy_file_service(jsonObject.optBoolean(\"proxy_file_service\"));\n config.setCustom_doh_host(jsonObject.optString(\"custom_doh_host\"));\n\n // 0.4.9.3\n config.setAuto_updateSession(jsonObject.optBoolean(\"auto_updateSession\"));\n config.setAuto_updateTime(jsonObject.optInt(\"auto_updateTime\"));\n config.setAuto_updateNumber(jsonObject.optInt(\"auto_updateNumber\"));\n config.setPandoraNext_outUrl(jsonObject.optString(\"pandoraNext_outUrl\"));\n\n // 0.5.0\n config.setOneAPi_outUrl(jsonObject.optString(\"oneAPi_outUrl\"));\n config.setOneAPi_intoToken(jsonObject.optString(\"oneAPi_intoToken\"));\n\n // 获取 captcha 相关属性\n JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject(\"captcha\")).orElse(new JSONObject());\n validation captchaSetting = new validation(\n captchaJson.optString(\"provider\", \"\"),\n captchaJson.optString(\"site_key\", \"\"),\n captchaJson.optString(\"site_secret\", \"\"),\n captchaJson.optBoolean(\"site_login\", false),\n captchaJson.optBoolean(\"setup_login\", false),\n captchaJson.optBoolean(\"oai_username\", false),\n captchaJson.optBoolean(\"oai_password\", false)\n );\n config.setValidation(captchaSetting);\n\n // 获取 tls 相关属性\n JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject(\"tls\")).orElse(new JSONObject());\n tls tlsSetting = new tls(\n tlsJson.optBoolean(\"enabled\", false),\n tlsJson.optString(\"cert_file\", \"\"),\n tlsJson.optString(\"key_file\", \"\")\n );\n config.setTls(tlsSetting);\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingUrl() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setBing(jsonObject.optString(\"bind\"));\n config.setAutoToken_url(jsonObject.optString(\"autoToken_url\"));\n config.setProxy_api_prefix(jsonObject.optString(\"proxy_api_prefix\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public systemSetting selectSettingLicense() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 将 JSONObject 转换为 Config 类的实例\n systemSetting config = new systemSetting();\n config.setLicense_id(jsonObject.optString(\"license_id\"));\n return config;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public String requireTimeTask(systemSetting tem) {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n\n JSONObject jsonObject = new JSONObject(jsonContent);\n // 0.4.9.3\n updateJsonValue(jsonObject, \"auto_updateSession\", tem.getAuto_updateSession());\n updateJsonValue(jsonObject, \"auto_updateTime\", tem.getAuto_updateTime());\n updateJsonValue(jsonObject, \"auto_updateNumber\", tem.getAuto_updateNumber());\n updateJsonValue(jsonObject, \"pandoraNext_outUrl\", tem.getPandoraNext_outUrl());\n // 0.5.0\n updateJsonValue(jsonObject, \"oneAPi_outUrl\", tem.getOneAPi_outUrl());\n updateJsonValue(jsonObject, \"oneAPi_intoToken\", tem.getOneAPi_intoToken());\n\n // 将修改后的 JSONObject 转换为格式化的 JSON 字符串\n String updatedJson = jsonObject.toString(2);\n Files.write(Paths.get(parent), updatedJson.getBytes());\n return \"修改定时任务和url成功!\";\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"修改定时任务和url失败!\";\n }\n\n public String[] selectOneAPi() {\n String parent = selectFile();\n try {\n // 读取 JSON 文件内容\n String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));\n // 将 JSON 字符串解析为 JSONObject\n JSONObject jsonObject = new JSONObject(jsonContent);\n String[] oneApi = new String[2];\n oneApi[0] = jsonObject.optString(\"oneAPi_outUrl\");\n oneApi[1] = jsonObject.optString(\"oneAPi_intoToken\");\n return oneApi;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n}" }, { "identifier": "MyTaskUtils", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/util/MyTaskUtils.java", "snippet": "@Slf4j\n@Service\npublic class MyTaskUtils {\n private final TaskScheduler taskScheduler;\n @Autowired\n private apiServiceImpl apiService;\n private ScheduledFuture<?> future;\n\n public MyTaskUtils(TaskScheduler taskScheduler) {\n this.taskScheduler = taskScheduler;\n }\n\n\n public void stopTask() {\n if (future != null) {\n future.cancel(true);\n log.info(\"取消定时任务成功!\");\n }\n }\n\n public void changeTask(systemSetting setting) {\n try {\n if (future != null) {\n future.cancel(true);\n }\n String cron = \"0 0 1 */\" + setting.getAuto_updateTime() + \" * ?\";\n future = taskScheduler.schedule(() -> {\n // 这里是任务内容\n System.out.println(\"自定义定时更新session_token开始进行...................\");\n for (int i = 0; i < setting.getAuto_updateNumber(); i++) {\n apiService.updateSession();\n log.info(\"更新session_token开始完成\");\n }\n }, new CronTrigger(cron));\n log.info(\"定时任务开启成功!\");\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n}" } ]
import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.service.impl.systemServiceImpl; import com.tokensTool.pandoraNext.util.MyTaskUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
5,491
package com.tokensTool.pandoraNext.controller; @RestController @RequestMapping("/api") public class taskController { private final MyTaskUtils myTaskUtils; @Autowired
package com.tokensTool.pandoraNext.controller; @RestController @RequestMapping("/api") public class taskController { private final MyTaskUtils myTaskUtils; @Autowired
private systemServiceImpl systemSetting;
2
2023-11-17 11:37:37+00:00
8k
bryan31/Akali
src/main/java/org/dromara/akali/proxy/AkaliByteBuddyProxy.java
[ { "identifier": "AkaliStrategyEnum", "path": "src/main/java/org/dromara/akali/enums/AkaliStrategyEnum.java", "snippet": "public enum AkaliStrategyEnum {\n\n FALLBACK, HOT_METHOD\n}" }, { "identifier": "AkaliMethodManager", "path": "src/main/java/org/dromara/akali/manager/AkaliMethodManager.java", "snippet": "public class AkaliMethodManager {\n\n private static final Logger log = LoggerFactory.getLogger(AkaliMethodManager.class);\n\n private static final Map<String, Tuple2<AkaliStrategyEnum, Annotation>> akaliMethodMap = new HashMap<>();\n\n public static void addMethodStr(String methodStr, Tuple2<AkaliStrategyEnum, Annotation> tuple){\n log.info(\"[AKALI] Register akali method:[{}][{}]\", tuple.r1.name(), methodStr);\n akaliMethodMap.put(methodStr, tuple);\n }\n\n public static Tuple2<AkaliStrategyEnum, Annotation> getAnnoInfo(String methodStr){\n return akaliMethodMap.get(methodStr);\n }\n\n public static boolean contain(String methodStr){\n return akaliMethodMap.containsKey(methodStr);\n }\n}" }, { "identifier": "AkaliRuleManager", "path": "src/main/java/org/dromara/akali/manager/AkaliRuleManager.java", "snippet": "public class AkaliRuleManager {\n private static final Logger log = LoggerFactory.getLogger(AkaliRuleManager.class);\n\n public static void registerFallbackRule(AkaliFallback akaliFallback, Method method){\n String resourceKey = MethodUtil.resolveMethodName(method);\n\n if (!FlowRuleManager.hasConfig(resourceKey)){\n FlowRule rule = new FlowRule();\n\n rule.setResource(resourceKey);\n rule.setGrade(akaliFallback.grade().getGrade());\n rule.setCount(akaliFallback.count());\n rule.setLimitApp(\"default\");\n\n FlowRuleManager.loadRules(ListUtil.toList(rule));\n log.info(\"[AKALI] Add Fallback Rule [{}]\", resourceKey);\n }\n }\n\n public static void registerHotRule(AkaliHot akaliHot, Method method){\n String resourceKey = MethodUtil.resolveMethodName(method);\n\n if (!ParamFlowRuleManager.hasRules(resourceKey)){\n ParamFlowRule rule = new ParamFlowRule();\n\n rule.setResource(MethodUtil.resolveMethodName(method));\n rule.setGrade(akaliHot.grade().getGrade());\n rule.setCount(akaliHot.count());\n rule.setDurationInSec(akaliHot.duration());\n rule.setParamIdx(0);\n\n ParamFlowRuleManager.loadRules(ListUtil.toList(rule));\n log.info(\"[AKALI] Add Hot Rule [{}]\", rule.getResource());\n }\n }\n}" }, { "identifier": "SphEngine", "path": "src/main/java/org/dromara/akali/sph/SphEngine.java", "snippet": "public class SphEngine {\n\n private static final Logger log = LoggerFactory.getLogger(SphEngine.class);\n\n public static Object process(Object bean, Method method, Object[] args, String methodStr, AkaliStrategyEnum akaliStrategyEnum) throws Throwable{\n switch (akaliStrategyEnum){\n case FALLBACK:\n if (SphO.entry(methodStr)){\n try{\n return method.invoke(bean, args);\n }finally {\n SphO.exit();\n }\n }else{\n log.info(\"[AKALI]Trigger fallback strategy for [{}]\", methodStr);\n return AkaliStrategyManager.getStrategy(akaliStrategyEnum).process(bean, method, args);\n }\n case HOT_METHOD:\n String convertParam = DigestUtil.md5Hex(JSON.toJSONString(args));\n Entry entry = null;\n try{\n entry = SphU.entry(methodStr, EntryType.IN, 1, convertParam);\n return method.invoke(bean, args);\n }catch (BlockException e){\n log.info(\"[AKALI]Trigger hotspot strategy for [{}]\", methodStr);\n return AkaliStrategyManager.getStrategy(akaliStrategyEnum).process(bean, method, args);\n }finally {\n if (entry != null){\n entry.exit(1, convertParam);\n }\n }\n default:\n throw new Exception(\"[AKALI] Strategy error!\");\n }\n }\n}" }, { "identifier": "SerialsUtil", "path": "src/main/java/org/dromara/akali/util/SerialsUtil.java", "snippet": "public class SerialsUtil {\n\n\tpublic static int serialInt = 1;\n\n\tprivate static final DecimalFormat format8 = new DecimalFormat(\"00000000\");\n\n\tprivate static final DecimalFormat format12 = new DecimalFormat(\"000000000000\");\n\n\tprivate static final BigInteger divisor;\n\n\tprivate static final BigInteger divisor12;\n\n\tstatic {\n\t\tdivisor = BigInteger.valueOf(19999999L).multiply(BigInteger.valueOf(5));\n\t\tdivisor12 = BigInteger.valueOf(190000000097L).multiply(BigInteger.valueOf(5));\n\t}\n\n\tpublic static String genSerialNo() {\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMddHHmmss\");\n\t\tString strNow = sdf.format(new Date());\n\n\t\t// 生成3位随机数\n\t\tRandom random = new Random();\n\t\tint intRandom = random.nextInt(999);\n\n\t\tString strRandom = String.valueOf(intRandom);\n\t\tint len = strRandom.length();\n\t\tfor (int i = 0; i < (3 - len); i++) {\n\t\t\tstrRandom = \"0\" + strRandom;\n\t\t}\n\t\tString serialStr = SerialsUtil.nextSerial();\n\t\treturn (strNow + strRandom + serialStr);\n\t}\n\n\tpublic static synchronized String nextSerial() {\n\t\tint serial = serialInt++;\n\t\tif (serial > 999) {\n\t\t\tserialInt = 1;\n\t\t\tserial = 1;\n\t\t}\n\t\tString serialStr = serial + \"\";\n\t\tint len = serialStr.length();\n\t\tfor (int i = 0; i < (3 - len); i++) {\n\t\t\tserialStr = \"0\" + serialStr;\n\t\t}\n\n\t\treturn serialStr;\n\t}\n\n\t/**\n\t * 生成一个12位随机数\n\t * @param seed 种子值\n\t * @return String 随机数\n\t */\n\tpublic static String randomNum12(long seed) {\n\t\t// 被除数\n\t\tBigInteger dividend = BigDecimal.valueOf(seed).pow(5).toBigInteger();\n\t\treturn format12.format(dividend.remainder(divisor12));\n\t}\n\n\t/**\n\t * 生成一个8位随机数\n\t * @param seed 种子值\n\t * @return String 随机数\n\t */\n\tpublic static String randomNum8(long seed) {\n\t\t// 被除数\n\t\tBigInteger dividend = BigDecimal.valueOf(seed).pow(5).toBigInteger();\n\t\treturn format8.format(dividend.remainder(divisor));\n\t}\n\n\t/*\n\t * 10进制转32进制(去除0,O,1,I)\n\t */\n\tpublic static String from10To32(String numStr, int size) {\n\t\tlong to = 32;\n\t\tlong num = Long.parseLong(numStr);\n\t\tString jg = \"\";\n\t\twhile (num != 0) {\n\t\t\tswitch (new Long(num % to).intValue()) {\n\t\t\t\tcase 0:\n\t\t\t\t\tjg = \"B\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tjg = \"R\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tjg = \"6\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tjg = \"U\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tjg = \"M\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tjg = \"E\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\t\tjg = \"H\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tjg = \"C\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tjg = \"G\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tjg = \"Q\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tjg = \"A\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\t\tjg = \"8\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tjg = \"3\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tjg = \"S\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tjg = \"J\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tjg = \"Y\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\tjg = \"7\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 17:\n\t\t\t\t\tjg = \"5\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 18:\n\t\t\t\t\tjg = \"W\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\t\tjg = \"9\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tjg = \"F\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tjg = \"T\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 22:\n\t\t\t\t\tjg = \"D\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tjg = \"2\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 24:\n\t\t\t\t\tjg = \"P\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 25:\n\t\t\t\t\tjg = \"Z\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 26:\n\t\t\t\t\tjg = \"N\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 27:\n\t\t\t\t\tjg = \"K\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 28:\n\t\t\t\t\tjg = \"V\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 29:\n\t\t\t\t\tjg = \"X\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 30:\n\t\t\t\t\tjg = \"L\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 31:\n\t\t\t\t\tjg = \"4\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tjg = String.valueOf(num % to) + jg;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnum = num / to;\n\t\t}\n\t\tif (jg.length() < size) {\n\t\t\tint loop = size - jg.length();\n\t\t\tfor (int i = 0; i < loop; i++) {\n\t\t\t\tjg = \"2\" + jg;\n\t\t\t}\n\t\t}\n\t\treturn jg;\n\t}\n\n\t/*\n\t * 10进制转32进制(去除0,O,1,I)\n\t */\n\tpublic static String from10To24(String numStr, int size) {\n\t\tlong to = 24;\n\t\tlong num = Long.parseLong(numStr);\n\t\tString jg = \"\";\n\t\twhile (num != 0) {\n\t\t\tswitch (new Long(num % to).intValue()) {\n\t\t\t\tcase 0:\n\t\t\t\t\tjg = \"B\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tjg = \"R\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tjg = \"U\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tjg = \"M\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\t\tjg = \"E\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 5:\n\t\t\t\t\tjg = \"H\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 6:\n\t\t\t\t\tjg = \"C\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 7:\n\t\t\t\t\tjg = \"G\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 8:\n\t\t\t\t\tjg = \"Q\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 9:\n\t\t\t\t\tjg = \"A\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 10:\n\t\t\t\t\tjg = \"S\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 11:\n\t\t\t\t\tjg = \"J\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 12:\n\t\t\t\t\tjg = \"Y\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 13:\n\t\t\t\t\tjg = \"W\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 14:\n\t\t\t\t\tjg = \"F\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 15:\n\t\t\t\t\tjg = \"T\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\tjg = \"D\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 17:\n\t\t\t\t\tjg = \"P\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 18:\n\t\t\t\t\tjg = \"Z\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 19:\n\t\t\t\t\tjg = \"N\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 20:\n\t\t\t\t\tjg = \"K\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 21:\n\t\t\t\t\tjg = \"V\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 22:\n\t\t\t\t\tjg = \"X\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 23:\n\t\t\t\t\tjg = \"L\" + jg;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tjg = String.valueOf(num % to) + jg;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnum = num / to;\n\t\t}\n\t\tif (jg.length() < size) {\n\t\t\tint loop = size - jg.length();\n\t\t\tfor (int i = 0; i < loop; i++) {\n\t\t\t\tjg = \"B\" + jg;\n\t\t\t}\n\t\t}\n\t\treturn jg;\n\t}\n\n\tpublic static String getUUID() {\n\t\tUUID uuid = UUID.randomUUID();\n\t\tString str = uuid.toString();\n\t\t// 去掉\"-\"符号\n\t\tString temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23)\n\t\t\t\t+ str.substring(24);\n\t\treturn temp;\n\t}\n\n\tpublic static String generateShortUUID() {\n\t\tString str = randomNum8(System.nanoTime());\n\t\treturn from10To24(str, 6);\n\t}\n\n\tpublic static String generateFileUUID() {\n\t\tString str = randomNum12(System.nanoTime());\n\t\treturn from10To32(str, 8);\n\t}\n\n\tpublic static String genToken() {\n\t\treturn from10To32(randomNum12(System.currentTimeMillis()), 8) + from10To32(randomNum12(System.nanoTime()), 8);\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tSet set = new HashSet();\n\t\tString str;\n\t\tfor (int i = 0; i < 300; i++) {\n\t\t\tstr = generateShortUUID();\n\t\t\tSystem.out.println(str);\n\t\t\tset.add(str);\n\t\t}\n\t\tSystem.out.println(set.size());\n\t}\n\n}" } ]
import cn.hutool.core.util.StrUtil; import com.alibaba.csp.sentinel.util.MethodUtil; import net.bytebuddy.implementation.attribute.MethodAttributeAppender; import org.dromara.akali.annotation.AkaliFallback; import org.dromara.akali.annotation.AkaliHot; import org.dromara.akali.enums.AkaliStrategyEnum; import org.dromara.akali.manager.AkaliMethodManager; import org.dromara.akali.manager.AkaliRuleManager; import org.dromara.akali.sph.SphEngine; import org.dromara.akali.util.SerialsUtil; import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.implementation.InvocationHandlerAdapter; import net.bytebuddy.matcher.ElementMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
4,051
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){
AkaliRuleManager.registerFallbackRule((AkaliFallback) anno, method);
2
2023-11-10 07:28:38+00:00
8k
quarkiverse/quarkus-langchain4j
openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/AiServicesTest.java
[ { "identifier": "DEFAULT_TOKEN", "path": "openai/openai-vanilla/deployment/src/test/java/io/quarkiverse/langchain4j/openai/test/WiremockUtils.java", "snippet": "public static final String DEFAULT_TOKEN = \"whatever\";" }, { "identifier": "MessageAssertUtils", "path": "openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/MessageAssertUtils.java", "snippet": "class MessageAssertUtils {\n\n static final TypeReference<Map<String, Object>> MAP_TYPE_REF = new TypeReference<>() {\n };\n private static final InstanceOfAssertFactory<Map, MapAssert<String, String>> MAP_STRING_STRING = map(String.class,\n String.class);\n private static final InstanceOfAssertFactory<List, ListAssert<Map>> LIST_MAP = list(Map.class);\n\n static void assertSingleRequestMessage(Map<String, Object> requestAsMap, String value) {\n assertMessages(requestAsMap, (listOfMessages -> {\n assertThat(listOfMessages).singleElement(as(MAP_STRING_STRING)).satisfies(message -> {\n assertThat(message)\n .containsEntry(\"role\", \"user\")\n .containsEntry(\"content\", value);\n });\n }));\n }\n\n static void assertMultipleRequestMessage(Map<String, Object> requestAsMap, List<MessageContent> messageContents) {\n assertMessages(requestAsMap, listOfMessages -> {\n assertThat(listOfMessages).asInstanceOf(LIST_MAP).hasSize(messageContents.size()).satisfies(l -> {\n for (int i = 0; i < messageContents.size(); i++) {\n MessageContent messageContent = messageContents.get(i);\n assertThat((Map<String, String>) l.get(i)).satisfies(message -> {\n assertThat(message)\n .containsEntry(\"role\", messageContent.getRole());\n if (messageContent.getContent() == null) {\n if (message.containsKey(\"content\")) {\n assertThat(message).containsEntry(\"content\", null);\n }\n } else {\n assertThat(message).containsEntry(\"content\", messageContent.getContent());\n }\n\n });\n }\n });\n });\n }\n\n @SuppressWarnings(\"rawtypes\")\n static void assertMessages(Map<String, Object> requestAsMap, Consumer<List<? extends Map>> messagesAssertions) {\n assertThat(requestAsMap).hasEntrySatisfying(\"messages\",\n o -> assertThat(o).asInstanceOf(list(Map.class)).satisfies(messagesAssertions));\n }\n\n static class MessageContent {\n private final String role;\n private final String content;\n\n public MessageContent(String role, String content) {\n this.role = role;\n this.content = content;\n }\n\n public String getRole() {\n return role;\n }\n\n public String getContent() {\n return content;\n }\n }\n}" }, { "identifier": "WiremockUtils", "path": "openai/openai-vanilla/deployment/src/test/java/io/quarkiverse/langchain4j/openai/test/WiremockUtils.java", "snippet": "public class WiremockUtils {\n\n public static final String DEFAULT_TOKEN = \"whatever\";\n private static final String DEFAULT_CHAT_MESSAGE_CONTENT = \"Hello there, how may I assist you today?\";\n private static final String CHAT_MESSAGE_CONTENT_TEMPLATE;\n private static final String DEFAULT_CHAT_RESPONSE_BODY;\n public static final ResponseDefinitionBuilder CHAT_RESPONSE_WITHOUT_BODY;\n private static final ResponseDefinitionBuilder DEFAULT_CHAT_RESPONSE;\n\n static {\n try (InputStream is = getClassLoader().getResourceAsStream(\"chat/default.json\")) {\n CHAT_MESSAGE_CONTENT_TEMPLATE = new String(is.readAllBytes(), StandardCharsets.UTF_8);\n DEFAULT_CHAT_RESPONSE_BODY = String.format(CHAT_MESSAGE_CONTENT_TEMPLATE, DEFAULT_CHAT_MESSAGE_CONTENT);\n CHAT_RESPONSE_WITHOUT_BODY = aResponse().withHeader(\"Content-Type\", \"application/json\");\n DEFAULT_CHAT_RESPONSE = CHAT_RESPONSE_WITHOUT_BODY\n .withBody(DEFAULT_CHAT_RESPONSE_BODY);\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private static ClassLoader getClassLoader() {\n ClassLoader loader = Thread.currentThread().getContextClassLoader();\n while (loader instanceof QuarkusClassLoader) {\n loader = loader.getParent();\n }\n return loader;\n }\n\n private static ResponseDefinitionBuilder defaultChatCompletionResponse() {\n return DEFAULT_CHAT_RESPONSE;\n }\n\n public static MappingBuilder chatCompletionMapping(String token) {\n return post(urlEqualTo(\"/v1/chat/completions\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static RequestPatternBuilder chatCompletionRequestPattern(String token) {\n return postRequestedFor(urlEqualTo(\"/v1/chat/completions\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static RequestPatternBuilder chatCompletionRequestPattern(String token, String organization) {\n return chatCompletionRequestPattern(token)\n .withHeader(\"OpenAI-Organization\", equalTo(organization));\n }\n\n public static MappingBuilder moderationMapping(String token) {\n return post(urlEqualTo(\"/v1/moderations\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static MappingBuilder defaultChatCompletionsStub() {\n return defaultChatCompletionsStub(DEFAULT_TOKEN);\n }\n\n public static MappingBuilder defaultChatCompletionsStub(String token) {\n return chatCompletionMapping(token)\n .willReturn(defaultChatCompletionResponse());\n }\n\n public static MappingBuilder chatCompletionsMessageContent(Optional<String> token, String messageContent) {\n return chatCompletionMapping(token.orElse(DEFAULT_TOKEN))\n .willReturn(\n CHAT_RESPONSE_WITHOUT_BODY.withBody(String.format(CHAT_MESSAGE_CONTENT_TEMPLATE, messageContent)));\n }\n\n}" } ]
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson; import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson; import static dev.langchain4j.data.message.ChatMessageType.AI; import static dev.langchain4j.data.message.ChatMessageType.SYSTEM; import static dev.langchain4j.data.message.ChatMessageType.USER; import static io.quarkiverse.langchain4j.openai.test.WiremockUtils.DEFAULT_TOKEN; import static java.time.Month.JULY; import static org.acme.examples.aiservices.MessageAssertUtils.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.validation.constraints.NotNull; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.stubbing.ServeEvent; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import dev.langchain4j.agent.tool.Tool; import dev.langchain4j.data.message.ChatMessage; import dev.langchain4j.memory.chat.ChatMemoryProvider; import dev.langchain4j.memory.chat.MessageWindowChatMemory; import dev.langchain4j.model.input.structured.StructuredPrompt; import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.openai.OpenAiModerationModel; import dev.langchain4j.model.output.structured.Description; import dev.langchain4j.service.AiServices; import dev.langchain4j.service.MemoryId; import dev.langchain4j.service.Moderate; import dev.langchain4j.service.ModerationException; import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; import dev.langchain4j.store.memory.chat.ChatMemoryStore; import io.opentelemetry.instrumentation.annotations.SpanAttribute; import io.quarkiverse.langchain4j.openai.test.WiremockUtils; import io.quarkus.test.QuarkusUnitTest;
5,296
assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt_and_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Medley Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with a Mediterranean twist.\\\",\\n\\\"steps\\\": [\\n\\\"Slice and dice, precise!\\\",\\n\\\"Mix and toss, no loss!\\\",\\n\\\"Sprinkle feta, get betta!\\\",\\n\\\"Garnish with olives, no jives!\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives")), "funny"); assertThat(result.title).isEqualTo("Greek Medley Salad"); assertThat(result.description).isNotBlank(); assertThat(result.steps).hasSize(4).satisfies(strings -> { assertThat(strings[0]).contains("Slice and dice"); assertThat(strings[3]).contains("jives"); }); assertThat(result.preparationTimeMinutes).isEqualTo(15); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a very funny chef"), new MessageContent("user", "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"))); } interface ProfessionalChef { @SystemMessage("You are a professional chef. You are friendly, polite and concise.") String answer(String question); } @Test void test_with_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Grilling chicken typically takes around 10-15 minutes per side, depending on the thickness of the chicken. It's important to ensure the internal temperature reaches 165°F (74°C) for safe consumption.")); ProfessionalChef chef = AiServices.create(ProfessionalChef.class, createChatModel()); String result = chef.answer("How long should I grill chicken?"); assertThat(result).contains("Grilling chicken typically"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional chef. You are friendly, polite and concise."), new MessageContent("user", "How long should I grill chicken?"))); } interface Translator { @SystemMessage("You are a professional translator into {{lang}}") @UserMessage("Translate the following text: {{text}}") String translate(@V("text") String text, @V("lang") String language); } @Test void test_with_system_and_user_messages() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Hallo, wie geht es dir?")); Translator translator = AiServices.create(Translator.class, createChatModel()); String translation = translator.translate("Hello, how are you?", "german"); assertThat(translation).isEqualTo("Hallo, wie geht es dir?"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional translator into german"), new MessageContent("user", "Translate the following text: Hello, how are you?"))); } interface Summarizer { @SystemMessage("Summarize every message from user in {{n}} bullet points. Provide only bullet points.") List<String> summarize(@UserMessage String text, int n); } @Test void test_with_system_message_and_user_message_as_argument() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "- AI is a branch of computer science\\n- AI aims to create machines that mimic human intelligence\\n- AI can perform tasks like recognizing patterns, making decisions, and predictions")); Summarizer summarizer = AiServices.create(Summarizer.class, createChatModel()); String text = "AI, or artificial intelligence, is a branch of computer science that aims to create " + "machines that mimic human intelligence. This can range from simple tasks such as recognizing " + "patterns or speech to more complex tasks like making decisions or predictions."; List<String> bulletPoints = summarizer.summarize(text, 3); assertThat(bulletPoints).hasSize(3).satisfies(list -> { assertThat(list.get(0)).contains("branch"); assertThat(list.get(2)).contains("predictions"); }); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "Summarize every message from user in 3 bullet points. Provide only bullet points."), new MessageContent("user", text + "\nYou must put every item on a separate line."))); } interface ChatWithModeration { @Moderate String chat(String message); } @Test void should_throw_when_text_is_flagged() {
package org.acme.examples.aiservices; public class AiServicesTest { @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class).addClasses(WiremockUtils.class, MessageAssertUtils.class)); static WireMockServer wireMockServer; static ObjectMapper mapper; private static OpenAiChatModel createChatModel() { return OpenAiChatModel.builder().baseUrl("http://localhost:8089/v1") .logRequests(true) .logResponses(true) .apiKey("whatever").build(); } private static OpenAiModerationModel createModerationModel() { return OpenAiModerationModel.builder().baseUrl("http://localhost:8089/v1") .logRequests(true) .logResponses(true) .apiKey("whatever").build(); } private static MessageWindowChatMemory createChatMemory() { return MessageWindowChatMemory.withMaxMessages(10); } @BeforeAll static void beforeAll() { wireMockServer = new WireMockServer(options().port(8089)); wireMockServer.start(); mapper = new ObjectMapper(); } @AfterAll static void afterAll() { wireMockServer.stop(); } @BeforeEach void setup() { wireMockServer.resetAll(); wireMockServer.stubFor(WiremockUtils.defaultChatCompletionsStub()); } interface Assistant { String chat(String message); } @Test public void test_simple_instruction_with_single_argument_and_no_annotations() throws IOException { String result = AiServices.create(Assistant.class, createChatModel()).chat("Tell me a joke about developers"); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about developers"); } interface Humorist { @UserMessage("Tell me a joke about {{wrapper.topic}}") String joke(@SpanAttribute @NotNull Wrapper wrapper); } public record Wrapper(String topic) { } @Test public void test_simple_instruction_with_single_argument() throws IOException { String result = AiServices.create(Humorist.class, createChatModel()).joke(new Wrapper("programmers")); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about programmers"); } interface DateTimeExtractor { @UserMessage("Extract date from {{it}}") LocalDate extractDateFrom(String text); @UserMessage("Extract time from {{it}}") LocalTime extractTimeFrom(String text); @UserMessage("Extract date and time from {{it}}") LocalDateTime extractDateTimeFrom(String text); } @Test void test_extract_date() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "1968-07-04")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalDate result = dateTimeExtractor.extractDateFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalDate.of(1968, JULY, 4)); assertSingleRequestMessage(getRequestAsMap(), "Extract date from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 2023-12-31"); } @Test void test_extract_time() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "23:45:00")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalTime result = dateTimeExtractor.extractTimeFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalTime.of(23, 45, 0)); assertSingleRequestMessage(getRequestAsMap(), "Extract time from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 23:59:59"); } @Test void test_extract_date_time() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "1968-07-04T23:45:00")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalDateTime result = dateTimeExtractor.extractDateTimeFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalDateTime.of(1968, JULY, 4, 23, 45, 0)); assertSingleRequestMessage(getRequestAsMap(), "Extract date and time from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 2023-12-31T23:59:59"); } enum Sentiment { POSITIVE, NEUTRAL, NEGATIVE } interface SentimentAnalyzer { @UserMessage("Analyze sentiment of {{it}}") Sentiment analyzeSentimentOf(String text); } @Test void test_extract_enum() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "POSITIVE")); SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, createChatModel()); Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf( "This LaptopPro X15 is wicked fast and that 4K screen is a dream."); assertThat(sentiment).isEqualTo(Sentiment.POSITIVE); assertSingleRequestMessage(getRequestAsMap(), "Analyze sentiment of This LaptopPro X15 is wicked fast and that 4K screen is a dream.\nYou must answer strictly in the following format: one of [POSITIVE, NEUTRAL, NEGATIVE]"); } record Person(String firstName, String lastName, LocalDate birthDate) { @JsonCreator public Person { } } interface PersonExtractor { @UserMessage("Extract information about a person from {{it}}") Person extractPersonFrom(String text); } @Test void test_extract_custom_POJO() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"firstName\\\": \\\"John\\\",\\n\\\"lastName\\\": \\\"Doe\\\",\\n\\\"birthDate\\\": \\\"1968-07-04\\\"\\n}")); PersonExtractor personExtractor = AiServices.create(PersonExtractor.class, createChatModel()); String text = "In 1968, amidst the fading echoes of Independence Day, " + "a child named John arrived under the calm evening sky. " + "This newborn, bearing the surname Doe, marked the start of a new journey."; Person result = personExtractor.extractPersonFrom(text); assertThat(result.firstName).isEqualTo("John"); assertThat(result.lastName).isEqualTo("Doe"); assertThat(result.birthDate).isEqualTo(LocalDate.of(1968, JULY, 4)); assertSingleRequestMessage(getRequestAsMap(), "Extract information about a person from In 1968, amidst the fading echoes of Independence Day, a child named John arrived under the calm evening sky. This newborn, bearing the surname Doe, marked the start of a new journey.\nYou must answer strictly in the following JSON format: {\n\"firstName\": (type: string),\n\"lastName\": (type: string),\n\"birthDate\": (type: date string (2023-12-31)),\n}"); } static class Recipe { private String title; private String description; @Description("each step should be described in 4 words, steps should rhyme") private String[] steps; private Integer preparationTimeMinutes; } @StructuredPrompt("Create a recipe of a {{dish}} that can be prepared using only {{ingredients}}") static class CreateRecipePrompt { private final String dish; private final List<String> ingredients; public CreateRecipePrompt(String dish, List<String> ingredients) { this.dish = dish; this.ingredients = ingredients; } public String getDish() { return dish; } public List<String> getIngredients() { return ingredients; } } interface Chef { @UserMessage("Create recipe using only {{it}}") Recipe createRecipeFrom(String... ingredients); Recipe createRecipeFrom(CreateRecipePrompt prompt); @SystemMessage("You are a very {{character}} chef") Recipe createRecipeFrom(@UserMessage CreateRecipePrompt prompt, String character); } @Test void test_create_recipe_from_list_of_ingredients() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with Mediterranean flavors.\\\",\\n\\\"steps\\\": [\\n\\\"Chop, dice, and slice.\\\",\\n\\\"Mix veggies with feta.\\\",\\n\\\"Drizzle with olive oil.\\\",\\n\\\"Toss gently, then serve.\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef.createRecipeFrom("cucumber", "tomato", "feta", "onion", "olives"); assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create recipe using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with Mediterranean flavors.\\\",\\n\\\"steps\\\": [\\n\\\"Chop, dice, and slice.\\\",\\n\\\"Mix veggies with feta.\\\",\\n\\\"Drizzle with olive oil.\\\",\\n\\\"Toss gently, then serve.\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives"))); assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt_and_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Medley Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with a Mediterranean twist.\\\",\\n\\\"steps\\\": [\\n\\\"Slice and dice, precise!\\\",\\n\\\"Mix and toss, no loss!\\\",\\n\\\"Sprinkle feta, get betta!\\\",\\n\\\"Garnish with olives, no jives!\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives")), "funny"); assertThat(result.title).isEqualTo("Greek Medley Salad"); assertThat(result.description).isNotBlank(); assertThat(result.steps).hasSize(4).satisfies(strings -> { assertThat(strings[0]).contains("Slice and dice"); assertThat(strings[3]).contains("jives"); }); assertThat(result.preparationTimeMinutes).isEqualTo(15); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a very funny chef"), new MessageContent("user", "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"))); } interface ProfessionalChef { @SystemMessage("You are a professional chef. You are friendly, polite and concise.") String answer(String question); } @Test void test_with_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Grilling chicken typically takes around 10-15 minutes per side, depending on the thickness of the chicken. It's important to ensure the internal temperature reaches 165°F (74°C) for safe consumption.")); ProfessionalChef chef = AiServices.create(ProfessionalChef.class, createChatModel()); String result = chef.answer("How long should I grill chicken?"); assertThat(result).contains("Grilling chicken typically"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional chef. You are friendly, polite and concise."), new MessageContent("user", "How long should I grill chicken?"))); } interface Translator { @SystemMessage("You are a professional translator into {{lang}}") @UserMessage("Translate the following text: {{text}}") String translate(@V("text") String text, @V("lang") String language); } @Test void test_with_system_and_user_messages() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Hallo, wie geht es dir?")); Translator translator = AiServices.create(Translator.class, createChatModel()); String translation = translator.translate("Hello, how are you?", "german"); assertThat(translation).isEqualTo("Hallo, wie geht es dir?"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional translator into german"), new MessageContent("user", "Translate the following text: Hello, how are you?"))); } interface Summarizer { @SystemMessage("Summarize every message from user in {{n}} bullet points. Provide only bullet points.") List<String> summarize(@UserMessage String text, int n); } @Test void test_with_system_message_and_user_message_as_argument() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "- AI is a branch of computer science\\n- AI aims to create machines that mimic human intelligence\\n- AI can perform tasks like recognizing patterns, making decisions, and predictions")); Summarizer summarizer = AiServices.create(Summarizer.class, createChatModel()); String text = "AI, or artificial intelligence, is a branch of computer science that aims to create " + "machines that mimic human intelligence. This can range from simple tasks such as recognizing " + "patterns or speech to more complex tasks like making decisions or predictions."; List<String> bulletPoints = summarizer.summarize(text, 3); assertThat(bulletPoints).hasSize(3).satisfies(list -> { assertThat(list.get(0)).contains("branch"); assertThat(list.get(2)).contains("predictions"); }); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "Summarize every message from user in 3 bullet points. Provide only bullet points."), new MessageContent("user", text + "\nYou must put every item on a separate line."))); } interface ChatWithModeration { @Moderate String chat(String message); } @Test void should_throw_when_text_is_flagged() {
wireMockServer.stubFor(WiremockUtils.moderationMapping(DEFAULT_TOKEN)
0
2023-11-13 09:10:27+00:00
8k
qiusunshine/xiu
VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/factory/HttpDefaultDataSourceFactory.java
[ { "identifier": "DefaultDataSource", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultDataSource.java", "snippet": "public final class DefaultDataSource implements DataSource {\n\n private static final String TAG = \"DefaultDataSource\";\n\n private static final String SCHEME_ASSET = \"asset\";\n private static final String SCHEME_CONTENT = \"content\";\n private static final String SCHEME_RTMP = \"rtmp\";\n private static final String SCHEME_UDP = \"udp\";\n private static final String SCHEME_DATA = DataSchemeDataSource.SCHEME_DATA;\n private static final String SCHEME_RAW = RawResourceDataSource.RAW_RESOURCE_SCHEME;\n private static final String SCHEME_ANDROID_RESOURCE = ContentResolver.SCHEME_ANDROID_RESOURCE;\n\n private final Context context;\n private final List<TransferListener> transferListeners;\n private final DataSource baseDataSource;\n\n // Lazily initialized.\n @Nullable private DataSource fileDataSource;\n @Nullable private DataSource assetDataSource;\n @Nullable private DataSource contentDataSource;\n @Nullable private DataSource rtmpDataSource;\n @Nullable private DataSource udpDataSource;\n @Nullable private DataSource dataSchemeDataSource;\n @Nullable private DataSource rawResourceDataSource;\n\n @Nullable private DataSource dataSource;\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n */\n public DefaultDataSource(Context context, boolean allowCrossProtocolRedirects) {\n this(\n context,\n /* userAgent= */ null,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,\n allowCrossProtocolRedirects);\n }\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP\n * to HTTPS and vice versa) are enabled when fetching remote data.\n */\n public DefaultDataSource(\n Context context, @Nullable String userAgent, boolean allowCrossProtocolRedirects) {\n this(\n context,\n userAgent,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,\n com.google.android.exoplayer2.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,\n allowCrossProtocolRedirects);\n }\n\n /**\n * Constructs a new instance, optionally configured to follow cross-protocol redirects.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param connectTimeoutMillis The connection timeout that should be used when requesting remote\n * data, in milliseconds. A timeout of zero is interpreted as an infinite timeout.\n * @param readTimeoutMillis The read timeout that should be used when requesting remote data, in\n * milliseconds. A timeout of zero is interpreted as an infinite timeout.\n * @param allowCrossProtocolRedirects Whether cross-protocol redirects (i.e. redirects from HTTP\n * to HTTPS and vice versa) are enabled when fetching remote data.\n */\n public DefaultDataSource(\n Context context,\n @Nullable String userAgent,\n int connectTimeoutMillis,\n int readTimeoutMillis,\n boolean allowCrossProtocolRedirects) {\n this(\n context,\n new DefaultHttpDataSource.Factory()\n .setUserAgent(userAgent)\n .setConnectTimeoutMs(connectTimeoutMillis)\n .setReadTimeoutMs(readTimeoutMillis)\n .setAllowCrossProtocolRedirects(allowCrossProtocolRedirects)\n .createDataSource());\n }\n\n /**\n * Constructs a new instance that delegates to a provided {@link DataSource} for URI schemes other\n * than file, asset and content.\n *\n * @param context A context.\n * @param baseDataSource A {@link DataSource} to use for URI schemes other than file, asset and\n * content. This {@link DataSource} should normally support at least http(s).\n */\n public DefaultDataSource(Context context, DataSource baseDataSource) {\n this.context = context.getApplicationContext();\n this.baseDataSource = Assertions.checkNotNull(baseDataSource);\n transferListeners = new ArrayList<>();\n }\n\n @Override\n public void addTransferListener(TransferListener transferListener) {\n Assertions.checkNotNull(transferListener);\n baseDataSource.addTransferListener(transferListener);\n transferListeners.add(transferListener);\n maybeAddListenerToDataSource(fileDataSource, transferListener);\n maybeAddListenerToDataSource(assetDataSource, transferListener);\n maybeAddListenerToDataSource(contentDataSource, transferListener);\n maybeAddListenerToDataSource(rtmpDataSource, transferListener);\n maybeAddListenerToDataSource(udpDataSource, transferListener);\n maybeAddListenerToDataSource(dataSchemeDataSource, transferListener);\n maybeAddListenerToDataSource(rawResourceDataSource, transferListener);\n }\n\n @Override\n public long open(DataSpec dataSpec) throws IOException {\n Assertions.checkState(dataSource == null);\n // Choose the correct source for the scheme.\n String scheme = dataSpec.uri.getScheme();\n if (Util.isLocalFileUri(dataSpec.uri)) {\n String uriPath = dataSpec.uri.getPath();\n if (uriPath != null && uriPath.startsWith(\"/android_asset/\")) {\n dataSource = getAssetDataSource();\n } else {\n dataSource = getFileDataSource();\n }\n } else if (SCHEME_ASSET.equals(scheme)) {\n dataSource = getAssetDataSource();\n } else if (SCHEME_CONTENT.equals(scheme)) {\n dataSource = getContentDataSource();\n } else if (SCHEME_RTMP.equals(scheme)) {\n dataSource = getRtmpDataSource();\n } else if (SCHEME_UDP.equals(scheme)) {\n dataSource = getUdpDataSource();\n } else if (SCHEME_DATA.equals(scheme)) {\n dataSource = getDataSchemeDataSource();\n } else if (SCHEME_RAW.equals(scheme) || SCHEME_ANDROID_RESOURCE.equals(scheme)) {\n dataSource = getRawResourceDataSource();\n } else {\n dataSource = baseDataSource;\n }\n // Open the source and return.\n return dataSource.open(dataSpec);\n }\n\n @Override\n public int read(byte[] buffer, int offset, int length) throws IOException {\n return Assertions.checkNotNull(dataSource).read(buffer, offset, length);\n }\n\n @Override\n @Nullable\n public Uri getUri() {\n return dataSource == null ? null : dataSource.getUri();\n }\n\n @Override\n public Map<String, List<String>> getResponseHeaders() {\n return dataSource == null ? new HashMap<String, List<String>>() : dataSource.getResponseHeaders();\n }\n\n @Override\n public void close() throws IOException {\n if (dataSource != null) {\n try {\n dataSource.close();\n } finally {\n dataSource = null;\n }\n }\n }\n\n private DataSource getUdpDataSource() {\n if (udpDataSource == null) {\n udpDataSource = new UdpDataSource();\n addListenersToDataSource(udpDataSource);\n }\n return udpDataSource;\n }\n\n private DataSource getFileDataSource() {\n if (fileDataSource == null) {\n fileDataSource = new FileDataSource();\n addListenersToDataSource(fileDataSource);\n }\n return fileDataSource;\n }\n\n private DataSource getAssetDataSource() {\n if (assetDataSource == null) {\n assetDataSource = new AssetDataSource(context);\n addListenersToDataSource(assetDataSource);\n }\n return assetDataSource;\n }\n\n private DataSource getContentDataSource() {\n if (contentDataSource == null) {\n contentDataSource = new ContentDataSource(context);\n addListenersToDataSource(contentDataSource);\n }\n return contentDataSource;\n }\n\n private DataSource getRtmpDataSource() {\n if (rtmpDataSource == null) {\n try {\n Class<?> clazz = Class.forName(\"com.google.android.exoplayer2.ext.rtmp.RtmpDataSource\");\n rtmpDataSource = (DataSource) clazz.getConstructor().newInstance();\n addListenersToDataSource(rtmpDataSource);\n } catch (ClassNotFoundException e) {\n // Expected if the app was built without the RTMP extension.\n Log.w(TAG, \"Attempting to play RTMP stream without depending on the RTMP extension\");\n } catch (Exception e) {\n // The RTMP extension is present, but instantiation failed.\n throw new RuntimeException(\"Error instantiating RTMP extension\", e);\n }\n if (rtmpDataSource == null) {\n rtmpDataSource = baseDataSource;\n }\n }\n return rtmpDataSource;\n }\n\n private DataSource getDataSchemeDataSource() {\n if (dataSchemeDataSource == null) {\n dataSchemeDataSource = new DataSchemeDataSource();\n addListenersToDataSource(dataSchemeDataSource);\n }\n return dataSchemeDataSource;\n }\n\n private DataSource getRawResourceDataSource() {\n if (rawResourceDataSource == null) {\n rawResourceDataSource = new RawResourceDataSource(context);\n addListenersToDataSource(rawResourceDataSource);\n }\n return rawResourceDataSource;\n }\n\n private void addListenersToDataSource(DataSource dataSource) {\n for (int i = 0; i < transferListeners.size(); i++) {\n dataSource.addTransferListener(transferListeners.get(i));\n }\n }\n\n private void maybeAddListenerToDataSource(\n @Nullable DataSource dataSource, TransferListener listener) {\n if (dataSource != null) {\n dataSource.addTransferListener(listener);\n }\n }\n}" }, { "identifier": "DefaultDataSourceFactory", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultDataSourceFactory.java", "snippet": "public final class DefaultDataSourceFactory implements Factory {\n\n private final Context context;\n @Nullable private final TransferListener listener;\n private final Factory baseDataSourceFactory;\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n */\n public DefaultDataSourceFactory(Context context) {\n this(context, /* userAgent= */ (String) null, /* listener= */ null);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n */\n public DefaultDataSourceFactory(Context context, @Nullable String userAgent) {\n this(context, userAgent, /* listener= */ null);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param userAgent The user agent that will be used when requesting remote data, or {@code null}\n * to use the default user agent of the underlying platform.\n * @param listener An optional listener.\n */\n public DefaultDataSourceFactory(\n Context context, @Nullable String userAgent, @Nullable TransferListener listener) {\n this(context, listener, new DefaultHttpDataSource.Factory().setUserAgent(userAgent));\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param baseDataSourceFactory A {@link Factory} to be used to create a base {@link DataSource}\n * for {@link com.google.android.exoplayer2.upstream.DefaultDataSource}.\n * @see com.google.android.exoplayer2.upstream.DefaultDataSource#DefaultDataSource(Context, DataSource)\n */\n public DefaultDataSourceFactory(Context context, Factory baseDataSourceFactory) {\n this(context, /* listener= */ null, baseDataSourceFactory);\n }\n\n /**\n * Creates an instance.\n *\n * @param context A context.\n * @param listener An optional listener.\n * @param baseDataSourceFactory A {@link Factory} to be used to create a base {@link DataSource}\n * for {@link com.google.android.exoplayer2.upstream.DefaultDataSource}.\n * @see com.google.android.exoplayer2.upstream.DefaultDataSource#DefaultDataSource(Context, DataSource)\n */\n public DefaultDataSourceFactory(\n Context context,\n @Nullable TransferListener listener,\n Factory baseDataSourceFactory) {\n this.context = context.getApplicationContext();\n this.listener = listener;\n this.baseDataSourceFactory = baseDataSourceFactory;\n }\n\n @Override\n public com.google.android.exoplayer2.upstream.DefaultDataSource createDataSource() {\n com.google.android.exoplayer2.upstream.DefaultDataSource dataSource =\n new DefaultDataSource(context, baseDataSourceFactory.createDataSource());\n if (listener != null) {\n dataSource.addTransferListener(listener);\n }\n return dataSource;\n }\n}" }, { "identifier": "HttpsUtils", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/HttpsUtils.java", "snippet": "public class HttpsUtils {\n public static X509TrustManager UnSafeTrustManager = new X509TrustManager() {\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n public static HostnameVerifier UnSafeHostnameVerifier = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n\n public HttpsUtils() {\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory() {\n return getSslSocketFactoryBase((X509TrustManager)null, (InputStream)null, (String)null);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(X509TrustManager trustManager) {\n return getSslSocketFactoryBase(trustManager, (InputStream)null, (String)null);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream... certificates) {\n return getSslSocketFactoryBase((X509TrustManager)null, (InputStream)null, (String)null, certificates);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream bksFile, String password, InputStream... certificates) {\n return getSslSocketFactoryBase((X509TrustManager)null, bksFile, password, certificates);\n }\n\n public static HttpsUtils.SSLParams getSslSocketFactory(InputStream bksFile, String password, X509TrustManager trustManager) {\n return getSslSocketFactoryBase(trustManager, bksFile, password);\n }\n\n private static HttpsUtils.SSLParams getSslSocketFactoryBase(X509TrustManager trustManager, InputStream bksFile, String password, InputStream... certificates) {\n HttpsUtils.SSLParams sslParams = new HttpsUtils.SSLParams();\n\n try {\n KeyManager[] keyManagers = prepareKeyManager(bksFile, password);\n TrustManager[] trustManagers = prepareTrustManager(certificates);\n X509TrustManager manager;\n if (trustManager != null) {\n manager = trustManager;\n } else if (trustManagers != null) {\n manager = chooseTrustManager(trustManagers);\n } else {\n manager = UnSafeTrustManager;\n }\n\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(keyManagers, new TrustManager[]{manager}, (SecureRandom)null);\n sslParams.sSLSocketFactory = sslContext.getSocketFactory();\n sslParams.trustManager = manager;\n return sslParams;\n } catch (NoSuchAlgorithmException var9) {\n throw new AssertionError(var9);\n } catch (KeyManagementException var10) {\n throw new AssertionError(var10);\n }\n }\n\n private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {\n try {\n if (bksFile != null && password != null) {\n KeyStore clientKeyStore = KeyStore.getInstance(\"BKS\");\n clientKeyStore.load(bksFile, password.toCharArray());\n KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n kmf.init(clientKeyStore, password.toCharArray());\n return kmf.getKeyManagers();\n } else {\n return null;\n }\n } catch (Exception var4) {\n var4.printStackTrace();\n return null;\n }\n }\n\n private static TrustManager[] prepareTrustManager(InputStream... certificates) {\n if (certificates != null && certificates.length > 0) {\n try {\n CertificateFactory certificateFactory = CertificateFactory.getInstance(\"X.509\");\n KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());\n keyStore.load((LoadStoreParameter)null);\n int index = 0;\n InputStream[] var4 = certificates;\n int var5 = certificates.length;\n\n for(int var6 = 0; var6 < var5; ++var6) {\n InputStream certStream = var4[var6];\n String certificateAlias = Integer.toString(index++);\n Certificate cert = certificateFactory.generateCertificate(certStream);\n keyStore.setCertificateEntry(certificateAlias, cert);\n\n try {\n if (certStream != null) {\n certStream.close();\n }\n } catch (IOException var11) {\n var11.printStackTrace();\n }\n }\n\n TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n tmf.init(keyStore);\n return tmf.getTrustManagers();\n } catch (Exception var12) {\n var12.printStackTrace();\n return null;\n }\n } else {\n return null;\n }\n }\n\n private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {\n TrustManager[] var1 = trustManagers;\n int var2 = trustManagers.length;\n\n for(int var3 = 0; var3 < var2; ++var3) {\n TrustManager trustManager = var1[var3];\n if (trustManager instanceof X509TrustManager) {\n return (X509TrustManager)trustManager;\n }\n }\n\n return null;\n }\n\n public static class SSLParams {\n public SSLSocketFactory sSLSocketFactory;\n public X509TrustManager trustManager;\n\n public SSLParams() {\n }\n }\n}" }, { "identifier": "DEFAULT_READ_TIMEOUT_MILLIS", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultHttpDataSource.java", "snippet": "public static final int DEFAULT_READ_TIMEOUT_MILLIS = 8 * 1000;" } ]
import android.content.Context; import android.net.Uri; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.util.Util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSource; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSourceFactory; import chuangyuan.ycj.videolibrary.upstream.HttpsUtils; import okhttp3.OkHttpClient; import okhttp3.brotli.BrotliInterceptor; import static chuangyuan.ycj.videolibrary.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS;
5,111
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险 HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); OkHttpClient okHttpClient = null; if (uri != null) { String url = uri.toString(); if (url.contains("://127.0.0.1") || url.contains("://192.168.") || url.contains("://0.0.0.") || url.contains("://10.")) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(BrotliInterceptor.INSTANCE) .sslSocketFactory(sslParams1.sSLSocketFactory, HttpsUtils.UnSafeTrustManager) .hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier)
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险 HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); OkHttpClient okHttpClient = null; if (uri != null) { String url = uri.toString(); if (url.contains("://127.0.0.1") || url.contains("://192.168.") || url.contains("://0.0.0.") || url.contains("://10.")) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(BrotliInterceptor.INSTANCE) .sslSocketFactory(sslParams1.sSLSocketFactory, HttpsUtils.UnSafeTrustManager) .hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier)
.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS * 2, TimeUnit.MILLISECONDS)
3
2023-11-10 14:28:40+00:00
8k
noear/folkmq
folkmq-test/src/test/java/features/cases/TestCase18_batch_subscribe.java
[ { "identifier": "MqClientDefault", "path": "folkmq/src/main/java/org/noear/folkmq/client/MqClientDefault.java", "snippet": "public class MqClientDefault implements MqClientInternal {\n private static final Logger log = LoggerFactory.getLogger(MqClientDefault.class);\n\n //服务端地址\n private final List<String> serverUrls;\n //客户端会话\n private ClusterClientSession clientSession;\n //客户端监听\n private final MqClientListener clientListener;\n //客户端配置\n private ClientConfigHandler clientConfigHandler;\n //订阅字典\n protected Map<String, MqSubscription> subscriptionMap = new HashMap<>();\n\n //自动回执\n protected boolean autoAcknowledge = true;\n\n public MqClientDefault(String... urls) {\n this.serverUrls = new ArrayList<>();\n this.clientListener = new MqClientListener(this);\n\n for (String url : urls) {\n url = url.replaceAll(\"folkmq:ws://\", \"sd:ws://\");\n url = url.replaceAll(\"folkmq://\", \"sd:tcp://\");\n serverUrls.add(url);\n }\n }\n\n @Override\n public MqClient connect() throws IOException {\n clientSession = (ClusterClientSession) SocketD.createClusterClient(serverUrls)\n .config(c -> c.fragmentSize(MqConstants.MAX_FRAGMENT_SIZE))\n .config(clientConfigHandler)\n .listen(clientListener)\n .open();\n\n return this;\n }\n\n @Override\n public void disconnect() throws IOException {\n clientSession.close();\n }\n\n @Override\n public MqClient config(ClientConfigHandler configHandler) {\n clientConfigHandler = configHandler;\n return this;\n }\n\n /**\n * 自动回执\n */\n @Override\n public MqClient autoAcknowledge(boolean auto) {\n this.autoAcknowledge = auto;\n return this;\n }\n\n /**\n * 订阅主题\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param consumerHandler 消费处理\n */\n @Override\n public void subscribe(String topic, String consumerGroup, MqConsumeHandler consumerHandler) throws IOException {\n MqSubscription subscription = new MqSubscription(topic, consumerGroup, consumerHandler);\n\n subscriptionMap.put(topic, subscription);\n\n if (clientSession != null) {\n for (ClientSession session : clientSession.getSessionAll()) {\n //如果有连接会话,则执行订阅\n Entity entity = new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_TOPIC, subscription.getTopic())\n .metaPut(MqConstants.MQ_META_CONSUMER_GROUP, subscription.getConsumerGroup())\n .at(MqConstants.BROKER_AT_SERVER_ALL);\n\n //使用 Qos1\n session.sendAndRequest(MqConstants.MQ_EVENT_SUBSCRIBE, entity).await();\n\n log.info(\"Client subscribe successfully: {}#{}, sessionId={}\", topic, consumerGroup, session.sessionId());\n }\n }\n }\n\n @Override\n public void unsubscribe(String topic, String consumerGroup) throws IOException {\n subscriptionMap.remove(topic);\n\n if (clientSession != null) {\n for (ClientSession session : clientSession.getSessionAll()) {\n //如果有连接会话\n Entity entity = new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_TOPIC, topic)\n .metaPut(MqConstants.MQ_META_CONSUMER_GROUP, consumerGroup)\n .at(MqConstants.BROKER_AT_SERVER_ALL);\n\n //使用 Qos1\n session.sendAndRequest(MqConstants.MQ_EVENT_UNSUBSCRIBE, entity).await();\n\n log.info(\"Client unsubscribe successfully: {}#{}, sessionId={}\", topic, consumerGroup, session.sessionId());\n }\n }\n }\n\n @Override\n public void publish(String topic, IMqMessage message) throws IOException {\n if (clientSession == null) {\n throw new SocketdConnectionException(\"Not connected!\");\n }\n\n ClientSession session = clientSession.getSessionOne();\n if (session == null || session.isValid() == false) {\n throw new SocketdException(\"No session is available!\");\n }\n\n Entity entity = MqUtils.publishEntityBuild(topic, message);\n\n if (message.getQos() > 0) {\n //::Qos1\n Entity resp = session.sendAndRequest(MqConstants.MQ_EVENT_PUBLISH, entity).await();\n\n int confirm = Integer.parseInt(resp.metaOrDefault(MqConstants.MQ_META_CONFIRM, \"0\"));\n if (confirm != 1) {\n String messsage = \"Client message publish confirm failed: \" + resp.dataAsString();\n throw new FolkmqException(messsage);\n }\n } else {\n //::Qos0\n session.send(MqConstants.MQ_EVENT_PUBLISH, entity);\n }\n }\n\n /**\n * 发布消息\n *\n * @param topic 主题\n * @param message 消息\n */\n @Override\n public CompletableFuture<Boolean> publishAsync(String topic, IMqMessage message) throws IOException {\n if (clientSession == null) {\n throw new SocketdConnectionException(\"Not connected!\");\n }\n\n ClientSession session = clientSession.getSessionOne();\n if (session == null || session.isValid() == false) {\n throw new SocketdException(\"No session is available!\");\n }\n\n CompletableFuture<Boolean> future = new CompletableFuture<>();\n Entity entity = MqUtils.publishEntityBuild(topic, message);\n\n if (message.getQos() > 0) {\n //::Qos1\n session.sendAndRequest(MqConstants.MQ_EVENT_PUBLISH, entity).thenReply(r -> {\n int confirm = Integer.parseInt(r.metaOrDefault(MqConstants.MQ_META_CONFIRM, \"0\"));\n if (confirm == 1) {\n future.complete(true);\n } else {\n String messsage = \"Client message publish confirm failed: \" + r.dataAsString();\n future.completeExceptionally(new FolkmqException(messsage));\n }\n });\n } else {\n //::Qos0\n session.send(MqConstants.MQ_EVENT_PUBLISH, entity);\n future.complete(true);\n }\n\n return future;\n }\n\n @Override\n public void unpublish(String topic, String tid) throws IOException {\n if (clientSession == null) {\n throw new SocketdConnectionException(\"Not connected!\");\n }\n\n ClientSession session = clientSession.getSessionOne();\n if (session == null || session.isValid() == false) {\n throw new SocketdException(\"No session is available!\");\n }\n\n Entity entity = new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_TOPIC, topic)\n .metaPut(MqConstants.MQ_META_TID, tid)\n .at(MqConstants.BROKER_AT_SERVER_ALL);\n\n //::Qos1\n Entity resp = session.sendAndRequest(MqConstants.MQ_EVENT_UNPUBLISH, entity).await();\n\n int confirm = Integer.parseInt(resp.metaOrDefault(MqConstants.MQ_META_CONFIRM, \"0\"));\n if (confirm != 1) {\n String messsage = \"Client message unpublish confirm failed: \" + resp.dataAsString();\n throw new FolkmqException(messsage);\n }\n }\n\n @Override\n public CompletableFuture<Boolean> unpublishAsync(String topic, String tid) throws IOException {\n if (clientSession == null) {\n throw new SocketdConnectionException(\"Not connected!\");\n }\n\n ClientSession session = clientSession.getSessionOne();\n if (session == null || session.isValid() == false) {\n throw new SocketdException(\"No session is available!\");\n }\n\n CompletableFuture<Boolean> future = new CompletableFuture<>();\n Entity entity = new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_TOPIC, topic)\n .metaPut(MqConstants.MQ_META_TID, tid)\n .at(MqConstants.BROKER_AT_SERVER_ALL);\n\n //::Qos1\n session.sendAndRequest(MqConstants.MQ_EVENT_UNPUBLISH, entity).thenReply(r -> {\n int confirm = Integer.parseInt(r.metaOrDefault(MqConstants.MQ_META_CONFIRM, \"0\"));\n if (confirm == 1) {\n future.complete(true);\n } else {\n String messsage = \"Client message unpublish confirm failed: \" + r.dataAsString();\n future.completeExceptionally(new FolkmqException(messsage));\n }\n });\n\n return future;\n }\n\n\n /**\n * 消费回执\n *\n * @param message 收到的消息\n * @param isOk 回执\n */\n @Override\n public void acknowledge(Session session, Message from, MqMessageReceivedImpl message, boolean isOk) throws IOException {\n //发送“回执”,向服务端反馈消费情况\n if (message.getQos() > 0) {\n if (session.isValid()) {\n session.replyEnd(from, new StringEntity(\"\")\n .metaPut(MqConstants.MQ_META_ACK, isOk ? \"1\" : \"0\"));\n }\n }\n }\n\n /**\n * 关闭\n */\n @Override\n public void close() throws IOException {\n clientSession.close();\n }\n}" }, { "identifier": "MqMessage", "path": "folkmq/src/main/java/org/noear/folkmq/client/MqMessage.java", "snippet": "public class MqMessage implements IMqMessage {\n private String tid;\n private String content;\n private Date scheduled;\n private int qos = 1;\n\n public MqMessage(String content){\n this.tid = StrUtils.guid();\n this.content = content;\n }\n\n @Override\n public String getTid() {\n return tid;\n }\n\n public String getContent() {\n return content;\n }\n\n public Date getScheduled() {\n return scheduled;\n }\n\n public int getQos() {\n return qos;\n }\n\n public MqMessage scheduled(Date scheduled) {\n this.scheduled = scheduled;\n return this;\n }\n\n public MqMessage qos(int qos) {\n this.qos = qos;\n return this;\n }\n}" }, { "identifier": "MqQueue", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqQueue.java", "snippet": "public interface MqQueue {\n /**\n * 获取主题\n */\n String getTopic();\n\n /**\n * 获取消费组\n */\n String getConsumerGroup();\n\n /**\n * 获取队列名\n * */\n String getQueueName();\n\n /**\n * 添加消费者会话\n */\n void addSession(Session session);\n\n /**\n * 移除消费者会话\n */\n void removeSession(Session session);\n\n /**\n * 获取所有消息会话\n * */\n Collection<Session> getSessions();\n\n /**\n * 消费者会话数量\n * */\n int sessionCount();\n\n /**\n * 添加消息\n */\n void add(MqMessageHolder messageHolder);\n\n /**\n * 移除消息\n * */\n void removeAt(String tid);\n\n /**\n * 派发消息\n * */\n boolean distribute();\n\n /**\n * 消息总量\n * */\n int messageTotal();\n\n /**\n * 消息总量2(用作校验)\n * */\n int messageTotal2();\n\n /**\n * 关闭\n */\n void close();\n}" }, { "identifier": "MqServerDefault", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServerDefault.java", "snippet": "public class MqServerDefault implements MqServer {\n //服务端监听器\n private final MqServiceListener serverListener;\n\n //服务端\n private Server server;\n //服务端配置处理\n private ServerConfigHandler serverConfigHandler;\n\n\n public MqServerDefault() {\n serverListener = new MqServiceListener(false);\n }\n\n /**\n * 服务端配置\n */\n @Override\n public MqServer config(ServerConfigHandler configHandler) {\n serverConfigHandler = configHandler;\n return this;\n }\n\n /**\n * 配置观察者\n */\n @Override\n public MqServer watcher(MqWatcher watcher) {\n serverListener.watcher(watcher);\n\n return this;\n }\n\n /**\n * 配置访问账号\n *\n * @param accessKey 访问者身份\n * @param accessSecretKey 访问者密钥\n */\n @Override\n public MqServer addAccess(String accessKey, String accessSecretKey) {\n serverListener.addAccess(accessKey, accessSecretKey);\n return this;\n }\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n @Override\n public MqServer addAccessAll(Map<String, String> accessMap) {\n serverListener.addAccessAll(accessMap);\n return this;\n }\n\n /**\n * 启动\n */\n @Override\n public MqServer start(int port) throws Exception {\n\n //创建 SocketD 服务并配置(使用 tpc 通讯)\n server = SocketD.createServer(\"sd:tcp\");\n\n server.config(c -> c.maxThreads(c.getCoreThreads() * 4));\n\n //配置\n if (serverConfigHandler != null) {\n server.config(serverConfigHandler);\n }\n\n server.config(c -> c.port(port)).listen(serverListener);\n\n //开始\n serverListener.start(() -> {\n //启动\n server.start();\n });\n\n return this;\n }\n\n /**\n * 停止\n */\n @Override\n public void stop() {\n serverListener.stop(() -> {\n //停止\n server.stop();\n });\n }\n\n @Override\n public MqServiceInternal getServerInternal() {\n return serverListener;\n }\n}" }, { "identifier": "MqServiceInternal", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServiceInternal.java", "snippet": "public interface MqServiceInternal {\n /**\n * 获取订阅关系(topic=>[queueName]) //queueName='topic#consumer'\n */\n Map<String, Set<String>> getSubscribeMap();\n\n /**\n * 获取队列字典(queueName=>Queue)\n */\n Map<String, MqQueue> getQueueMap();\n\n /**\n * 执行订阅\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param session 会话(即消费者)\n */\n void subscribeDo(String topic, String consumerGroup, Session session);\n\n /**\n * 执行取消订阅\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param session 会话(即消费者)\n */\n void unsubscribeDo(String topic, String consumerGroup, Session session);\n\n /**\n * 执行路由\n *\n * @param message 消息\n */\n void routingDo(Message message);\n\n /**\n * 执行路由\n *\n * @param queueName 队列名\n * @param message 消息\n * @param tid 事务Id\n * @param qos 质量等级\n * @param times 派发次数\n * @param scheduled 计划时间\n */\n void routingDo(String queueName, Message message, String tid, int qos, int times, long scheduled);\n\n /**\n * 保存\n */\n void save();\n}" } ]
import org.noear.folkmq.client.MqClientDefault; import org.noear.folkmq.client.MqMessage; import org.noear.folkmq.server.MqQueue; import org.noear.folkmq.server.MqServerDefault; import org.noear.folkmq.server.MqServiceInternal; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
4,145
package features.cases; /** * @author noear * @since 1.0 */ public class TestCase18_batch_subscribe extends BaseTestCase { public TestCase18_batch_subscribe(int port) { super(port); } @Override public void start() throws Exception { super.start(); //服务端 server = new MqServerDefault() .start(getPort()); //客户端 CountDownLatch countDownLatch = new CountDownLatch(1);
package features.cases; /** * @author noear * @since 1.0 */ public class TestCase18_batch_subscribe extends BaseTestCase { public TestCase18_batch_subscribe(int port) { super(port); } @Override public void start() throws Exception { super.start(); //服务端 server = new MqServerDefault() .start(getPort()); //客户端 CountDownLatch countDownLatch = new CountDownLatch(1);
client = new MqClientDefault("folkmq://127.0.0.1:" + getPort());
0
2023-11-18 19:09:28+00:00
8k
leluque/java2uml
src/main/java/br/com/luque/java2uml/plantuml/writer/classdiagram/PlantUMLWriter.java
[ { "identifier": "Rules", "path": "src/main/java/br/com/luque/java2uml/Rules.java", "snippet": "public class Rules {\n private final Set<String> packages;\n private final Set<String> classes;\n private final Set<String> ignorePackages;\n private final Set<String> ignoreClasses;\n\n public Rules() {\n this.packages = new HashSet<>();\n this.classes = new HashSet<>();\n this.ignorePackages = new HashSet<>();\n this.ignoreClasses = new HashSet<>();\n }\n\n public Rules addPackages(String... packagesName) {\n Objects.requireNonNull(packagesName);\n this.packages.addAll(Stream.of(packagesName).filter(p -> !p.isEmpty()).toList());\n return this;\n }\n\n public Rules addClasses(String... classesName) {\n Objects.requireNonNull(classesName);\n this.classes.addAll(Stream.of(classesName).filter(c -> !c.isEmpty()).toList());\n return this;\n }\n\n public Rules ignorePackages(String... packagesName) {\n Objects.requireNonNull(packagesName);\n this.ignorePackages.addAll(Stream.of(packagesName).filter(p -> !p.isEmpty()).toList());\n return this;\n }\n\n public Rules ignoreClasses(String... classesName) {\n Objects.requireNonNull(classesName);\n this.ignoreClasses.addAll(Stream.of(classesName).filter(c -> !c.isEmpty()).toList());\n return this;\n }\n\n public Set<String> getPackages() {\n return packages;\n }\n\n public Set<String> getClasses() {\n return classes;\n }\n\n public Set<String> getIgnorePackages() {\n return ignorePackages;\n }\n\n public Set<String> getIgnoreClasses() {\n return ignoreClasses;\n }\n\n public boolean includes(Class<?> originalClass) {\n return\n (\n packages.stream().anyMatch(p -> originalClass.getPackageName().startsWith(p)) ||\n classes.stream().anyMatch(c -> originalClass.getName().equals(c))\n ) &&\n (\n ignorePackages.stream().noneMatch(p -> originalClass.getPackageName().startsWith(p)) &&\n ignoreClasses.stream().noneMatch(c -> originalClass.getName().equals(c))\n );\n }\n}" }, { "identifier": "ClasspathSearcher", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/classsearch/ClasspathSearcher.java", "snippet": "public class ClasspathSearcher {\n private static final Logger logger = Logger.getLogger(ClasspathSearcher.class.getName());\n private final Rules rules;\n\n public ClasspathSearcher(Rules rules) {\n this.rules = Objects.requireNonNull(rules);\n }\n\n public Class<?>[] search() {\n return searchClasses();\n }\n\n private Class<?>[] searchClasses() {\n Set<Class<?>> classes = new HashSet<>();\n\n for (String qualifiedClassName : rules.getClasses()) {\n try {\n classes.add(Class.forName(qualifiedClassName));\n } catch (ClassNotFoundException e) {\n logger.warning(\"Class not found: \" + qualifiedClassName);\n }\n }\n\n for (String packageName : rules.getPackages()) {\n try {\n Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', '/'));\n while (resources.hasMoreElements()) {\n URL resource = resources.nextElement();\n\n classes.addAll(searchClassesRecursively(new File(resource.getPath()), packageName));\n }\n } catch (IOException e) {\n logger.warning(\"Package not found: \" + packageName);\n }\n }\n\n return classes.toArray(Class<?>[]::new);\n }\n\n private Collection<Class<?>> searchClassesRecursively(File folder, String packageName) {\n Objects.requireNonNull(folder);\n if (!folder.exists()) {\n return Collections.emptyList();\n } else if (!folder.isDirectory()) {\n throw new IllegalArgumentException(\"The folder must be a directory!\");\n }\n\n Set<Class<?>> classes = new HashSet<>();\n for (File child : Objects.requireNonNull(folder.listFiles())) {\n if (child.isDirectory()) {\n if (rules.getIgnorePackages().contains(packageName + \".\" + child.getName())) {\n continue;\n }\n\n classes.addAll(searchClassesRecursively(child, packageName + \".\" + child.getName()));\n } else if (child.getName().endsWith(\".class\")) {\n String qualifiedClassName = packageName + \".\" + child.getName().substring(0, child.getName().length() - \".class\".length());\n\n if (rules.getIgnoreClasses().contains(packageName + \".\" + qualifiedClassName)) {\n continue;\n }\n\n try {\n classes.add(Class.forName(qualifiedClassName));\n } catch (ClassNotFoundException e) {\n logger.warning(\"Class not found: \" + qualifiedClassName);\n }\n }\n }\n return classes;\n }\n}" }, { "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": "ClazzPool", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/ClazzPool.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class ClazzPool {\n private final Rules rules;\n private final Map<Class<?>, Clazz> clazzMap;\n\n public ClazzPool(Rules rules) {\n this.rules = Objects.requireNonNull(rules);\n this.clazzMap = new HashMap<>();\n }\n\n public Clazz getFor(Class<?> originalClass) {\n Objects.requireNonNull(originalClass);\n if (clazzMap.containsKey(originalClass)) {\n return clazzMap.get(originalClass);\n }\n Clazz clazz;\n if (rules.includes(originalClass)) {\n clazz = new ScopedClazz(originalClass, this);\n } else {\n clazz = new UnscopedClazz(originalClass, this);\n }\n clazzMap.put(originalClass, clazz);\n clazz.extractClassInfo();\n return clazzMap.get(originalClass);\n }\n\n\n public Rules getRules() {\n return rules;\n }\n\n public Clazz[] getClazzes() {\n return clazzMap.values().toArray(new Clazz[0]);\n }\n\n public Clazz[] getScopedClazzes() {\n return clazzMap.values().stream().filter(c -> c instanceof ScopedClazz).toArray(Clazz[]::new);\n }\n}" }, { "identifier": "RelationshipField", "path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/RelationshipField.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class RelationshipField extends Field {\n public enum Cardinalities {\n ONE, N\n }\n\n private Cardinalities cardinality;\n\n public enum Variations {\n ASSOCIATION, AGGREGATION, COMPOSITION\n }\n\n private Variations variation;\n\n private Clazz otherSide;\n private String mappedBy;\n\n public RelationshipField(Clazz clazz, java.lang.reflect.Field field, ClazzPool clazzPool) {\n super(clazz, field, clazzPool);\n extractRelationshipInfo();\n }\n\n public Cardinalities getCardinality() {\n return cardinality;\n }\n\n public Variations getVariation() {\n return variation;\n }\n\n public void setVariation(Variations variation) {\n this.variation = Objects.requireNonNull(variation);\n }\n\n public Clazz getOtherSide() {\n return otherSide;\n }\n\n public String getMappedBy() {\n return mappedBy;\n }\n\n public boolean isMappedBy() {\n return null != mappedBy;\n }\n\n public boolean isAssociation() {\n return Variations.ASSOCIATION.equals(getVariation());\n }\n\n public boolean isAggregation() {\n return Variations.AGGREGATION.equals(getVariation());\n }\n\n public boolean isComposition() {\n return Variations.COMPOSITION.equals(getVariation());\n }\n\n public static boolean isRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (isOneRelationship(field, clazzPool)) {\n return true;\n }\n if (isPureArrayRelationship(field, clazzPool)) {\n return true;\n }\n return isGenericRelationship(field, clazzPool);\n }\n\n private static boolean isOneRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n return clazzPool.getRules().includes(field.getType());\n }\n\n private static boolean isPureArrayRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().isArray()) {\n return false;\n }\n\n return clazzPool.getRules().includes(extractArrayType(field, clazzPool));\n }\n\n private static boolean isCollectionRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n return field.getType().getPackageName().startsWith(\"java.util\");\n }\n\n private static boolean isGenericRelationship(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().getPackageName().startsWith(\"java.util\")) {\n return false;\n }\n\n return extractScopedGenerics(field, clazzPool).length > 0;\n }\n\n private static Class<?> extractArrayType(java.lang.reflect.Field field, ClazzPool clazzPool) {\n if (!field.getType().isArray()) {\n return null;\n }\n\n // Handle the case of arrays of arrays ...\n Class<?> componentType = field.getType().getComponentType();\n while (componentType.isArray()) {\n componentType = componentType.getComponentType();\n }\n return componentType;\n }\n\n private static Class<?>[] extractScopedGenerics(java.lang.reflect.Field field, ClazzPool clazzPool) {\n // Handle the case of arrays of arrays of collections ...\n Type genericFieldType = field.getGenericType();\n while (genericFieldType instanceof GenericArrayType) {\n genericFieldType = ((GenericArrayType) genericFieldType).getGenericComponentType();\n }\n\n List<Class<?>> scopedGenerics = new ArrayList<>();\n if (genericFieldType instanceof ParameterizedType) {\n ParameterizedType generics = (ParameterizedType) genericFieldType;\n Type[] typeArguments = generics.getActualTypeArguments();\n for (Type typeArgument : typeArguments) {\n if (typeArgument instanceof Class<?> originalClass\n && clazzPool.getRules().includes(originalClass)) {\n scopedGenerics.add(originalClass);\n }\n }\n }\n return scopedGenerics.toArray(new Class<?>[0]);\n }\n\n private void extractRelationshipInfo() {\n if (isPureArrayRelationship(getField(), getClazzPool())) {\n cardinality = Cardinalities.N;\n otherSide = getClazzPool().getFor(extractArrayType(getField(), getClazzPool()));\n } else if (isGenericRelationship(getField(), getClazzPool())) {\n cardinality = isCollectionRelationship(getField(), getClazzPool()) ? Cardinalities.N : Cardinalities.ONE;\n\n // TODO: handle multiple relationships (more than one generic in the scope).\n Class<?>[] scopedGenerics = extractScopedGenerics(getField(), getClazzPool());\n if (scopedGenerics.length > 0) {\n otherSide = getClazzPool().getFor(scopedGenerics[0]);\n }\n } else if (isOneRelationship(getField(), getClazzPool())) { // This one must go last because it doesn't check if it is array nor collection to avoid double check.\n cardinality = Cardinalities.ONE;\n otherSide = getClazzPool().getFor(getField().getType());\n }\n\n MappedBy mappedByAnnotation = getField().getAnnotation(MappedBy.class);\n if (null != mappedByAnnotation) {\n mappedBy = mappedByAnnotation.value();\n }\n\n setVariation(Variations.ASSOCIATION);\n Aggregation aggregationAnnotation = getField().getAnnotation(Aggregation.class);\n if (null != aggregationAnnotation) {\n setVariation(Variations.AGGREGATION);\n }\n Composition compositionAnnotation = getField().getAnnotation(Composition.class);\n if (null != compositionAnnotation) {\n setVariation(Variations.COMPOSITION);\n }\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}" } ]
import br.com.luque.java2uml.Rules; import br.com.luque.java2uml.core.classdiagram.classsearch.ClasspathSearcher; import br.com.luque.java2uml.core.classdiagram.reflection.model.Clazz; import br.com.luque.java2uml.core.classdiagram.reflection.model.ClazzPool; import br.com.luque.java2uml.core.classdiagram.reflection.model.RelationshipField; import br.com.luque.java2uml.core.classdiagram.reflection.model.ScopedClazz; import java.util.Objects;
4,177
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules); ClasspathSearcher searcher = new ClasspathSearcher(rules); Class<?>[] classes = searcher.search();
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules); ClasspathSearcher searcher = new ClasspathSearcher(rules); Class<?>[] classes = searcher.search();
ClazzPool clazzPool = new ClazzPool(rules);
3
2023-11-10 16:49:58+00:00
8k
javpower/JavaVision
src/main/java/com/github/javpower/javavision/detect/Yolov8sOnnxRuntimeDetect.java
[ { "identifier": "AbstractOnnxRuntimeTranslator", "path": "src/main/java/com/github/javpower/javavision/detect/translator/AbstractOnnxRuntimeTranslator.java", "snippet": "public abstract class AbstractOnnxRuntimeTranslator {\n\n public OrtEnvironment environment;\n public OrtSession session;\n public String[] labels;\n public float confThreshold;\n public float nmsThreshold;\n\n static {\n // 加载opencv动态库,\n //System.load(ClassLoader.getSystemResource(\"lib/opencv_java470-无用.dll\").getPath());\n nu.pattern.OpenCV.loadLocally();\n }\n\n\n public AbstractOnnxRuntimeTranslator(String modelPath, String[] labels, float confThreshold, float nmsThreshold) throws OrtException {\n this.environment = OrtEnvironment.getEnvironment();\n OrtSession.SessionOptions sessionOptions = new OrtSession.SessionOptions();\n this.session = environment.createSession(modelPath, sessionOptions);\n this.labels = labels;\n this.confThreshold = confThreshold;\n this.nmsThreshold = nmsThreshold;\n }\n\n public List<Detection> runOcr(String imagePath) throws OrtException {\n Mat image = loadImage(imagePath);\n preprocessImage(image);\n float[][] outputData = runInference(image);\n Map<Integer, List<float[]>> class2Bbox = postprocessOutput(outputData);\n return convertDetections(class2Bbox);\n }\n // 实现加载图像的逻辑\n protected abstract Mat loadImage(String imagePath);\n // 实现图像预处理的逻辑\n protected abstract void preprocessImage(Mat image);\n // 实现推理的逻辑\n protected abstract float[][] runInference(Mat image) throws OrtException;\n // 实现输出后处理的逻辑\n protected abstract Map<Integer, List<float[]>> postprocessOutput(float[][] outputData);\n\n protected float[][] transposeMatrix(float[][] m) {\n float[][] temp = new float[m[0].length][m.length];\n for (int i = 0; i < m.length; i++)\n for (int j = 0; j < m[0].length; j++)\n temp[j][i] = m[i][j];\n return temp;\n }\n\n protected List<Detection> convertDetections(Map<Integer, List<float[]>> class2Bbox) {\n // 将边界框信息转换为 Detection 对象的逻辑\n List<Detection> detections = new ArrayList<>();\n for (Map.Entry<Integer, List<float[]>> entry : class2Bbox.entrySet()) {\n int label = entry.getKey();\n List<float[]> bboxes = entry.getValue();\n bboxes = nonMaxSuppression(bboxes, nmsThreshold);\n for (float[] bbox : bboxes) {\n String labelString = labels[label];\n detections.add(new Detection(labelString,entry.getKey(), Arrays.copyOfRange(bbox, 0, 4), bbox[4]));\n }\n }\n return detections;\n }\n public static List<float[]> nonMaxSuppression(List<float[]> bboxes, float iouThreshold) {\n\n List<float[]> bestBboxes = new ArrayList<>();\n\n bboxes.sort(Comparator.comparing(a -> a[4]));\n\n while (!bboxes.isEmpty()) {\n float[] bestBbox = bboxes.remove(bboxes.size() - 1);\n bestBboxes.add(bestBbox);\n bboxes = bboxes.stream().filter(a -> computeIOU(a, bestBbox) < iouThreshold).collect(Collectors.toList());\n }\n\n return bestBboxes;\n }\n public static float computeIOU(float[] box1, float[] box2) {\n\n float area1 = (box1[2] - box1[0]) * (box1[3] - box1[1]);\n float area2 = (box2[2] - box2[0]) * (box2[3] - box2[1]);\n\n float left = Math.max(box1[0], box2[0]);\n float top = Math.max(box1[1], box2[1]);\n float right = Math.min(box1[2], box2[2]);\n float bottom = Math.min(box1[3], box2[3]);\n\n float interArea = Math.max(right - left, 0) * Math.max(bottom - top, 0);\n float unionArea = area1 + area2 - interArea;\n return Math.max(interArea / unionArea, 1e-8f);\n\n }\n}" }, { "identifier": "Letterbox", "path": "src/main/java/com/github/javpower/javavision/entity/Letterbox.java", "snippet": "public class Letterbox {\n\n private Size newShape = new Size(640, 640);\n private final double[] color = new double[]{114,114,114};\n private final Boolean auto = false;\n private final Boolean scaleUp = true;\n private Integer stride = 32;\n\n private double ratio;\n private double dw;\n private double dh;\n\n public double getRatio() {\n return ratio;\n }\n\n public double getDw() {\n return dw;\n }\n\n public Integer getWidth() {\n return (int) this.newShape.width;\n }\n\n public Integer getHeight() {\n return (int) this.newShape.height;\n }\n\n public double getDh() {\n return dh;\n }\n\n public void setNewShape(Size newShape) {\n this.newShape = newShape;\n }\n\n public void setStride(Integer stride) {\n this.stride = stride;\n }\n\n public Mat letterbox(Mat im) { // 调整图像大小和填充图像,使满足步长约束,并记录参数\n\n int[] shape = {im.rows(), im.cols()}; // 当前形状 [height, width]\n // Scale ratio (new / old)\n double r = Math.min(this.newShape.height / shape[0], this.newShape.width / shape[1]);\n if (!this.scaleUp) { // 仅缩小,不扩大(一且为了mAP)\n r = Math.min(r, 1.0);\n }\n // Compute padding\n Size newUnpad = new Size(Math.round(shape[1] * r), Math.round(shape[0] * r));\n double dw = this.newShape.width - newUnpad.width, dh = this.newShape.height - newUnpad.height; // wh 填充\n if (this.auto) { // 最小矩形\n dw = dw % this.stride;\n dh = dh % this.stride;\n }\n dw /= 2; // 填充的时候两边都填充一半,使图像居于中心\n dh /= 2;\n if (shape[1] != newUnpad.width || shape[0] != newUnpad.height) { // resize\n Imgproc.resize(im, im, newUnpad, 0, 0, Imgproc.INTER_LINEAR);\n }\n int top = (int) Math.round(dh - 0.1), bottom = (int) Math.round(dh + 0.1);\n int left = (int) Math.round(dw - 0.1), right = (int) Math.round(dw + 0.1);\n // 将图像填充为正方形\n Core.copyMakeBorder(im, im, top, bottom, left, right, Core.BORDER_CONSTANT, new org.opencv.core.Scalar(this.color));\n this.ratio = r;\n this.dh = dh;\n this.dw = dw;\n return im;\n }\n}" }, { "identifier": "JarFileUtils", "path": "src/main/java/com/github/javpower/javavision/util/JarFileUtils.java", "snippet": "public class JarFileUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(JarFileUtils.class);\n\n /**\n * 文件前缀的最小长度\n */\n private static final int MIN_PREFIX_LENGTH = 3;\n\n /**\n * 临时文件\n */\n private static File temporaryDir;\n\n private JarFileUtils() {\n }\n\n /**\n * 从jar包中复制文件\n * 先将jar包中的动态库复制到系统临时文件夹,如果需要加载会进行加载,并且在JVM退出时自动删除。\n *\n * @param path 要复制文件的路径,必须以'/'开始,比如 /lib/monster.so,必须以'/'开始\n * @param dirName 保存的文件夹名称,必须以'/'开始,可为null\n * @param loadClass 用于提供{@link ClassLoader}加载动态库的类,如果为null,则使用JarFileUtils.class\n * @param load 是否加载,有些文件只需要复制到临时文件夹,不需要加载\n * @param deleteOnExit 是否在JVM退出时删除临时文件\n * @throws IOException 动态库读写错误\n * @throws FileNotFoundException 没有在jar包中找到指定的文件\n */\n public static synchronized void copyFileFromJar(String path, String dirName, Class<?> loadClass, boolean load, boolean deleteOnExit) throws IOException {\n\n String filename = checkFileName(path);\n\n // 创建临时文件夹\n if (temporaryDir == null) {\n temporaryDir = createTempDirectory(dirName);\n temporaryDir.deleteOnExit();\n }\n // 临时文件夹下的动态库名\n File temp = new File(temporaryDir, filename);\n if (!temp.exists()) {\n Class<?> clazz = loadClass == null ? JarFileUtils.class : loadClass;\n // 从jar包中复制文件到系统临时文件夹\n try (InputStream is = clazz.getResourceAsStream(path)) {\n if (is != null) {\n Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);\n } else {\n throw new NullPointerException(\"文件 \" + path + \" 在JAR中未找到.\");\n }\n } catch (IOException e) {\n Files.delete(temp.toPath());\n throw e;\n } catch (NullPointerException e) {\n Files.delete(temp.toPath());\n throw new FileNotFoundException(\"文件 \" + path + \" 在JAR中未找到.\");\n }\n }\n // 加载临时文件夹中的动态库\n if (load) {\n System.load(temp.getAbsolutePath());\n }\n if (deleteOnExit) {\n // 设置在JVM结束时删除临时文件\n temp.deleteOnExit();\n }\n logger.debug(\"将文件{}复制到{},加载此文件:{},JVM退出时删除此文件:{}\", path, dirName, load, deleteOnExit);\n }\n\n /**\n * 检查文件名是否正确\n *\n * @param path 文件路径\n * @return 文件名\n * @throws IllegalArgumentException 路径必须以'/'开始、文件名必须至少有3个字符长\n */\n private static String checkFileName(String path) {\n if (null == path || !path.startsWith(\"/\")) {\n throw new IllegalArgumentException(\"路径必须以文件分隔符开始.\");\n }\n\n // 从路径获取文件名\n String[] parts = path.split(\"/\");\n String filename = (parts.length > 1) ? parts[parts.length - 1] : null;\n\n // 检查文件名是否正确\n if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {\n throw new IllegalArgumentException(\"文件名必须至少有3个字符长.\");\n }\n return filename;\n }\n\n /**\n * 从jar包中复制models文件夹下的内容\n *\n * @param modelPath 文件夹路径\n */\n public static void copyModelsFromJar(String modelPath, boolean isDelOnExit) throws IOException {\n String base = modelPath.endsWith(\"/\") ? modelPath : modelPath + \"/\";\n if (modelPath.contains(PathConstants.ONNX)) {\n for (final String path : PathConstants.MODEL_ONNX_FILE_ARRAY) {\n copyFileFromJar(base + path, PathConstants.ONNX, null, Boolean.FALSE, isDelOnExit);\n }\n } else {\n for (final String path : PathConstants.MODEL_NCNN_FILE_ARRAY) {\n copyFileFromJar(base + path, PathConstants.NCNN, null, Boolean.FALSE, isDelOnExit);\n }\n }\n\n }\n\n /**\n * 在系统临时文件夹下创建临时文件夹\n */\n private static File createTempDirectory(String dirName) throws IOException {\n File dir = new File(PathConstants.TEMP_DIR, dirName);\n if (!dir.exists() && !dir.mkdirs()) {\n throw new IOException(\"无法在临时目录创建文件\" + dir);\n }\n return dir;\n }\n}" }, { "identifier": "PathConstants", "path": "src/main/java/com/github/javpower/javavision/util/PathConstants.java", "snippet": "public class PathConstants {\n\n private PathConstants() {\n }\n\n public static final String TEMP_DIR = System.getProperty(\"java.io.tmpdir\") + \"ocrJava\";\n\n /**\n * 推理引擎\n */\n public static final String NCNN = \"/ncnn\";\n public static final String ONNX = \"/onnx\";\n\n /**\n * 模型相关\n **/\n public static final String MODEL_NCNN_PATH = NCNN + \"/models\";\n public static final String MODEL_ONNX_PATH = ONNX + \"/models\";\n public static final String MODEL_SUFFIX_BIN = \".bin\";\n public static final String MODEL_SUFFIX_PARAM = \".param\";\n public static final String MODEL_SUFFIX_ONNX = \".onnx\";\n /**\n * 文本检测模型,可选版本v3、v4,默认v4版本\n */\n public static final String MODEL_DET_NAME_V3 = \"ch_PP-OCRv3_det_infer\";\n public static final String MODEL_DET_NAME_V4 = \"ch_PP-OCRv4_det_infer\";\n /**\n * 文本识别模型,可选版本v3、v4,默认v4版本\n */\n public static final String MODEL_REC_NAME_V3= \"ch_PP-OCRv3_rec_infer\";\n public static final String MODEL_REC_NAME_V4 = \"ch_PP-OCRv4_rec_infer\";\n public static final String MODEL_CLS_NAME = \"ch_ppocr_mobile_v2.0_cls_infer\";\n public static final String MODEL_KEYS_NAME = \"ppocr_keys_v1.txt\";\n public static final String[] MODEL_NCNN_FILE_ARRAY = new String[]{\n MODEL_DET_NAME_V3 + MODEL_SUFFIX_BIN, MODEL_DET_NAME_V3 + MODEL_SUFFIX_PARAM, MODEL_REC_NAME_V3 + MODEL_SUFFIX_BIN,\n MODEL_REC_NAME_V3 + MODEL_SUFFIX_PARAM, MODEL_CLS_NAME + MODEL_SUFFIX_BIN, MODEL_CLS_NAME + MODEL_SUFFIX_PARAM,\n MODEL_KEYS_NAME\n };\n public static final String[] MODEL_ONNX_FILE_ARRAY = new String[]{\n MODEL_DET_NAME_V3 + MODEL_SUFFIX_ONNX, MODEL_REC_NAME_V4 + MODEL_SUFFIX_ONNX,\n MODEL_CLS_NAME + MODEL_SUFFIX_ONNX, MODEL_KEYS_NAME\n };\n\n /**\n * 动态库\n **/\n public static final String OS_WINDOWS_32 = \"/win/win32/RapidOcr.dll\";\n public static final String OS_WINDOWS_64 = \"/win/x86_64/RapidOcr.dll\";\n public static final String OS_MAC_SILICON = \"/mac/arm64/libRapidOcr.dylib\";\n public static final String OS_MAC_INTEL = \"/mac/x86_64/libRapidOcr.dylib\";\n public static final String OS_LINUX = \"/linux/libRapidOcr.so\";\n\n\n}" } ]
import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtSession; import com.github.javpower.javavision.detect.translator.AbstractOnnxRuntimeTranslator; import com.github.javpower.javavision.entity.Letterbox; import com.github.javpower.javavision.util.JarFileUtils; import com.github.javpower.javavision.util.PathConstants; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.io.IOException; import java.nio.FloatBuffer; import java.util.*;
4,805
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException { Letterbox letterbox = new Letterbox(); int rows = letterbox.getHeight(); int cols = letterbox.getWidth(); int channels = image.channels(); float[] pixels = new float[channels * rows * cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double[] pixel = image.get(j, i); for (int k = 0; k < channels; k++) { pixels[rows * cols * k + j * cols + i] = (float) pixel[k] / 255.0f; } } } // 创建OnnxTensor对象 long[] shape = { 1L, (long)channels, (long)rows, (long)cols }; OnnxTensor tensor = OnnxTensor.createTensor(environment, FloatBuffer.wrap(pixels), shape); Map<String, OnnxTensor> inputs = new HashMap<>(); inputs.put(session.getInputNames().iterator().next(), tensor); OrtSession.Result output = session.run(inputs); float[][] outputData = ((float[][][]) output.get(0).getValue())[0]; return transposeMatrix(outputData); } // 实现输出后处理的逻辑 @Override protected Map<Integer, List<float[]>> postprocessOutput(float[][] outputData) { Map<Integer, List<float[]>> class2Bbox = new HashMap<>(); for (float[] bbox : outputData) { float[] conditionalProbabilities = Arrays.copyOfRange(bbox, 4, bbox.length); int label = argmax(conditionalProbabilities); float conf = conditionalProbabilities[label]; if (conf < confThreshold) continue; bbox[4] = conf; xywh2xyxy(bbox); if (bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) continue; class2Bbox.putIfAbsent(label, new ArrayList<>()); class2Bbox.get(label).add(bbox); } return class2Bbox; } private static void xywh2xyxy(float[] bbox) { float x = bbox[0]; float y = bbox[1]; float w = bbox[2]; float h = bbox[3]; bbox[0] = x - w * 0.5f; bbox[1] = y - h * 0.5f; bbox[2] = x + w * 0.5f; bbox[3] = y + h * 0.5f; } private static int argmax(float[] a) { float re = -Float.MAX_VALUE; int arg = -1; for (int i = 0; i < a.length; i++) { if (a[i] >= re) { re = a[i]; arg = i; } } return arg; } public static Yolov8sOnnxRuntimeDetect criteria() throws OrtException, IOException { // 这里需要引入JAR包的拷贝逻辑,您可以根据自己的需要将其处理为合适的方式
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException { Letterbox letterbox = new Letterbox(); int rows = letterbox.getHeight(); int cols = letterbox.getWidth(); int channels = image.channels(); float[] pixels = new float[channels * rows * cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double[] pixel = image.get(j, i); for (int k = 0; k < channels; k++) { pixels[rows * cols * k + j * cols + i] = (float) pixel[k] / 255.0f; } } } // 创建OnnxTensor对象 long[] shape = { 1L, (long)channels, (long)rows, (long)cols }; OnnxTensor tensor = OnnxTensor.createTensor(environment, FloatBuffer.wrap(pixels), shape); Map<String, OnnxTensor> inputs = new HashMap<>(); inputs.put(session.getInputNames().iterator().next(), tensor); OrtSession.Result output = session.run(inputs); float[][] outputData = ((float[][][]) output.get(0).getValue())[0]; return transposeMatrix(outputData); } // 实现输出后处理的逻辑 @Override protected Map<Integer, List<float[]>> postprocessOutput(float[][] outputData) { Map<Integer, List<float[]>> class2Bbox = new HashMap<>(); for (float[] bbox : outputData) { float[] conditionalProbabilities = Arrays.copyOfRange(bbox, 4, bbox.length); int label = argmax(conditionalProbabilities); float conf = conditionalProbabilities[label]; if (conf < confThreshold) continue; bbox[4] = conf; xywh2xyxy(bbox); if (bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) continue; class2Bbox.putIfAbsent(label, new ArrayList<>()); class2Bbox.get(label).add(bbox); } return class2Bbox; } private static void xywh2xyxy(float[] bbox) { float x = bbox[0]; float y = bbox[1]; float w = bbox[2]; float h = bbox[3]; bbox[0] = x - w * 0.5f; bbox[1] = y - h * 0.5f; bbox[2] = x + w * 0.5f; bbox[3] = y + h * 0.5f; } private static int argmax(float[] a) { float re = -Float.MAX_VALUE; int arg = -1; for (int i = 0; i < a.length; i++) { if (a[i] >= re) { re = a[i]; arg = i; } } return arg; } public static Yolov8sOnnxRuntimeDetect criteria() throws OrtException, IOException { // 这里需要引入JAR包的拷贝逻辑,您可以根据自己的需要将其处理为合适的方式
JarFileUtils.copyFileFromJar("/onnx/models/yolov8s.onnx", PathConstants.ONNX,null,false,true);
2
2023-11-10 01:57:37+00:00
8k
feiniaojin/graceful-response-boot2
src/main/java/com/feiniaojin/gracefulresponse/AutoConfig.java
[ { "identifier": "GlobalExceptionAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/GlobalExceptionAdvice.java", "snippet": "@ControllerAdvice\n@Order(200)\npublic class GlobalExceptionAdvice implements ApplicationContextAware {\n\n private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private ResponseFactory responseFactory;\n\n private ExceptionAliasRegister exceptionAliasRegister;\n\n @Resource\n private GracefulResponseProperties gracefulResponseProperties;\n\n @Resource\n private GracefulResponseProperties properties;\n\n /**\n * 异常处理逻辑.\n *\n * @param throwable 业务逻辑抛出的异常\n * @return 统一返回包装后的结果\n */\n @ExceptionHandler({Throwable.class})\n @ResponseBody\n public Response exceptionHandler(Throwable throwable) {\n if (gracefulResponseProperties.isPrintExceptionInGlobalAdvice()) {\n logger.error(\"Graceful Response:GlobalExceptionAdvice捕获到异常,message=[{}]\", throwable.getMessage(), throwable);\n }\n ResponseStatus statusLine;\n if (throwable instanceof GracefulResponseException) {\n statusLine = fromGracefulResponseExceptionInstance((GracefulResponseException) throwable);\n } else {\n //校验异常转自定义异常\n statusLine = fromExceptionInstance(throwable);\n }\n return responseFactory.newInstance(statusLine);\n }\n\n private ResponseStatus fromGracefulResponseExceptionInstance(GracefulResponseException exception) {\n String code = exception.getCode();\n if (code == null) {\n code = properties.getDefaultErrorCode();\n }\n return responseStatusFactory.newInstance(code,\n exception.getMsg());\n }\n\n private ResponseStatus fromExceptionInstance(Throwable throwable) {\n\n Class<? extends Throwable> clazz = throwable.getClass();\n\n ExceptionMapper exceptionMapper = clazz.getAnnotation(ExceptionMapper.class);\n\n //1.有@ExceptionMapper注解,直接设置结果的状态\n if (exceptionMapper != null) {\n boolean msgReplaceable = exceptionMapper.msgReplaceable();\n //异常提示可替换+抛出来的异常有自定义的异常信息\n if (msgReplaceable) {\n String throwableMessage = throwable.getMessage();\n if (throwableMessage != null) {\n return responseStatusFactory.newInstance(exceptionMapper.code(), throwableMessage);\n }\n }\n return responseStatusFactory.newInstance(exceptionMapper.code(),\n exceptionMapper.msg());\n }\n\n //2.有@ExceptionAliasFor异常别名注解,获取已注册的别名信息\n if (exceptionAliasRegister != null) {\n ExceptionAliasFor exceptionAliasFor = exceptionAliasRegister.getExceptionAliasFor(clazz);\n if (exceptionAliasFor != null) {\n return responseStatusFactory.newInstance(exceptionAliasFor.code(),\n exceptionAliasFor.msg());\n }\n }\n ResponseStatus defaultError = responseStatusFactory.defaultError();\n\n //3. 原生异常+originExceptionUsingDetailMessage=true\n //如果有自定义的异常信息,原生异常将直接使用异常信息进行返回,不再返回默认错误提示\n if (properties.getOriginExceptionUsingDetailMessage()) {\n String throwableMessage = throwable.getMessage();\n if (throwableMessage != null) {\n defaultError.setMsg(throwableMessage);\n }\n }\n return defaultError;\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.exceptionAliasRegister = applicationContext.getBean(ExceptionAliasRegister.class);\n }\n}" }, { "identifier": "NotVoidResponseBodyAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/NotVoidResponseBodyAdvice.java", "snippet": "@ControllerAdvice\n@Order(value = 1000)\npublic class NotVoidResponseBodyAdvice implements ResponseBodyAdvice<Object> {\n\n private final Logger logger = LoggerFactory.getLogger(NotVoidResponseBodyAdvice.class);\n\n @Resource\n private ResponseFactory responseFactory;\n @Resource\n private GracefulResponseProperties properties;\n\n /**\n * 路径过滤器\n */\n private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();\n\n /**\n * 只处理不返回void的,并且MappingJackson2HttpMessageConverter支持的类型.\n *\n * @param methodParameter 方法参数\n * @param clazz 处理器\n * @return 是否支持\n */\n @Override\n public boolean supports(MethodParameter methodParameter,\n Class<? extends HttpMessageConverter<?>> clazz) {\n Method method = methodParameter.getMethod();\n\n //method为空、返回值为void、非JSON,直接跳过\n if (Objects.isNull(method)\n || method.getReturnType().equals(Void.TYPE)\n || !MappingJackson2HttpMessageConverter.class.isAssignableFrom(clazz)) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Graceful Response:method为空、返回值为void、非JSON,跳过\");\n }\n return false;\n }\n\n //有ExcludeFromGracefulResponse注解修饰的,也跳过\n if (method.isAnnotationPresent(ExcludeFromGracefulResponse.class)) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Graceful Response:方法被@ExcludeFromGracefulResponse注解修饰,跳过:methodName={}\", method.getName());\n }\n return false;\n }\n\n //配置了例外包路径,则该路径下的controller都不再处理\n List<String> excludePackages = properties.getExcludePackages();\n if (!CollectionUtils.isEmpty(excludePackages)) {\n // 获取请求所在类的的包名\n String packageName = method.getDeclaringClass().getPackage().getName();\n if (excludePackages.stream().anyMatch(item -> ANT_PATH_MATCHER.match(item, packageName))) {\n logger.debug(\"Graceful Response:匹配到excludePackages例外配置,跳过:packageName={},\", packageName);\n return false;\n }\n }\n logger.debug(\"Graceful Response:非空返回值,需要进行封装\");\n return true;\n }\n\n @Override\n public Object beforeBodyWrite(Object body,\n MethodParameter methodParameter,\n MediaType mediaType,\n Class<? extends HttpMessageConverter<?>> clazz,\n ServerHttpRequest serverHttpRequest,\n ServerHttpResponse serverHttpResponse) {\n if (body == null) {\n return responseFactory.newSuccessInstance();\n } else if (body instanceof Response) {\n return body;\n } else {\n if (logger.isDebugEnabled()) {\n String path = serverHttpRequest.getURI().getPath();\n logger.debug(\"Graceful Response:非空返回值,执行封装:path={}\", path);\n }\n return responseFactory.newSuccessInstance(body);\n }\n }\n\n}" }, { "identifier": "ValidationExceptionAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/ValidationExceptionAdvice.java", "snippet": "@ControllerAdvice\n@Order(100)\npublic class ValidationExceptionAdvice {\n\n private final Logger logger = LoggerFactory.getLogger(ValidationExceptionAdvice.class);\n @Resource\n private RequestMappingHandlerMapping requestMappingHandlerMapping;\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private ResponseFactory responseFactory;\n\n @Resource\n private GracefulResponseProperties gracefulResponseProperties;\n\n @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})\n @ResponseBody\n public Response exceptionHandler(Exception e) throws Exception {\n\n if (e instanceof MethodArgumentNotValidException\n || e instanceof BindException) {\n ResponseStatus responseStatus = this.handleBindException((BindException) e);\n return responseFactory.newInstance(responseStatus);\n }\n\n if (e instanceof ConstraintViolationException) {\n ResponseStatus responseStatus = this.handleConstraintViolationException(e);\n return responseFactory.newInstance(responseStatus);\n }\n\n return responseFactory.newFailInstance();\n }\n\n //Controller方法的参数校验码\n //Controller方法>Controller类>DTO入参属性>DTO入参类>配置文件默认参数码>默认错误码\n private ResponseStatus handleBindException(BindException e) throws Exception {\n List<ObjectError> allErrors = e.getBindingResult().getAllErrors();\n String msg = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(\";\"));\n String code;\n //Controller方法上的注解\n ValidationStatusCode validateStatusCode = this.findValidationStatusCodeInController();\n if (validateStatusCode != null) {\n code = validateStatusCode.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //属性校验上的注解,只会取第一个属性上的注解,因此要配置\n //hibernate.validator.fail_fast=true\n List<FieldError> fieldErrors = e.getFieldErrors();\n if (!CollectionUtils.isEmpty(fieldErrors)) {\n FieldError fieldError = fieldErrors.get(0);\n String fieldName = fieldError.getField();\n Object target = e.getTarget();\n Field field = null;\n Class<?> clazz = null;\n Object obj = target;\n if (fieldName.contains(\".\")) {\n String[] strings = fieldName.split(\"\\\\.\");\n for (String fName : strings) {\n clazz = obj.getClass();\n field = obj.getClass().getDeclaredField(fName);\n field.setAccessible(true);\n obj = field.get(obj);\n }\n } else {\n clazz = target.getClass();\n field = target.getClass().getDeclaredField(fieldName);\n }\n\n ValidationStatusCode annotation = field.getAnnotation(ValidationStatusCode.class);\n //属性上找到注解\n if (annotation != null) {\n code = annotation.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //类上面找到注解\n annotation = clazz.getAnnotation(ValidationStatusCode.class);\n if (annotation != null) {\n code = annotation.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n }\n //默认的参数异常码\n code = gracefulResponseProperties.getDefaultValidateErrorCode();\n if (StringUtils.hasLength(code)) {\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的异常码\n code = gracefulResponseProperties.getDefaultErrorCode();\n return responseStatusFactory.newInstance(code, msg);\n }\n\n /**\n * 当前Controller方法\n *\n * @return\n * @throws Exception\n */\n private Method currentControllerMethod() throws Exception {\n RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();\n ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;\n HandlerExecutionChain handlerChain = requestMappingHandlerMapping.getHandler(sra.getRequest());\n assert handlerChain != null;\n HandlerMethod handler = (HandlerMethod) handlerChain.getHandler();\n return handler.getMethod();\n }\n\n private ResponseStatus handleConstraintViolationException(Exception e) throws Exception {\n\n ConstraintViolationException exception = (ConstraintViolationException) e;\n Set<ConstraintViolation<?>> violationSet = exception.getConstraintViolations();\n String msg = violationSet.stream().map(s -> s.getConstraintDescriptor().getMessageTemplate()).collect(Collectors.joining(\";\"));\n String code;\n ValidationStatusCode validationStatusCode = this.findValidationStatusCodeInController();\n if (validationStatusCode != null) {\n code = validationStatusCode.code();\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的参数异常码\n code = gracefulResponseProperties.getDefaultValidateErrorCode();\n if (StringUtils.hasLength(code)) {\n return responseStatusFactory.newInstance(code, msg);\n }\n //默认的异常码\n code = gracefulResponseProperties.getDefaultErrorCode();\n return responseStatusFactory.newInstance(code, msg);\n }\n\n /**\n * 找Controller中的ValidationStatusCode注解\n * 当前方法->当前Controller类\n *\n * @return\n * @throws Exception\n */\n private ValidationStatusCode findValidationStatusCodeInController() throws Exception {\n Method method = this.currentControllerMethod();\n //Controller方法上的注解\n ValidationStatusCode validateStatusCode = method.getAnnotation(ValidationStatusCode.class);\n //Controller类上的注解\n if (validateStatusCode == null) {\n validateStatusCode = method.getDeclaringClass().getAnnotation(ValidationStatusCode.class);\n }\n return validateStatusCode;\n }\n}" }, { "identifier": "VoidResponseBodyAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/VoidResponseBodyAdvice.java", "snippet": "@ControllerAdvice\n@Order(value = 1000)\npublic class VoidResponseBodyAdvice implements ResponseBodyAdvice<Object> {\n\n private final Logger logger = LoggerFactory.getLogger(VoidResponseBodyAdvice.class);\n\n @Resource\n private ResponseFactory responseFactory;\n\n /**\n * 只处理返回空的Controller方法.\n *\n * @param methodParameter 返回类型\n * @param clazz 消息转换器\n * @return 是否对这种返回值进行处理\n */\n @Override\n public boolean supports(MethodParameter methodParameter,\n Class<? extends HttpMessageConverter<?>> clazz) {\n\n return Objects.requireNonNull(methodParameter.getMethod()).getReturnType().equals(Void.TYPE)\n && MappingJackson2HttpMessageConverter.class.isAssignableFrom(clazz);\n }\n\n @Override\n public Object beforeBodyWrite(Object body,\n MethodParameter returnType,\n MediaType selectedContentType,\n Class<? extends HttpMessageConverter<?>> selectedConverterType,\n ServerHttpRequest request,\n ServerHttpResponse response) {\n return responseFactory.newSuccessInstance();\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": "DefaultResponseFactory", "path": "src/main/java/com/feiniaojin/gracefulresponse/defaults/DefaultResponseFactory.java", "snippet": "public class DefaultResponseFactory implements ResponseFactory {\n\n private final Logger logger = LoggerFactory.getLogger(DefaultResponseFactory.class);\n\n private static final Integer RESPONSE_STYLE_0 = 0;\n\n private static final Integer RESPONSE_STYLE_1 = 1;\n\n @Resource\n private ResponseStatusFactory responseStatusFactory;\n\n @Resource\n private GracefulResponseProperties properties;\n\n @Override\n public Response newEmptyInstance() {\n try {\n String responseClassFullName = properties.getResponseClassFullName();\n\n //配置了Response的全限定名,即自定义了Response,用配置的进行返回\n if (StringUtils.hasLength(responseClassFullName)) {\n Object newInstance = Class.forName(responseClassFullName).newInstance();\n return (Response) newInstance;\n } else {\n //没有配Response的全限定名,则创建DefaultResponse\n return generateDefaultResponse();\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private Response generateDefaultResponse() {\n Integer responseStyle = properties.getResponseStyle();\n if (Objects.isNull(responseStyle) || RESPONSE_STYLE_0.equals(responseStyle)) {\n return new DefaultResponseImplStyle0();\n } else if (RESPONSE_STYLE_1.equals(responseStyle)) {\n return new DefaultResponseImplStyle1();\n } else {\n logger.error(\"不支持的Response style类型,responseStyle={}\", responseStyle);\n throw new IllegalArgumentException(\"不支持的Response style类型\");\n }\n }\n\n @Override\n public Response newInstance(ResponseStatus responseStatus) {\n Response bean = this.newEmptyInstance();\n bean.setStatus(responseStatus);\n return bean;\n }\n\n @Override\n public Response newSuccessInstance() {\n Response emptyInstance = this.newEmptyInstance();\n emptyInstance.setStatus(responseStatusFactory.defaultSuccess());\n return emptyInstance;\n }\n\n @Override\n public Response newSuccessInstance(Object payload) {\n Response bean = this.newSuccessInstance();\n bean.setPayload(payload);\n return bean;\n }\n\n @Override\n public Response newFailInstance() {\n Response bean = this.newEmptyInstance();\n bean.setStatus(responseStatusFactory.defaultError());\n return bean;\n }\n\n}" }, { "identifier": "DefaultResponseStatusFactoryImpl", "path": "src/main/java/com/feiniaojin/gracefulresponse/defaults/DefaultResponseStatusFactoryImpl.java", "snippet": "public class DefaultResponseStatusFactoryImpl implements ResponseStatusFactory {\n\n @Resource\n private GracefulResponseProperties properties;\n\n @Override\n public ResponseStatus defaultSuccess() {\n\n DefaultResponseStatus defaultResponseStatus = new DefaultResponseStatus();\n defaultResponseStatus.setCode(properties.getDefaultSuccessCode());\n defaultResponseStatus.setMsg(properties.getDefaultSuccessMsg());\n return defaultResponseStatus;\n }\n\n @Override\n public ResponseStatus defaultError() {\n DefaultResponseStatus defaultResponseStatus = new DefaultResponseStatus();\n defaultResponseStatus.setCode(properties.getDefaultErrorCode());\n defaultResponseStatus.setMsg(properties.getDefaultErrorMsg());\n return defaultResponseStatus;\n }\n\n @Override\n public ResponseStatus newInstance(String code, String msg) {\n return new DefaultResponseStatus(code, msg);\n }\n}" } ]
import com.feiniaojin.gracefulresponse.advice.GlobalExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.NotVoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.advice.ValidationExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.VoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.api.ResponseFactory; import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseStatusFactoryImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
4,605
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:[email protected]">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean
@ConditionalOnMissingBean(value = GlobalExceptionAdvice.class)
0
2023-11-15 10:54:19+00:00
8k
innogames/flink-real-time-crm
src/main/java/com/innogames/analytics/rtcrm/App.java
[ { "identifier": "Config", "path": "src/main/java/com/innogames/analytics/rtcrm/config/Config.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Config {\n\n\tprivate int defaultParallelism;\n\tprivate int checkpointInterval;\n\tprivate String checkpointDir;\n\tprivate String kafkaBootstrapServers;\n\tprivate String kafkaGroupId;\n\tprivate String eventTopic;\n\tprivate String campaignTopic;\n\tprivate String triggerTopic;\n\n\tpublic Config() {\n\t}\n\n\tpublic int getDefaultParallelism() {\n\t\treturn defaultParallelism;\n\t}\n\n\tpublic void setDefaultParallelism(final int defaultParallelism) {\n\t\tthis.defaultParallelism = defaultParallelism;\n\t}\n\n\tpublic int getCheckpointInterval() {\n\t\treturn checkpointInterval;\n\t}\n\n\tpublic void setCheckpointInterval(final int checkpointInterval) {\n\t\tthis.checkpointInterval = checkpointInterval;\n\t}\n\n\tpublic String getCheckpointDir() {\n\t\treturn checkpointDir;\n\t}\n\n\tpublic void setCheckpointDir(final String checkpointDir) {\n\t\tthis.checkpointDir = checkpointDir;\n\t}\n\n\tpublic String getKafkaBootstrapServers() {\n\t\treturn kafkaBootstrapServers;\n\t}\n\n\tpublic void setKafkaBootstrapServers(final String kafkaBootstrapServers) {\n\t\tthis.kafkaBootstrapServers = kafkaBootstrapServers;\n\t}\n\n\tpublic String getEventTopic() {\n\t\treturn eventTopic;\n\t}\n\n\tpublic void setEventTopic(final String eventTopic) {\n\t\tthis.eventTopic = eventTopic;\n\t}\n\n\tpublic String getKafkaGroupId() {\n\t\treturn kafkaGroupId;\n\t}\n\n\tpublic void setKafkaGroupId(final String kafkaGroupId) {\n\t\tthis.kafkaGroupId = kafkaGroupId;\n\t}\n\n\tpublic String getCampaignTopic() {\n\t\treturn campaignTopic;\n\t}\n\n\tpublic void setCampaignTopic(final String campaignTopic) {\n\t\tthis.campaignTopic = campaignTopic;\n\t}\n\n\tpublic String getTriggerTopic() {\n\t\treturn triggerTopic;\n\t}\n\n\tpublic void setTriggerTopic(final String triggerTopic) {\n\t\tthis.triggerTopic = triggerTopic;\n\t}\n\n}" }, { "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": "EvaluateFilter", "path": "src/main/java/com/innogames/analytics/rtcrm/function/EvaluateFilter.java", "snippet": "public class EvaluateFilter extends BroadcastProcessFunction<TrackingEvent, Campaign, Tuple2<TrackingEvent, Campaign>> {\n\n\t@Override\n\tpublic void processElement(\n\t\tfinal TrackingEvent event,\n\t\tfinal ReadOnlyContext readOnlyContext,\n\t\tfinal Collector<Tuple2<TrackingEvent, Campaign>> collector\n\t) throws Exception {\n\t\tif (event == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfinal Instant now = Instant.now();\n\t\tfinal Iterable<Map.Entry<Integer, Campaign>> campaignState = readOnlyContext.getBroadcastState(App.CAMPAIGN_STATE_DESCRIPTOR).immutableEntries();\n\t\tfinal Stream<Campaign> campaigns = StreamSupport.stream(\n\t\t\tcampaignState.spliterator(),\n\t\t\tfalse\n\t\t).map(Map.Entry::getValue);\n\n\t\tcampaigns\n\t\t\t.filter(Campaign::isEnabled)\n\t\t\t.filter(crmCampaign -> crmCampaign.getGame().equals(event.getGame()))\n\t\t\t.filter(crmCampaign -> crmCampaign.getEventName().equals(event.getEventName()))\n\t\t\t.filter(crmCampaign -> crmCampaign.getStartDate() != null && now.isAfter(Instant.parse(crmCampaign.getStartDate())))\n\t\t\t.filter(crmCampaign -> crmCampaign.getEndDate() != null && now.isBefore(Instant.parse(crmCampaign.getEndDate())))\n\t\t\t.filter(crmCampaign -> evaluateScriptResult(evaluateScript(crmCampaign, event)))\n\t\t\t.map(crmCampaign -> new Tuple2<>(event, crmCampaign))\n\t\t\t.forEach(collector::collect);\n\t}\n\n\t@Override\n\tpublic void processBroadcastElement(\n\t\tfinal Campaign campaign,\n\t\tfinal Context context,\n\t\tfinal Collector<Tuple2<TrackingEvent, Campaign>> collector\n\t) throws Exception {\n\t\tif (campaign == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tcontext.getBroadcastState(App.CAMPAIGN_STATE_DESCRIPTOR).put(campaign.getCampaignId(), campaign);\n\t}\n\n\tprivate Object evaluateScript(final Campaign campaign, final TrackingEvent event) {\n\t\ttry {\n\t\t\tfinal JSObject filterFunction = campaign.getFilterFunction();\n\t\t\treturn filterFunction.call(null, event);\n\t\t} catch (final Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate boolean evaluateScriptResult(final Object result) {\n\t\tif (result instanceof Boolean) {\n\t\t\treturn (boolean) result;\n\t\t} else if (ScriptObjectMirror.isUndefined(result)) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n}" }, { "identifier": "StringToCampaign", "path": "src/main/java/com/innogames/analytics/rtcrm/map/StringToCampaign.java", "snippet": "public class StringToCampaign implements MapFunction<String, Campaign> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic Campaign map(final String campaignString) {\n\t\ttry {\n\t\t\treturn objectMapper.readValue(campaignString, Campaign.class);\n\t\t} catch (final JsonProcessingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" }, { "identifier": "StringToTrackingEvent", "path": "src/main/java/com/innogames/analytics/rtcrm/map/StringToTrackingEvent.java", "snippet": "public class StringToTrackingEvent implements MapFunction<String, TrackingEvent> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\t@Override\n\tpublic TrackingEvent map(final String eventString) {\n\t\ttry {\n\t\t\treturn objectMapper.readValue(eventString, TrackingEvent.class);\n\t\t} catch (final JsonProcessingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n}" }, { "identifier": "TriggerCampaignSink", "path": "src/main/java/com/innogames/analytics/rtcrm/sink/TriggerCampaignSink.java", "snippet": "public class TriggerCampaignSink extends RichSinkFunction<Tuple2<TrackingEvent, Campaign>> {\n\n\tprivate static final ObjectMapper objectMapper = new ObjectMapper();\n\n\tprivate transient StringProducer stringProducer;\n\tprivate String triggerTopic;\n\n\t@Override\n\tpublic void open(Configuration configuration) {\n\t\tfinal ParameterTool parameters = (ParameterTool) getRuntimeContext().getExecutionConfig().getGlobalJobParameters();\n\n\t\ttriggerTopic = parameters.getRequired(\"trigger_topic\");\n\n\t\tfinal String kafkaBootstrapServers = parameters.getRequired(\"kafka_bootstrap_servers\");\n\t\tfinal Properties properties = new Properties();\n\t\tproperties.put(\"bootstrap.servers\", kafkaBootstrapServers);\n\n\t\tstringProducer = new StringProducer(properties);\n\t\tstringProducer.start();\n\t}\n\n\t@Override\n\tpublic void invoke(final Tuple2<TrackingEvent, Campaign> tuple, final Context context) throws Exception {\n\t\tfinal TrackingEvent event = tuple.f0;\n\t\tfinal Campaign campaign = tuple.f1;\n\n\t\tstringProducer.send(triggerTopic, objectMapper.writeValueAsString(new Trigger(campaign, event)));\n\t\tstringProducer.flush();\n\t}\n\n\t@Override\n\tpublic void close() throws Exception {\n\t\tsuper.close();\n\t\tstringProducer.stop();\n\t}\n\n}" } ]
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrm.config.Config; import com.innogames.analytics.rtcrm.entity.Campaign; import com.innogames.analytics.rtcrm.entity.TrackingEvent; import com.innogames.analytics.rtcrm.function.EvaluateFilter; import com.innogames.analytics.rtcrm.map.StringToCampaign; import com.innogames.analytics.rtcrm.map.StringToTrackingEvent; import com.innogames.analytics.rtcrm.sink.TriggerCampaignSink; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; import org.apache.flink.streaming.api.datastream.BroadcastStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
3,952
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream")
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream")
.map(new StringToCampaign()).setParallelism(1).name("parse-campaign")
4
2023-11-12 17:52:45+00:00
8k
BlyznytsiaOrg/bring
core/src/main/java/io/github/blyznytsiaorg/bring/core/context/type/parameter/ParameterListValueTypeInjector.java
[ { "identifier": "AnnotationBringBeanRegistry", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/AnnotationBringBeanRegistry.java", "snippet": "@Slf4j\npublic class AnnotationBringBeanRegistry extends DefaultBringBeanFactory implements BeanRegistry, BeanDefinitionRegistry {\n\n @Getter\n protected ClassPathScannerFactory classPathScannerFactory;\n private final BeanCreator beanCreator;\n private final Set<String> currentlyCreatingBeans = new HashSet<>();\n @Getter\n private final Reflections reflections;\n\n public AnnotationBringBeanRegistry(Reflections reflections) {\n this.reflections = reflections;\n this.classPathScannerFactory = new ClassPathScannerFactory(reflections);\n this.beanCreator = new BeanCreator(this, classPathScannerFactory);\n }\n\n /**\n * Registers beans in the application context. Creates and stores singleton bean objects or suppliers for prototype beans.\n * Also defines the proper way to create beans depending on the type of the bean (annotated class or configuration bean) \n * and injects dependant beans.\n * \n * @param beanName The name of the bean to be registered.\n * @param beanDefinition The definition of the bean being registered.\n */\n @Override\n public void registerBean(String beanName, BeanDefinition beanDefinition) {\n log.info(\"Registering Bean with name \\\"{}\\\" into Bring context...\", beanName);\n\n Class<?> clazz = beanDefinition.getBeanClass();\n\n if (currentlyCreatingBeans.contains(beanName)) {\n log.error(\"Cyclic dependency detected!\");\n throw new CyclicBeanException(currentlyCreatingBeans);\n }\n\n if (isBeanCreated(beanName)) {\n log.info(\"Bean with name \\\"{}\\\" already created, no need to register it again.\", beanName);\n return;\n }\n\n currentlyCreatingBeans.add(beanName);\n\n if (beanDefinition.isConfigurationBean()) {\n beanCreator.registerConfigurationBean(beanName, beanDefinition);\n } else {\n beanCreator.create(clazz, beanName, beanDefinition);\n }\n\n currentlyCreatingBeans.clear();\n }\n\n /**\n * Stores a bean definition into {@code DefaultBringBeanFactory.beanDefinitionMap} by a name generated via \n * {@code AnnotationResolver}. Beans are created based on these bean definitions. \n * \n * @param beanDefinition The definition of the bean to be registered.\n */\n @Override\n public void registerBeanDefinition(BeanDefinition beanDefinition) {\n String beanName = classPathScannerFactory.resolveBeanName(beanDefinition.getBeanClass());\n addBeanDefinition(beanName, beanDefinition);\n }\n\n /**\n * Retrieves an existing bean with the given name from the container, or creates and registers a new bean if it doesn't exist.\n *\n * @param beanName The name of the bean to retrieve or create.\n * @return An instance of the requested bean. If the bean already exists, the existing instance is returned; otherwise, a new instance is created and returned.\n */\n public Object getOrCreateBean(String beanName) {\n Object existingBean = getBeanByName(beanName);\n\n if (Objects.nonNull(existingBean)) {\n return existingBean;\n }\n\n BeanDefinition beanDefinition = getBeanDefinitionMap().get(beanName);\n\n if (beanDefinition != null) {\n registerBean(beanName, beanDefinition);\n }\n\n return getBeanByName(beanName);\n }\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": "AbstractValueTypeInjector", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/type/AbstractValueTypeInjector.java", "snippet": "public abstract class AbstractValueTypeInjector {\n\n private static final BiFunction<List<BeanDefinition>, String, List<BeanDefinition>> PRIMARY_FILTER_FUNCTION =\n (beanDefinitions, qualifier) -> beanDefinitions.stream()\n .filter(BeanDefinition::isPrimary\n ).toList();\n\n private final AnnotationBringBeanRegistry beanRegistry;\n private final ClassPathScannerFactory classPathScannerFactory;\n\n private final BiFunction<List<BeanDefinition>, String, List<BeanDefinition>> QUALIFIER_FILTER_FUNCTION;\n\n /**\n * Constructs a new instance of {@code AbstractValueTypeInjector}.\n *\n * @param beanRegistry The bean registry for managing created beans.\n * @param classPathScannerFactory The factory for creating classpath scanners.\n */\n protected AbstractValueTypeInjector(AnnotationBringBeanRegistry beanRegistry,\n ClassPathScannerFactory classPathScannerFactory) {\n this.beanRegistry = beanRegistry;\n this.classPathScannerFactory = classPathScannerFactory;\n\n QUALIFIER_FILTER_FUNCTION = (beanDefinitions, qualifier) -> beanDefinitions.stream()\n .filter(bd -> classPathScannerFactory.resolveBeanName(bd.getBeanClass()).equals(qualifier))\n .toList();\n }\n\n /**\n * Injects dependencies for a List of classes into bean objects.\n *\n * @param value The list of classes for which dependencies need to be injected.\n * @return A list of bean objects representing the injected dependencies.\n */\n public List<Object> injectListDependency(List<Class<?>> value) {\n List<Object> dependencyObjects = new ArrayList<>();\n for (var impl : value) {\n String implBeanName = classPathScannerFactory.resolveBeanName(impl);\n Object dependecyObject = beanRegistry.getOrCreateBean(implBeanName);\n dependencyObjects.add(dependecyObject);\n }\n\n return dependencyObjects;\n }\n\n /**\n * Injects dependencies for a List of classes into bean objects and returns a set of unique dependencies.\n *\n * @param value The list of classes for which dependencies need to be injected.\n * @return A set of unique bean objects representing the injected dependencies.\n */\n public Set<Object> injectSetDependency(List<Class<?>> value) {\n Set<Object> dependencyObjects = new LinkedHashSet<>();\n for (var impl : value) {\n String implBeanName = classPathScannerFactory.resolveBeanName(impl);\n Object dependecyObject = beanRegistry.getOrCreateBean(implBeanName);\n dependencyObjects.add(dependecyObject);\n }\n\n return dependencyObjects;\n }\n\n public Object findImplementationByPrimaryOrQualifier(List<Class<?>> implementationTypes, Class<?> fieldType, String qualifier, String fieldName) {\n List<BeanDefinition> beanDefinitions = implementationTypes.stream()\n .map(impl -> beanRegistry.getBeanDefinitionMap().get(getBeanName(impl)))\n .toList();\n var dependencyObject = findProperBean(beanDefinitions, fieldType, qualifier, PRIMARY_FILTER_FUNCTION);\n\n if(dependencyObject.isPresent()) {\n return dependencyObject.get();\n } else {\n dependencyObject = findProperBean(beanDefinitions, fieldType, qualifier, QUALIFIER_FILTER_FUNCTION);\n if(dependencyObject.isPresent()) {\n return dependencyObject.get();\n } else {\n return findProperBeanByName(fieldType, fieldName);\n }\n }\n }\n\n private Object findProperBeanByName(Class<?> type, String paramName) {\n String beanName = checkByBeanName(getBeanNames(type), paramName, type);\n return beanRegistry.getOrCreateBean(beanName);\n }\n\n private String checkByBeanName(List<String> beanNames, String paramName, Class<?> type) {\n if (beanNames.isEmpty()) {\n if (type.isInterface()) {\n throw new NoSuchBeanException(String.format(\"No such bean that implements this %s \", type));\n }\n throw new NoSuchBeanException(type);\n }\n\n return beanNames.stream()\n .filter(name -> name.equalsIgnoreCase(paramName))\n .findFirst()\n .orElseThrow(() -> new NoUniqueBeanException(type, beanNames));\n }\n\n private List<String> getBeanNames (Class<?> clazz) {\n return clazz.isInterface()\n ? beanRegistry.getTypeToBeanNames().entrySet().stream()\n .filter(entry -> clazz.isAssignableFrom(entry.getKey()))\n .map(Map.Entry::getValue)\n .flatMap(Collection::stream)\n .toList()\n : Optional.ofNullable(beanRegistry.getTypeToBeanNames().get(clazz)).orElse(\n Collections.emptyList());\n }\n\n private <T> String getBeanName(Class<? extends T> type) {\n List<String> beanNames = Optional.ofNullable(beanRegistry.getTypeToBeanNames().get(type))\n .orElseThrow(() -> new NoSuchBeanException(type));\n if (beanNames.size() != 1) {\n throw new NoUniqueBeanException(type);\n }\n return beanNames.get(0);\n }\n\n private Optional<?> findProperBean(List<BeanDefinition> beanDefinitions,\n Class<?> interfaceType, String qualifier, BiFunction<List<BeanDefinition>, String, List<BeanDefinition>>filter) {\n if (beanDefinitions.size() == 1) {\n var beanDefinition = beanDefinitions.get(0);\n return Optional.ofNullable(beanRegistry.getOrCreateBean(classPathScannerFactory.resolveBeanName(beanDefinition.getBeanClass())));\n } else {\n var filteredBeanDefinitions = filter.apply(beanDefinitions, qualifier);\n\n if(filteredBeanDefinitions.size() > 1) {\n throw new NoUniqueBeanException(interfaceType);\n } else if (filteredBeanDefinitions.size() == 1) {\n var beanName = classPathScannerFactory.resolveBeanName(filteredBeanDefinitions.get(0).getBeanClass());\n return Optional.ofNullable(beanRegistry.getOrCreateBean(beanName));\n }\n }\n return Optional.empty();\n }\n\n}" }, { "identifier": "ReflectionUtils", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/utils/ReflectionUtils.java", "snippet": "@UtilityClass\n@Slf4j\npublic final class ReflectionUtils {\n private static final String BEAN_SHOULD_HAVE_MESSAGE = \"BeanProcessor '%s' should have \";\n private static final String BEAN_SHOULD_HAVE_DEFAULT_CONSTRUCTOR_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"only default constructor without params\";\n private static final String BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_ONE_PARAMETER_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"constructor with one parameter '%s'.\";\n private static final String BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_PARAMETERS_MESSAGE =\n BEAN_SHOULD_HAVE_MESSAGE + \"constructor with parameters '%s'.\";\n private static final String DELIMITER = \", \";\n\n public static final OrderComparator ORDER_COMPARATOR = new OrderComparator();\n private static final Paranamer info = new CachingParanamer(new QualifierAnnotationParanamer(new BytecodeReadingParanamer()));\n private static final String ARG = \"arg\";\n\n private static final String SET_METHOD_START_PREFIX = \"set\";\n\n /**\n * Checks if the given method is an autowired setter method.\n *\n * @param method The method to be checked\n * @return True if the method is an autowired setter method, otherwise false\n */\n public static boolean isAutowiredSetterMethod(Method method) {\n return method.isAnnotationPresent(Autowired.class) && method.getName().startsWith(SET_METHOD_START_PREFIX);\n }\n\n /**\n * Retrieves the instance of a class by invoking the default (parameterless) constructor.\n *\n * @param clazz The class for which an instance should be created\n * @return An instance of the specified class\n * @throws BeanPostProcessorConstructionLimitationException If the default constructor is not present or accessible\n */\n public static Object getConstructorWithOutParameters(Class<?> clazz) {\n try {\n Constructor<?> constructor = clazz.getConstructor();\n return constructor.newInstance();\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_DEFAULT_CONSTRUCTOR_MESSAGE, clazz.getSimpleName()));\n }\n }\n\n /**\n * Retrieves the instance of a class by invoking a constructor with a single parameter.\n *\n * @param clazz The class for which an instance should be created\n * @param parameterType The type of the constructor's single parameter\n * @param instance The instance to be passed as the constructor's argument\n * @return An instance of the specified class created using the provided parameter\n * @throws BeanPostProcessorConstructionLimitationException If the constructor with a single parameter is not present or accessible\n */\n public static Object getConstructorWithOneParameter(Class<?> clazz, Class<?> parameterType, Object instance) {\n try {\n Constructor<?> constructor = clazz.getConstructor(parameterType);\n return constructor.newInstance(instance);\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_ONE_PARAMETER_MESSAGE,\n clazz.getSimpleName(),\n parameterType.getSimpleName()));\n }\n }\n\n /**\n * Retrieves the instance of a class by invoking a constructor with multiple parameters.\n *\n * @param clazz The class for which an instance should be created\n * @param parameterTypesToInstance A map containing parameter types and their corresponding instances\n * @return An instance of the specified class created using the provided parameters\n * @throws BeanPostProcessorConstructionLimitationException If the constructor with specified parameters is not present or accessible\n */\n public static Object getConstructorWithParameters(Class<?> clazz, Map<Class<?>, Object> parameterTypesToInstance) {\n try {\n Constructor<?> constructor = clazz.getConstructor(parameterTypesToInstance.keySet().toArray(new Class[0]));\n return constructor.newInstance(parameterTypesToInstance.values().toArray());\n } catch (Exception ex) {\n throw new BeanPostProcessorConstructionLimitationException(\n String.format(BEAN_SHOULD_HAVE_CONSTRUCTOR_WITH_PARAMETERS_MESSAGE,\n clazz.getSimpleName(),\n parameterTypesToInstance.keySet().stream()\n .map(Class::getSimpleName)\n .collect(Collectors.joining(DELIMITER))));\n }\n }\n\n /**\n * Sets a field's value within an object.\n *\n * @param field The field to be modified\n * @param obj The object containing the field\n * @param value The value to be set in the field\n */\n @SneakyThrows\n public static void setField(Field field, Object obj, Object value) {\n log.trace(\"Setting into field \\\"{}\\\" of {} the value {}\", field.getName(), obj, value);\n try {\n field.setAccessible(true);\n field.set(obj, value);\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n }\n\n /**\n * Retrieves parameter names of a method or constructor.\n *\n * @param methodOrConstructor The method or constructor to retrieve parameter names from\n * @return A list of parameter names\n */\n public static List<String> getParameterNames(AccessibleObject methodOrConstructor) {\n return Arrays.stream(info.lookupParameterNames(methodOrConstructor)).toList();\n }\n\n /**\n * Extracts the position of a parameter.\n *\n * @param parameter The parameter to extract the position from\n * @return The position of the parameter\n */\n public static int extractParameterPosition(Parameter parameter) {\n String name = parameter.getName();\n return Integer.parseInt(name.substring(name.indexOf(ARG) + ARG.length()));\n }\n\n /**\n * Extracts implementation classes of a generic type.\n *\n * @param genericType The generic type\n * @param reflections The Reflections object to query types\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return A list of implementation classes\n */\n @SneakyThrows\n public static List<Class<?>> extractImplClasses(ParameterizedType genericType, Reflections reflections,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n Type actualTypeArgument = genericType.getActualTypeArguments()[0];\n if (actualTypeArgument instanceof Class actualTypeArgumentClass) {\n String name = actualTypeArgumentClass.getName();\n Class<?> interfaceClass = Class.forName(name);\n log.trace(\"Extracting implementations of {} for injection\", interfaceClass.getName());\n\n return reflections.getSubTypesOf(interfaceClass)\n .stream()\n .filter(implementation -> isImplementationAnnotated(implementation, createdBeanAnnotations))\n .sorted(ORDER_COMPARATOR)\n .collect(Collectors.toList());\n }\n return Collections.emptyList();\n }\n\n /**\n * Extracts implementation classes of a given type.\n *\n * @param type The type to extract implementations for\n * @param reflections The Reflections object to query types\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return A list of implementation classes\n */\n public static List<Class<?>> extractImplClasses(Class<?> type, Reflections reflections,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n return (List<Class<?>>)reflections.getSubTypesOf(type)\n .stream()\n .filter(implementation -> isImplementationAnnotated(implementation, createdBeanAnnotations))\n .toList();\n }\n\n /**\n * Checks if an implementation class is annotated with any of the specified annotations.\n *\n * @param implementation The implementation class to check\n * @param createdBeanAnnotations List of annotations indicating created beans\n * @return True if the implementation is annotated, otherwise false\n */\n private static boolean isImplementationAnnotated(Class<?> implementation,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n return Arrays.stream(implementation.getAnnotations())\n .map(Annotation::annotationType)\n .anyMatch(createdBeanAnnotations::contains);\n }\n\n /**\n * Invokes a method on an object and returns a Supplier for its result.\n *\n * @param method The method to invoke\n * @param obj The object to invoke the method on\n * @param params The parameters to pass to the method\n * @return A Supplier representing the method invocation\n */\n public static Supplier<Object> invokeBeanMethod(Method method, Object obj, Object[] params) {\n return () -> {\n try {\n return method.invoke(obj, params);\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n };\n }\n\n /**\n * Creates a new instance using the given constructor and arguments and returns a Supplier for it.\n *\n * @param constructor The constructor to create the instance\n * @param args The arguments to pass to the constructor\n * @param clazz The class of the instance to be created\n * @param proxy Boolean flag indicating whether to use proxy creation\n * @return A Supplier representing the new instance creation\n */\n public static Supplier<Object> createNewInstance(Constructor<?> constructor, Object[] args, Class<?> clazz,\n boolean proxy) {\n return () -> {\n try {\n if (proxy) {\n return ProxyUtils.createProxy(clazz, constructor, args);\n } else {\n return constructor.newInstance(args);\n }\n } catch (Exception e) {\n throw new BringGeneralException(e);\n }\n };\n }\n\n /**\n * Processes the annotations on the methods of a bean.\n *\n * @param bean The bean object\n * @param declaredMethods The methods of the bean to process\n * @param annotation The annotation to process\n * @throws ReflectiveOperationException If an error occurs during reflective operations\n */\n public static void processBeanPostProcessorAnnotation(Object bean,\n Method[] declaredMethods,\n Class<? extends Annotation> annotation)\n throws ReflectiveOperationException {\n for (Method declaredMethod : declaredMethods) {\n if (declaredMethod.isAnnotationPresent(annotation)) {\n declaredMethod.invoke(bean);\n }\n }\n }\n\n /**\n * Inner class extending AnnotationParanamer to handle Qualifier annotations.\n */\n private static class QualifierAnnotationParanamer extends AnnotationParanamer {\n\n public QualifierAnnotationParanamer(Paranamer fallback) {\n super(fallback);\n }\n\n @Override\n protected String getNamedValue(Annotation ann) {\n if (Objects.equals(Qualifier.class, ann.annotationType())) {\n Qualifier qualifier = (Qualifier) ann;\n return qualifier.value();\n } else {\n return null;\n }\n }\n\n @Override\n protected boolean isNamed(Annotation ann) {\n return Objects.equals(Qualifier.class, ann.annotationType());\n }\n }\n}" }, { "identifier": "extractImplClasses", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/utils/ReflectionUtils.java", "snippet": "@SneakyThrows\npublic static List<Class<?>> extractImplClasses(ParameterizedType genericType, Reflections reflections,\n List<Class<? extends Annotation>> createdBeanAnnotations) {\n Type actualTypeArgument = genericType.getActualTypeArguments()[0];\n if (actualTypeArgument instanceof Class actualTypeArgumentClass) {\n String name = actualTypeArgumentClass.getName();\n Class<?> interfaceClass = Class.forName(name);\n log.trace(\"Extracting implementations of {} for injection\", interfaceClass.getName());\n\n return reflections.getSubTypesOf(interfaceClass)\n .stream()\n .filter(implementation -> isImplementationAnnotated(implementation, createdBeanAnnotations))\n .sorted(ORDER_COMPARATOR)\n .collect(Collectors.toList());\n }\n return Collections.emptyList();\n}" } ]
import io.github.blyznytsiaorg.bring.core.context.impl.AnnotationBringBeanRegistry; import io.github.blyznytsiaorg.bring.core.context.scaner.ClassPathScannerFactory; import io.github.blyznytsiaorg.bring.core.context.type.AbstractValueTypeInjector; import io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils; import org.reflections.Reflections; import java.lang.annotation.Annotation; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.util.List; import static io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils.extractImplClasses;
6,130
package io.github.blyznytsiaorg.bring.core.context.type.parameter; /** * The {@code ParameterListValueTypeInjector} class is responsible for handling parameter injections for types of List. * It extends the functionality of the AbstractValueTypeInjector and works in conjunction with a framework, * utilizing the bean registry and classpath scanner to recognize parameters of type List. The injector extracts * implementation classes based on the generic type of the List and injects the corresponding dependencies. * * @author Blyzhnytsia Team * @since 1.0 */ public class ParameterListValueTypeInjector extends AbstractValueTypeInjector implements ParameterValueTypeInjector{ private final Reflections reflections; /** * Constructs a new instance of {@code ParameterListValueTypeInjector}. * * @param reflections The Reflections instance for scanning annotated classes. * @param beanRegistry The bean registry for managing created beans. * @param classPathScannerFactory The factory for creating classpath scanners. */ public ParameterListValueTypeInjector(Reflections reflections, AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { super(beanRegistry, classPathScannerFactory); this.reflections = reflections; } /** * Checks if the specified parameter is annotated with a value. * * @param parameter The parameter to check. * @return {@code true} if the parameter is of type List, {@code false} otherwise. */ @Override public boolean hasAnnotatedWithValue(Parameter parameter) { return List.class.isAssignableFrom(parameter.getType()); } /** * Sets the value to the specified parameter by injecting dependencies based on the generic type of the List. * * @param parameter The parameter to inject value into. * @param createdBeanAnnotations The annotations used for creating the bean. * @return The result of injecting dependencies into the List parameter. */ @Override public Object setValueToSetter(Parameter parameter, String parameterName, List<Class<? extends Annotation>> createdBeanAnnotations) { ParameterizedType genericTypeOfField = (ParameterizedType) parameter.getParameterizedType();
package io.github.blyznytsiaorg.bring.core.context.type.parameter; /** * The {@code ParameterListValueTypeInjector} class is responsible for handling parameter injections for types of List. * It extends the functionality of the AbstractValueTypeInjector and works in conjunction with a framework, * utilizing the bean registry and classpath scanner to recognize parameters of type List. The injector extracts * implementation classes based on the generic type of the List and injects the corresponding dependencies. * * @author Blyzhnytsia Team * @since 1.0 */ public class ParameterListValueTypeInjector extends AbstractValueTypeInjector implements ParameterValueTypeInjector{ private final Reflections reflections; /** * Constructs a new instance of {@code ParameterListValueTypeInjector}. * * @param reflections The Reflections instance for scanning annotated classes. * @param beanRegistry The bean registry for managing created beans. * @param classPathScannerFactory The factory for creating classpath scanners. */ public ParameterListValueTypeInjector(Reflections reflections, AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { super(beanRegistry, classPathScannerFactory); this.reflections = reflections; } /** * Checks if the specified parameter is annotated with a value. * * @param parameter The parameter to check. * @return {@code true} if the parameter is of type List, {@code false} otherwise. */ @Override public boolean hasAnnotatedWithValue(Parameter parameter) { return List.class.isAssignableFrom(parameter.getType()); } /** * Sets the value to the specified parameter by injecting dependencies based on the generic type of the List. * * @param parameter The parameter to inject value into. * @param createdBeanAnnotations The annotations used for creating the bean. * @return The result of injecting dependencies into the List parameter. */ @Override public Object setValueToSetter(Parameter parameter, String parameterName, List<Class<? extends Annotation>> createdBeanAnnotations) { ParameterizedType genericTypeOfField = (ParameterizedType) parameter.getParameterizedType();
List<Class<?>> dependencies = ReflectionUtils.extractImplClasses(genericTypeOfField, reflections, createdBeanAnnotations);
3
2023-11-10 13:42:05+00:00
8k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/terminalfragment/TerminalFragment.java
[ { "identifier": "BAUD_RATE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int BAUD_RATE = 19200;" }, { "identifier": "DATA_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int DATA_BITS = 8;" }, { "identifier": "PARITY_NONE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final String PARITY_NONE = \"PARITY_NONE\";" }, { "identifier": "STOP_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int STOP_BITS = 1;" }, { "identifier": "LauncherOutputData", "path": "app/src/main/java/com/johndeweydev/awps/model/data/LauncherOutputData.java", "snippet": "public class LauncherOutputData {\n\n private String time;\n private final String output;\n\n\n public LauncherOutputData(String time, String output) {\n this.time = time;\n this.output = output;\n }\n\n public String getTime() {\n return time;\n }\n\n public String getOutput() {\n return output;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n}" }, { "identifier": "TerminalViewModel", "path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/terminalviewmodel/TerminalViewModel.java", "snippet": "public class TerminalViewModel extends ViewModel implements ViewModelIOControl,\n TerminalRepoSerial.RepositoryEvent {\n\n /**\n * Device id, port number and baud rate is set by terminal fragment as a backup source\n * in case getArgument is empty when terminal fragment goes to onCreateView state\n * */\n public int deviceIdFromTerminalArgs;\n public int portNumFromTerminalArgs;\n public int baudRateFromTerminalArgs;\n\n public TerminalRepoSerial terminalRepoSerial;\n public MutableLiveData<ArrayList<UsbDeviceData>> devicesList = new MutableLiveData<>();\n public MutableLiveData<LauncherOutputData> currentSerialOutput = new MutableLiveData<>();\n public MutableLiveData<LauncherOutputData> currentSerialOutputRaw = new MutableLiveData<>();\n public MutableLiveData<String> currentSerialInputError = new MutableLiveData<>();\n public MutableLiveData<String> currentSerialOutputError = new MutableLiveData<>();\n\n public TerminalViewModel(TerminalRepoSerial terminalRepoSerial) {\n Log.w(\"dev-log\", \"TerminalViewModel: Created new instance of TerminalViewModel\");\n this.terminalRepoSerial = terminalRepoSerial;\n terminalRepoSerial.setEventHandler(this);\n }\n\n public void writeDataToDevice(String data) {\n terminalRepoSerial.writeDataToDevice(data);\n }\n\n public int getAvailableDevices() {\n ArrayList<UsbDeviceData> devices = terminalRepoSerial.getAvailableDevices();\n devicesList.setValue(devices);\n return devices.size();\n }\n\n @Override\n public void setLauncherEventHandler() {\n terminalRepoSerial.setLauncherEventHandler();\n }\n\n @Override\n public String connectToDevice(DeviceConnectionParamData deviceConnectionParamData) {\n return terminalRepoSerial.connectToDevice(deviceConnectionParamData);\n }\n\n @Override\n public void disconnectFromDevice() {\n terminalRepoSerial.disconnectFromDevice();\n }\n\n @Override\n public void startEventDrivenReadFromDevice() {\n terminalRepoSerial.startEventDrivenReadFromDevice();\n }\n\n @Override\n public void stopEventDrivenReadFromDevice() {\n terminalRepoSerial.stopEventDrivenReadFromDevice();\n }\n\n @Override\n public void onRepoOutputRaw(LauncherOutputData launcherSerialOutputData) {\n String time = \"[\" + launcherSerialOutputData.getTime() + \"]\";\n launcherSerialOutputData.setTime(time);\n currentSerialOutputRaw.postValue(launcherSerialOutputData);\n }\n @Override\n public void onRepoOutputFormatted(LauncherOutputData launcherSerialOutputData) {\n Log.d(\"dev-log\", \"TerminalViewModel.onLauncherOutputFormatted: Serial -> \" +\n launcherSerialOutputData.getOutput());\n\n String time = \"[\" + launcherSerialOutputData.getTime() + \"]\";\n launcherSerialOutputData.setTime(time);\n currentSerialOutput.postValue(launcherSerialOutputData);\n }\n @Override\n public void onRepoOutputError(String error) {\n Log.d(\"dev-log\", \"TerminalViewModel.onLauncherOutputError: Serial -> \" + error);\n currentSerialOutputError.postValue(error);\n }\n @Override\n public void onRepoInputError(String input) {\n Log.d(\"dev-log\", \"TerminalViewModel.onLauncherInputError: Serial -> \" + input);\n currentSerialInputError.postValue(input);\n }\n}" }, { "identifier": "AutoArmaArgs", "path": "app/src/main/java/com/johndeweydev/awps/view/autoarmafragment/AutoArmaArgs.java", "snippet": "public class AutoArmaArgs implements Parcelable {\n\n private final int deviceId;\n private final int portNum;\n private final int baudRate;\n private String selectedArmament = \"\";\n\n public AutoArmaArgs(int deviceId, int portNum, int baudRate, String selectedArmament) {\n this.deviceId = deviceId;\n this.portNum = portNum;\n this.baudRate = baudRate;\n this.selectedArmament = selectedArmament;\n }\n\n public int getDeviceId() {\n return deviceId;\n }\n\n public int getPortNum() {\n return portNum;\n }\n\n public int getBaudRate() {\n return baudRate;\n }\n\n public String getSelectedArmament() {return selectedArmament;}\n\n protected AutoArmaArgs(Parcel in) {\n deviceId = in.readInt();\n portNum = in.readInt();\n baudRate = in.readInt();\n selectedArmament = in.readString();\n }\n\n public static final Creator<com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs>\n CREATOR = new Creator<com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs>() {\n @Override\n public com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs createFromParcel(Parcel in) {\n return new com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs(in);\n }\n\n @Override\n public com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs[] newArray(int size) {\n return new com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(@NonNull Parcel dest, int flags) {\n dest.writeInt(deviceId);\n dest.writeInt(portNum);\n dest.writeInt(baudRate);\n dest.writeString(selectedArmament);\n }\n}" }, { "identifier": "ManualArmaArgs", "path": "app/src/main/java/com/johndeweydev/awps/view/manualarmafragment/ManualArmaArgs.java", "snippet": "public class ManualArmaArgs implements Parcelable {\n\n private final int deviceId;\n private final int portNum;\n private final int baudRate;\n private String selectedArmament = \"\";\n\n public ManualArmaArgs(int deviceId, int portNum, int baudRate, String selectedArmament) {\n this.deviceId = deviceId;\n this.portNum = portNum;\n this.baudRate = baudRate;\n this.selectedArmament = selectedArmament;\n }\n\n public int getDeviceId() {\n return deviceId;\n }\n\n public int getPortNum() {\n return portNum;\n }\n\n public String getSelectedArmament() {return selectedArmament;}\n\n protected ManualArmaArgs(Parcel in) {\n deviceId = in.readInt();\n portNum = in.readInt();\n baudRate = in.readInt();\n selectedArmament = in.readString();\n }\n\n public static final Creator<com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs>\n CREATOR = new Creator<>() {\n @Override\n public com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs createFromParcel(Parcel in) {\n return new com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs(in);\n }\n\n @Override\n public com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs[] newArray(int size) {\n return new com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(@NonNull Parcel dest, int flags) {\n dest.writeInt(deviceId);\n dest.writeInt(portNum);\n dest.writeInt(baudRate);\n dest.writeString(selectedArmament);\n }\n}" } ]
import static com.johndeweydev.awps.AppConstants.BAUD_RATE; import static com.johndeweydev.awps.AppConstants.DATA_BITS; import static com.johndeweydev.awps.AppConstants.PARITY_NONE; import static com.johndeweydev.awps.AppConstants.STOP_BITS; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText; import com.johndeweydev.awps.R; import com.johndeweydev.awps.databinding.FragmentTerminalBinding; import com.johndeweydev.awps.model.data.DeviceConnectionParamData; import com.johndeweydev.awps.model.data.LauncherOutputData; import com.johndeweydev.awps.viewmodel.serial.terminalviewmodel.TerminalViewModel; import com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs; import com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs;
3,706
if (terminalArgs == null) { Log.d("dev-log", "TerminalFragment.onViewCreated: Terminal args is null"); Navigation.findNavController(binding.getRoot()).popBackStack(); return; } binding.materialToolBarTerminal.setNavigationOnClickListener(v -> binding.drawerLayoutTerminal.open()); TerminalRVAdapter terminalRVAdapter = setupRecyclerView(); binding.navigationViewTerminal.setNavigationItemSelectedListener(item -> navItemSelected(item, terminalRVAdapter)); binding.buttonCreateCommandTerminal.setOnClickListener(v -> showDialogAskUserToEnterInstructionCode()); setupObservers(terminalRVAdapter); } private TerminalRVAdapter setupRecyclerView() { TerminalRVAdapter terminalRVAdapter = new TerminalRVAdapter(); LinearLayoutManager layout = new LinearLayoutManager(requireContext()); layout.setStackFromEnd(true); binding.recyclerViewLogsTerminal.setAdapter(terminalRVAdapter); binding.recyclerViewLogsTerminal.setLayoutManager(layout); return terminalRVAdapter; } private void showDialogAskUserToEnterInstructionCode() { View dialogCommandInput = LayoutInflater.from(requireContext()).inflate( R.layout.dialog_command_input, null); TextInputEditText textInputEditTextDialogCommandInput = dialogCommandInput.findViewById( R.id.textInputEditTextDialogCommandInput); textInputEditTextDialogCommandInput.requestFocus(); MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle("Command Instruction Input"); builder.setMessage("Enter command instruction code that will be sent to the launcher module"); builder.setView(dialogCommandInput); builder.setPositiveButton("SEND", (dialog, which) -> { if (textInputEditTextDialogCommandInput.getText() == null) { dialog.dismiss(); } String instructionCode = textInputEditTextDialogCommandInput.getText().toString(); terminalViewModel.writeDataToDevice(instructionCode); }); builder.setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss()); AlertDialog dialog = builder.create(); if (dialog.getWindow() != null) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } dialog.show(); } private void setupObservers(TerminalRVAdapter terminalRVAdapter) { final Observer<LauncherOutputData> currentSerialOutputObserver = s -> { if (s == null) { return; } terminalRVAdapter.appendNewTerminalLog(s); binding.recyclerViewLogsTerminal.scrollToPosition(terminalRVAdapter.getItemCount() - 1); }; terminalViewModel.currentSerialOutputRaw.observe(getViewLifecycleOwner(), currentSerialOutputObserver); terminalViewModel.currentSerialOutput.observe(getViewLifecycleOwner(), currentSerialOutputObserver); setupSerialInputErrorListener(); setupSerialOutputErrorListener(); } private void setupSerialInputErrorListener() { final Observer<String> writeErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialInputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Error on user input"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error writing " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialInputError.observe(getViewLifecycleOwner(), writeErrorListener); } private void setupSerialOutputErrorListener() { final Observer<String> onNewDataErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialOutputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Error on serial output"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error: " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialOutputError.observe( getViewLifecycleOwner(), onNewDataErrorListener); } @Override public void onResume() { super.onResume(); Log.d("dev-log", "TerminalFragment.onResume: Fragment resumed"); Log.d("dev-log", "TerminalFragment.onResume: Connecting to device"); connectToDevice(); terminalViewModel.setLauncherEventHandler(); } private void connectToDevice() { int deviceId = terminalArgs.getDeviceId(); int portNum = terminalArgs.getPortNum(); DeviceConnectionParamData deviceConnectionParamData = new DeviceConnectionParamData(
package com.johndeweydev.awps.view.terminalfragment; public class TerminalFragment extends Fragment { private FragmentTerminalBinding binding; private String selectedArmament; private TerminalViewModel terminalViewModel; private TerminalArgs terminalArgs = null; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { terminalViewModel = new ViewModelProvider(requireActivity()).get(TerminalViewModel.class); binding = FragmentTerminalBinding.inflate(inflater, container, false); if (getArguments() == null) { Log.d("dev-log", "TerminalFragment.onCreateView: Get arguments is null"); } else { Log.d("dev-log", "TerminalFragment.onCreateView: Initializing fragment args"); TerminalFragmentArgs terminalFragmentArgs; if (getArguments().isEmpty()) { Log.w("dev-log", "TerminalFragment.onCreateView: Terminal argument is missing, " + "using data in the view model"); terminalArgs = new TerminalArgs( terminalViewModel.deviceIdFromTerminalArgs, terminalViewModel.portNumFromTerminalArgs, terminalViewModel.baudRateFromTerminalArgs); } else { Log.d("dev-log", "TerminalFragment.onCreateView: Getting terminal argument " + "from bundle"); terminalFragmentArgs = TerminalFragmentArgs.fromBundle(getArguments()); terminalArgs = terminalFragmentArgs.getTerminalArgs(); terminalViewModel.deviceIdFromTerminalArgs = terminalArgs.getDeviceId(); terminalViewModel.portNumFromTerminalArgs = terminalArgs.getPortNum(); terminalViewModel.baudRateFromTerminalArgs = terminalArgs.getBaudRate(); } } return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (terminalArgs == null) { Log.d("dev-log", "TerminalFragment.onViewCreated: Terminal args is null"); Navigation.findNavController(binding.getRoot()).popBackStack(); return; } binding.materialToolBarTerminal.setNavigationOnClickListener(v -> binding.drawerLayoutTerminal.open()); TerminalRVAdapter terminalRVAdapter = setupRecyclerView(); binding.navigationViewTerminal.setNavigationItemSelectedListener(item -> navItemSelected(item, terminalRVAdapter)); binding.buttonCreateCommandTerminal.setOnClickListener(v -> showDialogAskUserToEnterInstructionCode()); setupObservers(terminalRVAdapter); } private TerminalRVAdapter setupRecyclerView() { TerminalRVAdapter terminalRVAdapter = new TerminalRVAdapter(); LinearLayoutManager layout = new LinearLayoutManager(requireContext()); layout.setStackFromEnd(true); binding.recyclerViewLogsTerminal.setAdapter(terminalRVAdapter); binding.recyclerViewLogsTerminal.setLayoutManager(layout); return terminalRVAdapter; } private void showDialogAskUserToEnterInstructionCode() { View dialogCommandInput = LayoutInflater.from(requireContext()).inflate( R.layout.dialog_command_input, null); TextInputEditText textInputEditTextDialogCommandInput = dialogCommandInput.findViewById( R.id.textInputEditTextDialogCommandInput); textInputEditTextDialogCommandInput.requestFocus(); MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle("Command Instruction Input"); builder.setMessage("Enter command instruction code that will be sent to the launcher module"); builder.setView(dialogCommandInput); builder.setPositiveButton("SEND", (dialog, which) -> { if (textInputEditTextDialogCommandInput.getText() == null) { dialog.dismiss(); } String instructionCode = textInputEditTextDialogCommandInput.getText().toString(); terminalViewModel.writeDataToDevice(instructionCode); }); builder.setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss()); AlertDialog dialog = builder.create(); if (dialog.getWindow() != null) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } dialog.show(); } private void setupObservers(TerminalRVAdapter terminalRVAdapter) { final Observer<LauncherOutputData> currentSerialOutputObserver = s -> { if (s == null) { return; } terminalRVAdapter.appendNewTerminalLog(s); binding.recyclerViewLogsTerminal.scrollToPosition(terminalRVAdapter.getItemCount() - 1); }; terminalViewModel.currentSerialOutputRaw.observe(getViewLifecycleOwner(), currentSerialOutputObserver); terminalViewModel.currentSerialOutput.observe(getViewLifecycleOwner(), currentSerialOutputObserver); setupSerialInputErrorListener(); setupSerialOutputErrorListener(); } private void setupSerialInputErrorListener() { final Observer<String> writeErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialInputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Error on user input"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error writing " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialInputError.observe(getViewLifecycleOwner(), writeErrorListener); } private void setupSerialOutputErrorListener() { final Observer<String> onNewDataErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialOutputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Error on serial output"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error: " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialOutputError.observe( getViewLifecycleOwner(), onNewDataErrorListener); } @Override public void onResume() { super.onResume(); Log.d("dev-log", "TerminalFragment.onResume: Fragment resumed"); Log.d("dev-log", "TerminalFragment.onResume: Connecting to device"); connectToDevice(); terminalViewModel.setLauncherEventHandler(); } private void connectToDevice() { int deviceId = terminalArgs.getDeviceId(); int portNum = terminalArgs.getPortNum(); DeviceConnectionParamData deviceConnectionParamData = new DeviceConnectionParamData(
BAUD_RATE, DATA_BITS, STOP_BITS, PARITY_NONE, deviceId, portNum);
3
2023-11-15 15:54:39+00:00
8k
Charles7c/continew-starter
continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseController.java
[ { "identifier": "StringConstants", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/constant/StringConstants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringConstants implements StrPool {\n\n /**\n * 空字符串\n */\n public static final String EMPTY = \"\";\n\n /**\n * 空格\n */\n public static final String SPACE = \" \";\n\n /**\n * 分号\n */\n public static final String SEMICOLON = \";\";\n\n /**\n * 星号\n */\n public static final String ASTERISK = \"*\";\n\n /**\n * 问号\n */\n public static final String QUESTION_MARK = \"?\";\n\n /**\n * 中文逗号\n */\n public static final String CHINESE_COMMA = \",\";\n\n /**\n * 路径模式\n */\n public static final String PATH_PATTERN = \"/**\";\n}" }, { "identifier": "Api", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/enums/Api.java", "snippet": "public enum Api {\n\n /**\n * 所有 API\n */\n ALL,\n /**\n * 分页\n */\n PAGE,\n /**\n * 树列表\n */\n TREE,\n /**\n * 列表\n */\n LIST,\n /**\n * 详情\n */\n GET,\n /**\n * 新增\n */\n ADD,\n /**\n * 修改\n */\n UPDATE,\n /**\n * 删除\n */\n DELETE,\n /**\n * 导出\n */\n EXPORT,\n}" }, { "identifier": "PageQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/PageQuery.java", "snippet": "@Data\n@ParameterObject\n@NoArgsConstructor\n@Schema(description = \"分页查询条件\")\npublic class PageQuery extends SortQuery {\n\n @Serial\n private static final long serialVersionUID = 1L;\n /**\n * 默认页码:1\n */\n private static final int DEFAULT_PAGE = 1;\n /**\n * 默认每页条数:10\n */\n private static final int DEFAULT_SIZE = 10;\n\n /**\n * 页码\n */\n @Schema(description = \"页码\", example = \"1\")\n @Min(value = 1, message = \"页码最小值为 {value}\")\n private Integer page = DEFAULT_PAGE;\n\n /**\n * 每页条数\n */\n @Schema(description = \"每页条数\", example = \"10\")\n @Range(min = 1, max = 1000, message = \"每页条数(取值范围 {min}-{max})\")\n private Integer size = DEFAULT_SIZE;\n\n /**\n * 基于分页查询条件转换为 MyBatis Plus 分页条件\n *\n * @param <T> 列表数据类型\n * @return MyBatis Plus 分页条件\n */\n public <T> IPage<T> toPage() {\n Page<T> mybatisPage = new Page<>(this.getPage(), this.getSize());\n Sort pageSort = this.getSort();\n if (CollUtil.isNotEmpty(pageSort)) {\n for (Sort.Order order : pageSort) {\n OrderItem orderItem = new OrderItem();\n orderItem.setAsc(order.isAscending());\n orderItem.setColumn(StrUtil.toUnderlineCase(order.getProperty()));\n mybatisPage.addOrder(orderItem);\n }\n }\n return mybatisPage;\n }\n}" }, { "identifier": "SortQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/SortQuery.java", "snippet": "@Data\n@Schema(description = \"排序查询条件\")\npublic class SortQuery implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 排序条件\n */\n @Schema(description = \"排序条件\", example = \"createTime,desc\")\n private String[] sort;\n\n /**\n * 解析排序条件为 Spring 分页排序实体\n *\n * @return Spring 分页排序实体\n */\n public Sort getSort() {\n if (ArrayUtil.isEmpty(sort)) {\n return Sort.unsorted();\n }\n\n List<Sort.Order> orders = new ArrayList<>(sort.length);\n if (StrUtil.contains(sort[0], StringConstants.COMMA)) {\n // e.g \"sort=createTime,desc&sort=name,asc\"\n for (String s : sort) {\n List<String> sortList = StrUtil.splitTrim(s, StringConstants.COMMA);\n Sort.Order order =\n new Sort.Order(Sort.Direction.valueOf(sortList.get(1).toUpperCase()), sortList.get(0));\n orders.add(order);\n }\n } else {\n // e.g \"sort=createTime,desc\"\n Sort.Order order = new Sort.Order(Sort.Direction.valueOf(sort[1].toUpperCase()), sort[0]);\n orders.add(order);\n }\n return Sort.by(orders);\n }\n}" }, { "identifier": "PageDataResp", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/resp/PageDataResp.java", "snippet": "@Data\n@Schema(description = \"分页信息\")\npublic class PageDataResp<L> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 列表数据\n */\n @Schema(description = \"列表数据\")\n private List<L> list;\n\n /**\n * 总记录数\n */\n @Schema(description = \"总记录数\", example = \"10\")\n private long total;\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息,并将源数据转换为指定类型数据\n *\n * @param page MyBatis Plus 分页数据\n * @param targetClass 目标类型 Class 对象\n * @param <T> 源列表数据类型\n * @param <L> 目标列表数据类型\n * @return 分页信息\n */\n public static <T, L> PageDataResp<L> build(IPage<T> page, Class<L> targetClass) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(BeanUtil.copyToList(page.getRecords(), targetClass));\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息\n *\n * @param page MyBatis Plus 分页数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(IPage<L> page) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(page.getRecords());\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于列表数据构建分页信息\n *\n * @param page 页码\n * @param size 每页条数\n * @param list 列表数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(int page, int size, List<L> list) {\n if (CollUtil.isEmpty(list)) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setTotal(list.size());\n // 对列表数据进行分页\n int fromIndex = (page - 1) * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n pageDataResp.setList(new ArrayList<>(0));\n } else if (toIndex >= list.size()) {\n pageDataResp.setList(list.subList(fromIndex, list.size()));\n } else {\n pageDataResp.setList(list.subList(fromIndex, toIndex));\n }\n return pageDataResp;\n }\n\n /**\n * 空分页信息\n *\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n private static <L> PageDataResp<L> empty() {\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(new ArrayList<>(0));\n return pageDataResp;\n }\n}" }, { "identifier": "R", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/resp/R.java", "snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Schema(description = \"响应信息\")\npublic class R<T> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 是否成功\n */\n @Schema(description = \"是否成功\", example = \"true\")\n private boolean success;\n\n /**\n * 业务状态码\n */\n @Schema(description = \"业务状态码\", example = \"200\")\n private int code;\n\n /**\n * 业务状态信息\n */\n @Schema(description = \"业务状态信息\", example = \"操作成功\")\n private String msg;\n\n /**\n * 响应数据\n */\n @Schema(description = \"响应数据\")\n private T data;\n\n /**\n * 时间戳\n */\n @Schema(description = \"时间戳\", example = \"1691453288\")\n private long timestamp = DateUtil.currentSeconds();\n\n /**\n * 成功状态码\n */\n private static final int SUCCESS_CODE = HttpStatus.OK.value();\n /**\n * 失败状态码\n */\n private static final int FAIL_CODE = HttpStatus.INTERNAL_SERVER_ERROR.value();\n\n private R(boolean success, int code, String msg, T data) {\n this.success = success;\n this.code = code;\n this.msg = msg;\n this.data = data;\n }\n\n public static <T> R<T> ok() {\n return new R<>(true, SUCCESS_CODE, \"操作成功\", null);\n }\n\n public static <T> R<T> ok(T data) {\n return new R<>(true, SUCCESS_CODE, \"操作成功\", data);\n }\n\n public static <T> R<T> ok(String msg) {\n return new R<>(true, SUCCESS_CODE, msg, null);\n }\n\n public static <T> R<T> ok(String msg, T data) {\n return new R<>(true, SUCCESS_CODE, msg, data);\n }\n\n public static <T> R<T> fail() {\n return new R<>(false, FAIL_CODE, \"操作失败\", null);\n }\n\n public static <T> R<T> fail(String msg) {\n return new R<>(false, FAIL_CODE, msg, null);\n }\n\n public static <T> R<T> fail(T data) {\n return new R<>(false, FAIL_CODE, \"操作失败\", data);\n }\n\n public static <T> R<T> fail(String msg, T data) {\n return new R<>(false, FAIL_CODE, msg, data);\n }\n\n public static <T> R<T> fail(int code, String msg) {\n return new R<>(false, code, msg, null);\n }\n}" } ]
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.StrUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import jakarta.servlet.http.HttpServletResponse; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import top.charles7c.continew.starter.core.constant.StringConstants; import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping; import top.charles7c.continew.starter.extension.crud.enums.Api; import top.charles7c.continew.starter.extension.crud.model.query.PageQuery; import top.charles7c.continew.starter.extension.crud.model.query.SortQuery; import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp; import top.charles7c.continew.starter.extension.crud.model.resp.R; import java.util.List;
4,445
/* * 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.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree") public R<List<Tree<Long>>> tree(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<Tree<Long>> list = baseService.tree(query, sortQuery, false); return R.ok(list); } /** * 查询列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 列表信息 */ @Operation(summary = "查询列表", description = "查询列表") @ResponseBody @GetMapping("/list") public R<List<L>> list(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<L> list = baseService.list(query, sortQuery); return R.ok(list); } /** * 查看详情 * * @param id ID * @return 详情信息 */ @Operation(summary = "查看详情", description = "查看详情") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @GetMapping("/{id}") public R<D> get(@PathVariable Long id) { this.checkPermission(Api.LIST); D detail = baseService.get(id); return R.ok(detail); } /** * 新增 * * @param req 创建信息 * @return 自增 ID */ @Operation(summary = "新增数据", description = "新增数据") @ResponseBody @PostMapping public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody C req) { this.checkPermission(Api.ADD); Long id = baseService.add(req); return R.ok("新增成功", id); } /** * 修改 * * @param req 修改信息 * @param id ID * @return / */ @Operation(summary = "修改数据", description = "修改数据") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @PutMapping("/{id}") public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody C req, @PathVariable Long id) { this.checkPermission(Api.UPDATE); baseService.update(req, id); return R.ok("修改成功"); } /** * 删除 * * @param ids ID 列表 * @return / */ @Operation(summary = "删除数据", description = "删除数据") @Parameter(name = "ids", description = "ID 列表", example = "1,2", in = ParameterIn.PATH) @ResponseBody @DeleteMapping("/{ids}") public R delete(@PathVariable List<Long> ids) { this.checkPermission(Api.DELETE); baseService.delete(ids); return R.ok("删除成功"); } /** * 导出 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @param response 响应对象 */ @Operation(summary = "导出数据", description = "导出数据") @GetMapping("/export") public void export(Q query, SortQuery sortQuery, HttpServletResponse response) { this.checkPermission(Api.EXPORT); baseService.export(query, sortQuery, response); } /** * 根据 API 类型进行权限验证 * * @param api API 类型 */ private void checkPermission(Api api) { CrudRequestMapping crudRequestMapping = this.getClass().getDeclaredAnnotation(CrudRequestMapping.class); String path = crudRequestMapping.value();
/* * 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.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree") public R<List<Tree<Long>>> tree(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<Tree<Long>> list = baseService.tree(query, sortQuery, false); return R.ok(list); } /** * 查询列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 列表信息 */ @Operation(summary = "查询列表", description = "查询列表") @ResponseBody @GetMapping("/list") public R<List<L>> list(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<L> list = baseService.list(query, sortQuery); return R.ok(list); } /** * 查看详情 * * @param id ID * @return 详情信息 */ @Operation(summary = "查看详情", description = "查看详情") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @GetMapping("/{id}") public R<D> get(@PathVariable Long id) { this.checkPermission(Api.LIST); D detail = baseService.get(id); return R.ok(detail); } /** * 新增 * * @param req 创建信息 * @return 自增 ID */ @Operation(summary = "新增数据", description = "新增数据") @ResponseBody @PostMapping public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody C req) { this.checkPermission(Api.ADD); Long id = baseService.add(req); return R.ok("新增成功", id); } /** * 修改 * * @param req 修改信息 * @param id ID * @return / */ @Operation(summary = "修改数据", description = "修改数据") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @PutMapping("/{id}") public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody C req, @PathVariable Long id) { this.checkPermission(Api.UPDATE); baseService.update(req, id); return R.ok("修改成功"); } /** * 删除 * * @param ids ID 列表 * @return / */ @Operation(summary = "删除数据", description = "删除数据") @Parameter(name = "ids", description = "ID 列表", example = "1,2", in = ParameterIn.PATH) @ResponseBody @DeleteMapping("/{ids}") public R delete(@PathVariable List<Long> ids) { this.checkPermission(Api.DELETE); baseService.delete(ids); return R.ok("删除成功"); } /** * 导出 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @param response 响应对象 */ @Operation(summary = "导出数据", description = "导出数据") @GetMapping("/export") public void export(Q query, SortQuery sortQuery, HttpServletResponse response) { this.checkPermission(Api.EXPORT); baseService.export(query, sortQuery, response); } /** * 根据 API 类型进行权限验证 * * @param api API 类型 */ private void checkPermission(Api api) { CrudRequestMapping crudRequestMapping = this.getClass().getDeclaredAnnotation(CrudRequestMapping.class); String path = crudRequestMapping.value();
String permissionPrefix = String.join(StringConstants.COLON, StrUtil.splitTrim(path, StringConstants.SLASH));
0
2023-11-16 15:48:18+00:00
8k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/ShrineManager.java
[ { "identifier": "Devotions", "path": "src/main/java/me/xidentified/devotions/Devotions.java", "snippet": "@Getter\npublic class Devotions extends JavaPlugin {\n @Getter private static Devotions instance;\n private DevotionManager devotionManager;\n private RitualManager ritualManager;\n private final Map<String, Miracle> miraclesMap = new HashMap<>();\n private CooldownManager cooldownManager;\n private MeditationManager meditationManager;\n private ShrineListener shrineListener;\n private YamlConfiguration deitiesConfig;\n private FileConfiguration ritualConfig;\n private FileConfiguration soundsConfig;\n private StorageManager storageManager;\n private DevotionStorage devotionStorage;\n private Translator translations;\n private FileConfiguration savedItemsConfig = null;\n private File savedItemsConfigFile = null;\n\n @Override\n public void onEnable() {\n saveDefaultConfig();\n initializePlugin();\n loadSoundsConfig();\n reloadSavedItemsConfig();\n\n TinyTranslationsBukkit.enable(this);\n translations = TinyTranslationsBukkit.application(this);\n translations.setMessageStorage(new YamlMessageStorage(new File(getDataFolder(), \"/lang/\")));\n translations.setStyleStorage(new YamlStyleStorage(new File(getDataFolder(), \"/lang/styles.yml\")));\n\n translations.addMessages(TinyTranslations.messageFieldsFromClass(Messages.class));\n\n loadLanguages();\n\n // Set the LocaleProvider\n translations.setLocaleProvider(audience -> {\n // Read settings from config\n boolean usePlayerClientLocale = getConfig().getBoolean(\"use-player-client-locale\", true);\n String fallbackLocaleCode = getConfig().getString(\"default-locale\", \"en\");\n Locale fallbackLocale = Locale.forLanguageTag(fallbackLocaleCode);\n\n if (audience == null || !usePlayerClientLocale) {\n return fallbackLocale;\n }\n\n return audience.getOrDefault(Identity.LOCALE, fallbackLocale);\n });\n\n // If PAPI is installed we'll register placeholders\n if(Bukkit.getPluginManager().getPlugin(\"PlaceholderAPI\") != null) {\n new Placeholders(this).register();\n debugLog(\"PlaceholderAPI expansion enabled!\");\n }\n }\n\n private Map<String, Deity> loadDeities(YamlConfiguration deitiesConfig) {\n Map<String, Deity> deityMap = new HashMap<>();\n ConfigurationSection deitiesSection = deitiesConfig.getConfigurationSection(\"deities\");\n assert deitiesSection != null;\n for (String deityKey : deitiesSection.getKeys(false)) {\n ConfigurationSection deityConfig = deitiesSection.getConfigurationSection(deityKey);\n\n assert deityConfig != null;\n String name = deityConfig.getString(\"name\");\n String lore = deityConfig.getString(\"lore\");\n String domain = deityConfig.getString(\"domain\");\n String alignment = deityConfig.getString(\"alignment\");\n List<String> favoredRituals = deityConfig.getStringList(\"rituals\");\n\n // Load offerings\n List<String> offeringStrings = deityConfig.getStringList(\"offerings\");\n List<Offering> favoredOfferings = offeringStrings.stream()\n .map(offeringString -> {\n String[] parts = offeringString.split(\":\");\n if (parts.length < 3) {\n getLogger().warning(\"Invalid offering format for deity \" + deityKey + \": \" + offeringString);\n return null;\n }\n\n String type = parts[0];\n String itemId = parts[1];\n int favorValue;\n try {\n favorValue = Integer.parseInt(parts[2]);\n } catch (NumberFormatException e) {\n getLogger().warning(\"Invalid favor value in offerings for deity \" + deityKey + \": \" + parts[2]);\n return null;\n }\n\n List<String> commands = new ArrayList<>();\n if (parts.length > 3) {\n commands = Arrays.asList(parts[3].split(\";\"));\n debugLog(\"Loaded commands for offering: \" + commands);\n }\n\n ItemStack itemStack;\n if (\"Saved\".equalsIgnoreCase(type)) {\n itemStack = loadSavedItem(itemId);\n if (itemStack == null) {\n getLogger().warning(\"Saved item not found: \" + itemId + \" for deity: \" + deityKey);\n return null;\n }\n } else {\n Material material = Material.matchMaterial(itemId);\n if (material == null) {\n getLogger().warning(\"Invalid material in offerings for deity \" + deityKey + \": \" + itemId);\n return null;\n }\n itemStack = new ItemStack(material);\n }\n return new Offering(itemStack, favorValue, commands);\n })\n .filter(Objects::nonNull)\n .collect(Collectors.toList());\n\n // Parse blessings\n List<Blessing> deityBlessings = deityConfig.getStringList(\"blessings\").stream()\n .map(this::parseBlessing)\n .collect(Collectors.toList());\n\n // Parse curses\n List<Curse> deityCurses = deityConfig.getStringList(\"curses\").stream()\n .map(this::parseCurse)\n .collect(Collectors.toList());\n\n List<Miracle> deityMiracles = new ArrayList<>();\n\n for (String miracleString : deityConfig.getStringList(\"miracles\")) {\n Miracle miracle = parseMiracle(miracleString);\n if (miracle != null) {\n deityMiracles.add(miracle);\n miraclesMap.put(miracleString, miracle);\n } else {\n debugLog(\"Failed to parse miracle: \" + miracleString + \" for deity \" + deityKey);\n }\n }\n\n Deity deity = new Deity(this, name, lore, domain, alignment, favoredOfferings, favoredRituals, deityBlessings, deityCurses, deityMiracles);\n deityMap.put(deityKey.toLowerCase(), deity);\n getLogger().info(\"Loaded deity \" + deity.getName() + \" with \" + favoredOfferings.size() + \" offerings.\");\n }\n\n return deityMap;\n }\n\n private Miracle parseMiracle(String miracleString) {\n debugLog(\"Parsing miracle: \" + miracleString);\n MiracleEffect effect;\n List<Condition> conditions = new ArrayList<>();\n\n String[] parts = miracleString.split(\":\", 2);\n String miracleType = parts[0]; // Define miracleType here\n\n debugLog(\"Parsed miracleString: \" + miracleString);\n debugLog(\"Miracle type: \" + miracleType);\n if (parts.length > 1) {\n debugLog(\"Command/Argument: \" + parts[1]);\n }\n\n switch (miracleType) {\n case \"revive_on_death\" -> {\n effect = new ReviveOnDeath();\n conditions.add(new IsDeadCondition());\n }\n case \"stop_burning\" -> {\n effect = new SaveFromBurning();\n conditions.add(new IsOnFireCondition());\n }\n case \"repair_all\" -> {\n effect = new RepairAllItems();\n conditions.add(new HasRepairableItemsCondition());\n }\n case \"summon_aid\" -> {\n effect = new SummonAidEffect(3); // Summoning 3 entities.\n conditions.add(new LowHealthCondition());\n conditions.add(new NearHostileMobsCondition());\n }\n case \"village_hero\" -> {\n effect = new HeroEffectInVillage();\n conditions.add(new NearVillagersCondition());\n }\n case \"double_crops\" -> {\n if (parts.length > 1) {\n try {\n int duration = Integer.parseInt(parts[1]);\n effect = new DoubleCropDropsEffect(this, duration);\n conditions.add(new NearCropsCondition());\n } catch (NumberFormatException e) {\n debugLog(\"Invalid duration provided for double_crops miracle.\");\n return null;\n }\n } else {\n debugLog(\"No duration provided for double_crops miracle.\");\n return null;\n }\n }\n case \"run_command\" -> {\n if (parts.length > 1) {\n String command = parts[1];\n effect = new ExecuteCommandEffect(command);\n } else {\n debugLog(\"No command provided for run_command miracle.\");\n return null;\n }\n }\n default -> {\n debugLog(\"Unrecognized miracle encountered in parseMiracle!\");\n return null;\n }\n }\n\n return new Miracle(miracleType, conditions, effect);\n }\n\n private Blessing parseBlessing(String blessingString) {\n String[] parts = blessingString.split(\",\");\n PotionEffectType effect = PotionEffectType.getByName(parts[0]);\n int strength = Integer.parseInt(parts[1]);\n int duration = Integer.parseInt(parts[2]);\n return new Blessing(parts[0], duration, strength, effect);\n }\n\n private Curse parseCurse(String curseString) {\n String[] parts = curseString.split(\",\");\n PotionEffectType effect = PotionEffectType.getByName(parts[0]);\n int strength = Integer.parseInt(parts[1]);\n int duration = Integer.parseInt(parts[2]);\n return new Curse(parts[0], duration, strength, effect);\n }\n\n public YamlConfiguration getDeitiesConfig() {\n if (deitiesConfig == null) {\n File deitiesFile = new File(getDataFolder(), \"deities.yml\");\n deitiesConfig = YamlConfiguration.loadConfiguration(deitiesFile);\n }\n return deitiesConfig;\n }\n\n private void loadRituals() {\n ConfigurationSection ritualsSection = ritualConfig.getConfigurationSection(\"rituals\");\n if (ritualsSection == null) {\n getLogger().warning(\"No rituals section found in config.\");\n return;\n }\n\n for (String key : ritualsSection.getKeys(false)) {\n try {\n String path = \"rituals.\" + key + \".\";\n\n // Parse general info\n String displayName = ritualConfig.getString(path + \"display_name\");\n String description = ritualConfig.getString(path + \"description\");\n int favorReward = ritualConfig.getInt(path + \"favor\");\n\n // Parse item\n String itemString = ritualConfig.getString(path + \"item\");\n RitualItem ritualItem = null;\n if (itemString != null) {\n String[] parts = itemString.split(\":\");\n if (parts.length == 2) {\n String type = parts[0];\n String itemId = parts[1];\n\n if (\"SAVED\".equalsIgnoreCase(type)) {\n ItemStack savedItem = loadSavedItem(itemId);\n if (savedItem == null) {\n getLogger().warning(\"Saved item not found: \" + itemId + \" for ritual: \" + key);\n } else {\n ritualItem = new RitualItem(\"SAVED\", savedItem);\n }\n } else if (\"VANILLA\".equalsIgnoreCase(type)) {\n ritualItem = new RitualItem(\"VANILLA\", itemId);\n } else {\n getLogger().warning(\"Unknown item type: \" + type + \" for ritual: \" + key);\n }\n }\n }\n\n // Parse conditions\n String expression = ritualConfig.getString(path + \"conditions.expression\", \"\");\n String time = ritualConfig.getString(path + \"conditions.time\");\n String biome = ritualConfig.getString(path + \"conditions.biome\");\n String weather = ritualConfig.getString(path + \"conditions.weather\");\n String moonPhase = ritualConfig.getString(path + \"conditions.moon_phase\");\n double minAltitude = ritualConfig.getDouble(path + \"conditions.min_altitude\", 0.0);\n int minExperience = ritualConfig.getInt(path + \"conditions.min_experience\", 0);\n double minHealth = ritualConfig.getDouble(path + \"conditions.min_health\", 0.0);\n int minHunger = ritualConfig.getInt(path + \"conditions.min_hunger\", 0);\n\n RitualConditions ritualConditions = new RitualConditions(expression, time, biome, weather, moonPhase,\n minAltitude, minExperience, minHealth, minHunger);\n\n // Parse outcome\n List<String> outcomeCommands;\n if (ritualConfig.isList(path + \"outcome-command\")) {\n outcomeCommands = ritualConfig.getStringList(path + \"outcome-command\");\n } else {\n String singleCommand = ritualConfig.getString(path + \"outcome-command\");\n if (singleCommand == null || singleCommand.isEmpty()) {\n getLogger().warning(\"No outcome specified for ritual: \" + key);\n continue; // Skip if no command is provided\n }\n outcomeCommands = Collections.singletonList(singleCommand);\n }\n RitualOutcome ritualOutcome = new RitualOutcome(\"RUN_COMMAND\", outcomeCommands);\n\n // Parse objectives\n List<RitualObjective> objectives = new ArrayList<>();\n try {\n List<Map<?, ?>> objectivesList = ritualConfig.getMapList(path + \"objectives\");\n for (Map<?, ?> objectiveMap : objectivesList) {\n String typeStr = (String) objectiveMap.get(\"type\");\n RitualObjective.Type type = RitualObjective.Type.valueOf(typeStr);\n String objDescription = (String) objectiveMap.get(\"description\");\n String target = (String) objectiveMap.get(\"target\");\n int count = (Integer) objectiveMap.get(\"count\");\n\n RitualObjective objective = new RitualObjective(this, type, objDescription, target, count);\n objectives.add(objective);\n debugLog(\"Loaded objective \" + objDescription + \" for ritual \" + key);\n }\n } catch (Exception e) {\n getLogger().warning(\"Failed to load objectives for ritual: \" + key);\n e.printStackTrace();\n }\n\n\n // Create and store the ritual\n Ritual ritual = new Ritual(this, displayName, description, ritualItem, favorReward, ritualConditions, ritualOutcome, objectives);\n RitualManager.getInstance(this).addRitual(key, ritual); // Store the ritual and key\n } catch (Exception e) {\n getLogger().severe(\"Failed to load ritual with key: \" + key);\n e.printStackTrace();\n }\n }\n }\n\n public void spawnParticles(Location location, Particle particle, int count, double radius, double velocity) {\n World world = location.getWorld();\n Particle.DustOptions dustOptions = null;\n if (particle == Particle.REDSTONE) {\n dustOptions = new Particle.DustOptions(Color.RED, 1.0f); // You can adjust the color and size as needed\n }\n\n for (int i = 0; i < count; i++) {\n double phi = Math.acos(2 * Math.random() - 1); // Angle for elevation\n double theta = 2 * Math.PI * Math.random(); // Angle for azimuth\n\n double x = radius * Math.sin(phi) * Math.cos(theta);\n double y = radius * Math.sin(phi) * Math.sin(theta);\n double z = radius * Math.cos(phi);\n\n Location particleLocation = location.clone().add(x, y, z);\n Vector direction = particleLocation.toVector().subtract(location.toVector()).normalize().multiply(velocity);\n\n if (dustOptions != null) {\n world.spawnParticle(particle, particleLocation, 0, direction.getX(), direction.getY(), direction.getZ(), 0, dustOptions);\n } else {\n world.spawnParticle(particle, particleLocation, 0, direction.getX(), direction.getY(), direction.getZ(), 0);\n }\n }\n }\n\n public void spawnRitualMobs(Location center, EntityType entityType, int count, double radius) {\n World world = center.getWorld();\n List<Location> validLocations = new ArrayList<>();\n\n // Find valid spawn locations\n for (int i = 0; i < count * 10; i++) {\n double angle = 2 * Math.PI * i / count;\n double x = center.getX() + radius * Math.sin(angle);\n double z = center.getZ() + radius * Math.cos(angle);\n Location potentialLocation = new Location(world, x, center.getY(), z);\n Block block = potentialLocation.getBlock();\n if (block.getType() == Material.AIR && block.getRelative(BlockFace.DOWN).getType().isSolid() && block.getRelative(BlockFace.UP).getType() == Material.AIR) {\n validLocations.add(potentialLocation);\n }\n }\n\n // Spawn mobs at valid locations\n for (int i = 0; i < Math.min(count, validLocations.size()); i++) {\n world.spawnEntity(validLocations.get(i), entityType);\n }\n }\n\n public void reloadConfigurations() {\n reloadConfig();\n reloadRitualConfig();\n reloadSoundsConfig();\n loadLanguages();\n\n // Reset the DevotionManager\n if (devotionManager != null) {\n devotionManager.reset();\n }\n\n initializePlugin();\n }\n\n private void loadRitualConfig() {\n File ritualFile = new File(getDataFolder(), \"rituals.yml\");\n if (!ritualFile.exists()) {\n saveResource(\"rituals.yml\", false);\n }\n ritualConfig = YamlConfiguration.loadConfiguration(ritualFile);\n }\n\n private void reloadRitualConfig() {\n File ritualFile = new File(getDataFolder(), \"rituals.yml\");\n if (ritualFile.exists()) {\n ritualConfig = YamlConfiguration.loadConfiguration(ritualFile);\n }\n loadRituals();\n }\n\n private Map<String, Deity> reloadDeitiesConfig() {\n File deitiesFile = new File(getDataFolder(), \"deities.yml\");\n if (!deitiesFile.exists()) {\n saveResource(\"deities.yml\", false);\n }\n\n if (deitiesFile.exists()) {\n deitiesConfig = YamlConfiguration.loadConfiguration(deitiesFile);\n return loadDeities(deitiesConfig);\n } else {\n getLogger().severe(\"Unable to create default deities.yml\");\n return new HashMap<>(); // Return an empty map as a fallback\n }\n }\n\n private void reloadSoundsConfig() {\n File soundFile = new File(getDataFolder(), \"sounds.yml\");\n if (soundFile.exists()) {\n soundsConfig = YamlConfiguration.loadConfiguration(soundFile);\n }\n loadRituals();\n }\n\n public void reloadSavedItemsConfig() {\n if (savedItemsConfigFile == null) {\n savedItemsConfigFile = new File(getDataFolder(), \"savedItems.yml\");\n }\n savedItemsConfig = YamlConfiguration.loadConfiguration(savedItemsConfigFile);\n\n // Look for defaults in the jar\n InputStream defConfigStream = getResource(\"savedItems.yml\");\n if (defConfigStream != null) {\n YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream));\n savedItemsConfig.setDefaults(defConfig);\n }\n }\n\n public FileConfiguration getSavedItemsConfig() {\n if (savedItemsConfig == null) {\n reloadSavedItemsConfig();\n }\n return savedItemsConfig;\n }\n\n /**\n * Run to reload changes to message files\n */\n public void loadLanguages() {\n\n if (!new File(getDataFolder(), \"/lang/styles.yml\").exists()) {\n saveResource(\"lang/styles.yml\", false);\n }\n translations.loadStyles();\n\n // save default translations\n translations.saveLocale(Locale.ENGLISH);\n saveResource(\"lang/de.yml\", false);\n\n // load\n translations.loadLocales();\n }\n\n public void loadSoundsConfig() {\n File soundsFile = new File(getDataFolder(), \"sounds.yml\");\n if (!soundsFile.exists()) {\n saveResource(\"sounds.yml\", false);\n }\n soundsConfig = YamlConfiguration.loadConfiguration(soundsFile);\n debugLog(\"sounds.yml successfully loaded!\");\n }\n\n private void initializePlugin() {\n HandlerList.unregisterAll(this);\n instance = this;\n loadRitualConfig();\n\n // Initiate manager classes\n this.storageManager = new StorageManager(this);\n\n // Clear existing data before re-initializing\n if (devotionManager != null) {\n devotionManager.clearData();\n }\n\n Map<String, Deity> loadedDeities = reloadDeitiesConfig();\n this.devotionStorage = new DevotionStorage(storageManager);\n this.devotionManager = new DevotionManager(this, loadedDeities);\n ShrineManager shrineManager = new ShrineManager(this);\n loadRituals();\n ShrineStorage shrineStorage = new ShrineStorage(this, storageManager);\n shrineManager.setShrineStorage(shrineStorage);\n ritualManager = RitualManager.getInstance(this);\n this.cooldownManager = new CooldownManager(this);\n this.meditationManager = new MeditationManager(this);\n FavorCommand favorCmd = new FavorCommand(this);\n ShrineCommandExecutor shrineCmd = new ShrineCommandExecutor(devotionManager, shrineManager);\n DeityCommand deityCmd = new DeityCommand(this);\n RitualCommand ritualCommand = new RitualCommand(this);\n\n // Register commands\n Objects.requireNonNull(getCommand(\"deity\")).setExecutor(deityCmd);\n Objects.requireNonNull(getCommand(\"deity\")).setTabCompleter(deityCmd);\n Objects.requireNonNull(getCommand(\"favor\")).setExecutor(favorCmd);\n Objects.requireNonNull(getCommand(\"favor\")).setTabCompleter(favorCmd);\n Objects.requireNonNull(getCommand(\"shrine\")).setExecutor(shrineCmd);\n Objects.requireNonNull(getCommand(\"shrine\")).setTabCompleter(shrineCmd);\n Objects.requireNonNull(getCommand(\"devotions\")).setExecutor(new DevotionsCommandExecutor(this));\n Objects.requireNonNull(getCommand(\"ritual\")).setExecutor(ritualCommand);\n Objects.requireNonNull(getCommand(\"ritual\")).setTabCompleter(ritualCommand);\n\n // Register admin commands\n TestMiracleCommand testMiracleCmd = new TestMiracleCommand(miraclesMap);\n Objects.requireNonNull(getCommand(\"testmiracle\")).setExecutor(testMiracleCmd);\n\n // Register listeners\n this.shrineListener = new ShrineListener(this, shrineManager, cooldownManager);\n RitualListener.initialize(this, shrineManager);\n getServer().getPluginManager().registerEvents(new DoubleCropDropsEffect(this, 90), this);\n getServer().getPluginManager().registerEvents(new PlayerListener(this), this);\n\n // Register events\n getServer().getPluginManager().registerEvents(RitualListener.getInstance(), this);\n getServer().getPluginManager().registerEvents(shrineListener, this);\n getServer().getPluginManager().registerEvents(shrineCmd, this);\n\n debugLog(\"Devotions successfully initialized!\");\n }\n\n @Override\n public void onDisable() {\n // Unregister all listeners\n HandlerList.unregisterAll(this);\n\n // Save all player devotions to ensure data is not lost on shutdown\n devotionManager.saveAllPlayerDevotions();\n\n // Cancel tasks\n getServer().getScheduler().cancelTasks(this);\n ritualManager.ritualDroppedItems.clear();\n\n translations.close();\n }\n\n public int getShrineLimit() {\n return getConfig().getInt(\"shrine-limit\", 3);\n }\n\n public void debugLog(String message) {\n if (getConfig().getBoolean(\"debug_mode\")) {\n getLogger().info(\"[DEBUG] \" + message);\n }\n }\n\n public void playConfiguredSound(Player player, String key) {\n if (soundsConfig == null) {\n debugLog(\"soundsConfig is null.\");\n return;\n }\n\n String soundKey = \"sounds.\" + key;\n if (soundsConfig.contains(soundKey)) {\n String soundName = soundsConfig.getString(soundKey + \".sound\");\n float volume = (float) soundsConfig.getDouble(soundKey + \".volume\");\n float pitch = (float) soundsConfig.getDouble(soundKey + \".pitch\");\n\n Sound sound = Sound.valueOf(soundName);\n player.playSound(player.getLocation(), sound, volume, pitch);\n } else {\n debugLog(\"Sound \" + soundKey + \" not found in sounds.yml!\");\n }\n }\n\n private ItemStack loadSavedItem(String name) {\n File storageFolder = new File(getDataFolder(), \"storage\");\n File itemsFile = new File(storageFolder, \"savedItems.yml\");\n FileConfiguration config = YamlConfiguration.loadConfiguration(itemsFile);\n\n if (config.contains(\"items.\" + name)) {\n return ItemStack.deserialize(config.getConfigurationSection(\"items.\" + name).getValues(false));\n }\n return null;\n }\n\n public void sendMessage(CommandSender sender, ComponentLike componentLike) {\n if (componentLike instanceof Message msg) {\n // Translate the message into the locale of the command sender\n componentLike = translations.process(msg, TinyTranslationsBukkit.getLocale(sender));\n }\n TinyTranslationsBukkit.sendMessage(sender, componentLike);\n }\n\n}" }, { "identifier": "Shrine", "path": "src/main/java/me/xidentified/devotions/Shrine.java", "snippet": "@Getter\npublic class Shrine {\n private final Location location;\n private final UUID owner;\n @Setter private Deity deity;\n\n public Shrine(Location location, Deity deity, UUID owner) {\n this.location = location;\n this.deity = deity;\n this.owner = owner;\n }\n\n}" }, { "identifier": "ShrineStorage", "path": "src/main/java/me/xidentified/devotions/storage/ShrineStorage.java", "snippet": "public class ShrineStorage {\n private final Devotions plugin;\n private final File shrineFile;\n private final YamlConfiguration yaml;\n\n public ShrineStorage(Devotions plugin, StorageManager storageManager) {\n this.plugin = plugin;\n shrineFile = new File(storageManager.getStorageFolder(), \"shrines.yml\");\n if (!shrineFile.exists()) {\n try {\n shrineFile.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n yaml = YamlConfiguration.loadConfiguration(shrineFile);\n }\n\n public void saveShrine(Shrine shrine) {\n String key = generateShrineKey(shrine);\n String deityName = shrine.getDeity().getName();\n\n // Save the shrine details in a single line format\n yaml.set(\"shrines.\" + key, deityName);\n save();\n }\n\n public void removeShrine(Location location, UUID ownerUUID) {\n String key = findKeyByLocationAndOwner(location, ownerUUID);\n if (key != null) {\n yaml.set(\"shrines.\" + key, null);\n save();\n }\n }\n\n private String generateShrineKey(Shrine shrine) {\n Location location = shrine.getLocation();\n UUID ownerUUID = shrine.getOwner();\n return location.getWorld().getName() + \",\" +\n location.getBlockX() + \",\" +\n location.getBlockY() + \",\" +\n location.getBlockZ() + \",\" +\n ownerUUID.toString();\n }\n\n private String findKeyByLocationAndOwner(Location location, UUID ownerUUID) {\n ConfigurationSection shrinesSection = yaml.getConfigurationSection(\"shrines\");\n if (shrinesSection == null) return null;\n\n for (String key : shrinesSection.getKeys(false)) {\n String[] parts = key.split(\",\");\n if (parts.length < 5) continue; // Skip if the format is incorrect\n\n World world = Bukkit.getWorld(parts[0]);\n int x = Integer.parseInt(parts[1]);\n int y = Integer.parseInt(parts[2]);\n int z = Integer.parseInt(parts[3]);\n UUID storedOwnerUUID = UUID.fromString(parts[4]);\n\n Location storedLocation = new Location(world, x, y, z);\n if (storedLocation.equals(location) && storedOwnerUUID.equals(ownerUUID)) {\n return key;\n }\n }\n\n return null;\n }\n\n\n public List<Shrine> loadAllShrines(DevotionManager devotionManager) {\n List<Shrine> loadedShrines = new ArrayList<>();\n ConfigurationSection shrineSection = yaml.getConfigurationSection(\"shrines\");\n if (shrineSection == null) {\n plugin.debugLog(\"Shrine section is null.\");\n return loadedShrines;\n }\n\n for (String shrineKey : shrineSection.getKeys(false)) {\n String[] parts = shrineKey.split(\",\");\n World world = Bukkit.getWorld(parts[0]);\n if (world == null) {\n plugin.debugLog(\"World not found: \" + parts[0]);\n continue;\n }\n int x = Integer.parseInt(parts[1]);\n int y = Integer.parseInt(parts[2]);\n int z = Integer.parseInt(parts[3]);\n UUID ownerUUID = UUID.fromString(parts[4]);\n\n String deityName = shrineSection.getString(shrineKey);\n Deity deity = devotionManager.getDeityByName(deityName);\n if (deity == null) {\n plugin.debugLog(\"Deity not found: \" + deityName);\n continue;\n }\n\n Location location = new Location(world, x, y, z);\n Shrine shrine = new Shrine(location, deity, ownerUUID);\n loadedShrines.add(shrine);\n }\n\n plugin.getLogger().info(\"Loaded \" + loadedShrines.size() + \" shrines.\");\n return loadedShrines;\n }\n\n private void save() {\n try {\n yaml.save(shrineFile);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" } ]
import lombok.Getter; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.storage.ShrineStorage; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap;
6,915
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin;
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin;
private ShrineStorage shrineStorage;
2
2023-11-10 07:03:24+00:00
8k
Appu26J/Calculator
src/appu26j/Calculator.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}\n\t\n\tpublic static void loadAssets()\n\t{\n\t\tFile assetsDirectory = new File(tempDirectory, \"calculator\");\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, \"calculator\" + File.separator + name);\n\t}\n}" }, { "identifier": "FontRenderer", "path": "src/appu26j/gui/font/FontRenderer.java", "snippet": "public class FontRenderer\n{\n private final HashMap<Character, Float> cachedWidths = new HashMap<>();\n public static final int CHAR_DATA_MALLOC_SIZE = 96;\n public static final int FONT_TEX_W = 512;\n public static final int FONT_TEX_H = FONT_TEX_W;\n public static final int BAKE_FONT_FIRST_CHAR = 32;\n public static final int GLYPH_COUNT = CHAR_DATA_MALLOC_SIZE;\n protected final STBTTBakedChar.Buffer charData;\n protected final STBTTFontinfo fontInfo;\n protected final int fontSize, textureID;\n protected final float ascent, descent, lineGap;\n \n public FontRenderer(File font, int fontSize)\n {\n this.fontSize = fontSize;\n this.charData = STBTTBakedChar.malloc(CHAR_DATA_MALLOC_SIZE);\n this.fontInfo = STBTTFontinfo.create();\n int textureID = 0;\n float ascent = 0, descent = 0, lineGap = 0;\n \n try\n {\n ByteBuffer ttfFileData = this.getByteBuffer(font);\n ByteBuffer texData = BufferUtils.createByteBuffer(FONT_TEX_W * FONT_TEX_H);\n STBTruetype.stbtt_BakeFontBitmap(ttfFileData, fontSize, texData, FONT_TEX_W, FONT_TEX_H, BAKE_FONT_FIRST_CHAR, charData);\n \n try (MemoryStack stack = MemoryStack.stackPush())\n {\n STBTruetype.stbtt_InitFont(this.fontInfo, ttfFileData);\n float pixelScale = STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, fontSize);\n IntBuffer ascentBuffer = stack.ints(0);\n IntBuffer descentBuffer = stack.ints(0);\n IntBuffer lineGapBuffer = stack.ints(0);\n STBTruetype.stbtt_GetFontVMetrics(this.fontInfo, ascentBuffer, descentBuffer, lineGapBuffer);\n ascent = ascentBuffer.get(0) * pixelScale;\n descent = descentBuffer.get(0) * pixelScale;\n }\n \n textureID = glGenTextures();\n glBindTexture(GL_TEXTURE_2D, textureID);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, FONT_TEX_W, FONT_TEX_H, 0, GL_ALPHA, GL_UNSIGNED_BYTE, texData);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n \n catch (Exception e)\n {\n \te.printStackTrace();\n }\n \n this.textureID = textureID;\n this.ascent = ascent;\n this.descent = descent;\n this.lineGap = lineGap;\n char[] allLetters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()_+-={}[];':\\\"<>?,./ \".toCharArray();\n\n for (char letter : allLetters)\n {\n this.cachedWidths.put(letter, getCharWidth(letter));\n }\n }\n \n public void shutdown()\n {\n this.charData.free();\n this.fontInfo.free();\n \n if (this.textureID != 0)\n {\n glDeleteTextures(this.textureID);\n }\n }\n \n public ByteBuffer getByteBuffer(File file) throws IOException \n {\n ByteBuffer buffer;\n \n try (FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel())\n {\n buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());\n }\n \n return buffer;\n }\n \n public void drawStringWithShadow(String text, float x, float y, Color color)\n {\n \tthis.drawString(text, x + ((float) this.fontSize / 12), y + ((float) this.fontSize / 12), color.darker().darker().darker().darker());\n \tthis.drawString(text, x, y, color);\n }\n \n public void drawString(String text, float x, float y, Color color)\n {\n y += this.ascent;\n\n try (MemoryStack stack = MemoryStack.stackPush())\n {\n FloatBuffer xPosition = stack.mallocFloat(1);\n FloatBuffer yPosition = stack.mallocFloat(1);\n xPosition.put(x);\n yPosition.put(y);\n xPosition.flip();\n yPosition.flip();\n STBTTAlignedQuad stbttAlignedQuad = STBTTAlignedQuad.malloc(stack);\n glBindTexture(GL_TEXTURE_2D, this.textureID);\n GlStateManager.enableTexture2D();\n GlStateManager.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(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F);\n glBegin(GL_TRIANGLES);\n int firstCP = BAKE_FONT_FIRST_CHAR;\n int lastCP = BAKE_FONT_FIRST_CHAR + GLYPH_COUNT - 1;\n \n for (int i = 0; i < text.length(); i++)\n {\n int codePoint = text.codePointAt(i);\n \n if (codePoint == '§')\n {\n \tGlStateManager.color(color.getRed() / 340F, color.getGreen() / 340F, color.getBlue() / 340F, color.getAlpha() / 340F);\n \tcontinue;\n }\n \n if (codePoint == '\\n')\n {\n \txPosition.put(0, x);\n yPosition.put(0, yPosition.get(0) + fontSize);\n continue;\n }\n \n else if (codePoint < firstCP || codePoint > lastCP)\n {\n continue;\n }\n \n STBTruetype.stbtt_GetBakedQuad(this.charData, FONT_TEX_W, FONT_TEX_H, codePoint - firstCP, xPosition, yPosition, stbttAlignedQuad, true);\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n }\n \n glEnd();\n\t\t\tGlStateManager.disableBlend();\n\t\t\tGlStateManager.disableAlpha();\n\t\t\tGlStateManager.disableTexture2D();\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n }\n\n public float getStringWidth(String text)\n {\n float length = 0;\n\n for (char character : text.toCharArray())\n {\n if (this.cachedWidths.containsKey(character))\n {\n length += this.cachedWidths.get(character);\n }\n\n else\n {\n float charWidth = this.getCharWidth(character);\n this.cachedWidths.put(character, charWidth);\n length += charWidth;\n }\n }\n\n return length;\n }\n\n private float getCharWidth(char character)\n {\n float length = 0;\n\n try (MemoryStack memoryStack = MemoryStack.stackPush())\n {\n IntBuffer advancedWidth = memoryStack.mallocInt(1);\n IntBuffer leftSideBearing = memoryStack.mallocInt(1);\n STBTruetype.stbtt_GetCodepointHMetrics(this.fontInfo, character, advancedWidth, leftSideBearing);\n length += advancedWidth.get(0);\n }\n\n return length * STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, this.fontSize);\n }\n}" }, { "identifier": "GuiCalculator", "path": "src/appu26j/gui/screens/GuiCalculator.java", "snippet": "public class GuiCalculator extends GuiScreen\n{\n private final ArrayList<Button> buttons = new ArrayList<>();\n private String equation = \"0\";\n\n @Override\n public void drawScreen(float mouseX, float mouseY)\n {\n for (Button button : this.buttons)\n {\n button.drawScreen(mouseX, mouseY);\n }\n\n String string = this.equation;\n\n if (string.endsWith(\"root\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"root(\" + number + \")\";\n }\n\n else if (string.endsWith(\"xx\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = number + \" * \" + number;\n }\n\n else if (string.endsWith(\"sin\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"sin(\" + number + \")\";\n }\n\n else if (string.endsWith(\"cos\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"cos(\" + number + \")\";\n }\n\n else if (string.endsWith(\"&\"))\n {\n String[] parts = this.getEquation().split(\" \");\n ArrayList<Double> numbers = new ArrayList<>();\n\n for (String part : parts)\n {\n if (!this.containsOperator(part))\n {\n numbers.add(Double.valueOf(part));\n }\n }\n\n String number = String.valueOf(numbers.get(0));\n\n if (number.endsWith(\".0\"))\n {\n number = number.substring(0, number.length() - 2);\n }\n\n string = \"1 / \" + number;\n }\n\n this.fontRendererExtraBig.drawString(string, this.width - (this.fontRendererExtraBig.getStringWidth(string) + 10), this.height / 15, new Color(50, 50, 50));\n }\n\n @Override\n public void mouseClicked(int mouseButton, float mouseX, float mouseY)\n {\n super.mouseClicked(mouseButton, mouseX, mouseY);\n\n for (Button button : this.buttons)\n {\n button.mouseClicked(mouseButton, mouseX, mouseY);\n }\n }\n\n @Override\n public void initGUI(float width, float height)\n {\n super.initGUI(width, height);\n\n if (this.buttons.isEmpty())\n {\n float xOffset = 15, yOffset = height - 430;\n this.buttons.add(new Button(\"x2\", false, xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"root\", false, 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"sin\", false, 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"cos\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"<-\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"7\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"8\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"9\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"/\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"%\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"4\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"5\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"6\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"*\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"1/x\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"1\", xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"2\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"3\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"-\", false, 255 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"+\", false, 340 + xOffset, yOffset, 75, 75, this));\n yOffset += 85;\n this.buttons.add(new Button(\"clr\", false, xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"0\", 85 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\".\", 170 + xOffset, yOffset, 75, 75, this));\n this.buttons.add(new Button(\"=\", false, 255 + xOffset, yOffset, 160, 75, this));\n }\n }\n\n public String getEquation()\n {\n return this.equation;\n }\n\n public void appendEquation(String text)\n {\n if (this.equation.equals(\"0\") && !this.containsOperator(text))\n {\n this.equation = \"\";\n }\n\n this.equation += text;\n }\n\n public void backSpaceEquation()\n {\n if (this.equation.length() > 1)\n {\n this.equation = this.equation.substring(0, this.equation.length() - 1);\n this.equation = this.equation.trim();\n }\n\n else\n {\n this.equation = \"0\";\n }\n }\n\n public void appendAtStartEquation(String text)\n {\n this.equation = text + this.equation;\n }\n\n public void setEquation(String equation)\n {\n this.equation = equation;\n }\n\n public void clearEquation()\n {\n this.equation = \"0\";\n }\n\n public boolean containsOperator(String text)\n {\n text = text.trim();\n return text.endsWith(\"xx\") || text.endsWith(\"root\") || text.endsWith(\"sin\") || text.endsWith(\"cos\") || text.endsWith(\"/\") || text.endsWith(\"%\") || text.endsWith(\"*\") || text.endsWith(\"&\") || text.endsWith(\"-\") || text.endsWith(\"+\");\n }\n}" }, { "identifier": "GuiScreen", "path": "src/appu26j/gui/screens/GuiScreen.java", "snippet": "public abstract class GuiScreen extends Gui\n{\n\tprotected FontRenderer fontRendererExtraBig, fontRendererBig, fontRendererMid, fontRendererMidSmall, fontRenderer;\n\tprotected float width = 0, height = 0;\n\t\n\tpublic abstract void drawScreen(float mouseX, float mouseY);\n\t\n\tpublic void mouseClicked(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void mouseReleased(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void charTyped(char character, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void keyPressed(int key, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void initGUI(float width, float height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.fontRenderer = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 28);\n\t\tthis.fontRendererMidSmall = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 36);\n\t\tthis.fontRendererMid = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 54);\n\t\tthis.fontRendererBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 72);\n\t\tthis.fontRendererExtraBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 88);\n\t}\n\t\n\tprotected boolean isInsideBox(float mouseX, float mouseY, float x, float y, float width, float height)\n\t{\n\t\treturn mouseX > x && mouseX < width && mouseY > y && mouseY < height;\n\t}\n\t\n\tpublic ArrayList<FontRenderer> getFontRenderers()\n\t{\n\t\treturn new ArrayList<>(Arrays.asList(this.fontRenderer, this.fontRendererMidSmall, this.fontRendererMid, this.fontRendererBig, this.fontRendererExtraBig));\n\t}\n}" } ]
import appu26j.assets.Assets; import appu26j.gui.font.FontRenderer; import appu26j.gui.screens.GuiCalculator; import appu26j.gui.screens.GuiScreen; import org.lwjgl.glfw.GLFWCharCallback; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWKeyCallback; import org.lwjgl.glfw.GLFWMouseButtonCallback; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.DoubleBuffer; import java.util.Objects; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
5,179
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0;
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0;
private GuiScreen currentScreen;
3
2023-11-10 18:00:58+00:00
8k
SplitfireUptown/datalinkx
flinkx/flinkx-restapi/flinkx-restapi-reader/src/main/java/com/dtstack/flinkx/restapi/inputformat/HttpClient.java
[ { "identifier": "ConstantValue", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java", "snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final String TWO_POINT_SYMBOL = \"..\";\n public static final String EQUAL_SYMBOL = \"=\";\n public static final String COLON_SYMBOL = \":\";\n public static final String SINGLE_QUOTE_MARK_SYMBOL = \"'\";\n public static final String DOUBLE_QUOTE_MARK_SYMBOL = \"\\\"\";\n public static final String COMMA_SYMBOL = \",\";\n public static final String SEMICOLON_SYMBOL = \";\";\n\n public static final String SINGLE_SLASH_SYMBOL = \"/\";\n public static final String DOUBLE_SLASH_SYMBOL = \"//\";\n\n public static final String LEFT_PARENTHESIS_SYMBOL = \"(\";\n public static final String RIGHT_PARENTHESIS_SYMBOL = \")\";\n\n\n public static final String DATA_TYPE_UNSIGNED = \"UNSIGNED\";\n\n\n public static final String KEY_HTTP = \"http\";\n\n public static final String PROTOCOL_HTTP = \"http://\";\n public static final String PROTOCOL_HTTPS = \"https://\";\n public static final String PROTOCOL_HDFS = \"hdfs://\";\n public static final String PROTOCOL_JDBC_MYSQL = \"jdbc:mysql://\";\n\n public static final String SYSTEM_PROPERTIES_KEY_OS = \"os.name\";\n public static final String SYSTEM_PROPERTIES_KEY_USER_DIR = \"user.dir\";\n public static final String SYSTEM_PROPERTIES_KEY_JAVA_VENDOR = \"java.vendor\";\n public static final String SYSTEM_PROPERTIES_KEY_FILE_ENCODING = \"file.encoding\";\n\n public static final String OS_WINDOWS = \"windows\";\n\n public static final String SHIP_FILE_PLUGIN_LOAD_MODE = \"shipfile\";\n public static final String CLASS_PATH_PLUGIN_LOAD_MODE = \"classpath\";\n\n public static final String TIME_SECOND_SUFFIX = \"sss\";\n public static final String TIME_MILLISECOND_SUFFIX = \"SSS\";\n\n public static final String FILE_SUFFIX_XML = \".xml\";\n\n public static final int MAX_BATCH_SIZE = 200000;\n\n public static final long STORE_SIZE_G = 1024L * 1024 * 1024;\n\n public static final long STORE_SIZE_M = 1024L * 1024;\n}" }, { "identifier": "MetaColumn", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/reader/MetaColumn.java", "snippet": "public class MetaColumn implements Serializable {\n\n private String name;\n private String type;\n private Integer index;\n private String value;\n private SimpleDateFormat timeFormat;\n private String splitter;\n private Boolean isPart;\n\n public static List<MetaColumn> getMetaColumns(List columns, boolean generateIndex){\n List<MetaColumn> metaColumns = new ArrayList<>();\n if(columns != null && columns.size() > 0) {\n if (columns.get(0) instanceof Map) {\n for (int i = 0; i < columns.size(); i++) {\n Map sm = (Map) columns.get(i);\n MetaColumn mc = new MetaColumn();\n\n Object colIndex = sm.get(\"index\");\n if(colIndex != null) {\n if(colIndex instanceof Integer) {\n mc.setIndex((Integer) colIndex);\n } else if(colIndex instanceof Double) {\n Double doubleColIndex = (Double) colIndex;\n mc.setIndex(doubleColIndex.intValue());\n }\n } else {\n if (generateIndex) {\n mc.setIndex(i);\n } else {\n mc.setIndex(-1);\n }\n }\n\n mc.setName(sm.get(\"name\") != null ? String.valueOf(sm.get(\"name\")) : null);\n mc.setType(sm.get(\"type\") != null ? String.valueOf(sm.get(\"type\")) : null);\n mc.setValue(sm.get(\"value\") != null ? String.valueOf(sm.get(\"value\")) : null);\n mc.setSplitter(sm.get(\"splitter\") != null ? String.valueOf(sm.get(\"splitter\")) : null);\n mc.setPart(sm.get(\"isPart\") != null ? (Boolean) sm.get(\"isPart\") : false);\n\n if(sm.get(\"format\") != null && String.valueOf(sm.get(\"format\")).trim().length() > 0){\n mc.setTimeFormat(DateUtil.buildDateFormatter(String.valueOf(sm.get(\"format\"))));\n }\n\n metaColumns.add(mc);\n }\n } else if (columns.get(0) instanceof String) {\n if(columns.size() == 1 && ConstantValue.STAR_SYMBOL.equals(columns.get(0))){\n MetaColumn mc = new MetaColumn();\n mc.setName(ConstantValue.STAR_SYMBOL);\n metaColumns.add(mc);\n } else {\n for (int i = 0; i < columns.size(); i++) {\n MetaColumn mc = new MetaColumn();\n mc.setName(String.valueOf(columns.get(i)));\n if (generateIndex) {\n mc.setIndex(i);\n } else {\n mc.setIndex(-1);\n }\n metaColumns.add(mc);\n }\n }\n } else {\n throw new IllegalArgumentException(\"column argument error\");\n }\n }\n\n return metaColumns;\n }\n\n public static List<MetaColumn> getMetaColumns(List columns){\n return getMetaColumns(columns, true);\n }\n\n public static List<String> getColumnNames(List columns){\n List<String> columnNames = new ArrayList<>();\n\n List<MetaColumn> metaColumns = getMetaColumns(columns);\n for (MetaColumn metaColumn : metaColumns) {\n columnNames.add(metaColumn.getName());\n }\n\n return columnNames;\n }\n\n public static MetaColumn getMetaColumn(List columns, String name){\n List<MetaColumn> metaColumns = getMetaColumns(columns);\n for (MetaColumn metaColumn : metaColumns) {\n if(StringUtils.isNotEmpty(metaColumn.getName()) && metaColumn.getName().equals(name)){\n return metaColumn;\n }\n }\n\n return null;\n }\n\n public String getSplitter() {\n return splitter;\n }\n\n public void setSplitter(String splitter) {\n this.splitter = splitter;\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 getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Integer getIndex() {\n return index;\n }\n\n public void setIndex(Integer index) {\n this.index = index;\n }\n\n public String getValue() {\n return value;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n public SimpleDateFormat getTimeFormat() {\n return timeFormat;\n }\n\n public void setTimeFormat(SimpleDateFormat timeFormat) {\n this.timeFormat = timeFormat;\n }\n\n public Boolean getPart() {\n return isPart;\n }\n\n public void setPart(Boolean part) {\n isPart = part;\n }\n}" }, { "identifier": "HttpUtil", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/HttpUtil.java", "snippet": "public class HttpUtil {\n protected static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);\n private static final int COUNT = 32;\n private static final int TOTAL_COUNT = 1000;\n private static final int TIME_OUT = 5000;\n private static final int EXECUTION_COUNT = 5;\n\n public static Gson gson = new Gson();\n\n public static CloseableHttpClient getHttpClient() {\n // 设置自定义的重试策略\n MyServiceUnavailableRetryStrategy strategy = new MyServiceUnavailableRetryStrategy\n .Builder()\n .executionCount(EXECUTION_COUNT)\n .retryInterval(1000)\n .build();\n // 设置自定义的重试Handler\n MyHttpRequestRetryHandler retryHandler = new MyHttpRequestRetryHandler\n .Builder()\n .executionCount(EXECUTION_COUNT)\n .build();\n // 设置超时时间\n RequestConfig requestConfig = RequestConfig.custom()\n .setConnectTimeout(TIME_OUT)\n .setConnectionRequestTimeout(TIME_OUT)\n .setSocketTimeout(TIME_OUT)\n .build();\n // 设置Http连接池\n PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();\n pcm.setDefaultMaxPerRoute(COUNT);\n pcm.setMaxTotal(TOTAL_COUNT);\n\n return HttpClientBuilder.create()\n .setServiceUnavailableRetryStrategy(strategy)\n .setRetryHandler(retryHandler)\n .setDefaultRequestConfig(requestConfig)\n .setConnectionManager(pcm)\n .build();\n// return HttpClientBuilder.create().build();\n }\n\n public static HttpRequestBase getRequest(String method,\n String data,\n Map<String, String> header,\n String url) {\n LOG.debug(\"current request url: {} current method:{} \\n\", url, method);\n HttpRequestBase request = null;\n\n if (HttpMethod.GET.name().equalsIgnoreCase(method)) {\n request = new HttpGet(url);\n } else if (HttpMethod.POST.name().equalsIgnoreCase(method)) {\n HttpPost post = new HttpPost(url);\n post.setEntity(getEntityData(data));\n request = post;\n } else {\n throw new UnsupportedOperationException(\"Unsupported method:\" + method);\n }\n\n for (Map.Entry<String, String> entry : header.entrySet()) {\n request.addHeader(entry.getKey(), entry.getValue());\n }\n return request;\n }\n\n public static void closeClient(CloseableHttpClient httpClient) {\n try {\n httpClient.close();\n } catch (IOException e) {\n throw new RuntimeException(\"close client error\");\n }\n }\n\n public static StringEntity getEntityData(String data) {\n StringEntity stringEntity = new StringEntity(data, StandardCharsets.UTF_8);\n stringEntity.setContentEncoding(StandardCharsets.UTF_8.name());\n return stringEntity;\n }\n}" }, { "identifier": "MapUtils", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/MapUtils.java", "snippet": "public class MapUtils {\n\n\n public static Object getData(Map<String, Object> data, String[] names) {\n Map<String, Object> tempHashMap = data;\n for (int i = 0; i < names.length; i++) {\n if (tempHashMap.containsKey(names[i]) && i != names.length - 1) {\n if (Objects.isNull(tempHashMap.get(names[i]))) {\n return null;\n }\n if (tempHashMap.get(names[i]) instanceof Map) {\n tempHashMap = (Map<String, Object>) tempHashMap.get(names[i]);\n } else if (tempHashMap.get(names[i]) instanceof String) {\n try {\n tempHashMap = GsonUtil.GSON.fromJson((String) tempHashMap.get(names[i]), GsonUtil.gsonMapTypeToken);\n } catch (Exception e) {\n return null;\n }\n } else {\n return null;\n }\n } else if (i == names.length - 1) {\n return tempHashMap.get(names[i]);\n } else {\n return null;\n }\n }\n return null;\n }\n}" }, { "identifier": "RestContext", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/RestContext.java", "snippet": "public class RestContext {\n\n private String requestType;\n\n private String url;\n\n private String format;\n\n private boolean first;\n\n private ThreadLocal<Set<String>> setThreadLocal = new ThreadLocal<>();\n\n private Map<String, Object> prevRequestValue = new HashMap<>(16);\n\n private Map<String, Object> requestValue;\n\n private Map<ParamType, Map<String, ParamDefinition>> paramDefinitions;\n\n private Object object = new Object();\n\n public RestContext(String requestType,String url,String format) {\n this.requestType =requestType;\n this.url =url;\n this.requestValue = new HashMap<>(32);\n this.paramDefinitions = new HashMap<>(32);\n this.first = true;\n this.format=format;\n }\n\n public void updateValue(){\n prevRequestValue = requestValue;\n requestValue=new HashMap<>(requestValue.size());\n }\n\n public Map<String, Object> getPreValue() {\n return requestValue;\n }\n\n\n public httprequestApi.Httprequest build() {\n // 根据当前value计算出httprequest\n httprequestApi.Httprequest httprequest = new httprequestApi.Httprequest();\n\n Map<String, Object> body = new HashMap<>(16);\n Map<String, String> header = new HashMap<>(16);\n Map<String, Object> param = new HashMap<>(16);\n if (first) {\n paramDefinitions.get(ParamType.BODY).forEach((k, v) -> {\n body.put(k, v.getValue());\n });\n\n paramDefinitions.get(ParamType.HEADER).forEach((k, v) -> {\n header.put(k, v.getValue().toString());\n });\n\n paramDefinitions.get(ParamType.PARAM).forEach((k, v) -> {\n param.put(k, v.getValue());\n });\n first = false;\n } else {\n paramDefinitions.get(ParamType.BODY).forEach((k, v) -> {\n if (v instanceof ParamDefinitionNextAble) {\n body.put(k, ((ParamDefinitionNextAble) v).getNextValue());\n } else {\n body.put(k, v.getValue());\n }\n });\n\n paramDefinitions.get(ParamType.HEADER).forEach((k, v) -> {\n if (v instanceof ParamDefinitionNextAble) {\n header.put(k, ((ParamDefinitionNextAble) v).getNextValue().toString());\n } else {\n header.put(k, v.getValue().toString());\n }\n });\n\n paramDefinitions.get(ParamType.PARAM).forEach((k, v) -> {\n if (v instanceof ParamDefinitionNextAble) {\n param.put(k, ((ParamDefinitionNextAble) v).getNextValue());\n } else {\n param.put(k, v.getValue());\n }\n });\n }\n httprequest.buildBody(body).buildHeader(header).buildParam(param);\n return httprequest;\n }\n\n public httprequestApi.Httprequest buildNext() {\n // 计算下一次的请求 但是不会更新preValue值\n return null;\n }\n\n public void parseAndInt(Map<String, Map<String, String>> job, ParamType paramType) {\n paramDefinitions.put(paramType, ParamFactory.createDefinition(paramType, job, this).stream().collect(Collectors.toMap(ParamDefinition::getName, Function.identity())));\n }\n\n\n\n protected void updateValue(String key, Object value) {\n requestValue.put(key, value);\n }\n\n private Object getValueQuick(String key) {\n return prevRequestValue.get(key);\n }\n\n protected Object getValue(String key) {\n if (setThreadLocal.get() == null) {\n setThreadLocal.set(new HashSet<>(paramDefinitions.size() * 8));\n }\n if (setThreadLocal.get().contains(key)) {\n throw new RuntimeException(\"循环依赖\");\n }\n setThreadLocal.get().add(key);\n Object data = getValueQuick(key);\n if (Objects.isNull(data) && first) {\n String[] s = key.split(\"\\\\.\");\n ParamType paramType = ParamType.valueOf(s[0].toUpperCase(Locale.ENGLISH));\n if (Objects.isNull(paramDefinitions.get(paramType))) {\n data = null;\n } else {\n ParamDefinition definition = paramDefinitions.get(paramType).get(s[1]);\n //没查到对应的动态变量\n if (Objects.isNull(definition)) {\n prevRequestValue.put(key, object);\n } else {\n Object value = definition.getValue();\n data=value;\n prevRequestValue.put(key,value );\n }\n }\n }\n setThreadLocal.get().remove(key);\n\n if (data == object) {\n data = null;\n }\n return data;\n }\n //循环依赖使用有向图判断\n\n public Map<ParamType, Map<String, ParamDefinition>> getParamDefinitions() {\n return paramDefinitions;\n }\n\n public String getRequestType() {\n return requestType;\n }\n\n public String getUrl() {\n return url;\n }\n\n public String getFormat() {\n return format;\n }\n\n}" }, { "identifier": "ReadRecordException", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/exception/ReadRecordException.java", "snippet": "public class ReadRecordException extends RuntimeException {\n public ReadRecordException() {\n }\n\n public ReadRecordException(String message) {\n super(message);\n }\n}" }, { "identifier": "ResponseRetryException", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/exception/ResponseRetryException.java", "snippet": "public class ResponseRetryException extends RuntimeException {\n public ResponseRetryException() {\n }\n\n public ResponseRetryException(String message) {\n super(message);\n }\n\n public ResponseRetryException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public ResponseRetryException(Throwable cause) {\n super(cause);\n }\n\n public ResponseRetryException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}" }, { "identifier": "DataHandler", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/handler/DataHandler.java", "snippet": "public abstract class DataHandler {\n\n protected String key;\n\n protected Set<String> value;\n\n public DataHandler(String key, Set<String> value) {\n this.key = key;\n this.value = value;\n }\n\n public boolean isPipei(Map<String, Object> responseData) {\n return responseData.containsKey(key) && value.contains(responseData.get(key).toString());\n }\n\n public abstract void execute(Map<String, Object> responseData);\n\n}" }, { "identifier": "httprequestApi", "path": "flinkx/flinkx-restapi/flinkx-restapi-core/src/main/java/com/dtstack/flinkx/restapi/common/httprequestApi.java", "snippet": "public abstract class httprequestApi<R> {\n\n abstract R execute();\n\n\n abstract void getHttpRequest();\n\n public static class Httprequest {\n private Map<String, Object> body;\n private Map<String, Object> param;\n private Map<String, String> header;\n\n public Httprequest buildBody(Map<String, Object> body) {\n this.body = body;\n return this;\n }\n\n public Httprequest buildParam(Map<String, Object> param) {\n this.param = param;\n return this;\n }\n\n public Httprequest buildHeader(Map<String, String> header) {\n this.header = header;\n return this;\n }\n\n @Override\n public String toString() {\n return \"Httprequest{\" +\n \"body:\" + body +\n \", param:\" + param +\n \", header:\" + header +\n '}';\n }\n\n public Map<String, Object> getBody() {\n return body;\n }\n\n public Map<String, Object> getParam() {\n return param;\n }\n\n public Map<String, String> getHeader() {\n return header;\n }\n }\n}" }, { "identifier": "ExceptionUtil", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/util/ExceptionUtil.java", "snippet": "public class ExceptionUtil {\n\n private static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);\n\n public static String getErrorMessage(Throwable e) {\n if (null == e) {\n return null;\n }\n\n try (StringWriter stringWriter = new StringWriter();\n PrintWriter writer = new PrintWriter(stringWriter)) {\n e.printStackTrace(writer);\n writer.flush();\n stringWriter.flush();\n StringBuffer buffer = stringWriter.getBuffer();\n return buffer.toString();\n } catch (Throwable ee) {\n logger.error(\"\", ee);\n }\n return null;\n }\n}" }, { "identifier": "GsonUtil", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/util/GsonUtil.java", "snippet": "public class GsonUtil {\n private static final Logger LOG = LoggerFactory.getLogger(GsonUtil.class);\n public static Gson GSON = getGson();\n public static Type gsonMapTypeToken = new TypeToken<HashMap<String, Object>>(){}.getType();\n\n @SuppressWarnings(\"unchecked\")\n private static Gson getGson() {\n GSON = new GsonBuilder()\n .disableHtmlEscaping()\n .setPrettyPrinting()\n .create();\n try {\n Field factories = Gson.class.getDeclaredField(\"factories\");\n factories.setAccessible(true);\n Object o = factories.get(GSON);\n Class<?>[] declaredClasses = Collections.class.getDeclaredClasses();\n for (Class c : declaredClasses) {\n if (\"java.util.Collections$UnmodifiableList\".equals(c.getName())) {\n Field listField = c.getDeclaredField(\"list\");\n listField.setAccessible(true);\n List<TypeAdapterFactory> list = (List<TypeAdapterFactory>) listField.get(o);\n int i = list.indexOf(ObjectTypeAdapter.FACTORY);\n list.set(i, new TypeAdapterFactory() {\n @Override\n public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {\n if (type.getRawType() == Object.class) {\n return new TypeAdapter() {\n @Override\n public Object read(JsonReader in) throws IOException {\n JsonToken token = in.peek();\n //判断字符串的实际类型\n switch (token) {\n case BEGIN_ARRAY:\n List<Object> list = new ArrayList<>();\n in.beginArray();\n while (in.hasNext()) {\n list.add(read(in));\n }\n in.endArray();\n return list;\n\n case BEGIN_OBJECT:\n Map<String, Object> map = new LinkedTreeMap<>();\n in.beginObject();\n while (in.hasNext()) {\n map.put(in.nextName(), read(in));\n }\n in.endObject();\n return map;\n case STRING:\n return in.nextString();\n case NUMBER:\n String s = in.nextString();\n if (s.contains(\".\")) {\n return Double.valueOf(s);\n } else {\n try {\n return Integer.valueOf(s);\n } catch (Exception e) {\n return Long.valueOf(s);\n }\n }\n case BOOLEAN:\n return in.nextBoolean();\n case NULL:\n in.nextNull();\n return null;\n default:\n throw new IllegalStateException();\n }\n }\n\n @Override\n public void write(JsonWriter out, Object value) throws IOException {\n if (value == null) {\n out.nullValue();\n return;\n }\n //noinspection unchecked\n TypeAdapter<Object> typeAdapter = gson.getAdapter((Class<Object>) value.getClass());\n if (typeAdapter instanceof ObjectTypeAdapter) {\n out.beginObject();\n out.endObject();\n return;\n }\n typeAdapter.write(out, value);\n }\n };\n }\n return null;\n }\n });\n break;\n }\n }\n } catch (Exception e) {\n LOG.error(ExceptionUtil.getErrorMessage(e));\n }\n return GSON;\n }\n}" } ]
import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.reader.MetaColumn; import com.dtstack.flinkx.restapi.common.HttpUtil; import com.dtstack.flinkx.restapi.common.MapUtils; import com.dtstack.flinkx.restapi.common.RestContext; import com.dtstack.flinkx.restapi.common.exception.ReadRecordException; import com.dtstack.flinkx.restapi.common.exception.ResponseRetryException; import com.dtstack.flinkx.restapi.common.handler.DataHandler; import com.dtstack.flinkx.restapi.common.httprequestApi; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.flink.types.Row; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
6,129
/* * 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 com.dtstack.flinkx.restapi.inputformat; /** * httpClient * * @author by [email protected] * @Date 2020/9/25 */ public class HttpClient { private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); private ScheduledExecutorService scheduledExecutorService; protected transient CloseableHttpClient httpClient; private final long intervalTime; private BlockingQueue<Row> queue; private RestContext restContext; private static final String THREAD_NAME = "restApiReader-thread"; private List<MetaColumn> metaColumns;
/* * 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 com.dtstack.flinkx.restapi.inputformat; /** * httpClient * * @author by [email protected] * @Date 2020/9/25 */ public class HttpClient { private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); private ScheduledExecutorService scheduledExecutorService; protected transient CloseableHttpClient httpClient; private final long intervalTime; private BlockingQueue<Row> queue; private RestContext restContext; private static final String THREAD_NAME = "restApiReader-thread"; private List<MetaColumn> metaColumns;
private List<DataHandler> handlers;
7
2023-11-16 02:22:52+00:00
8k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/BetterFlowers.java
[ { "identifier": "CustomFlowerBrushListener", "path": "src/main/java/com/uroria/betterflowers/listeners/CustomFlowerBrushListener.java", "snippet": "public final class CustomFlowerBrushListener implements Listener {\n\n private final FlowerManager flowerManager;\n private final List<Block> flowerBlocks;\n\n public CustomFlowerBrushListener(BetterFlowers betterFlowers) {\n this.flowerManager = betterFlowers.getFlowerManager();\n this.flowerBlocks = new ArrayList<>();\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(PlayerInteractEvent playerInteractEvent) {\n\n if (playerInteractEvent.getAction().isLeftClick()) return;\n if (playerInteractEvent.getHand() != EquipmentSlot.HAND) return;\n if (!playerInteractEvent.hasItem() || playerInteractEvent.getItem() == null) return;\n if (playerInteractEvent.getItem().getType() != Material.BLAZE_ROD) return;\n\n final var currentLocation = playerInteractEvent.getPlayer().getTargetBlock(null, 200).getLocation();\n if (currentLocation.getBlock().getType() == Material.AIR) return;\n if (currentLocation.getBlock().getType() != Material.SHORT_GRASS) currentLocation.add(0, 1, 0);\n\n final var oldBlocks = new HashMap<Vector, BlockData>();\n final var item = playerInteractEvent.getItem();\n\n if (!flowerManager.getBrushes().containsKey(item)) return;\n final var radius = flowerManager.getBrushes().get(item).radius();\n final var airRandomizer = flowerManager.getBrushes().get(item).airRandomizer();\n handleRadiusPlacement(playerInteractEvent, oldBlocks, radius, currentLocation, airRandomizer);\n handleFlowerHistory(playerInteractEvent, oldBlocks);\n\n playerInteractEvent.getPlayer().playSound(currentLocation, Sound.BLOCK_AMETHYST_BLOCK_RESONATE, 1, 0);\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(BlockPhysicsEvent blockPhysicsEvent) {\n var currentBlock = blockPhysicsEvent.getBlock();\n if (flowerBlocks.contains(currentBlock)) blockPhysicsEvent.setCancelled(true);\n }\n\n private void handleRadiusPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, int radius, Location location, float air) {\n\n for (var innerLocation : getPlayerCircle(location, radius)) {\n if (air >= new Random().nextFloat()) continue;\n if (!adjustHeight(innerLocation)) continue;\n handleFlowerPlacement(playerInteractEvent, oldBlocks, innerLocation);\n }\n }\n\n private void handleFlowerPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, Location currentLocation) {\n\n final var item = playerInteractEvent.getItem();\n final var flowerBrush = flowerManager.getBrushes().get(item);\n final var flowerOptions = flowerBrush.flowerGroupData();\n final var flowerGroup = flowerOptions.get(new Random().nextInt(flowerOptions.size()));\n final var flowers = flowerGroup.flowerData();\n final var values = flowerManager.getFlowerRandomizer().get(flowerGroup);\n\n if (!onCorrectGround(currentLocation, flowerGroup, flowerBrush.maskData())) return;\n\n for (int i = 0; i < flowers.size(); i++) {\n if (values.get(i) && new Random().nextBoolean()) continue;\n\n final var currentBlock = currentLocation.getBlock();\n oldBlocks.put(currentBlock.getLocation().toVector(), currentBlock.getBlockData());\n\n flowerBlocks.add(currentBlock);\n flowers.get(i).getSingleFlower().setFlower(currentBlock);\n currentLocation.add(0, 1, 0);\n }\n }\n\n private Collection<Location> getPlayerCircle(Location location, int radius) {\n final var locations = new ArrayList<Location>();\n\n for (int x = -radius; x < radius; x++)\n for (int z = -radius; z < radius; z++) {\n final var newLocation = new Location(location.getWorld(), location.getX() + x, location.getY(), location.getZ() + z);\n if (location.distance(newLocation) < radius) locations.add(newLocation);\n }\n\n return locations;\n }\n\n private void handleFlowerHistory(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks) {\n\n final var player = playerInteractEvent.getPlayer();\n final var uuid = player.getUniqueId();\n final var history = new Operation(oldBlocks, player.getWorld());\n\n if (flowerManager.getOperationHistory().containsKey(uuid)) {\n var copy = new ArrayList<>(List.copyOf(flowerManager.getOperationHistory().get(uuid)));\n copy.add(history);\n\n flowerManager.getOperationHistory().put(uuid, copy);\n } else flowerManager.getOperationHistory().put(uuid, List.of(history));\n }\n\n private boolean adjustHeight(Location location) {\n final var block = location.getBlock();\n\n for (var index = 0; index < 10; index++) {\n\n final var y = block.isSolid() ? location.getBlockY() + index : location.getBlockY() - index;\n final var currentBlock = location.getWorld().getBlockAt(location.getBlockX(), y, location.getBlockZ());\n\n if (currentBlock.isSolid()) {\n location.setY(currentBlock.getY() + 1);\n return true;\n }\n\n final var nextBlock = block.isSolid() ? currentBlock.getRelative(BlockFace.UP) : currentBlock.getRelative(BlockFace.DOWN);\n if (!nextBlock.isSolid()) continue;\n location.setY(nextBlock.getY() + 1);\n return true;\n }\n\n return false;\n }\n\n private boolean onCorrectGround(Location location, FlowerGroupData data, Map<FlowerGroupData, Material> maskData) {\n final var floorType = location.getBlock().getRelative(BlockFace.DOWN).getType();\n\n if (maskData.isEmpty()) return true;\n if (!maskData.containsKey(data)) return true;\n return maskData.get(data) == floorType;\n }\n}" }, { "identifier": "CustomFlowerPlaceListener", "path": "src/main/java/com/uroria/betterflowers/listeners/CustomFlowerPlaceListener.java", "snippet": "public final class CustomFlowerPlaceListener implements Listener {\n\n private final FlowerManager flowerManager;\n private final List<Block> flowerBlocks;\n\n public CustomFlowerPlaceListener(BetterFlowers betterFlowers) {\n this.flowerManager = betterFlowers.getFlowerManager();\n this.flowerBlocks = new ArrayList<>();\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(PlayerInteractEvent playerInteractEvent) {\n\n if (playerInteractEvent.getAction().isLeftClick()) return;\n if (playerInteractEvent.getHand() != EquipmentSlot.HAND) return;\n if (!playerInteractEvent.hasItem() || playerInteractEvent.getItem() == null) return;\n\n if (playerInteractEvent.getItem().getType() != Material.BLAZE_POWDER) return;\n if (playerInteractEvent.getClickedBlock() == null) return;\n if (playerInteractEvent.getInteractionPoint() == null) return;\n\n final var currentLocation = playerInteractEvent.getInteractionPoint();\n final var oldBlocks = new HashMap<Vector, BlockData>();\n\n handleFlowerPlacement(playerInteractEvent, oldBlocks, currentLocation);\n handleFlowerHistory(playerInteractEvent, oldBlocks);\n\n playerInteractEvent.getPlayer().playSound(currentLocation, Sound.BLOCK_AMETHYST_BLOCK_RESONATE, 1, 0);\n }\n\n @EventHandler(priority = EventPriority.LOWEST)\n private void onCustomFlowerPlaceEvent(BlockPhysicsEvent blockPhysicsEvent) {\n var currentBlock = blockPhysicsEvent.getBlock();\n if (flowerBlocks.contains(currentBlock)) blockPhysicsEvent.setCancelled(true);\n }\n\n private void handleFlowerPlacement(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks, Location currentLocation) {\n\n final var item = playerInteractEvent.getItem();\n if (!flowerManager.getFlowers().containsKey(item)) return;\n\n final var flowerGroupData = flowerManager.getFlowers().get(item);\n final var flowers = flowerGroupData.flowerData();\n final var values = flowerManager.getFlowerRandomizer().get(flowerGroupData);\n final var offset = playerLookUp(playerInteractEvent.getPlayer()) ? -1 : 1;\n if (playerLookUp(playerInteractEvent.getPlayer())) currentLocation.add(0, -1, 0);\n\n for (int i = 0; i < flowers.size(); i++) {\n if (values.get(i) && new Random().nextBoolean()) continue;\n\n final var currentBlock = currentLocation.getBlock();\n oldBlocks.put(currentBlock.getLocation().toVector(), currentBlock.getBlockData());\n\n flowerBlocks.add(currentBlock);\n flowers.get(i).getSingleFlower().setFlower(currentBlock);\n currentLocation.add(0, offset, 0);\n }\n }\n\n private void handleFlowerHistory(PlayerInteractEvent playerInteractEvent, HashMap<Vector, BlockData> oldBlocks) {\n\n final var location = playerInteractEvent.getClickedBlock();\n if (location == null) return;\n\n final var history = new Operation(oldBlocks, playerInteractEvent.getClickedBlock().getWorld());\n final var uuid = playerInteractEvent.getPlayer().getUniqueId();\n\n if (flowerManager.getOperationHistory().containsKey(uuid)) {\n var copy = new ArrayList<>(List.copyOf(flowerManager.getOperationHistory().get(uuid)));\n copy.add(history);\n\n flowerManager.getOperationHistory().put(uuid, copy);\n } else flowerManager.getOperationHistory().put(uuid, List.of(history));\n }\n\n private boolean playerLookUp(Player player) {\n return player.getPitch() < 0.0F;\n }\n}" }, { "identifier": "FlowerManager", "path": "src/main/java/com/uroria/betterflowers/managers/FlowerManager.java", "snippet": "@Getter\npublic final class FlowerManager {\n\n private final Map<ItemStack, FlowerGroupData> flowers;\n private final Map<ItemStack, BrushData> brushes;\n private final Map<FlowerGroupData, List<Boolean>> flowerRandomizer;\n private final Map<UUID, List<Operation>> operationHistory;\n\n public FlowerManager() {\n this.flowers = new HashMap<>();\n this.brushes = new HashMap<>();\n this.flowerRandomizer = new HashMap<>();\n this.operationHistory = new HashMap<>();\n }\n}" }, { "identifier": "LanguageManager", "path": "src/main/java/com/uroria/betterflowers/managers/LanguageManager.java", "snippet": "public final class LanguageManager {\n\n private final Map<String, String> singleMessage;\n private final Map<String, List<String>> multiMessage;\n\n public LanguageManager() {\n this.singleMessage = new HashMap<>();\n this.multiMessage = new HashMap<>();\n\n readConfig();\n }\n\n public void sendPlayerMessage(Player player, String key) {\n player.sendMessage(getComponent(key));\n }\n\n public void sendPlayersMessage(Collection<Player> players, String key) {\n players.forEach(player -> sendPlayerMessage(player, key));\n }\n\n public Component getComponent(String key, String regex, String value) {\n final var string = getStringFromConfig(key).replace(regex, value);\n return MiniMessage.miniMessage().deserialize(string);\n }\n\n public Component getComponent(String key) {\n final var string = getStringFromConfig(key);\n return MiniMessage.miniMessage().deserialize(string);\n }\n\n public List<Component> getComponents(String key) {\n return getStringsFromConfig(key).stream().map(string -> MiniMessage.miniMessage().deserialize(string)).toList();\n }\n\n private void readLangaugeFromResources(String path) {\n\n final var inputStream = getClass().getClassLoader().getResourceAsStream(\"language.json\");\n if (inputStream == null) return;\n\n try {\n final var reader = new BufferedReader(new InputStreamReader(inputStream));\n final var stringBuilder = new StringBuilder();\n\n String line;\n\n while ((line = reader.readLine()) != null) {\n stringBuilder.append(line);\n }\n\n final var jsonString = stringBuilder.toString();\n final var jsonFile = new Gson().fromJson(jsonString, JsonObject.class);\n\n jsonFile.keySet().forEach(key -> {\n\n final var element = jsonFile.get(key);\n readConfigData(key, element);\n\n });\n\n writeFile(path + \"/language.json\", jsonString);\n\n } catch (IOException exception) {\n throw new RuntimeException(exception);\n }\n }\n\n private void writeFile(String path, String data) {\n\n try (var fileWriter = new FileWriter(path)) {\n\n fileWriter.write(data);\n fileWriter.flush();\n\n } catch (IOException ioException) {\n throw new RuntimeException(ioException);\n }\n }\n\n private void readLanguageFileFromJson(File file) {\n\n try {\n\n final var jsonFile = JsonParser.parseReader(new FileReader(file)).getAsJsonObject();\n\n jsonFile.keySet().forEach(key -> {\n\n final var element = jsonFile.get(key);\n readConfigData(key, element);\n\n });\n\n } catch (FileNotFoundException fileNotFoundException) {\n throw new RuntimeException(fileNotFoundException);\n }\n }\n\n private void readConfigData(String key, JsonElement element) {\n\n if (element.isJsonArray()) {\n\n final var list = new ArrayList<String>();\n\n for (var jsonElement : element.getAsJsonArray().asList()) {\n list.add(jsonElement.getAsString());\n }\n\n this.multiMessage.put(key, list);\n return;\n }\n\n this.singleMessage.put(key, element.getAsString());\n }\n\n private void readConfig() {\n\n final var path = Bukkit.getPluginsFolder() + \"/BetterFlowers\";\n final var file = new File(path + \"/language.json\");\n\n try {\n\n if (new File(path).mkdir()) throw new FileNotFoundException();\n\n if (file.exists()) {\n readLanguageFileFromJson(file);\n return;\n }\n\n readLangaugeFromResources(path);\n\n } catch (FileNotFoundException exception) {\n readLangaugeFromResources(path);\n }\n }\n\n private String getStringFromConfig(String key) {\n return this.singleMessage.getOrDefault(key, key);\n }\n\n private String getStringFromConfig(String key, String optional) {\n return this.singleMessage.getOrDefault(key, optional);\n }\n\n private List<String> getStringsFromConfig(String key) {\n return this.multiMessage.getOrDefault(key, List.of(key));\n }\n\n private List<String> getStringsFromConfig(String key, List<String> optional) {\n return this.multiMessage.getOrDefault(key, optional);\n }\n}" } ]
import com.uroria.betterflowers.commands.Flower; import com.uroria.betterflowers.commands.FlowerBrush; import com.uroria.betterflowers.commands.UndoFlower; import com.uroria.betterflowers.listeners.CustomFlowerBrushListener; import com.uroria.betterflowers.listeners.CustomFlowerPlaceListener; import com.uroria.betterflowers.managers.FlowerManager; import com.uroria.betterflowers.managers.LanguageManager; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.util.List;
3,911
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin { private final FlowerManager flowerManager; private final LanguageManager languageManager; public BetterFlowers() { this.flowerManager = new FlowerManager(); this.languageManager = new LanguageManager(); } @Override public void onEnable() { registerCommands(); registerListener(); } private void registerCommands() { final var flowerCommand = getCommand("flower"); if (flowerCommand != null) { flowerCommand.setAliases(List.of("f", "F")); flowerCommand.setExecutor(new Flower(this)); } final var flowerBrushCommand = getCommand("flowerbrush"); if (flowerBrushCommand != null) { flowerBrushCommand.setAliases(List.of("fb", "Fb", "fB", "FB")); flowerBrushCommand.setExecutor(new FlowerBrush(this)); } final var undoFlowerCommand = getCommand("undoflower"); if (undoFlowerCommand != null) { undoFlowerCommand.setAliases(List.of("uf", "Uf", "uF", "UF")); undoFlowerCommand.setExecutor(new UndoFlower(this)); } } private void registerListener() { Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin { private final FlowerManager flowerManager; private final LanguageManager languageManager; public BetterFlowers() { this.flowerManager = new FlowerManager(); this.languageManager = new LanguageManager(); } @Override public void onEnable() { registerCommands(); registerListener(); } private void registerCommands() { final var flowerCommand = getCommand("flower"); if (flowerCommand != null) { flowerCommand.setAliases(List.of("f", "F")); flowerCommand.setExecutor(new Flower(this)); } final var flowerBrushCommand = getCommand("flowerbrush"); if (flowerBrushCommand != null) { flowerBrushCommand.setAliases(List.of("fb", "Fb", "fB", "FB")); flowerBrushCommand.setExecutor(new FlowerBrush(this)); } final var undoFlowerCommand = getCommand("undoflower"); if (undoFlowerCommand != null) { undoFlowerCommand.setAliases(List.of("uf", "Uf", "uF", "UF")); undoFlowerCommand.setExecutor(new UndoFlower(this)); } } private void registerListener() { Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);
Bukkit.getPluginManager().registerEvents(new CustomFlowerBrushListener(this), this);
0
2023-11-18 16:13:59+00:00
8k
Appu26J/Softuninstall
src/appu26j/Softuninstall.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": "FontRenderer", "path": "src/appu26j/gui/font/FontRenderer.java", "snippet": "public class FontRenderer\n{\n private final HashMap<Character, Float> cachedWidths = new HashMap<>();\n public static final int CHAR_DATA_MALLOC_SIZE = 96;\n public static final int FONT_TEX_W = 512;\n public static final int FONT_TEX_H = FONT_TEX_W;\n public static final int BAKE_FONT_FIRST_CHAR = 32;\n public static final int GLYPH_COUNT = CHAR_DATA_MALLOC_SIZE;\n protected final STBTTBakedChar.Buffer charData;\n protected final STBTTFontinfo fontInfo;\n protected final int fontSize, textureID;\n protected final float ascent, descent, lineGap;\n \n public FontRenderer(File font, int fontSize)\n {\n this.fontSize = fontSize;\n this.charData = STBTTBakedChar.malloc(CHAR_DATA_MALLOC_SIZE);\n this.fontInfo = STBTTFontinfo.create();\n int textureID = 0;\n float ascent = 0, descent = 0, lineGap = 0;\n \n try\n {\n ByteBuffer ttfFileData = this.getByteBuffer(font);\n ByteBuffer texData = BufferUtils.createByteBuffer(FONT_TEX_W * FONT_TEX_H);\n STBTruetype.stbtt_BakeFontBitmap(ttfFileData, fontSize, texData, FONT_TEX_W, FONT_TEX_H, BAKE_FONT_FIRST_CHAR, charData);\n \n try (MemoryStack stack = MemoryStack.stackPush())\n {\n STBTruetype.stbtt_InitFont(this.fontInfo, ttfFileData);\n float pixelScale = STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, fontSize);\n IntBuffer ascentBuffer = stack.ints(0);\n IntBuffer descentBuffer = stack.ints(0);\n IntBuffer lineGapBuffer = stack.ints(0);\n STBTruetype.stbtt_GetFontVMetrics(this.fontInfo, ascentBuffer, descentBuffer, lineGapBuffer);\n ascent = ascentBuffer.get(0) * pixelScale;\n descent = descentBuffer.get(0) * pixelScale;\n }\n \n textureID = glGenTextures();\n glBindTexture(GL_TEXTURE_2D, textureID);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, FONT_TEX_W, FONT_TEX_H, 0, GL_ALPHA, GL_UNSIGNED_BYTE, texData);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n \n catch (Exception e)\n {\n \te.printStackTrace();\n }\n \n this.textureID = textureID;\n this.ascent = ascent;\n this.descent = descent;\n this.lineGap = lineGap;\n char[] allLetters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()_+-={}[];':\\\"<>?,./ \".toCharArray();\n\n for (char letter : allLetters)\n {\n this.cachedWidths.put(letter, getCharWidth(letter));\n }\n }\n \n public void shutdown()\n {\n this.charData.free();\n this.fontInfo.free();\n \n if (this.textureID != 0)\n {\n glDeleteTextures(this.textureID);\n }\n }\n \n public ByteBuffer getByteBuffer(File file) throws IOException \n {\n ByteBuffer buffer;\n \n try (FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel())\n {\n buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());\n }\n \n return buffer;\n }\n \n public void drawStringWithShadow(String text, float x, float y, Color color)\n {\n \tthis.drawString(text, x + ((float) this.fontSize / 12), y + ((float) this.fontSize / 12), color.darker().darker().darker().darker());\n \tthis.drawString(text, x, y, color);\n }\n \n public void drawString(String text, float x, float y, Color color)\n {\n y += this.ascent;\n\n try (MemoryStack stack = MemoryStack.stackPush())\n {\n FloatBuffer xPosition = stack.mallocFloat(1);\n FloatBuffer yPosition = stack.mallocFloat(1);\n xPosition.put(x);\n yPosition.put(y);\n xPosition.flip();\n yPosition.flip();\n STBTTAlignedQuad stbttAlignedQuad = STBTTAlignedQuad.malloc(stack);\n glBindTexture(GL_TEXTURE_2D, this.textureID);\n GlStateManager.enableTexture2D();\n GlStateManager.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(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F);\n glBegin(GL_TRIANGLES);\n int firstCP = BAKE_FONT_FIRST_CHAR;\n int lastCP = BAKE_FONT_FIRST_CHAR + GLYPH_COUNT - 1;\n \n for (int i = 0; i < text.length(); i++)\n {\n int codePoint = text.codePointAt(i);\n \n if (codePoint == '§')\n {\n \tGlStateManager.color(color.getRed() / 340F, color.getGreen() / 340F, color.getBlue() / 340F, color.getAlpha() / 340F);\n \tcontinue;\n }\n \n if (codePoint == '\\n')\n {\n \txPosition.put(0, x);\n yPosition.put(0, yPosition.get(0) + fontSize);\n continue;\n }\n \n else if (codePoint < firstCP || codePoint > lastCP)\n {\n continue;\n }\n \n STBTruetype.stbtt_GetBakedQuad(this.charData, FONT_TEX_W, FONT_TEX_H, codePoint - firstCP, xPosition, yPosition, stbttAlignedQuad, true);\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());\n glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y0());\n glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());\n glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());\n }\n \n glEnd();\n\t\t\tGlStateManager.disableBlend();\n\t\t\tGlStateManager.disableAlpha();\n\t\t\tGlStateManager.disableTexture2D();\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n }\n\n public float getStringWidth(String text)\n {\n float length = 0;\n\n for (char character : text.toCharArray())\n {\n if (this.cachedWidths.containsKey(character))\n {\n length += this.cachedWidths.get(character);\n }\n\n else\n {\n float charWidth = this.getCharWidth(character);\n this.cachedWidths.put(character, charWidth);\n length += charWidth;\n }\n }\n\n return length;\n }\n\n private float getCharWidth(char character)\n {\n float length = 0;\n\n try (MemoryStack memoryStack = MemoryStack.stackPush())\n {\n IntBuffer advancedWidth = memoryStack.mallocInt(1);\n IntBuffer leftSideBearing = memoryStack.mallocInt(1);\n STBTruetype.stbtt_GetCodepointHMetrics(this.fontInfo, character, advancedWidth, leftSideBearing);\n length += advancedWidth.get(0);\n }\n\n return length * STBTruetype.stbtt_ScaleForPixelHeight(this.fontInfo, this.fontSize);\n }\n}" }, { "identifier": "GuiScreen", "path": "src/appu26j/gui/screens/GuiScreen.java", "snippet": "public abstract class GuiScreen extends Gui\n{\n\tprotected FontRenderer fontRendererExtraBig, fontRendererBig, fontRendererMid, fontRendererMidSmall, fontRenderer;\n\tprotected float width = 0, height = 0;\n\t\n\tpublic abstract void drawScreen(float mouseX, float mouseY);\n\t\n\tpublic void mouseClicked(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void mouseReleased(int mouseButton, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void charTyped(char character, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void keyPressed(int key, float mouseX, float mouseY)\n\t{\n\t\t;\n\t}\n\n\tpublic void scroll(float scrollY)\n\t{\n\t\t;\n\t}\n\t\n\tpublic void initGUI(float width, float height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.fontRenderer = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 28);\n\t\tthis.fontRendererMidSmall = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 36);\n\t\tthis.fontRendererMid = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 54);\n\t\tthis.fontRendererBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 72);\n\t\tthis.fontRendererExtraBig = new FontRenderer(Assets.getAsset(\"segoeui.ttf\"), 88);\n\t}\n\t\n\tprotected boolean isInsideBox(float mouseX, float mouseY, float x, float y, float width, float height)\n\t{\n\t\treturn mouseX > x && mouseX < width && mouseY > y && mouseY < height;\n\t}\n\t\n\tpublic ArrayList<FontRenderer> getFontRenderers()\n\t{\n\t\treturn new ArrayList<>(Arrays.asList(this.fontRenderer, this.fontRendererMidSmall, this.fontRendererMid, this.fontRendererBig, this.fontRendererExtraBig));\n\t}\n}" }, { "identifier": "GuiSoftuninstall", "path": "src/appu26j/gui/screens/GuiSoftuninstall.java", "snippet": "public class GuiSoftuninstall extends GuiScreen\n{\n public static final ArrayList<AppInfo> apps = new ArrayList<>();\n private String previousUninstalledApp = \"\";\n private float scroll = 0, maxScroll = 0;\n private boolean dragging = false;\n public static int loading = 2;\n private Texture delete;\n\n @Override\n public void drawScreen(float mouseX, float mouseY)\n {\n if (!apps.isEmpty())\n {\n if (this.dragging)\n {\n float progress = (mouseY - 15) / (this.height - 30);\n this.scroll = this.maxScroll * progress;\n\n if (this.scroll < 0)\n {\n this.scroll = 0;\n }\n\n if (this.scroll > this.maxScroll)\n {\n this.scroll = this.maxScroll;\n }\n }\n\n this.maxScroll = 0;\n float y = 15 - this.scroll;\n ArrayList<AppInfo> finalApps = new ArrayList<>(apps);\n\n for (AppInfo appInfo : finalApps)\n {\n Gui.drawRect(15, y, this.width - 40, y + 60, this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) ? new Color(235, 235, 235) : new Color(245, 245, 245));\n this.fontRenderer.drawString(appInfo.getName(), 25, y, new Color(50, 50, 50));\n GL11.glEnable(GL11.GL_SCISSOR_TEST);\n ScissorUtil.scissor(0, 0, this.width - 100, this.height);\n this.fontRenderer.drawString(appInfo.getUninstallCmd(), this.fontRenderer.getStringWidth(appInfo.getPublisher()) + 30, y + 27, new Color(175, 175, 175));\n GL11.glDisable(GL11.GL_SCISSOR_TEST);\n this.fontRenderer.drawString(appInfo.getPublisher(), 25, y + 27, new Color(125, 125, 125));\n Gui.drawImage(this.delete, this.width - 95, y + 4, 0, 0, 48, 48, 48, 48);\n y += 75;\n this.maxScroll += 75;\n }\n\n this.maxScroll -= (loading == 0 ? 685 : 625);\n\n if (this.maxScroll < 0)\n {\n this.maxScroll = 0;\n }\n\n if (this.scroll > this.maxScroll)\n {\n this.scroll = this.maxScroll;\n }\n\n if (loading != 0)\n {\n this.fontRendererMid.drawString(\"Loading...\", (this.width / 2) - (this.fontRendererMid.getStringWidth(\"Loading...\") / 2), y - 10, new Color(100, 100, 100));\n }\n\n Gui.drawRect(this.width - 27, 15, this.width - 13, this.height - 15, new Color(200, 200, 200));\n float scrollProgress = (this.scroll / this.maxScroll);\n float yPos = ((this.height - 180) * scrollProgress) + 90;\n Gui.drawRect(this.width - 27, yPos - 75, this.width - 13, yPos + 75, new Color(245, 245, 245));\n }\n }\n\n @Override\n public void mouseClicked(int mouseButton, float mouseX, float mouseY)\n {\n super.mouseClicked(mouseButton, mouseX, mouseY);\n float y = 15 - this.scroll;\n ArrayList<AppInfo> finalApps = new ArrayList<>(apps);\n\n for (AppInfo appInfo : finalApps)\n {\n if (this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) && !this.previousUninstalledApp.equals(appInfo.getName()))\n {\n new Thread(() ->\n {\n try\n {\n Process process = Runtime.getRuntime().exec(appInfo.getUninstallCmd());\n process.waitFor();\n String output = Registry.execute(\"QUERY \" + appInfo.getRegistryPath() + \" /v DisplayName\");\n\n if (output.contains(\"ERROR: The system was unable to find the specified registry key or value.\"))\n {\n GuiSoftuninstall.apps.remove(appInfo);\n }\n\n this.previousUninstalledApp = \"\";\n }\n\n catch (Exception e)\n {\n ;\n }\n }).start();\n\n this.previousUninstalledApp = appInfo.getName();\n break;\n }\n\n y += 75;\n }\n\n if (this.isInsideBox(mouseX, mouseY, this.width - 37, 5, this.width - 3, this.height - 5) && mouseButton == 0)\n {\n this.dragging = true;\n }\n }\n\n @Override\n public void mouseReleased(int mouseButton, float mouseX, float mouseY)\n {\n super.mouseReleased(mouseButton, mouseX, mouseY);\n this.dragging = false;\n }\n\n @Override\n public void initGUI(float width, float height)\n {\n super.initGUI(width, height);\n AppUtil.loadApps();\n this.delete = Gui.getTexture(Assets.getAsset(\"delete.png\"));\n }\n\n @Override\n public void scroll(float scrollY)\n {\n super.scroll(scrollY);\n this.scroll -= scrollY * 37.5F;\n\n if (this.scroll < 0)\n {\n this.scroll = 0;\n }\n\n if (this.scroll > this.maxScroll)\n {\n this.scroll = this.maxScroll;\n }\n }\n}" } ]
import appu26j.assets.Assets; import appu26j.gui.font.FontRenderer; import appu26j.gui.screens.GuiScreen; import appu26j.gui.screens.GuiSoftuninstall; import org.lwjgl.glfw.*; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.DoubleBuffer; import java.util.Objects; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
4,591
package appu26j; public enum Softuninstall { INSTANCE; private final int width = 900, height = 700; private float mouseX = 0, mouseY = 0;
package appu26j; public enum Softuninstall { INSTANCE; private final int width = 900, height = 700; private float mouseX = 0, mouseY = 0;
private GuiScreen currentScreen;
2
2023-11-13 03:20:19+00:00
8k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/UserController.java
[ { "identifier": "Role", "path": "src/main/java/com/myfood/dto/Role.java", "snippet": "@Entity\n@Table(name = \"roles\")\npublic class Role {\n\n\n /** Unique identifier for the role. Automatically generated. */\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n\t/** Name of the role. Must be unique and not null. */\n @Column(name = \"name\", nullable = false)\n private String name;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"role\",fetch = FetchType.LAZY, cascade = CascadeType.ALL )\n private List<User> users;\n \n /** Default constructor required by JPA. */\n public Role() {\n }\n \n /**\n * Constructor for the {@code Role} class that allows setting the identifier,\n * name, and the list of users associated with this role.\n *\n * @param id The unique identifier of the role.\n * @param name The name of the role.\n * @param user The list of users associated with this role.\n */\n public Role(Long id, String name) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n \n public Role(String name) {\n \tthis.name = name;\n }\n \n\n\n /**\n * Get the unique identifier of the role.\n *\n * @return The unique identifier of the role.\n */\n public Long getId() {\n return id;\n }\n\n /**\n * Get the name of the role.\n *\n * @return The name of the role.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Set the unique identifier of the role.\n *\n * @param id The unique identifier of the role.\n */\n public void setId(Long id) {\n this.id = id;\n }\n\n /**\n * Set the name of the role.\n *\n * @param name The name of the role.\n */\n public void setName(String name) {\n this.name = name;\n }\n \n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Role [id=\" + id + \", name=\" + name + \", users=\" + users + \"]\";\n\t}\n\n}" }, { "identifier": "User", "path": "src/main/java/com/myfood/dto/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User {\n\t\n\t/**\n\t* The unique identifier for the user.\n\t*/\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t/**\n\t* The email address of the user. It is unique and cannot be null.\n\t*/\n\t@Email\n\t@NotBlank\n\t@Size(max = 80)\n\t@Column(name = \"email\", unique = true)\n\tprivate String email;\n\t\n\t/**\n\t* The password associated with the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Column(name = \"password\")\n\tprivate String password;\n\t\n\t/**\n\t* The username of the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Size(max = 60)\n\t@Column(name = \"name\", unique = true)\n\tprivate String username;\n\t\n\t/**\n\t* Represents the role of the user within the system. Multiple users can share the same role.\n\t* This field is mapped as a one-to-one relationship with the {@code Role} entity,\n\t* and it includes cascading persistence to ensure the role is persisted along with the user.\n\t*/\n\t@ManyToOne\n\tprivate Role role;\n\n @OneToMany(mappedBy = \"user\" ,fetch = FetchType.EAGER ,cascade = CascadeType.ALL )\n @JsonIgnore\n private List<Order> orders;\n \n @Column(name = \"created_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime createdAt;\n\n @Column(name = \"updated_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime updatedAt;\n\n\t/**\n\t * Default constructor for the {@code User} class.\n\t */\n\tpublic User() {\n\t}\n\t\n\tpublic User(Long id, String email, String password, String username , LocalDateTime createdAt ,LocalDateTime updatedAt) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = new Role();\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Parameterized constructor for the {@code User} class.\n\t *\n\t * @param id The unique identifier for the user.\n\t * @param email The email address of the user.\n\t * @param password The password associated with the user.\n\t * @param username The username of the user.\n\t * @param role The role of the user in the system.\n\t */\n\tpublic User(Long id, String email, String password, String username, Role role, LocalDateTime createdAt ,LocalDateTime updatedAt ) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = role;\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Get the unique identifier of the user.\n\t *\n\t * @return The unique identifier of the user.\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Set the unique identifier of the user.\n\t *\n\t * @param id The unique identifier of the user.\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Get the email address of the user.\n\t *\n\t * @return The email address of the user.\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Set the email address of the user.\n\t *\n\t * @param email The email address of the user.\n\t */\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Get the password associated with the user.\n\t *\n\t * @return The password associated with the user.\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * Set the password associated with the user.\n\t *\n\t * @param password The password associated with the user.\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * Get the username of the user.\n\t *\n\t * @return The username of the user.\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * Set the username of the user.\n\t *\n\t * @param username The username of the user.\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * Get the role of the user in the system.\n\t *\n\t * @return The role of the user.\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\t/**\n\t * Set the role of the user in the system.\n\t *\n\t * @param role The role of the user.\n\t */\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [id=\" + id + \", email=\" + email + \", password=\" + password + \", username=\" + username + \", role=\"\n\t\t\t\t+ role + \"]\";\n\t}\n\n\n\t/**\n\t * @return the orders\n\t */\n\tpublic List<Order> getOrders() {\n\t\treturn orders;\n\t}\n\n\t/**\n\t * @param orders the orders to set\n\t */\n\tpublic void setOrders(List<Order> orders) {\n\t\tthis.orders = orders;\n\t}\n\n\t/**\n\t * @return the createdAt\n\t */\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\t/**\n\t * @param createdAt the createdAt to set\n\t */\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\t/**\n\t * @return the updatedAt\n\t */\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\t/**\n\t * @param updatedAt the updatedAt to set\n\t */\n\tpublic void setUpdatedAt(LocalDateTime updatedAt) {\n\t\tthis.updatedAt = updatedAt;\n\t}\n}" }, { "identifier": "UserDTO", "path": "src/main/java/com/myfood/dto/UserDTO.java", "snippet": "public class UserDTO {\n\n\tprivate Long id;\n\tprivate String email;\n\tprivate String username;\n\tprivate Role role;\n private LocalDateTime createdAt;\n private LocalDateTime updatedAt;\n\n\tprivate UserDTO(Builder builder) {\n\t\tthis.id = builder.id;\n\t\tthis.email = builder.email;\n\t\tthis.username = builder.username;\n\t\tthis.role = builder.role;\n\t\tthis.createdAt = builder.createdAt;\n\t\tthis.updatedAt = builder.updatedAt;\n\t}\n\t\n\t/**\n\t * @return the createdAt\n\t */\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\t\n\t/**\n\t * @return the updatedAt\n\t */\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\t/**\n\t * @return the id\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @return the email\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * @return the username\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * @return the role\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\tpublic static class Builder {\n\t\tprivate Long id;\n\t\tprivate String email;\n\t\tprivate String username;\n\t\tprivate Role role;\n\t\tprivate LocalDateTime createdAt;\n\t\tprivate LocalDateTime updatedAt;\n\n\t\tpublic Builder() {\n\t\t}\n\t\t\n\t\t/**\n\t\t * @param updatedAt the id to set\n\t\t */\n\t\tpublic Builder setUpdatedAt(LocalDateTime updatedAt) {\n\t\t\tthis.updatedAt = updatedAt;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t/**\n\t\t * @param createdAt the id to set\n\t\t */\n\t\tpublic Builder setCreatedAt(LocalDateTime createdAt) {\n\t\t\tthis.createdAt = createdAt;\n\t\t\treturn this;\n\t\t}\n\t\t\n\n\t\t/**\n\t\t * @param id the id to set\n\t\t */\n\t\tpublic Builder setId(Long id) {\n\t\t\tthis.id = id;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @param email the email to set\n\t\t */\n\t\tpublic Builder setEmail(String email) {\n\t\t\tthis.email = email;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @param username the username to set\n\t\t */\n\t\tpublic Builder setUsername(String username) {\n\t\t\tthis.username = username;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @param role the role to set\n\t\t */\n\t\tpublic Builder setRole(Role role) {\n\t\t\tthis.role = role;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @return newUserDTO\n\t\t */\n\t\tpublic UserDTO build() {\n\t\t\treturn new UserDTO(this);\n\t\t}\n\t}\n\n\n\n\n\n\n\n}" }, { "identifier": "RolServiceImpl", "path": "src/main/java/com/myfood/services/RolServiceImpl.java", "snippet": "@Service\npublic class RolServiceImpl implements IRolService {\n\n\t@Autowired\n\tprivate IRolDAO rolDao;\n\n\t@Override\n\tpublic List<Role> getAllRoles() {\n\t\treturn rolDao.findAll();\n\t}\n\n\t@Override\n\tpublic Optional<Role> getOneRole(Long id) {\n\t\treturn rolDao.findById(id);\n\t}\n\n\t@Override\n\tpublic Role createRole(Role entity) {\n\t\treturn rolDao.save(entity);\n\t}\n\n\t@Override\n\tpublic Role updateRole(Role entity) {\n\t\treturn rolDao.save(entity);\n\t}\n\n\t@Override\n\tpublic void deleteRole(Long id) {\n\t\trolDao.deleteById(id);\n\t}\n\n\t/**\n * Check if the provided Role is valid.\n *\n * @param category The Role to validate.\n * @return true if the Role is valid, false otherwise.\n */\n\tpublic boolean isValidRole(String role) {\n\t\tString[] roleValid = {\"USER\", \"CHEF\", \"ADMIN\"};\n\t\t return Arrays.asList(roleValid).contains(role);\n\t}\n\n\t@Override\n\tpublic Optional<Role> findByName(String User) {\n\t\treturn rolDao.findByName(User);\n\t}\n\t\n}" }, { "identifier": "UserServiceImpl", "path": "src/main/java/com/myfood/services/UserServiceImpl.java", "snippet": "@Service\npublic class UserServiceImpl implements IUserService {\n\t\n\t@Autowired\n\tprivate IUserDAO userDao;\n\n\t@Override\n\tpublic List<User> getAllUsers() {\n\t\treturn userDao.findAll();\n\t}\n\n\t@Override\n\tpublic Optional<User> getOneUser(Long id){\n\t\treturn userDao.findById(id);\n\t}\n\n\t@Override\n\tpublic User createUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic User updateUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic void deleteUser(Long id) {\n\t\tuserDao.deleteById(id);;\n\t}\n\n /**\n * Get a user by username.\n *\n * @param username The username of the user.\n * @return The user with the specified username, or null if not found.\n */\n public User getUserByUsername(String username) {\n return userDao.findByUsername(username);\n }\n\n\n\tpublic Page<User> findAllWithPagination(Pageable pageable) {\n\t\treturn userDao.findAll(pageable);\n\t}\n\n\t\n\n}" } ]
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.myfood.dto.Role; import com.myfood.dto.User; import com.myfood.dto.UserDTO; import com.myfood.services.RolServiceImpl; import com.myfood.services.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
3,784
package com.myfood.controllers; /** * @author David Maza * */ /** * @author Davi Maza * */ /** * Controller class for handling user-related operations. * * This controller provides endpoints for basic CRUD operations on users. * * @RestController Indicates that this class is a Spring MVC Controller. * @RequestMapping("/api/v1") Base mapping for all endpoints in this controller. */ @RestController @RequestMapping("api/v1") public class UserController { @Autowired
package com.myfood.controllers; /** * @author David Maza * */ /** * @author Davi Maza * */ /** * Controller class for handling user-related operations. * * This controller provides endpoints for basic CRUD operations on users. * * @RestController Indicates that this class is a Spring MVC Controller. * @RequestMapping("/api/v1") Base mapping for all endpoints in this controller. */ @RestController @RequestMapping("api/v1") public class UserController { @Autowired
private UserServiceImpl userServ;
4
2023-11-10 16:09:43+00:00
8k
Artillex-Studios/AxGraves
src/main/java/com/artillexstudios/axgraves/listeners/DeathListener.java
[ { "identifier": "GravePreSpawnEvent", "path": "src/main/java/com/artillexstudios/axgraves/api/events/GravePreSpawnEvent.java", "snippet": "public class GravePreSpawnEvent extends Event implements Cancellable {\n private static final HandlerList handlerList = new HandlerList();\n private final Player player;\n private final Grave grave;\n private boolean isCancelled = false;\n\n public GravePreSpawnEvent(@NotNull Player player, @NotNull Grave grave) {\n super(!Bukkit.isPrimaryThread());\n\n this.player = player;\n this.grave = grave;\n }\n\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return handlerList;\n }\n\n public static HandlerList getHandlerList() {\n return handlerList;\n }\n\n @NotNull\n public Player getPlayer() {\n return player;\n }\n\n @NotNull\n public Grave getGrave() {\n return grave;\n }\n\n @Override\n public boolean isCancelled() {\n return isCancelled;\n }\n\n @Override\n public void setCancelled(boolean isCancelled) {\n this.isCancelled = isCancelled;\n }\n}" }, { "identifier": "GraveSpawnEvent", "path": "src/main/java/com/artillexstudios/axgraves/api/events/GraveSpawnEvent.java", "snippet": "public class GraveSpawnEvent extends Event {\n private static final HandlerList handlerList = new HandlerList();\n private final Player player;\n private final Grave grave;\n\n public GraveSpawnEvent(@NotNull Player player, @NotNull Grave grave) {\n super(!Bukkit.isPrimaryThread());\n\n this.player = player;\n this.grave = grave;\n }\n\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return handlerList;\n }\n\n public static HandlerList getHandlerList() {\n return handlerList;\n }\n\n @NotNull\n public Player getPlayer() {\n return player;\n }\n\n @NotNull\n public Grave getGrave() {\n return grave;\n }\n}" }, { "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": "ExperienceUtils", "path": "src/main/java/com/artillexstudios/axgraves/utils/ExperienceUtils.java", "snippet": "public final class ExperienceUtils {\n // credit: https://gist.githubusercontent.com/Jikoo/30ec040443a4701b8980/raw/0745ca25a8aaaf749ba2f2164a809e998f6a37c4/Experience.java\n\n public static int getExp(@NotNull Player player) {\n return getExpFromLevel(player.getLevel()) + Math.round(getExpToNext(player.getLevel()) * player.getExp());\n }\n\n public static int getExpFromLevel(int level) {\n if (level > 30) {\n return (int) (4.5 * level * level - 162.5 * level + 2220);\n }\n if (level > 15) {\n return (int) (2.5 * level * level - 40.5 * level + 360);\n }\n return level * level + 6 * level;\n }\n\n public static double getLevelFromExp(long exp) {\n int level = getIntLevelFromExp(exp);\n\n // Get remaining exp progressing towards next level. Cast to float for next bit of math.\n float remainder = exp - (float) getExpFromLevel(level);\n\n // Get level progress with float precision.\n float progress = remainder / getExpToNext(level);\n\n // Slap both numbers together and call it a day. While it shouldn't be possible for progress\n // to be an invalid value (value < 0 || 1 <= value)\n return ((double) level) + progress;\n }\n\n public static int getIntLevelFromExp(long exp) {\n if (exp > 1395) {\n return (int) ((Math.sqrt(72 * exp - 54215D) + 325) / 18);\n }\n if (exp > 315) {\n return (int) (Math.sqrt(40 * exp - 7839D) / 10 + 8.1);\n }\n if (exp > 0) {\n return (int) (Math.sqrt(exp + 9D) - 3);\n }\n return 0;\n }\n\n private static int getExpToNext(int level) {\n if (level >= 30) {\n // Simplified formula. Internal: 112 + (level - 30) * 9\n return level * 9 - 158;\n }\n if (level >= 15) {\n // Simplified formula. Internal: 37 + (level - 15) * 5\n return level * 5 - 38;\n }\n // Internal: 7 + level * 2\n return level * 2 + 7;\n }\n\n public static void changeExp(Player player, int exp) {\n exp += getExp(player);\n\n if (exp < 0) {\n exp = 0;\n }\n\n double levelAndExp = getLevelFromExp(exp);\n int level = (int) levelAndExp;\n player.setLevel(level);\n player.setExp((float) (levelAndExp - level));\n }\n}" }, { "identifier": "CONFIG", "path": "src/main/java/com/artillexstudios/axgraves/AxGraves.java", "snippet": "public static Config CONFIG;" } ]
import com.artillexstudios.axgraves.api.events.GravePreSpawnEvent; import com.artillexstudios.axgraves.api.events.GraveSpawnEvent; import com.artillexstudios.axgraves.grave.Grave; import com.artillexstudios.axgraves.grave.SpawnedGrave; import com.artillexstudios.axgraves.utils.ExperienceUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import static com.artillexstudios.axgraves.AxGraves.CONFIG;
3,735
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return; Grave grave = null; if (!event.getKeepInventory()) { grave = new Grave(player.getLocation(), player, event.getDrops().toArray(new ItemStack[0]), ExperienceUtils.getExp(player)); } else if (CONFIG.getBoolean("override-keep-inventory", true)) { grave = new Grave(player.getLocation(), player, player.getInventory().getContents(), ExperienceUtils.getExp(player)); player.setLevel(0); player.setTotalExperience(0); player.getInventory().clear(); } if (grave == null) return;
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return; Grave grave = null; if (!event.getKeepInventory()) { grave = new Grave(player.getLocation(), player, event.getDrops().toArray(new ItemStack[0]), ExperienceUtils.getExp(player)); } else if (CONFIG.getBoolean("override-keep-inventory", true)) { grave = new Grave(player.getLocation(), player, player.getInventory().getContents(), ExperienceUtils.getExp(player)); player.setLevel(0); player.setTotalExperience(0); player.getInventory().clear(); } if (grave == null) return;
final GravePreSpawnEvent gravePreSpawnEvent = new GravePreSpawnEvent(player, grave);
0
2023-11-18 16:37:27+00:00
8k
GoldenStack/minestom-ca
src/main/java/dev/goldenstack/minestom_ca/server/Main.java
[ { "identifier": "AutomataWorld", "path": "src/main/java/dev/goldenstack/minestom_ca/AutomataWorld.java", "snippet": "public interface AutomataWorld {\n\n Map<Instance, AutomataWorld> WORLDS = new HashMap<>();\n\n static void register(AutomataWorld world) {\n final AutomataWorld prev = WORLDS.put(world.instance(), world);\n if (prev != null) {\n throw new IllegalStateException(\"An AutomataWorld is already registered for the instance \" + world.instance());\n }\n }\n\n static AutomataWorld get(Instance instance) {\n return WORLDS.get(instance);\n }\n\n /**\n * Simulates one tick of progress for the world.\n */\n void tick();\n\n /**\n * Handles an external block change (e.g. block place or break)\n */\n void handlePlacement(int x, int y, int z, Map<Integer, Integer> properties);\n\n default void handlePlacement(Point point, Block block) {\n handlePlacement(point.blockX(), point.blockY(), point.blockZ(),\n Map.of(0, (int) block.stateId()));\n }\n\n void handleChunkLoad(int chunkX, int chunkZ);\n\n void handleChunkUnload(int chunkX, int chunkZ);\n\n Map<Integer, Integer> queryIndexes(int x, int y, int z);\n\n default Map<String, Integer> queryNames(int x, int y, int z) {\n Map<Integer, String> variables = new HashMap<>();\n for (var entry : program().variables().entrySet()) {\n variables.put(entry.getValue(), entry.getKey());\n }\n final Map<Integer, Integer> indexes = queryIndexes(x, y, z);\n Map<String, Integer> names = new HashMap<>();\n for (Map.Entry<Integer, Integer> entry : indexes.entrySet()) {\n final String name = variables.get(entry.getKey());\n if (name != null) names.put(name, entry.getValue());\n else names.put(\"var\" + entry.getKey(), entry.getValue());\n }\n return Map.copyOf(names);\n }\n\n /**\n * Gets the instance that is being ticked\n *\n * @return the ticked instance\n */\n Instance instance();\n\n Program program();\n}" }, { "identifier": "LazyWorld", "path": "src/main/java/dev/goldenstack/minestom_ca/backends/lazy/LazyWorld.java", "snippet": "@SuppressWarnings(\"UnstableApiUsage\")\npublic final class LazyWorld implements AutomataWorld {\n private final Instance instance;\n private final Program program;\n private final List<Rule> rules;\n private final int sectionCount;\n private final int minY;\n\n private final int stateCount;\n private final boolean[] trackedStates = new boolean[Short.MAX_VALUE];\n\n private final Map<Long, LChunk> loadedChunks = new HashMap<>();\n\n final class LChunk {\n // Block indexes to track next tick\n private final Set<Integer> trackedBlocks = new HashSet<>();\n private final LSection[] sections = new LSection[sectionCount];\n\n {\n Arrays.setAll(sections, i -> new LSection());\n }\n\n int getState(int x, int y, int z, int stateIndex) {\n final LSection section = sections[(y - minY) / 16];\n final Palette palette = section.states[stateIndex - 1];\n return palette.get(ChunkUtils.toSectionRelativeCoordinate(x),\n ChunkUtils.toSectionRelativeCoordinate(y),\n ChunkUtils.toSectionRelativeCoordinate(z));\n }\n\n void setState(int x, int y, int z, int stateIndex, int value) {\n final LSection section = sections[(y - minY) / 16];\n final Palette palette = section.states[stateIndex - 1];\n palette.set(ChunkUtils.toSectionRelativeCoordinate(x),\n ChunkUtils.toSectionRelativeCoordinate(y),\n ChunkUtils.toSectionRelativeCoordinate(z),\n value);\n }\n\n private final class LSection {\n private final Palette[] states = new Palette[stateCount - 1];\n\n {\n Arrays.setAll(states, i -> Palette.blocks());\n }\n }\n }\n\n public LazyWorld(Instance instance, Program program) {\n this.instance = instance;\n this.program = program;\n this.rules = program.rules();\n this.sectionCount = instance.getDimensionType().getHeight() / 16;\n this.minY = instance.getDimensionType().getMinY();\n\n this.stateCount = RuleAnalysis.stateCount(rules);\n for (Rule rule : rules) {\n RuleAnalysis.queryExpression(rule.condition(), Rule.Expression.Literal.class, literal -> {\n if (literal.value() < 0 || literal.value() >= trackedStates.length) return;\n this.trackedStates[literal.value()] = true;\n });\n }\n\n // Register loaded chunks\n System.out.println(\"Registering loaded chunks...\");\n for (Chunk c : instance.getChunks()) {\n handleChunkLoad(c.getChunkX(), c.getChunkZ());\n }\n System.out.println(\"Loaded chunks registered\");\n }\n\n @Override\n public void tick() {\n Map<Point, Map<Integer, Integer>> changes = new HashMap<>();\n // Retrieve changes\n for (var entry : loadedChunks.entrySet()) {\n final long chunkIndex = entry.getKey();\n final LChunk lChunk = entry.getValue();\n final int chunkX = ChunkUtils.getChunkCoordX(chunkIndex);\n final int chunkZ = ChunkUtils.getChunkCoordZ(chunkIndex);\n for (int blockIndex : lChunk.trackedBlocks) {\n final int localX = ChunkUtils.blockIndexToChunkPositionX(blockIndex);\n final int localY = ChunkUtils.blockIndexToChunkPositionY(blockIndex);\n final int localZ = ChunkUtils.blockIndexToChunkPositionZ(blockIndex);\n final int x = localX + chunkX * 16;\n final int y = localY;\n final int z = localZ + chunkZ * 16;\n final Map<Integer, Integer> updated = executeRules(x, y, z);\n if (updated != null) changes.put(new Vec(x, y, z), updated);\n }\n }\n // Apply changes\n for (Map.Entry<Point, Map<Integer, Integer>> entry : changes.entrySet()) {\n final Point point = entry.getKey();\n final Map<Integer, Integer> blockChange = entry.getValue();\n for (Map.Entry<Integer, Integer> changeEntry : blockChange.entrySet()) {\n final int stateIndex = changeEntry.getKey();\n final int value = changeEntry.getValue();\n if (stateIndex == 0) {\n try {\n final Block block = Block.fromStateId((short) value);\n assert block != null;\n this.instance.setBlock(point, block);\n } catch (IllegalStateException ignored) {\n }\n } else {\n final LChunk lChunk = loadedChunks.get(ChunkUtils.getChunkIndex(\n ChunkUtils.getChunkCoordinate(point.blockX()),\n ChunkUtils.getChunkCoordinate(point.blockZ())));\n if (lChunk == null) continue;\n lChunk.setState(point.blockX(), point.blockY(), point.blockZ(),\n stateIndex, value);\n }\n }\n }\n // Prepare for next tick\n for (LChunk lchunk : loadedChunks.values()) lchunk.trackedBlocks.clear();\n for (Point point : changes.keySet()) {\n final int blockX = point.blockX();\n final int blockY = point.blockY();\n final int blockZ = point.blockZ();\n register(blockX, blockY, blockZ);\n }\n }\n\n private Map<Integer, Integer> executeRules(int x, int y, int z) {\n Map<Integer, Integer> block = new HashMap<>();\n for (Rule rule : rules) {\n if (!verifyCondition(x, y, z, rule.condition())) continue;\n for (Rule.Result result : rule.results()) {\n switch (result) {\n case Rule.Result.SetIndex set -> {\n final int index = set.stateIndex();\n final int value = expression(x, y, z, set.expression());\n block.put(index, value);\n }\n case Rule.Result.BlockCopy blockCopy -> {\n final int blockX = x + blockCopy.x();\n final int blockY = y + blockCopy.y();\n final int blockZ = z + blockCopy.z();\n // Copy block state\n final Block targetBlock = instance.getBlock(blockX, blockY, blockZ);\n final int stateId = targetBlock.stateId();\n block.put(0, stateId);\n // Copy other states\n LChunk lChunk = loadedChunks.get(ChunkUtils.getChunkIndex(\n ChunkUtils.getChunkCoordinate(blockX),\n ChunkUtils.getChunkCoordinate(blockZ)));\n for (int i = 1; i < stateCount; i++) {\n final int value = lChunk.getState(blockX, blockY, blockZ, i);\n block.put(i, value);\n }\n }\n case Rule.Result.TriggerEvent triggerEvent -> {\n final String eventName = triggerEvent.event();\n final Rule.Expression eventExpression = triggerEvent.expression();\n if (eventExpression != null) {\n final int value = expression(x, y, z, eventExpression);\n System.out.println(\"Event: \" + eventName + \"=\" + value);\n } else {\n System.out.println(\"Event: \" + eventName);\n }\n }\n }\n }\n }\n if (block.isEmpty()) return null;\n return block;\n }\n\n private boolean verifyCondition(int x, int y, int z, Rule.Condition condition) {\n return switch (condition) {\n case Rule.Condition.And and -> {\n for (Rule.Condition c : and.conditions()) {\n if (!verifyCondition(x, y, z, c)) yield false;\n }\n yield true;\n }\n case Rule.Condition.Equal equal -> {\n final int first = expression(x, y, z, equal.first());\n final int second = expression(x, y, z, equal.second());\n yield first == second;\n }\n case Rule.Condition.Not not -> !verifyCondition(x, y, z, not.condition());\n };\n }\n\n private int expression(int x, int y, int z, Rule.Expression expression) {\n return switch (expression) {\n case Rule.Expression.Index index -> {\n final int stateIndex = index.stateIndex();\n if (stateIndex == 0) {\n try {\n yield instance.getBlock(x, y, z).stateId();\n } catch (NullPointerException e) {\n yield 0;\n }\n } else {\n final LChunk lChunk = loadedChunks.get(ChunkUtils.getChunkIndex(\n ChunkUtils.getChunkCoordinate(x),\n ChunkUtils.getChunkCoordinate(z)));\n if (lChunk == null) yield 0;\n yield lChunk.getState(x, y, z, stateIndex);\n }\n }\n case Rule.Expression.NeighborIndex index -> expression(\n x + index.x(), y + index.y(), z + index.z(),\n new Rule.Expression.Index(index.stateIndex()));\n case Rule.Expression.Literal literal -> literal.value();\n case Rule.Expression.NeighborsCount neighborsCount -> {\n int count = 0;\n for (Point offset : neighborsCount.offsets()) {\n final int nX = x + offset.blockX();\n final int nY = y + offset.blockY();\n final int nZ = z + offset.blockZ();\n if (verifyCondition(nX, nY, nZ, neighborsCount.condition())) count++;\n }\n yield count;\n }\n case Rule.Expression.Compare compare -> {\n final int first = expression(x, y, z, compare.first());\n final int second = expression(x, y, z, compare.second());\n yield (int) Math.signum(first - second);\n }\n case Rule.Expression.Operation operation -> {\n final int first = expression(x, y, z, operation.first());\n final int second = expression(x, y, z, operation.second());\n yield switch (operation.type()) {\n case ADD -> first + second;\n case SUBTRACT -> first - second;\n case MULTIPLY -> first * second;\n case DIVIDE -> first / second;\n case MODULO -> first % second;\n };\n }\n };\n }\n\n @Override\n public void handlePlacement(int x, int y, int z, Map<Integer, Integer> properties) {\n LChunk lChunk = loadedChunks.get(ChunkUtils.getChunkIndex(\n ChunkUtils.getChunkCoordinate(x),\n ChunkUtils.getChunkCoordinate(z)));\n for (int i = 1; i < stateCount; i++) {\n final int value = properties.getOrDefault(i, 0);\n lChunk.setState(x, y, z, i, value);\n }\n register(x, y, z);\n }\n\n @Override\n public void handleChunkLoad(int chunkX, int chunkZ) {\n final Chunk chunk = instance.getChunk(chunkX, chunkZ);\n assert chunk != null;\n int sectionY = 0;\n final int localX = chunk.getChunkX() * 16;\n final int localZ = chunk.getChunkZ() * 16;\n for (Section section : chunk.getSections()) {\n final int localY = sectionY++ * 16 - minY;\n section.blockPalette().getAllPresent((x, y, z, value) -> {\n if (!trackedStates[value]) return;\n final int blockX = localX + x;\n final int blockY = localY + y;\n final int blockZ = localZ + z;\n register(blockX, blockY, blockZ);\n });\n }\n }\n\n private void register(int x, int y, int z) {\n for (Point offset : Neighbors.MOORE_3D_SELF) {\n final int nX = x + offset.blockX();\n final int nY = y + offset.blockY();\n final int nZ = z + offset.blockZ();\n\n final int chunkX = ChunkUtils.getChunkCoordinate(nX);\n final int chunkZ = ChunkUtils.getChunkCoordinate(nZ);\n final long chunkIndex = ChunkUtils.getChunkIndex(chunkX, chunkZ);\n LChunk lChunk = this.loadedChunks.computeIfAbsent(chunkIndex,\n k -> new LChunk());\n\n final int localX = ChunkUtils.toSectionRelativeCoordinate(nX);\n final int localZ = ChunkUtils.toSectionRelativeCoordinate(nZ);\n final int blockIndex = ChunkUtils.getBlockIndex(localX, nY, localZ);\n lChunk.trackedBlocks.add(blockIndex);\n }\n }\n\n @Override\n public void handleChunkUnload(int chunkX, int chunkZ) {\n final long chunkIndex = ChunkUtils.getChunkIndex(chunkX, chunkZ);\n this.loadedChunks.remove(chunkIndex);\n }\n\n @Override\n public Map<Integer, Integer> queryIndexes(int x, int y, int z) {\n final int chunkX = ChunkUtils.getChunkCoordinate(x);\n final int chunkZ = ChunkUtils.getChunkCoordinate(z);\n final LChunk lChunk = this.loadedChunks.get(ChunkUtils.getChunkIndex(chunkX, chunkZ));\n Map<Integer, Integer> indexes = new HashMap<>();\n indexes.put(0, (int) instance.getBlock(x, y, z).stateId());\n for (int i = 1; i < stateCount; i++) {\n final int value = lChunk.getState(x, y, z, i);\n indexes.put(i, value);\n }\n return Map.copyOf(indexes);\n }\n\n @Override\n public Instance instance() {\n return instance;\n }\n\n @Override\n public Program program() {\n return program;\n }\n}" }, { "identifier": "StartCommand", "path": "src/main/java/dev/goldenstack/minestom_ca/server/commands/StartCommand.java", "snippet": "public final class StartCommand extends Command {\n public StartCommand() {\n super(\"start\");\n setDefaultExecutor(this::execute);\n }\n\n private void execute(CommandSender sender, CommandContext context) {\n sender.sendMessage(Component.text(\"Starting CA ticker\"));\n Main.RUNNING.set(true);\n }\n}" }, { "identifier": "StateCommand", "path": "src/main/java/dev/goldenstack/minestom_ca/server/commands/StateCommand.java", "snippet": "public final class StateCommand extends Command {\n public StateCommand() {\n super(\"state\");\n setCondition(Conditions::playerOnly);\n var loop = Loop(\"states\", Group(\"state\",\n Word(\"state_name\").setSuggestionCallback(itemStates()),\n Integer(\"state_value\")));\n\n addSyntax((sender, context) -> {\n Player player = ((Player) sender);\n PlayerInventory inventory = player.getInventory();\n ItemStack itemStack = inventory.getItemInMainHand();\n for (CommandContext states : context.get(loop)) {\n final String stateName = states.get(\"state_name\");\n final int stateValue = states.get(\"state_value\");\n itemStack = itemStack.withTag(Tag.Integer(stateName), stateValue);\n }\n inventory.setItemInMainHand(itemStack);\n player.sendMessage(\"States applied to item! \" + itemStack.toItemNBT());\n }, loop);\n }\n\n private SuggestionCallback itemStates() {\n // FIXME: seem to be a problem inside minestom\n return (sender, context, suggestion) -> {\n if (!(sender instanceof Player player)) return;\n final AutomataWorld world = AutomataWorld.get(player.getInstance());\n final Program program = world.program();\n final Map<String, Integer> variables = program.variables();\n for (String name : variables.keySet()) {\n suggestion.addEntry(new SuggestionEntry(name, Component.empty()));\n }\n };\n }\n}" }, { "identifier": "StopCommand", "path": "src/main/java/dev/goldenstack/minestom_ca/server/commands/StopCommand.java", "snippet": "public final class StopCommand extends Command {\n public StopCommand() {\n super(\"stop\");\n setDefaultExecutor(this::execute);\n }\n\n private void execute(CommandSender sender, CommandContext context) {\n sender.sendMessage(Component.text(\"Stopping CA ticker\"));\n Main.RUNNING.set(false);\n }\n}" } ]
import dev.goldenstack.minestom_ca.AutomataWorld; import dev.goldenstack.minestom_ca.Program; import dev.goldenstack.minestom_ca.backends.lazy.LazyWorld; import dev.goldenstack.minestom_ca.server.commands.StartCommand; import dev.goldenstack.minestom_ca.server.commands.StateCommand; import dev.goldenstack.minestom_ca.server.commands.StopCommand; import net.kyori.adventure.text.Component; import net.minestom.server.MinecraftServer; import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.instance.InstanceChunkLoadEvent; import net.minestom.server.event.instance.InstanceChunkUnloadEvent; import net.minestom.server.event.instance.InstanceTickEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; import net.minestom.server.event.player.PlayerBlockInteractEvent; import net.minestom.server.event.player.PlayerBlockPlaceEvent; import net.minestom.server.event.player.PlayerLoginEvent; import net.minestom.server.instance.InstanceContainer; import net.minestom.server.instance.LightingChunk; import net.minestom.server.instance.block.Block; import net.minestom.server.inventory.PlayerInventory; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import org.jglrxavpok.hephaistos.nbt.NBT; import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.jglrxavpok.hephaistos.nbt.NBTInt; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean;
4,698
package dev.goldenstack.minestom_ca.server; public final class Main { public static final AtomicBoolean RUNNING = new AtomicBoolean(true); private static final Program FILE_PROGRAM = Program.fromFile(Path.of("rules/piston")); public static void main(String[] args) { MinecraftServer minecraftServer = MinecraftServer.init(); // Register commands MinecraftServer.getCommandManager().register(new StartCommand());
package dev.goldenstack.minestom_ca.server; public final class Main { public static final AtomicBoolean RUNNING = new AtomicBoolean(true); private static final Program FILE_PROGRAM = Program.fromFile(Path.of("rules/piston")); public static void main(String[] args) { MinecraftServer minecraftServer = MinecraftServer.init(); // Register commands MinecraftServer.getCommandManager().register(new StartCommand());
MinecraftServer.getCommandManager().register(new StopCommand());
4
2023-11-18 21:49:11+00:00
8k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/world/EM_WorldData.java
[ { "identifier": "EnumLogVerbosity", "path": "src/main/java/enviromine/core/EM_ConfigHandler.java", "snippet": "public enum EnumLogVerbosity\n{\n\tNONE(0),\n\tLOW(1),\n\tNORMAL(2),\n\tALL(3);\n\n\tprivate final int level;\n\n\tprivate EnumLogVerbosity(int level)\n\t{\n\t\tthis.level = level;\n\t}\n\n\tpublic int getLevel()\n\t{\n\t\treturn this.level;\n\t}\n}" }, { "identifier": "EM_Settings", "path": "src/main/java/enviromine/core/EM_Settings.java", "snippet": "public class EM_Settings\n{\n\tpublic static final UUID FROST1_UUID = UUID.fromString(\"B0C5F86A-78F3-417C-8B5A-527B90A1E919\");\n\tpublic static final UUID FROST2_UUID = UUID.fromString(\"5C4111A7-A66C-40FB-9FAD-1C6ADAEE7E27\");\n\tpublic static final UUID FROST3_UUID = UUID.fromString(\"721E793E-2203-4F6F-883F-6F44D7DDCCE1\");\n\tpublic static final UUID HEAT1_UUID = UUID.fromString(\"CA6E2CFA-4C53-4CD2-AAD3-3D6177A4F126\");\n\tpublic static final UUID DEHY1_UUID = UUID.fromString(\"38909A39-E1A1-4E93-9016-B2CCBE83D13D\");\n\n\tpublic static File worldDir = null;\n\n\t//Mod Data\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String MOD_ID = \"enviromine\";\n\tpublic static final String MOD_NAME = \"EnviroMine\";\n\tpublic static final String MOD_NAME_COLORIZED = EnumChatFormatting.AQUA + MOD_NAME + EnumChatFormatting.RESET;\n\tpublic static final String Channel = \"EM_CH\";\n\tpublic static final String Proxy = \"enviromine.core.proxies\";\n\tpublic static final String URL = \"https://modrinth.com/mod/enviromine-for-galaxy-odyssey\";\n\tpublic static final String VERSION_CHECKER_URL = \"https://gitgud.io/AstroTibs/enviromine-for-galaxy-odyssey/-/raw/1.7.10/CURRENT_VERSION\";\n\tpublic static final String GUI_FACTORY = MOD_ID+\".client.gui.menu.config.EnviroMineGuiFactory\";\n\n\tpublic static boolean versionChecker;\n\n\tpublic static int loggerVerbosity;\n\n public static boolean DeathFromHeartAttack;\n\n public static int HeartAttackTimeToDie;\n public static int HbmGasMaskBreakMultiplier;\n\n public static int EnviromineGasMaskBreakMultiplier;\n public static int HbmGasMaskBreakChanceNumber;\n\n public static boolean hardcoregases = false;\n\n\tpublic static boolean enablePhysics = false;\n\tpublic static boolean enableLandslide = true;\n\tpublic static boolean waterCollapse = true; // Added out of necessity/annoyance -- AstroTibs\n\n\tpublic static float blockTempDropoffPower = 0.75F;\n\tpublic static int scanRadius = 6;\n\tpublic static float auraRadius = 0.5F;\n\n\t@ShouldOverride\n\tpublic static boolean enableAirQ = true;\n\t@ShouldOverride\n\tpublic static boolean enableHydrate = true;\n\t@ShouldOverride\n\tpublic static boolean enableSanity = true;\n\t@ShouldOverride\n\tpublic static boolean enableBodyTemp = true;\n\n\tpublic static boolean trackNonPlayer = false;\n\n\tpublic static boolean spreadIce = false;\n\n\tpublic static boolean useFarenheit = false;\n\tpublic static String heatBarPos;\n\tpublic static String waterBarPos;\n\tpublic static String sanityBarPos;\n\tpublic static String oxygenBarPos;\n\n\tpublic static int dirtBottleID = 5001;\n\tpublic static int saltBottleID = 5002;\n\tpublic static int coldBottleID = 5003;\n\tpublic static int camelPackID = 5004;\n\n\tpublic static final String GAS_MASK_FILL_TAG_KEY = \"gasMaskFill\";\n\tpublic static final String GAS_MASK_MAX_TAG_KEY = \"gasMaskMax\";\n\tpublic static final String CAMEL_PACK_FILL_TAG_KEY = \"camelPackFill\";\n\tpublic static final String CAMEL_PACK_MAX_TAG_KEY = \"camelPackMax\";\n\tpublic static final String IS_CAMEL_PACK_TAG_KEY = \"isCamelPack\";\n\tpublic static int gasMaskMax = 1000;\n\tpublic static int filterRestore = 500;\n\tpublic static int camelPackMax = 100;\n\tpublic static float gasMaskUpdateRestoreFraction = 1F;\n\n\t/*\n\tpublic static int gasMaskID = 5005;\n\tpublic static int airFilterID = 5006;\n\tpublic static int hardHatID = 5007;\n\tpublic static int rottenFoodID = 5008;\n\n\tpublic static int blockElevatorTopID = 501;\n\tpublic static int blockElevatorBottomID = 502;\n\tpublic static int gasBlockID = 503;\n\tpublic static int fireGasBlockID = 504;\n\t*/\n\n\tpublic static int hypothermiaPotionID = 27;\n\tpublic static int heatstrokePotionID = 28;\n\tpublic static int frostBitePotionID = 29;\n\tpublic static int dehydratePotionID = 30;\n\tpublic static int insanityPotionID = 31;\n\n\tpublic static boolean enableHypothermiaGlobal = true;\n\tpublic static boolean enableHeatstrokeGlobal = true;\n\tpublic static boolean enableFrostbiteGlobal = true;\n\tpublic static boolean frostbitePermanent = true;\n\n\t//Gases\n\tpublic static boolean renderGases = false;\n\tpublic static int gasTickRate = 32; //GasFires are 4x faster than this\n\tpublic static int gasPassLimit = -1;\n\tpublic static boolean gasWaterLike = true;\n\tpublic static boolean slowGases = true; // Normal gases use random ticks to move\n\tpublic static boolean noGases = false;\n\n\t//World Gen\n\tpublic static boolean shaftGen = true;\n\tpublic static boolean gasGen = true;\n\tpublic static boolean oldMineGen = true;\n\n\t//Properties\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.ArmorPropsEncoder\")\n\t@ShouldOverride({String.class, ArmorProperties.class})\n\tpublic static HashMap<String,ArmorProperties> armorProperties = new HashMap<String,ArmorProperties>();\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.BlocksPropsEncoder\")\n\t@ShouldOverride({String.class, BlockProperties.class})\n\tpublic static HashMap<String,BlockProperties> blockProperties = new HashMap<String,BlockProperties>();\n\t@ShouldOverride({Integer.class, EntityProperties.class})\n\tpublic static HashMap<Integer,EntityProperties> livingProperties = new HashMap<Integer,EntityProperties>();\n\t@ShouldOverride({String.class, ItemProperties.class})\n\tpublic static HashMap<String,ItemProperties> itemProperties = new HashMap<String,ItemProperties>();\n\t@ShouldOverride({Integer.class, BiomeProperties.class})\n\tpublic static HashMap<Integer,BiomeProperties> biomeProperties = new HashMap<Integer,BiomeProperties>();\n\t@ShouldOverride({Integer.class, DimensionProperties.class})\n\tpublic static HashMap<Integer,DimensionProperties> dimensionProperties = new HashMap<Integer,DimensionProperties>();\n\n\tpublic static HashMap<String,StabilityType> stabilityTypes = new HashMap<String,StabilityType>();\n\n\t@ShouldOverride({String.class, RotProperties.class})\n\tpublic static HashMap<String,RotProperties> rotProperties = new HashMap<String,RotProperties>();\n\n\tpublic static boolean streamsDrink = true;\n\tpublic static boolean witcheryVampireImmunities = true;\n\tpublic static boolean witcheryWerewolfImmunities = true;\n\tpublic static boolean matterOverdriveAndroidImmunities = true;\n\n\tpublic static int updateCap = 128;\n\tpublic static boolean stoneCracks = true;\n\tpublic static String defaultStability = \"loose\";\n\n\tpublic static double sanityMult = 1.0D;\n\tpublic static double hydrationMult = 1.0D;\n\tpublic static double tempMult = 1.0D;\n\tpublic static double airMult = 1.0D;\n\n\t//public static boolean updateCheck = true;\n\t//public static boolean useDefaultConfig = true;\n\tpublic static boolean genConfigs = false;\n\tpublic static boolean genDefaults = false;\n\n\tpublic static int physInterval = 6;\n\tpublic static int worldDelay = 1000;\n\tpublic static int chunkDelay = 1000;\n\tpublic static int entityFailsafe = 1;\n\tpublic static boolean villageAssist = true;\n\n\tpublic static boolean minimalHud;\n\tpublic static boolean limitCauldron;\n\tpublic static boolean allowTinting = true;\n\tpublic static boolean torchesBurn = true;\n\tpublic static boolean torchesGoOut = true;\n\tpublic static boolean genFlammableCoal = true; // In case you don't want burny-coal\n\tpublic static boolean randomizeInsanityPitch = true;\n\tpublic static boolean catchFireAtHighTemps = true;\n\n\tpublic static int caveDimID = -3;\n\tpublic static int caveBiomeID = 23;\n\tpublic static boolean disableCaves = false;\n\tpublic static int limitElevatorY = 10;\n\tpublic static boolean caveOreEvent = true;\n\tpublic static boolean caveLava = false;\n\tpublic static int caveRavineRarity = 30;\n\tpublic static int caveTunnelRarity = 7;\n\tpublic static int caveDungeons = 8;\n\tpublic static int caveLiquidY = 32;\n\tpublic static boolean caveFlood = true;\n\tpublic static boolean caveRespawn = false;\n\tpublic static boolean enforceWeights = false;\n\tpublic static ArrayList<CaveGenProperties> caveGenProperties = new ArrayList<CaveGenProperties>();\n\tpublic static HashMap<Integer, CaveSpawnProperties> caveSpawnProperties = new HashMap<Integer, CaveSpawnProperties>();\n\n\tpublic static boolean foodSpoiling = true;\n\tpublic static int foodRotTime = 7;\n\n\t/** Whether or not this overridden with server settings */\n\tpublic static boolean isOverridden = false;\n\tpublic static boolean enableConfigOverride = false;\n\tpublic static boolean profileOverride = false;\n\tpublic static String profileSelected = \"default\";\n\n\tpublic static boolean enableQuakes = true;\n\tpublic static boolean quakePhysics = true;\n\tpublic static int quakeRarity = 100;\n\n\tpublic static boolean finiteWater = false;\n\tpublic static float thingChance = 0.000001F;\n\tpublic static boolean noNausea = false;\n\tpublic static boolean keepStatus = false;\n\tpublic static boolean renderGear = true;\n\tpublic static String[] cauldronHeatingBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\tpublic static String[] notWaterBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\n\tpublic static boolean voxelMenuExists = false;\n\n\t/**\n\t * Tells the server that this field should be sent to the client to overwrite<br>\n\t * Usage:<br>\n\t * <tt>@ShouldOverride</tt> - for ints/booleans/floats/Strings<br>\n\t * <tt>@ShouldOverride(Class[] value)</tt> - for ArrayList or HashMap types\n\t * */\n\t@Target(ElementType.FIELD)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic @interface ShouldOverride\n\t{\n\t\tClass<?>[] value() default {};\n\t}\n}" }, { "identifier": "EnviroMine", "path": "src/main/java/enviromine/core/EnviroMine.java", "snippet": "@Mod(modid = EM_Settings.MOD_ID, name = EM_Settings.MOD_NAME, version = EM_Settings.VERSION, guiFactory = EM_Settings.GUI_FACTORY)\npublic class EnviroMine\n{\n\tpublic static Logger logger;\n\tpublic static BiomeGenCaves caves;\n\tpublic static EnviroTab enviroTab;\n\n\t@Instance(EM_Settings.MOD_ID)\n\tpublic static EnviroMine instance;\n\n\t@SidedProxy(clientSide = EM_Settings.Proxy + \".EM_ClientProxy\", serverSide = EM_Settings.Proxy + \".EM_CommonProxy\")\n\tpublic static EM_CommonProxy proxy;\n\n\tpublic SimpleNetworkWrapper network;\n\n\t//public static EM_WorldData theWorldEM;\n\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event)\n\t{\n\t\t// The following overrides the mcmod.info file!\n\t\t// Adapted from Jabelar's Magic Beans:\n\t\t// https://github.com/jabelar/MagicBeans-1.7.10/blob/e48456397f9c6c27efce18e6b9ad34407e6bc7c7/src/main/java/com/blogspot/jabelarminecraft/magicbeans/MagicBeans.java\n event.getModMetadata().autogenerated = false ; // stops it from complaining about missing mcmod.info\n\n event.getModMetadata().name = \t\t\t// name\n \t\tEnumChatFormatting.AQUA +\n \t\tEM_Settings.MOD_NAME;\n\n event.getModMetadata().version = \t\t// version\n \t\tEnumChatFormatting.DARK_AQUA +\n \t\tEM_Settings.VERSION;\n\n event.getModMetadata().credits = \t\t// credits\n \t\tEnumChatFormatting.AQUA +\n \t\t\"Big thanks to the IronArmy and EpicNation for all the hard work debugging this mod.\";\n\n event.getModMetadata().authorList.clear();\n event.getModMetadata().authorList.add( // authorList - added as a list\n \t\tEnumChatFormatting.BLUE +\n \t\t\"Funwayguy, TimbuckTato, GenDeathrow, thislooksfun, AstroTibs\"\n \t\t);\n\n event.getModMetadata().url = EnumChatFormatting.GRAY +\n \t\tEM_Settings.URL;\n\n event.getModMetadata().description = \t// description\n\t \t\tEnumChatFormatting.GREEN +\n\t \t\t\"Adds more realism to Minecraft with environmental effects, physics, gases and a cave dimension.\";\n\n event.getModMetadata().logoFile = \"title.png\";\n\n\n\t\tlogger = event.getModLog();\n\n\t\tenviroTab = new EnviroTab(\"enviromine.enviroTab\");\n\n\t\tLegacyHandler.preInit();\n\t\tLegacyHandler.init();\n\n\t\tproxy.preInit(event);\n\n\t\tObjectHandler.initItems();\n\t\tObjectHandler.registerItems();\n\t\tObjectHandler.initBlocks();\n\t\tObjectHandler.registerBlocks();\n\n\t\t// Load Configuration files And Custom files\n\t\tEM_ConfigHandler.initConfig();\n\n\n // Version check monitors\n\t\t// Have to be initialized after the configs so that the value is read\n/* \tif ((EM_Settings.VERSION).contains(\"DEV\"))\n \t{\n \t\tFMLCommonHandler.instance().bus().register(DevVersionWarning.instance);\n \t}\n \telse if (EM_Settings.versionChecker)\n \t{\n \t\tFMLCommonHandler.instance().bus().register(VersionChecker.instance);\n \t}\n*/\n\n\t\tObjectHandler.registerGases();\n\t\tObjectHandler.registerEntities();\n\n\t\tif(EM_Settings.shaftGen == true)\n\t\t{\n\t\t\tVillagerRegistry.instance().registerVillageCreationHandler(new EnviroShaftCreationHandler());\n\t\t\tMapGenStructureIO.func_143031_a(EM_VillageMineshaft.class, \"ViMS\");\n\t\t}\n\n\t\tthis.network = NetworkRegistry.INSTANCE.newSimpleChannel(EM_Settings.Channel);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerServer.class, PacketEnviroMine.class, 0, Side.SERVER);\n\t\tthis.network.registerMessage(PacketEnviroMine.HandlerClient.class, PacketEnviroMine.class, 1, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketAutoOverride.Handler.class, PacketAutoOverride.class, 2, Side.CLIENT);\n\t\tthis.network.registerMessage(PacketServerOverride.Handler.class, PacketServerOverride.class, 3, Side.CLIENT);\n\n\n\t\tGameRegistry.registerWorldGenerator(new WorldFeatureGenerator(), 20);\n\t}\n\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent event)\n\t{\n\t\tproxy.init(event);\n\n\t\tObjectHandler.registerRecipes();\n\n\t\tEnviroUtils.extendPotionList();\n\n\t\tEnviroPotion.RegisterPotions();\n\n\t\tEnviroAchievements.InitAchievements();\n\n\t\tcaves = (BiomeGenCaves)(new BiomeGenCaves(EM_Settings.caveBiomeID).setColor(0).setBiomeName(\"Caves\").setDisableRain().setTemperatureRainfall(1.0F, 0.0F));\n\t\t//GameRegistry.addBiome(caves);\n\t\tBiomeDictionary.registerBiomeType(caves, Type.WASTELAND);\n\n\n\t\tDimensionManager.registerProviderType(EM_Settings.caveDimID, WorldProviderCaves.class, false);\n\t\tDimensionManager.registerDimension(EM_Settings.caveDimID, EM_Settings.caveDimID);\n\n\n\t\tproxy.registerTickHandlers();\n\t\tproxy.registerEventHandlers();\n\t}\n\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event)\n\t{\n\t\tproxy.postInit(event);\n\n\t\t//TODO Moved inside of Config Handler.general config to add in custom list\n\t\t//ObjectHandler.LoadIgnitionSources();\n\n\t\tEM_ConfigHandler.initConfig(); // Second pass for object initialized after pre-init\n\t}\n\n\t@EventHandler\n\tpublic void serverStart(FMLServerStartingEvent event)\n\t{\n\t\tMinecraftServer server = MinecraftServer.getServer();\n\t\tICommandManager command = server.getCommandManager();\n\t\tServerCommandManager manager = (ServerCommandManager) command;\n\n\t\tmanager.registerCommand(new CommandPhysics());\n\t\tmanager.registerCommand(new EnviroCommand());\n\t\tmanager.registerCommand(new QuakeCommand());\n\t}\n}" } ]
import org.apache.logging.log4j.Level; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData;
4,889
package enviromine.world; public class EM_WorldData extends WorldSavedData { private static final String IDENTIFIER = "EM_WorldData"; private String profile = "default"; public static EM_WorldData theWorldEM; public EM_WorldData() { super(IDENTIFIER); } public EM_WorldData(String identifier) { super(identifier); } @Override public void readFromNBT(NBTTagCompound nbt) { this.profile = nbt.getString("Profile"); } public boolean setProfile(String newProfile) { this.profile = newProfile; this.markDirty(); return true; } public String getProfile() { return profile; } public EM_WorldData getEMWorldData() { return theWorldEM; } @Override public void writeToNBT(NBTTagCompound nbt) { nbt.setString("Profile", profile); } public static EM_WorldData get(World world) { EM_WorldData data = (EM_WorldData)world.loadItemData(EM_WorldData.class, IDENTIFIER); if (data == null) { data = new EM_WorldData(); world.setItemData(IDENTIFIER, data);
package enviromine.world; public class EM_WorldData extends WorldSavedData { private static final String IDENTIFIER = "EM_WorldData"; private String profile = "default"; public static EM_WorldData theWorldEM; public EM_WorldData() { super(IDENTIFIER); } public EM_WorldData(String identifier) { super(identifier); } @Override public void readFromNBT(NBTTagCompound nbt) { this.profile = nbt.getString("Profile"); } public boolean setProfile(String newProfile) { this.profile = newProfile; this.markDirty(); return true; } public String getProfile() { return profile; } public EM_WorldData getEMWorldData() { return theWorldEM; } @Override public void writeToNBT(NBTTagCompound nbt) { nbt.setString("Profile", profile); } public static EM_WorldData get(World world) { EM_WorldData data = (EM_WorldData)world.loadItemData(EM_WorldData.class, IDENTIFIER); if (data == null) { data = new EM_WorldData(); world.setItemData(IDENTIFIER, data);
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, "Enviromine World Data Doesn't Exist. Creating now");
1
2023-11-16 18:15:29+00:00
8k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/maven/MavenProjectAnalyzer.java
[ { "identifier": "MavenProject", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/MavenProject.java", "snippet": "public class MavenProject {\n\n\tprivate final Path projectRoot;\n\n\tprivate final Resource pomFile;\n\n\t// FIXME: 945 temporary method, model should nopt come from Maven\n\tprivate final Model pomModel;\n\n\tprivate List<MavenProject> collectedProjects = new ArrayList<>();\n\n\tprivate Xml.Document sourceFile;\n\n\tprivate final MavenArtifactDownloader rewriteMavenArtifactDownloader;\n\n\tprivate final List<Resource> resources;\n\n\tprivate ProjectId projectId;\n\n\tpublic MavenProject(Path projectRoot, Resource pomFile, Model pomModel,\n\t\t\tMavenArtifactDownloader rewriteMavenArtifactDownloader, List<Resource> resources) {\n\t\tthis.projectRoot = projectRoot;\n\t\tthis.pomFile = pomFile;\n\t\tthis.pomModel = pomModel;\n\t\tthis.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader;\n\t\tthis.resources = resources;\n\t\tprojectId = new ProjectId(getGroupId(), getArtifactId());\n\t}\n\n\tpublic File getFile() {\n\t\treturn ResourceUtil.getPath(pomFile).toFile();\n\t}\n\n\tpublic Path getBasedir() {\n\t\t// TODO: 945 Check if this is correct\n\t\treturn pomFile == null ? null : ResourceUtil.getPath(pomFile).getParent();\n\t}\n\n\tpublic void setCollectedProjects(List<MavenProject> collected) {\n\t\tthis.collectedProjects = collected;\n\t}\n\n\tpublic List<MavenProject> getCollectedProjects() {\n\t\treturn collectedProjects;\n\t}\n\n\tpublic Resource getResource() {\n\t\treturn pomFile;\n\t}\n\n\t/**\n\t * @return absolute Path of Module\n\t */\n\tpublic Path getModulePath() {\n\t\treturn projectRoot.resolve(getModuleDir());\n\t}\n\n\t/**\n\t * @return Path for Module relative to {@code baseDir}.\n\t */\n\tpublic Path getModuleDir() {\n\t\tif (getBasedir() == null) {\n\t\t\treturn null;\n\t\t}\n\t\telse if (\"pom.xml\"\n\t\t\t.equals(LinuxWindowsPathUnifier.relativize(projectRoot, ResourceUtil.getPath(pomFile)).toString())) {\n\t\t\treturn Path.of(\"\");\n\t\t}\n\t\telse {\n\t\t\treturn LinuxWindowsPathUnifier.relativize(projectRoot, ResourceUtil.getPath(pomFile)).getParent();\n\t\t}\n\t}\n\n\tpublic String getGroupIdAndArtifactId() {\n\t\treturn this.pomModel.getGroupId() + \":\" + pomModel.getArtifactId();\n\t}\n\n\tpublic Path getPomFilePath() {\n\t\treturn ResourceUtil.getPath(pomFile);\n\t}\n\n\tpublic Plugin getPlugin(String s) {\n\t\treturn pomModel.getBuild() == null ? null : pomModel.getBuild().getPluginsAsMap().get(s);\n\t}\n\n\tpublic Properties getProperties() {\n\t\treturn pomModel.getProperties();\n\t}\n\n\tpublic MavenRuntimeInformation getMavenRuntimeInformation() {\n\t\t// FIXME: 945 implement this\n\t\treturn new MavenRuntimeInformation();\n\t}\n\n\tpublic String getName() {\n\t\treturn pomModel.getName();\n\t}\n\n\tpublic String getGroupId() {\n\t\treturn pomModel.getGroupId() == null ? pomModel.getParent().getGroupId() : pomModel.getGroupId();\n\t}\n\n\tpublic String getArtifactId() {\n\t\treturn pomModel.getArtifactId();\n\t}\n\n\t/**\n\t * FIXME: when the version of parent pom is null (inherited by it's parent) the\n\t * version will be null.\n\t */\n\tpublic String getVersion() {\n\t\treturn pomModel.getVersion() == null ? pomModel.getParent().getVersion() : pomModel.getVersion();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString groupId = pomModel.getGroupId() == null ? pomModel.getParent().getGroupId() : pomModel.getGroupId();\n\t\treturn groupId + \":\" + pomModel.getArtifactId();\n\t}\n\n\tpublic String getBuildDirectory() {\n\t\tString s = pomModel.getBuild() != null ? pomModel.getBuild().getDirectory() : null;\n\t\treturn s == null\n\t\t\t\t? ResourceUtil.getPath(pomFile).getParent().resolve(\"target\").toAbsolutePath().normalize().toString()\n\t\t\t\t: s;\n\t}\n\n\tpublic String getSourceDirectory() {\n\t\tString s = pomModel.getBuild() != null ? pomModel.getBuild().getSourceDirectory() : null;\n\t\treturn s == null ? ResourceUtil.getPath(pomFile)\n\t\t\t.getParent()\n\t\t\t.resolve(\"src/main/java\")\n\t\t\t.toAbsolutePath()\n\t\t\t.normalize()\n\t\t\t.toString() : s;\n\t}\n\n\tpublic List<Path> getCompileClasspathElements() {\n\t\tScope scope = Scope.Compile;\n\t\treturn getClasspathElements(scope);\n\t}\n\n\tpublic List<Path> getTestClasspathElements() {\n\t\treturn getClasspathElements(Scope.Test);\n\t}\n\n\t@NotNull\n\tprivate List<Path> getClasspathElements(Scope scope) {\n\t\tMavenResolutionResult pom = getSourceFile().getMarkers().findFirst(MavenResolutionResult.class).get();\n\t\tList<ResolvedDependency> resolvedDependencies = pom.getDependencies().get(scope);\n\t\tif (resolvedDependencies != null) {\n\t\t\treturn resolvedDependencies\n\t\t\t\t// FIXME: 945 - deal with dependencies to projects in reactor\n\t\t\t\t//\n\t\t\t\t.stream()\n\t\t\t\t.filter(rd -> rd.getRepository() != null)\n\t\t\t\t.map(rd -> rewriteMavenArtifactDownloader.downloadArtifact(rd))\n\t\t\t\t.filter(Objects::nonNull)\n\t\t\t\t.distinct()\n\t\t\t\t.toList();\n\t\t}\n\t\telse {\n\t\t\treturn new ArrayList<>();\n\t\t}\n\t}\n\n\tpublic String getTestSourceDirectory() {\n\t\tString s = pomModel.getBuild() != null ? pomModel.getBuild().getSourceDirectory() : null;\n\t\treturn s == null ? ResourceUtil.getPath(pomFile)\n\t\t\t.getParent()\n\t\t\t.resolve(\"src/test/java\")\n\t\t\t.toAbsolutePath()\n\t\t\t.normalize()\n\t\t\t.toString() : s;\n\t}\n\n\tpublic void setSourceFile(Xml.Document sourceFile) {\n\t\tthis.sourceFile = sourceFile;\n\t}\n\n\tprivate static List<Resource> listJavaSources(List<Resource> resources, Path sourceDirectory) {\n\t\treturn resources.stream().filter(whenIn(sourceDirectory)).filter(whenFileNameEndsWithJava()).toList();\n\t}\n\n\t@NotNull\n\tprivate static Predicate<Resource> whenFileNameEndsWithJava() {\n\t\treturn p -> ResourceUtil.getPath(p).getFileName().toString().endsWith(\".java\");\n\t}\n\n\t@NotNull\n\tprivate static Predicate<Resource> whenIn(Path sourceDirectory) {\n\t\treturn r -> {\n\t\t\tString resourcePath = LinuxWindowsPathUnifier.unifiedPathString(r);\n\t\t\tString sourceDirectoryPath = LinuxWindowsPathUnifier.unifiedPathString(sourceDirectory);\n\t\t\treturn resourcePath.startsWith(sourceDirectoryPath);\n\t\t};\n\t}\n\n\tpublic List<Resource> getJavaSourcesInTarget() {\n\t\treturn listJavaSources(getResources(), getBasedir().resolve(getBuildDirectory()));\n\t}\n\n\tprivate List<Resource> getResources() {\n\t\treturn this.resources;\n\t}\n\n\tpublic List<Resource> getMainJavaSources() {\n\t\tPath sourceDir = getProjectRoot().resolve(getModuleDir()).resolve(\"src/main/java\");\n\t\treturn listJavaSources(resources, sourceDir);\n\t}\n\n\tpublic List<Resource> getTestJavaSources() {\n\t\treturn listJavaSources(resources, getProjectRoot().resolve(getModuleDir()).resolve(\"src/test/java\"));\n\t}\n\n\tpublic ProjectId getProjectId() {\n\t\treturn projectId;\n\t}\n\n\tpublic Object getProjectEncoding() {\n\t\treturn getPomModel().getProperties().get(\"project.build.sourceEncoding\");\n\t}\n\n\tpublic Path getProjectRoot() {\n\t\treturn projectRoot;\n\t}\n\n\tpublic Resource getPomFile() {\n\t\treturn pomFile;\n\t}\n\n\tpublic Model getPomModel() {\n\t\treturn pomModel;\n\t}\n\n\tpublic Xml.Document getSourceFile() {\n\t\treturn sourceFile;\n\t}\n\n\tpublic MavenArtifactDownloader getRewriteMavenArtifactDownloader() {\n\t\treturn rewriteMavenArtifactDownloader;\n\t}\n\n\tpublic void setProjectId(ProjectId projectId) {\n\t\tthis.projectId = projectId;\n\t}\n\n}" }, { "identifier": "ParserContext", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/ParserContext.java", "snippet": "public class ParserContext {\n\n\tprivate final Path baseDir;\n\n\tprivate final List<Resource> resources;\n\n\tprivate final List<MavenProject> sortedProjects;\n\n\tpublic ParserContext(Path baseDir, List<Resource> resources, List<MavenProject> sortedProjects) {\n\t\tthis.baseDir = baseDir;\n\t\tthis.resources = resources;\n\t\tthis.sortedProjects = sortedProjects;\n\t}\n\n\tprivate Map<Path, Xml.Document> pathDocumentMap;\n\n\tpublic List<Resource> getResources() {\n\t\treturn resources;\n\t}\n\n\tpublic List<MavenProject> getSortedProjects() {\n\t\treturn sortedProjects;\n\t}\n\n\tpublic List<String> getActiveProfiles() {\n\t\t// FIXME: Add support for Maven profiles\n\t\treturn List.of(\"default\");\n\t}\n\n\tpublic Resource getMatchingBuildFileResource(MavenProject pom) {\n\t\treturn resources.stream()\n\t\t\t.filter(r -> ResourceUtil.getPath(r).toString().equals(pom.getPomFilePath().toString()))\n\t\t\t.findFirst()\n\t\t\t.orElseThrow(() -> new IllegalStateException(\n\t\t\t\t\t\"Could not find a resource in the list of resources that matches the path of MavenProject '%s'\"\n\t\t\t\t\t\t.formatted(pom.getPomFile().toString())));\n\t}\n\n\tpublic List<Resource> getBuildFileResources() {\n\t\treturn sortedProjects.stream().map(p -> p.getPomFile()).toList();\n\t}\n\n\tpublic Xml.Document getXmlDocument(Path path) {\n\t\treturn pathDocumentMap.get(path);\n\t}\n\n\tpublic void setParsedBuildFiles(List<Xml.Document> xmlDocuments) {\n\t\tthis.pathDocumentMap = xmlDocuments.stream()\n\t\t\t.peek(doc -> addSourceFileToModel(baseDir, getSortedProjects(), doc))\n\t\t\t.collect(Collectors.toMap(doc -> baseDir.resolve(doc.getSourcePath()), doc -> doc));\n\t}\n\n\tpublic List<Xml.Document> getSortedBuildFileDocuments() {\n\t\treturn getSortedProjects().stream().map(p -> pathDocumentMap.get(p.getFile().toPath())).toList();\n\t}\n\n\tprivate void addSourceFileToModel(Path baseDir, List<MavenProject> sortedProjectsList, Xml.Document s) {\n\t\tsortedProjectsList.stream()\n\t\t\t.filter(p -> ResourceUtil.getPath(p.getPomFile())\n\t\t\t\t.toString()\n\t\t\t\t.equals(baseDir.resolve(s.getSourcePath()).toString()))\n\t\t\t.forEach(p -> p.setSourceFile(s));\n\t}\n\n}" }, { "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 java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.maven.model.*; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jetbrains.annotations.NotNull; import org.openrewrite.maven.utilities.MavenArtifactDownloader; import org.springframework.core.io.Resource; import org.springframework.rewrite.parsers.MavenProject; import org.springframework.rewrite.parsers.ParserContext; import org.springframework.rewrite.utils.LinuxWindowsPathUnifier; import org.springframework.rewrite.utils.ResourceUtil; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.*;
4,023
/* * 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; /** * Implements the ordering of Maven (reactor) build projects. See <a href= * "https://maven.apache.org/guides/mini/guide-multiple-modules.html#reactor-sorting">Reactor * Sorting</a> * * @author Fabian Krüger */ public class MavenProjectAnalyzer { private static final String POM_XML = "pom.xml"; private static final MavenXpp3Reader XPP_3_READER = new MavenXpp3Reader(); private final MavenArtifactDownloader rewriteMavenArtifactDownloader; public MavenProjectAnalyzer(MavenArtifactDownloader rewriteMavenArtifactDownloader) { this.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader; }
/* * 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; /** * Implements the ordering of Maven (reactor) build projects. See <a href= * "https://maven.apache.org/guides/mini/guide-multiple-modules.html#reactor-sorting">Reactor * Sorting</a> * * @author Fabian Krüger */ public class MavenProjectAnalyzer { private static final String POM_XML = "pom.xml"; private static final MavenXpp3Reader XPP_3_READER = new MavenXpp3Reader(); private final MavenArtifactDownloader rewriteMavenArtifactDownloader; public MavenProjectAnalyzer(MavenArtifactDownloader rewriteMavenArtifactDownloader) { this.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader; }
public List<MavenProject> getSortedProjects(Path baseDir, List<Resource> resources) {
0
2023-11-14 23:02:37+00:00
8k
giftorg/gift
gift-analyze/src/main/java/org/giftorg/analyze/AnalyzeApplication.java
[ { "identifier": "AnalyzeTask", "path": "gift-analyze/src/main/java/org/giftorg/analyze/entity/AnalyzeTask.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class AnalyzeTask extends RetryTask {\n private Repository project;\n\n private Integer retryCount;\n\n public static final Integer MAX_RETRY_COUNT = 3;\n\n public static final String TOPIC = \"gift-analyze\";\n\n public AnalyzeTask(Repository project) {\n this.project = project;\n this.retryCount = RetryTask.DEFAULT_RETRY_COUNT;\n }\n\n public boolean isRetry() {\n return retryCount++ < MAX_RETRY_COUNT;\n }\n\n @Override\n public String topic() {\n return TOPIC;\n }\n\n}" }, { "identifier": "Repository", "path": "gift-analyze/src/main/java/org/giftorg/analyze/entity/Repository.java", "snippet": "@Slf4j\n@Data\npublic class Repository implements Serializable, Cloneable {\n private Integer id;\n\n private Integer repoId;\n\n private String name;\n\n private String fullName;\n\n private Integer stars;\n\n private String author;\n\n private String url;\n\n private String description;\n\n private Integer size;\n\n private String defaultBranch;\n\n private String readme;\n\n private String readmeCn;\n\n private List<String> tags;\n\n private String hdfsPath;\n\n private boolean isTranslated = false;\n\n private boolean isTagged = false;\n\n private static final int CHUNK_SIZE = 1000;\n\n public Repository() {\n }\n\n public Repository(String name, String readme) {\n this.name = name;\n this.readme = readme;\n }\n\n @Override\n public Repository clone() throws CloneNotSupportedException {\n return (Repository) super.clone();\n }\n\n private static final String REPOSITORY_TRANSLATION_PROMPT = \"去除以上文档中任何链接、许可等无关内容,使用中文总结上面的内容,保留核心文字描述,且必须保留文档中的名词、相关的项目名称。\";\n\n /**\n * 翻译项目文档\n */\n public void translation() throws Exception {\n if (isTranslated) return;\n if (!CharsetUtil.isChinese(readme)) {\n BigModel xingHuo = new ChatGPT();\n List<BigModel.Message> messages = readmeContentMessages();\n messages.add(new BigModel.Message(\"user\", REPOSITORY_TRANSLATION_PROMPT));\n readmeCn = xingHuo.chat(messages);\n // TODO: 添加更优的判断方式\n // TODO: 根据星火响应的特征,失败时一般会响应 “很抱歉,您没有提供任何文档或链接供我删除无关内容。请提供相关文档或链接,我将为您删除其中的无关内容并使用中文概括核心文本描述。”\n if (readmeCn.isEmpty() || readmeCn.contains(\"抱歉\") || readmeCn.contains(\"对不起\"))\n throw new Exception(\"translation failed, xinghuo response: \" + readmeCn);\n } else {\n readmeCn = readme;\n }\n isTranslated = true;\n }\n\n // 根据用户输入的项目文档,生成与项目相关的中文搜索词列表,尽量详细覆盖大部分可能的搜索词,回答以英文逗号分隔。回答示例:\"管理系统,电商,秒杀,MySQL,Redis,Spring\";\n private static final String REPOSITORY_TAGGING_PROMPT = \"Generate a Chinese keyword list related to the project based on the user-inputted project documents, aiming to cover as many possible search terms in detail as possible. Provide the answers separated by English commas.\\nExample answer: \\\"管理系统,电商,秒杀,MySQL,Redis,Spring\\\"\\n\";\n\n /**\n * 获取项目关键词列表\n */\n public void tagging() throws Exception {\n if (isTagged) return;\n BigModel gpt = new ChatGPT();\n List<BigModel.Message> messages = new ArrayList<>();\n // TODO: 添加是否已翻译判断?\n messages.add(new BigModel.Message(\"user\", readmeCn));\n messages.add(new BigModel.Message(\"system\", REPOSITORY_TAGGING_PROMPT));\n String answer = gpt.chat(messages);\n tags = Arrays.asList(StringUtil.trimEnd(answer, \".\").split(\",\\\\s*\"));\n isTagged = true;\n }\n\n public List<BigModel.Message> readmeContentMessages() {\n List<BigModel.Message> messages = new ArrayList<>();\n List<String> chunks = splitReadmeContent();\n for (String chunk : chunks) {\n messages.add(new BigModel.Message(\"user\", chunk));\n }\n return messages;\n }\n\n public List<String> splitReadmeContent() {\n String content = MarkdownUtil.extractText(readme);\n ;\n System.out.println(content);\n List<String> chunks = new ArrayList<>();\n for (int i = 0; i <= content.length() / CHUNK_SIZE; i++) {\n chunks.add(content.substring(i * CHUNK_SIZE, Math.min(content.length(), (i + 1) * CHUNK_SIZE)));\n }\n return chunks;\n }\n\n public static void main(String[] args) throws Exception {\n Repository repository = new Repository(\"test\", \"hello world.\");\n repository.translation();\n log.info(\"readmeCn: {}\", repository.readmeCn);\n TokenPool.closeDefaultTokenPool();\n }\n}" }, { "identifier": "AnalyzeService", "path": "gift-analyze/src/main/java/org/giftorg/analyze/service/AnalyzeService.java", "snippet": "public interface AnalyzeService {\n\n void run(Repository repository) throws IOException;\n}" }, { "identifier": "AnalyzeServiceImpl", "path": "gift-analyze/src/main/java/org/giftorg/analyze/service/impl/AnalyzeServiceImpl.java", "snippet": "@Slf4j\npublic class AnalyzeServiceImpl implements AnalyzeService {\n private static final FunctionESDao fd = new FunctionESDao();\n private static final RepositoryESDao rd = new RepositoryESDao();\n private final JavaSparkContext sc;\n\n public AnalyzeServiceImpl(SparkContext sc) {\n this.sc = new JavaSparkContext(sc);\n }\n\n /**\n * 分析程序启动入口\n */\n public void run(Repository repository) throws IOException {\n analyzeRepository(repository);\n }\n\n /**\n * 项目仓库分析\n */\n private void analyzeRepository(Repository repository) throws IOException {\n // 获取仓库中所有文件\n List<String> files = HDFS.getRepoFiles(repository.getHdfsPath());\n\n String readme = null;\n for (String file : files) {\n if (file.endsWith(\"README.md\")) {\n if (readme == null) {\n readme = file;\n }\n } else {\n // 其它文件进行代码分析\n analyzeCode(repository.getId(), file);\n }\n }\n\n // 项目文档分析\n handleDoc(repository, readme);\n }\n\n /**\n * 代码文件分析\n */\n private void analyzeCode(Integer repoId, String file) {\n // TODO: 支持更多语言\n if (file.endsWith(\".java\")) {\n JavaPairRDD<String, String> fileRDD = sc.wholeTextFiles(file);\n\n JavaRDD<Function> funcRDD = fileRDD.flatMap((FlatMapFunction<Tuple2<String, String>, Function>) f -> {\n CodeSpliter analyzer = new JavaCodeSpliter();\n List<Function> functions = analyzer.splitFunctions(new ByteArrayInputStream(f._2().getBytes()));\n return functions.iterator();\n });\n\n JavaRDD<Function> analyzeFuncRDD = funcRDD.map(function -> {\n boolean isOfHighValue = function.analyze();\n function.setRepoId(repoId);\n function.setFilePath(file);\n return isOfHighValue ? function : null;\n });\n\n for (Function function : analyzeFuncRDD.collect()) {\n if (function == null) return;\n try {\n fd.insert(function);\n log.info(\"analyze function success: {}\", function);\n } catch (Exception e) {\n log.error(\"analyze function failed: \" + e.getMessage());\n throw new RuntimeException(e);\n }\n }\n }\n }\n\n /**\n * 仓库文档处理\n */\n private void handleDoc(Repository repository, String doc) {\n JavaPairRDD<String, String> fileRDD = sc.wholeTextFiles(doc);\n\n JavaRDD<Repository> repoRDD = fileRDD.map(docContent -> {\n Repository repo = repository.clone();\n repo.setReadme(docContent._2());\n repo.translation();\n repo.tagging();\n return repo;\n });\n\n try {\n for (Repository repo : repoRDD.collect()) {\n if (repo == null) return;\n rd.insert(repo);\n log.info(\"analyze repository success: {}\", repo);\n }\n } catch (Exception e) {\n log.error(\"analyze repository failed: \" + e.getMessage());\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "Config", "path": "gift-common/src/main/java/org/giftorg/common/config/Config.java", "snippet": "@Slf4j\npublic class Config {\n private static final String DEFAULT_CONFIG_PATH = \"config.yaml\";\n\n public static Properties.SparkProperties sparkConfig;\n public static Properties.HDFSProperties hdfsConfig;\n public static Properties.XingHouProperties xingHouConfig;\n public static Properties.ChatGPTProperties chatGPTConfig;\n public static Properties.ChatGLMProperties chatGLMConfig;\n public static Properties.KafkaProperties kafkaConfig;\n public static Properties.ElasticsearchProperties elasticsearchConfig;\n\n // 初始化项目配置\n static {\n log.info(\"Initializing configuration ...\");\n\n String configPath = DEFAULT_CONFIG_PATH;\n boolean isSpark = true;\n try {\n configPath = SparkFiles.get(DEFAULT_CONFIG_PATH);\n } catch (Exception e) {\n isSpark = false;\n }\n\n InputStream in;\n if (isSpark && new File(configPath).exists()) {\n try {\n in = Files.newInputStream(Paths.get(configPath));\n log.info(\"config path: {}\", configPath);\n } catch (Exception e) {\n log.error(\"init config failed: {}\", e.getMessage(), e);\n throw new RuntimeException(e);\n }\n } else {\n configPath = DEFAULT_CONFIG_PATH;\n try {\n ClassPathResource configResource = new ClassPathResource(configPath);\n in = configResource.getStream();\n log.info(\"config path: {}\", configResource.getPath());\n } catch (Exception e) {\n log.error(\"init config failed: {}\", e.getMessage(), e);\n throw new RuntimeException(e);\n }\n }\n\n Properties config;\n try {\n config = new Yaml().loadAs(in, Properties.class);\n in.close();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n sparkConfig = config.spark;\n hdfsConfig = config.hdfs;\n xingHouConfig = config.xingHou;\n chatGPTConfig = config.chatGPT;\n chatGLMConfig = config.chatGLM;\n kafkaConfig = config.kafka;\n elasticsearchConfig = config.elasticsearch;\n }\n}" }, { "identifier": "Elasticsearch", "path": "gift-common/src/main/java/org/giftorg/common/elasticsearch/Elasticsearch.java", "snippet": "@Slf4j\npublic class Elasticsearch {\n private static final String serverUrl = Config.elasticsearchConfig.getHostUrl();\n private static final RestClient restClient;\n\n // 分词器\n // ik_max_word: 细粒度分词器\n // ik_smart: 粗粒度分词器\n public static final String IK_MAX_WORD_ANALYZER = \"ik_max_word\";\n public static final String IK_SMART_ANALYZER = \"ik_smart\";\n public static final String WHITE_SPACE_ANALYZER = \"whitespace\";\n\n static {\n restClient = RestClient\n .builder(HttpHost.create(serverUrl))\n .build();\n }\n\n /**\n * 获取 Elasticsearch 客户端单例\n */\n public static ElasticsearchClient EsClient() {\n ElasticsearchTransport transport = new RestClientTransport(\n restClient,\n new JacksonJsonpMapper());\n return new ElasticsearchClient(transport);\n }\n\n /**\n * 关闭 Elasticsearch 客户端\n */\n public static void close() {\n try {\n restClient.close();\n } catch (Exception e) {\n log.error(\"rest client close failed: {}\", e.getMessage());\n }\n }\n\n /**\n * 使用向量检索所有文档\n * @param index es 索引\n * @param field es 索引中的向量字段\n * @param embedding 待检索的向量\n * @param type 返回的文档类型\n * @return 检索结果,包含所有文档,按相似度降序排列\n */\n public static <T> List<T> retrieval(String index, String field, List<Double> embedding, Class<T> type) throws IOException {\n SearchResponse<T> resp = EsClient().search(\n search -> search.index(index).query(query -> query\n .scriptScore(ss -> ss\n .script(s -> s.inline(l -> l\n .source(\"cosineSimilarity(params.query_vector, '\" + field + \"') + 1.0\")\n .params(\"query_vector\", JsonData.of(embedding))\n ))\n .query(q -> q.matchAll(ma -> ma))\n )\n ),\n type\n );\n\n List<T> result = new ArrayList<>();\n resp.hits().hits().forEach(hit -> {\n result.add(hit.source());\n });\n\n return result;\n }\n\n /**\n * 使用指定值过滤,并向量化检索文档\n * @param index es 索引\n * @param textFields es 索引中的文本字段\n * @param text 待检索的文本\n * @param embeddingField es 索引中的向量字段\n * @param type 返回的文档类型\n * @return 检索结果,仅包含过滤后的文档,按相似度降序排列\n */\n public static <T> List<T> retrieval(String index, List<String> textFields, String text, String embeddingField, Class<T> type) throws Exception {\n BigModel model = new ChatGLM();\n List<Double> embedding = model.textEmbedding(text);\n\n SearchResponse<T> resp = EsClient().search(\n search -> search.index(index).query(query -> query\n .scriptScore(ss -> ss\n .script(s -> s.inline(l -> l\n .source(\"cosineSimilarity(params.query_vector, '\" + embeddingField + \"') + 1.0\")\n .params(\"query_vector\", JsonData.of(embedding))\n ))\n .query(q -> q.multiMatch(mm -> mm\n .query(text).\n fields(textFields).\n operator(Operator.Or)\n ))\n )\n ),\n type\n );\n\n List<T> result = new ArrayList<>();\n resp.hits().hits().forEach(hit -> {\n result.add(hit.source());\n });\n\n return result;\n }\n}" }, { "identifier": "KafkaConsumerClient", "path": "gift-common/src/main/java/org/giftorg/common/kafka/KafkaConsumerClient.java", "snippet": "public class KafkaConsumerClient {\n\n public KafkaConsumer<String, String> kafkaConsumer;\n\n public KafkaConsumerClient(String topic, String groupId) {\n Properties props = new Properties();\n props.setProperty(\"bootstrap.servers\", Config.kafkaConfig.getHostUrl());\n props.setProperty(\"group.id\", groupId);\n props.setProperty(\"enable.auto.commit\", \"false\");\n props.setProperty(\"auto.commit.interval.ms\", \"1000\");\n props.setProperty(\"key.deserializer\", \"org.apache.kafka.common.serialization.StringDeserializer\");\n props.setProperty(\"value.deserializer\", \"org.apache.kafka.common.serialization.StringDeserializer\");\n props.setProperty(\"max.poll.records\", \"1\");\n\n kafkaConsumer = new KafkaConsumer<>(props);\n kafkaConsumer.subscribe(Arrays.asList(topic));\n }\n\n /**\n * 拉取消息\n */\n public ConsumerRecords<String, String> poll(int timeout) {\n return kafkaConsumer.poll(Duration.ofMillis(timeout));\n }\n\n /**\n * 异步提交offset\n */\n public void commitAsync() {\n kafkaConsumer.commitAsync();\n }\n\n /**\n * 同步提交offset\n */\n public void commitSync() {\n kafkaConsumer.commitSync();\n }\n\n public static void main(String[] args) {\n KafkaConsumerClient consumer = new KafkaConsumerClient(\"test-topic\", \"test\");\n while (true) {\n ConsumerRecords<String, String> records = consumer.poll(1000);\n for (ConsumerRecord<String, String> record : records)\n System.out.printf(\"topic = %s, offset = %d, key = %s, value = %s%n\", record.topic(), record.offset(), record.key(), record.value());\n }\n }\n}" }, { "identifier": "KafkaProducerClient", "path": "gift-common/src/main/java/org/giftorg/common/kafka/KafkaProducerClient.java", "snippet": "public class KafkaProducerClient {\n\n Producer<String, String> kafkaProducer;\n\n public KafkaProducerClient() {\n Properties props = new Properties();\n props.put(\"bootstrap.servers\", Config.kafkaConfig.getHostUrl());\n props.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n props.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\n props.put(\"batch.size\", 10);\n props.put(\"linger.ms\", 1000);\n\n kafkaProducer = new KafkaProducer<>(props);\n }\n\n /**\n * 发送消息\n */\n public Future<RecordMetadata> send(ProducerRecord<String, String> producerRecord) {\n return kafkaProducer.send(producerRecord);\n }\n\n /**\n * 发送消息并指定回调函数\n */\n public Future<RecordMetadata> send(ProducerRecord<String, String> producerRecord, Callback callback) {\n return kafkaProducer.send(producerRecord, callback);\n }\n\n public static void main(String[] args) {\n KafkaProducerClient producer = new KafkaProducerClient();\n for (int i = 0; i < 20; i++) {\n Future<RecordMetadata> result = producer.send(new ProducerRecord<>(\"test-topic\", Integer.toString(i), Integer.toString(i)));\n try {\n RecordMetadata metadata = result.get();\n System.out.println(metadata);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n}" }, { "identifier": "TokenPool", "path": "gift-common/src/main/java/org/giftorg/common/tokenpool/TokenPool.java", "snippet": "@Slf4j\n@Getter\npublic class TokenPool extends Thread {\n // 全局 TokenPool\n private static TokenPool tokenPool = null;\n\n // token 列表\n private final List<Token> tokens;\n\n // 可用 token 队列\n private final BlockingQueue<Token> tokenQueue;\n\n // api 任务队列\n private final BlockingQueue<APITask> apiTaskQueue;\n\n // 每个 token 在每个周期的可用次数\n private final Integer frequency;\n\n // 周期(秒)\n private final Integer cycle;\n\n // 最大线程数\n private Integer maxThread = 10;\n\n // 线程池\n private ExecutorService executorService;\n\n // 程序状态\n private Boolean active = true;\n\n // 定时器\n private Timer tokenTimer;\n\n public TokenPool(List<String> tokens, Integer cycle, Integer frequency) {\n this.cycle = cycle;\n this.frequency = frequency;\n this.tokenQueue = new LinkedBlockingQueue<>();\n this.apiTaskQueue = new LinkedBlockingQueue<>();\n\n this.tokens = new ArrayList<>();\n for (String token : tokens) {\n Token t = new Token(token);\n this.tokens.add(t);\n for (int i = 0; i < frequency; i++) {\n tokenQueue.add(t);\n }\n }\n\n this.start();\n }\n\n public TokenPool(List<String> tokens, Integer cycle, Integer frequency, Integer maxThread) {\n this.cycle = cycle;\n this.frequency = frequency;\n this.tokenQueue = new LinkedBlockingQueue<>();\n this.apiTaskQueue = new LinkedBlockingQueue<>();\n this.maxThread = maxThread;\n\n this.tokens = new ArrayList<>();\n for (String token : tokens) {\n Token t = new Token(token);\n this.tokens.add(t);\n for (int i = 0; i < frequency; i++) {\n tokenQueue.add(t);\n }\n }\n\n this.start();\n }\n\n /**\n * 获取全局的 TokenPool\n */\n public static TokenPool getTokenPool(List<String> tokens, Integer cycle, Integer frequency) {\n if (tokenPool == null) {\n tokenPool = new TokenPool(tokens, cycle, frequency);\n }\n return tokenPool;\n }\n\n /**\n * 获取全局的 TokenPool,并指定 api token 任务执行的最大线程数\n */\n public static TokenPool getTokenPool(List<String> tokens, Integer cycle, Integer frequency, Integer maxThread) {\n if (tokenPool == null) {\n tokenPool = new TokenPool(tokens, cycle, frequency, maxThread);\n }\n return tokenPool;\n }\n\n /**\n * 添加 api token 任务,异步执行\n */\n public void addTask(APITask apiTask) {\n apiTaskQueue.add(apiTask);\n }\n\n /**\n * 添加 api token 任务,同步执行并返回执行结态\n */\n public APITaskResult runTask(APITask apiTask) {\n APITasker apiTasker = new APITasker(apiTask);\n apiTaskQueue.add(apiTasker);\n try {\n return apiTasker.getResult();\n } catch (InterruptedException e) {\n return new APITaskResult(e);\n }\n }\n\n /**\n * Token 池的调度程序\n */\n public void run() {\n tokenTimer = new Timer();\n executorService = Executors.newFixedThreadPool(maxThread);\n\n // 从队列中取出 token,执行任务\n while (active) {\n // 从任务队列中取出任务\n APITask apiTask;\n try {\n apiTask = apiTaskQueue.take();\n } catch (InterruptedException ignored) {\n continue;\n } catch (Exception e) {\n log.error(\"take api task error: {}\", e.toString());\n continue;\n }\n\n // 从 token 队列中取出 token\n Token token;\n try {\n token = tokenQueue.take();\n } catch (InterruptedException ignored) {\n continue;\n } catch (Exception e) {\n log.error(\"take token error: {}\", e.toString());\n continue;\n }\n\n // 执行任务\n executorService.submit(() -> {\n try {\n apiTask.run(useToken(token));\n } catch (Exception e) {\n e.getStackTrace();\n log.error(\"api task error: {}\", e.toString());\n }\n });\n }\n }\n\n private String useToken(Token token) {\n String t = token.useToken();\n tokenTimer.schedule(new TimerTask() {\n @Override\n public void run() {\n tokenQueue.add(token);\n }\n }, cycle * 1000 - (System.currentTimeMillis() - token.pollLastTime()));\n return t;\n }\n\n /**\n * 关闭 TokenPool\n */\n public void close() {\n active = false;\n tokenTimer.cancel();\n executorService.shutdown();\n super.interrupt();\n }\n\n /**\n * 关闭全局的 TokenPool\n */\n public static void closeDefaultTokenPool() {\n if (tokenPool != null) {\n tokenPool.close();\n }\n }\n}" } ]
import org.giftorg.common.kafka.KafkaProducerClient; import org.giftorg.common.tokenpool.TokenPool; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.giftorg.analyze.entity.AnalyzeTask; import org.giftorg.analyze.entity.Repository; import org.giftorg.analyze.service.AnalyzeService; import org.giftorg.analyze.service.impl.AnalyzeServiceImpl; import org.giftorg.common.config.Config; import org.giftorg.common.elasticsearch.Elasticsearch; import org.giftorg.common.kafka.KafkaConsumerClient;
6,218
/** * 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.analyze; @Slf4j public class AnalyzeApplication { public static void main(String[] args) { SparkConf conf = new SparkConf() .setAppName("GiftAnalyzer")
/** * 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.analyze; @Slf4j public class AnalyzeApplication { public static void main(String[] args) { SparkConf conf = new SparkConf() .setAppName("GiftAnalyzer")
.setMaster(Config.sparkConfig.getMaster());
4
2023-11-15 08:58:35+00:00
8k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/comparison/LineImpl.java
[ { "identifier": "Constants", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/Constants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Constants {\n\n public static final String ROOT_PACKAGE = \"com.exadel.etoolbox.anydiff\";\n\n public static final int DEFAULT_COLUMN_WIDTH = 60;\n public static final boolean DEFAULT_ARRANGE_ATTRIBUTES = true;\n public static final boolean DEFAULT_IGNORE_SPACES = true;\n public static final int DEFAULT_INDENT = 2;\n public static final boolean DEFAULT_NORMALIZE = true;\n\n public static final int MAX_CONTEXT_LENGTH = 8;\n\n public static final String AT = \"@\";\n public static final char COLON_CHAR = ':';\n public static final char DASH_CHAR = '-';\n public static final String DOT = \".\";\n public static final String ELLIPSIS = \"...\";\n public static final String EQUALS = \"=\";\n public static final String HASH = \"#\";\n public static final String PIPE = \"|\";\n public static final String QUOTE = \"\\\"\";\n public static final String SLASH = \"/\";\n public static final char SLASH_CHAR = '/';\n public static final char UNDERSCORE_CHAR = '_';\n\n public static final String ATTR_HREF = \"href\";\n public static final String ATTR_ID = \"id\";\n\n public static final String CLASS_HEADER = \"header\";\n public static final String CLASS_LEFT = \"left\";\n public static final String CLASS_PATH = \"path\";\n public static final String CLASS_RIGHT = \"right\";\n\n public static final char BRACKET_OPEN = '[';\n public static final char BRACKET_CLOSE = ']';\n\n public static final String TAG_AUTO_CLOSE = \"/>\";\n public static final String TAG_CLOSE = \">\";\n public static final char TAG_CLOSE_CHAR = '>';\n public static final String TAG_OPEN = \"<\";\n public static final char TAG_OPEN_CHAR = '<';\n public static final String TAG_PRE_CLOSE = \"</\";\n\n public static final String TAG_ATTR_OPEN = EQUALS + QUOTE;\n public static final String TAG_ATTR_CLOSE = QUOTE;\n\n public static final String LABEL_LEFT = \"Left\";\n public static final String LABEL_RIGHT = \"Right\";\n}" }, { "identifier": "OutputType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/OutputType.java", "snippet": "public enum OutputType {\n CONSOLE, LOG, HTML\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}" }, { "identifier": "DiffEntry", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/DiffEntry.java", "snippet": "public interface DiffEntry extends Adaptable {\n\n /* ---------\n Accessors\n --------- */\n\n /**\n * Gets the {@link Diff} instance this entry belongs to\n * @return {@link Diff} instance\n */\n Diff getDiff();\n\n /**\n * Gets the name to distinguish the type of difference. Defaults to the name of the implementing class\n * @return String value. A non-empty string is expected\n */\n default String getName() {\n return StringUtils.removeEnd(getClass().getSimpleName(), \"Impl\");\n }\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 Content\n ------- */\n\n /**\n * Gets the left part of the comparison included in the current difference\n * @return String value\n */\n default String getLeft() {\n return getLeft(false);\n }\n\n /**\n * Gets the left part of the comparison included in the current difference\n * @param includeContext If set to true, the \"context\" elements (those going before and after the actual difference)\n * are added to the result. Otherwise, only the difference itself is returned\n * @return String value\n */\n String getLeft(boolean includeContext);\n\n /**\n * Gets the right part of the comparison included in the current difference\n * @return String value\n */\n default String getRight() {\n return getRight(false);\n }\n\n /**\n * Gets the right part of the comparison included in the current difference\n * @param includeContext If set to true, the \"context\" elements (those going before and after the actual\n * difference)\n * @return String value\n */\n String getRight(boolean includeContext);\n\n /* ----------\n Operations\n ---------- */\n\n /**\n * Accepts the difference, that is, silences it so that it no longer leads to the {@link AnyDiff} reporting a\n * mismatch. However, the difference is still included in the {@link Diff} and can be displayed to the user\n */\n void accept();\n}" }, { "identifier": "DiffState", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/DiffState.java", "snippet": "public enum DiffState {\n UNCHANGED {\n @Override\n public boolean isChange() {\n return false;\n }\n\n @Override\n public boolean isInsertion() {\n return false;\n }\n\n @Override\n public boolean isDeletion() {\n return false;\n }\n },\n CHANGE {\n @Override\n public boolean isChange() {\n return true;\n }\n\n @Override\n public boolean isInsertion() {\n return false;\n }\n\n @Override\n public boolean isDeletion() {\n return false;\n }\n },\n LEFT_MISSING {\n @Override\n public boolean isChange() {\n return false;\n }\n\n @Override\n public boolean isInsertion() {\n return true;\n }\n\n @Override\n public boolean isDeletion() {\n return false;\n }\n },\n RIGHT_MISSING {\n @Override\n public boolean isChange() {\n return false;\n }\n\n @Override\n public boolean isInsertion() {\n return false;\n }\n\n @Override\n public boolean isDeletion() {\n return true;\n }\n };\n\n /**\n * A shortcut method getting whether the difference is a change\n * @return True or false\n */\n public abstract boolean isChange();\n\n /**\n * A shortcut method getting whether the difference is an insertion\n * @return True or false\n */\n public abstract boolean isInsertion();\n\n /**\n * A shortcut method getting whether the difference is a deletion\n * @return True or false\n */\n public abstract boolean isDeletion();\n}" }, { "identifier": "EntryHolder", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/EntryHolder.java", "snippet": "public interface EntryHolder {\n\n /**\n * Gets the list of child {@link DiffEntry} instances\n * @return {@code List} of {@code DiffEntry} instances\n */\n List<? extends DiffEntry> children();\n\n /**\n * Instructs the {@code EntryHolder} to exclude the specified {@link DiffEntry} from the list of its children\n * @param value {@code DiffEntry} instance to exclude\n */\n void exclude(DiffEntry value);\n}" }, { "identifier": "Fragment", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Fragment.java", "snippet": "public interface Fragment extends CharSequence, Adaptable {\n\n /**\n * Gets the string (either the left or the right part of the comparison) this {@link Fragment} belongs to\n * @return A non-null string\n */\n String getSource();\n\n /**\n * Gets whether this {@link Fragment} represents an insertion (i.e., a part of the line to the right that is missing\n * in the line to the left)\n * @return True or false\n */\n boolean isInsert();\n\n /**\n * Gets whether this {@link Fragment} represents a deletion (i.e., a part of the line to the left that is missing in\n * the line to the right)\n * @return True or false\n */\n boolean isDelete();\n\n /**\n * Gets whether the difference is \"pending\", that is, has not been silenced and will eventually make\n * {@link AnyDiff} report a mismatch\n * @return True or false\n */\n default boolean isPending() {\n return isInsert() || isDelete();\n }\n\n /**\n * Gets whether this {@link Fragment} equals to the provided other string content-wise\n * @param other String value to compare to\n * @return True or false\n */\n default boolean equals(String other) {\n return StringUtils.equals(toString(), other);\n }\n}" }, { "identifier": "FragmentHolder", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/FragmentHolder.java", "snippet": "public interface FragmentHolder {\n\n /* -------\n Content\n ------- */\n\n /**\n * Gets the list of {@link Fragment} instances from the left side of the comparison\n * @return A list of {@code Fragment} objects\n */\n List<Fragment> getLeftFragments();\n\n /**\n * Gets the list of {@link Fragment} instances from the right side of the comparison\n * @return A list of {@code Fragment} objects\n */\n List<Fragment> getRightFragments();\n\n /**\n * Gets the list of {@link Fragment} instances from both sides of the comparison\n * @return A list of {@code Fragment} objects\n */\n default List<Fragment> getFragments() {\n return Stream.concat(getLeftFragments().stream(), getRightFragments().stream()).collect(Collectors.toList());\n }\n\n /* ----------\n Operations\n ---------- */\n\n /**\n * Accepts the fragment, that is, silences it so that it no longer leads to the {@link AnyDiff} reporting a\n * mismatch. However, the fragment is still included in the {@link Diff} and can be displayed to the user\n */\n void accept(Fragment value);\n\n /**\n * Instructs the {@code FragmentHolder} to exclude the specified {@link Fragment} from the list of its children\n * @param value {@code Fragment} object to exclude\n */\n void exclude(Fragment value);\n}" }, { "identifier": "PrintableEntry", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/PrintableEntry.java", "snippet": "public interface PrintableEntry {\n\n /**\n * Retrieves the string representation of the difference in the specified format\n * @param target {@code OutputType} value representing the desired output format\n * @return A non-null string value\n */\n String toString(OutputType target);\n\n /**\n * Retrieves the string representation of the difference in the specified format\n * @param target {@code OutputType} value representing the desired output format\n * @param element An optional token that specifies the selection of element(-s) to be printed\n * @return A non-null string value\n */\n default String toString(OutputType target, String element) {\n return toString(target);\n }\n}" } ]
import com.exadel.etoolbox.anydiff.Constants; import com.exadel.etoolbox.anydiff.OutputType; import com.exadel.etoolbox.anydiff.diff.Diff; import com.exadel.etoolbox.anydiff.diff.DiffEntry; import com.exadel.etoolbox.anydiff.diff.DiffState; import com.exadel.etoolbox.anydiff.diff.EntryHolder; import com.exadel.etoolbox.anydiff.diff.Fragment; import com.exadel.etoolbox.anydiff.diff.FragmentHolder; import com.exadel.etoolbox.anydiff.diff.PrintableEntry; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List;
4,909
if (fragmentPairs == null) { initFragmentsCache(); } return fragmentPairs; } @Override public String getLeft(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return left.toString(); } @Override public String getRight(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return right.toString(); } @Override public List<Fragment> getLeftFragments() { if (leftFragments == null) { initFragmentsCache(); } return leftFragments; } @Override public List<Fragment> getRightFragments() { if (rightFragments == null) { initFragmentsCache(); } return rightFragments; } /** * Gets the left side of the current line * @return A {@link MarkedString} instance */ MarkedString getLeftSide() { return left; } /** * Gets the right side of the current line * @return A {@link MarkedString} instance */ MarkedString getRightSide() { return right; } private void initFragmentsCache() { leftFragments = isMarkupType ? left.getMarkupFragments() : left.getFragments(); rightFragments = isMarkupType ? right.getMarkupFragments() : right.getFragments(); if (leftFragments.size() != rightFragments.size() || leftFragments.isEmpty() || ((FragmentImpl) leftFragments.get(0)).getLineOffset() != ((FragmentImpl) rightFragments.get(0)).getLineOffset()) { fragmentPairs = Collections.emptyList(); return; } Iterator<Fragment> leftIterator = leftFragments.iterator(); Iterator<Fragment> rightIterator = rightFragments.iterator(); fragmentPairs = new ArrayList<>(); while (leftIterator.hasNext()) { Fragment leftFragment = leftIterator.next(); Fragment rightFragment = rightIterator.next(); fragmentPairs.add(new FragmentPairImpl(this, leftFragment, rightFragment)); } } private void resetFragmentsCache() { leftFragments = null; rightFragments = null; fragmentPairs = null; } /* ---------- Operations ---------- */ @Override public void accept() { left.accept(); right.accept(); resetFragmentsCache(); } @Override public void accept(Fragment value) { left.accept(value); right.accept(value); resetFragmentsCache(); } @Override public void exclude(DiffEntry value) { if (!(value instanceof FragmentPairImpl)) { return; } FragmentPairImpl fragmentPair = (FragmentPairImpl) value; left.unmark(fragmentPair.getLeftFragment()); right.unmark(fragmentPair.getRightFragment()); resetFragmentsCache(); } @Override public void exclude(Fragment value) { left.unmark(value); right.unmark(value); resetFragmentsCache(); } /* ------ Output ------ */ @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.comparison; /** * Implements {@link DiffEntry} to represent a line within a block of text that either contains a difference or poses * a visual context * @see DiffEntry */ class LineImpl implements DiffEntry, FragmentHolder, EntryHolder, PrintableEntry { private static final MarkedString CONTEXT_ELLIPSIS = new MarkedString(Constants.ELLIPSIS, Marker.CONTEXT); private final MarkedString left; private final MarkedString right; /** * Gets whether the current line is a context line */ @Getter(value = lombok.AccessLevel.PACKAGE) private boolean isContext; private boolean isMarkupType; private List<Fragment> leftFragments; private List<Fragment> rightFragments; private List<FragmentPairImpl> fragmentPairs; /** * Assigns the reference to the block this line belongs to */ @Setter(value = lombok.AccessLevel.PACKAGE) private AbstractBlock block; /** * Initializes a new instance of {@link LineImpl} class * @param left The left side of the line * @param right The right side of the line */ LineImpl(MarkedString left, MarkedString right) { this.left = left != null ? left : new MarkedString(null); this.right = right != null ? right : new MarkedString(null); } /* --------------- State accessors --------------- */ /** * Gets the number of differences in the current line * @return An integer value */ int getCount() { if (getState() == DiffState.UNCHANGED) { return 0; } // Will sum up to X "unpaired" fragments + Y pairs (every pair count as 1) return getLeftFragments().size() + getRightFragments().size() - children().size(); } int getPendingCount() { if (getState() == DiffState.UNCHANGED) { return 0; } // Will sum up to X "unpaired" fragments + Y pairs (every pair count as 1) long result = getLeftFragments().stream().filter(Fragment::isPending).count() + getRightFragments().stream().filter(Fragment::isPending).count() - children().stream().filter(c -> ((FragmentPairImpl) c).isPending()).count(); return (int) result; } @Override public DiffState getState() { if (isContext) { return DiffState.UNCHANGED; } if (MarkedString.isEmpty(left) && !MarkedString.isEmpty(right)) { return right.hasChanges() ? DiffState.LEFT_MISSING : DiffState.UNCHANGED; } if (!MarkedString.isEmpty(left) && MarkedString.isEmpty(right)) { return left.hasChanges() ? DiffState.RIGHT_MISSING : DiffState.UNCHANGED; } if (MarkedString.isEmpty(left)) { return DiffState.UNCHANGED; } return left.hasChanges() || right.hasChanges() ? DiffState.CHANGE : DiffState.UNCHANGED; } /* --------------- Other accessors --------------- */ @Override public Diff getDiff() { return block != null ? block.getDiff() : null; } /** * Calculates the number of spaces that indent both the left and right sides of the current line * @return An integer value */ int getIndent() { int leftIndent = left.getIndent(); int rightIndent = right.getIndent(); if (leftIndent == 0 && left.toString().isEmpty()) { return rightIndent; } else if (rightIndent == 0 && right.toString().isEmpty()) { return leftIndent; } return Math.min(leftIndent, rightIndent); } /** * Sets the flag saying that the current line is a context line */ void setIsContext() { isContext = true; left.mark(Marker.CONTEXT); right.mark(Marker.CONTEXT); } /** * Sets the flag saying that the current line contains XML or HTML markup */ void setIsMarkup() { isMarkupType = true; } /** * Removes the specified number of characters from the left side of the current line. Used to trim leading spaces * and provide a more compact output */ void cutLeft(int count) { if (count == 0) { return; } left.cutLeft(count); right.cutLeft(count); } private int getColumnWidth() { return block != null ? block.getColumnWidth() : Constants.DEFAULT_COLUMN_WIDTH; } /* ------- Content ------- */ @Override public List<? extends DiffEntry> children() { if (fragmentPairs == null) { initFragmentsCache(); } return fragmentPairs; } @Override public String getLeft(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return left.toString(); } @Override public String getRight(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return right.toString(); } @Override public List<Fragment> getLeftFragments() { if (leftFragments == null) { initFragmentsCache(); } return leftFragments; } @Override public List<Fragment> getRightFragments() { if (rightFragments == null) { initFragmentsCache(); } return rightFragments; } /** * Gets the left side of the current line * @return A {@link MarkedString} instance */ MarkedString getLeftSide() { return left; } /** * Gets the right side of the current line * @return A {@link MarkedString} instance */ MarkedString getRightSide() { return right; } private void initFragmentsCache() { leftFragments = isMarkupType ? left.getMarkupFragments() : left.getFragments(); rightFragments = isMarkupType ? right.getMarkupFragments() : right.getFragments(); if (leftFragments.size() != rightFragments.size() || leftFragments.isEmpty() || ((FragmentImpl) leftFragments.get(0)).getLineOffset() != ((FragmentImpl) rightFragments.get(0)).getLineOffset()) { fragmentPairs = Collections.emptyList(); return; } Iterator<Fragment> leftIterator = leftFragments.iterator(); Iterator<Fragment> rightIterator = rightFragments.iterator(); fragmentPairs = new ArrayList<>(); while (leftIterator.hasNext()) { Fragment leftFragment = leftIterator.next(); Fragment rightFragment = rightIterator.next(); fragmentPairs.add(new FragmentPairImpl(this, leftFragment, rightFragment)); } } private void resetFragmentsCache() { leftFragments = null; rightFragments = null; fragmentPairs = null; } /* ---------- Operations ---------- */ @Override public void accept() { left.accept(); right.accept(); resetFragmentsCache(); } @Override public void accept(Fragment value) { left.accept(value); right.accept(value); resetFragmentsCache(); } @Override public void exclude(DiffEntry value) { if (!(value instanceof FragmentPairImpl)) { return; } FragmentPairImpl fragmentPair = (FragmentPairImpl) value; left.unmark(fragmentPair.getLeftFragment()); right.unmark(fragmentPair.getRightFragment()); resetFragmentsCache(); } @Override public void exclude(Fragment value) { left.unmark(value); right.unmark(value); resetFragmentsCache(); } /* ------ Output ------ */ @Override
public String toString(OutputType target) {
1
2023-11-16 14:29:45+00:00
8k
Walter-Stroebel/Jllama
src/main/java/nl/infcomtec/jllama/TextImage.java
[ { "identifier": "ImageObject", "path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java", "snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new LinkedList<>();\n\n public ImageObject(Image image) {\n putImage(image);\n }\n\n /**\n * @return The most recent image.\n */\n public BufferedImage getImage() {\n return image;\n }\n\n /**\n * Stay informed.\n *\n * @param listener called when another client changes the image.\n */\n public synchronized void addListener(ImageObjectListener listener) {\n listeners.add(listener);\n }\n\n void sendSignal(Object msg) {\n for (ImageObjectListener listener : listeners) {\n listener.signal(msg);\n }\n }\n\n public enum MouseEvents {\n clicked_left, clicked_right, dragged, moved, pressed_left, released_left, pressed_right, released_right\n };\n\n public synchronized void forwardMouse(MouseEvents ev, Point2D p) {\n for (ImageObjectListener listener : listeners) {\n listener.mouseEvent(this, ev, p);\n }\n }\n\n /**\n * Replace image.\n *\n * @param replImage If null image may still have been altered in place, else\n * replace image with replImage. All listeners will be notified.\n */\n public synchronized final void putImage(Image replImage) {\n int oldWid = null == this.image ? 0 : this.image.getWidth();\n if (null != replImage) {\n this.image = new BufferedImage(replImage.getWidth(null), replImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = this.image.createGraphics();\n g2.drawImage(replImage, 0, 0, null);\n g2.dispose();\n }\n for (ImageObjectListener listener : listeners) {\n if (0 == oldWid) {\n listener.imageChanged(this, 1.0);\n } else {\n listener.imageChanged(this, 1.0 * oldWid / this.image.getWidth());\n }\n }\n }\n\n public int getWidth() {\n return getWidth(null);\n }\n\n @Override\n public int getWidth(ImageObserver io) {\n return image.getWidth(io);\n }\n\n @Override\n public int getHeight(ImageObserver io) {\n return image.getHeight(io);\n }\n\n public int getHeight() {\n return getHeight(null);\n }\n\n @Override\n public ImageProducer getSource() {\n return image.getSource();\n }\n\n @Override\n public Graphics getGraphics() {\n return image.getGraphics();\n }\n\n @Override\n public Object getProperty(String string, ImageObserver io) {\n return image.getProperty(string, null);\n }\n\n public HashMap<String, BitShape> calculateClosestAreas(final Map<String, Point2D> pois) {\n long nanos = System.nanoTime();\n final HashMap<String, BitShape> ret = new HashMap<>();\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n ret.put(e.getKey(), new BitShape(getWidth()));\n }\n\n int numThreads = Runtime.getRuntime().availableProcessors() - 2; // Number of threads to use, leaving some cores for routine work.\n if (numThreads < 1) {\n numThreads = 1;\n }\n ExecutorService executor = Executors.newFixedThreadPool(numThreads);\n\n int rowsPerThread = getHeight() / numThreads;\n for (int i = 0; i < numThreads; i++) {\n final int yStart = i * rowsPerThread;\n final int yEnd = (i == numThreads - 1) ? getHeight() : yStart + rowsPerThread;\n executor.submit(new Runnable() {\n @Override\n public void run() {\n for (int y = yStart; y < yEnd; y++) {\n for (int x = 0; x < getWidth(); x++) {\n double d = 0;\n String poi = null;\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n double d2 = e.getValue().distance(x, y);\n if (poi == null || d2 < d) {\n poi = e.getKey();\n d = d2;\n }\n }\n synchronized (ret.get(poi)) {\n ret.get(poi).set(new Point2D.Double(x, y));\n }\n }\n }\n }\n });\n }\n executor.shutdown();\n try {\n if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {\n throw new RuntimeException(\"This cannot be right.\");\n }\n } catch (InterruptedException ex) {\n throw new RuntimeException(\"We are asked to stop?\", ex);\n }\n System.out.format(\"calculateClosestAreas W=%d,H=%d,P=%d,T=%.2f ms\\n\",\n getWidth(), getHeight(), pois.size(), (System.nanoTime() - nanos) / 1e6);\n return ret;\n }\n\n /**\n * Callback listener.\n */\n public static class ImageObjectListener {\n\n public final String name;\n\n public ImageObjectListener(String name) {\n this.name = name;\n }\n\n /**\n * Image may have been altered.\n *\n * @param imgObj Source.\n * @param resizeHint The width of the previous image divided by the\n * width of the new image. See ImageViewer why this is useful.\n */\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // default is no action\n }\n\n /**\n * Used to forward mouse things by viewer implementations.\n *\n * @param imgObj Source.\n * @param ev Our event definition.\n * @param p Point of the event in image pixels.\n */\n public void mouseEvent(ImageObject imgObj, MouseEvents ev, Point2D p) {\n // default ignore\n }\n\n /**\n * Generic signal, generally causes viewer implementations to repaint.\n *\n * @param any\n */\n public void signal(Object any) {\n // default ignore\n }\n }\n}" }, { "identifier": "ImageViewer", "path": "src/main/java/nl/infcomtec/simpleimage/ImageViewer.java", "snippet": "public class ImageViewer {\n\n private static final int MESSAGE_HEIGHT = 200;\n private static final int MESSAGE_WIDTH = 800;\n public List<Component> tools;\n private String message = null;\n private long messageMillis = 0;\n private long shownLast = 0;\n private Font messageFont = UIManager.getFont(\"Label.font\");\n\n protected final ImageObject imgObj;\n private LUT lut;\n private List<Marker> marks;\n\n public ImageViewer(ImageObject imgObj) {\n this.imgObj = imgObj;\n }\n\n public ImageViewer(Image image) {\n imgObj = new ImageObject(image);\n }\n\n public synchronized void flashMessage(Font font, String msg, long millis) {\n messageFont = font;\n messageMillis = millis;\n message = msg;\n shownLast = 0;\n imgObj.sendSignal(null);\n }\n\n public synchronized void flashMessage(String msg, long millis) {\n flashMessage(messageFont, msg, millis);\n }\n\n public synchronized void flashMessage(String msg) {\n flashMessage(messageFont, msg, 3000);\n }\n\n public synchronized void addMarker(Marker marker) {\n if (null == marks) {\n marks = new LinkedList<>();\n }\n marks.add(marker);\n imgObj.putImage(null);\n }\n\n public synchronized void clearMarkers() {\n marks = null;\n imgObj.putImage(null);\n }\n\n public ImageViewer(File f) {\n ImageObject tmp;\n try {\n tmp = new ImageObject(ImageIO.read(f));\n } catch (Exception ex) {\n tmp = showError(f);\n }\n imgObj = tmp;\n }\n\n /**\n * Although there are many reasons an image may not load, all we can do\n * about it is tell the user by creating an image with the failure.\n *\n * @param f File we tried to load.\n */\n private ImageObject showError(File f) {\n BufferedImage img = new BufferedImage(MESSAGE_WIDTH, MESSAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);\n Graphics2D gr = img.createGraphics();\n String msg1 = \"Cannot open image:\";\n String msg2 = f.getAbsolutePath();\n Font font = gr.getFont();\n float points = 24;\n int w, h;\n do {\n font = font.deriveFont(points);\n gr.setFont(font);\n FontMetrics metrics = gr.getFontMetrics(font);\n w = Math.max(metrics.stringWidth(msg1), metrics.stringWidth(msg2));\n h = metrics.getHeight() * 2; // For two lines of text\n if (w > MESSAGE_WIDTH - 50 || h > MESSAGE_HEIGHT / 3) {\n points--;\n }\n } while (w > MESSAGE_WIDTH || h > MESSAGE_HEIGHT / 3);\n gr.drawString(msg1, 50, MESSAGE_HEIGHT / 3);\n gr.drawString(msg2, 50, MESSAGE_HEIGHT / 3 * 2);\n gr.dispose();\n return new ImageObject(img);\n }\n\n /**\n * Often images have overly bright or dark areas. This permits to have a\n * lighter or darker view.\n *\n * @return this for chaining.\n */\n public synchronized ImageViewer addShadowView() {\n ButtonGroup bg = new ButtonGroup();\n addChoice(bg, new AbstractAction(\"Dark\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.darker();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Normal\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.unity();\n imgObj.putImage(null);\n }\n }, true);\n addChoice(bg, new AbstractAction(\"Bright\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.brighter();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Brighter\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt(0);\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Extreme\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt2();\n imgObj.putImage(null);\n }\n });\n return this;\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action) {\n return addChoice(group, action, false);\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @param selected Only useful if true.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action, boolean selected) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n JCheckBox button = new JCheckBox(action);\n button.setSelected(selected);\n if (null != group) {\n group.add(button);\n if (selected) {\n group.setSelected(button.getModel(), selected);\n }\n }\n tools.add(button);\n return this;\n }\n\n public synchronized ImageViewer addButton(Action action) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(action));\n return this;\n }\n\n public synchronized ImageViewer addMaxButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_MAX);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addOrgButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_ORG);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addAnything(Component comp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(comp);\n return this;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel).\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanel() {\n final JPanel ret = new JPanelImpl();\n return ret;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanelTools() {\n final JPanel outer = new JPanel();\n outer.setLayout(new BorderLayout());\n outer.add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n outer.add(tb, BorderLayout.NORTH);\n }\n return outer;\n }\n\n /**\n * Show the image in a JFrame component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JFrame.\n */\n public JFrame getScalePanFrame() {\n final JFrame ret = new JFrame();\n ret.setAlwaysOnTop(true);\n ret.getContentPane().setLayout(new BorderLayout());\n ret.getContentPane().add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n ret.getContentPane().add(tb, BorderLayout.NORTH);\n }\n ret.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n ret.pack();\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n ret.setVisible(true);\n }\n });\n return ret;\n }\n\n public ImageObject getImageObject() {\n return imgObj;\n }\n\n public enum ScaleCommand {\n SCALE_ORG, SCALE_MAX\n }\n\n private class JPanelImpl extends JPanel {\n\n int ofsX = 0;\n int ofsY = 0;\n double scale = 1;\n private BufferedImage dispImage = null;\n\n private Point pixelMouse(MouseEvent e) {\n int ax = e.getX() - ofsX;\n int ay = e.getY() - ofsY;\n ax = (int) Math.round(ax / scale);\n ay = (int) Math.round(ay / scale);\n return new Point(ax, ay);\n }\n\n public JPanelImpl() {\n MouseAdapter ma = new MouseAdapter() {\n private int lastX, lastY;\n\n @Override\n public void mousePressed(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.pressed_right, pixelMouse(e));\n } else {\n lastX = e.getX();\n lastY = e.getY();\n }\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.dragged, pixelMouse(e));\n } else {\n ofsX += e.getX() - lastX;\n ofsY += e.getY() - lastY;\n lastX = e.getX();\n lastY = e.getY();\n repaint(); // Repaint the panel to reflect the new position\n }\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int notches = e.getWheelRotation();\n scale += notches * 0.1; // Adjust the scaling factor\n if (scale < 0.1) {\n scale = 0.1; // Prevent the scale from becoming too small\n }\n dispImage = null;\n repaint(); // Repaint the panel to reflect the new scale\n }\n };\n addMouseListener(ma);\n addMouseMotionListener(ma);\n addMouseWheelListener(ma);\n imgObj.addListener(new ImageObject.ImageObjectListener(\"Repaint\") {\n @Override\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // If the image we are displaying is for instance 512 pixels and\n // the new image is 1536, we need to adjust scaling to match.\n scale *= resizeHint;\n dispImage = null;\n repaint(); // Repaint the panel to reflect any changes\n }\n\n @Override\n public void signal(Object any) {\n if (any instanceof ScaleCommand) {\n ScaleCommand sc = (ScaleCommand) any;\n switch (sc) {\n case SCALE_MAX: {\n double w = (1.0 * getWidth()) / imgObj.getWidth();\n double h = (1.0 * getHeight()) / imgObj.getHeight();\n System.out.format(\"%f %f %d %d\\n\", w, h, imgObj.getWidth(), getWidth());\n if (w > h) {\n scale = h;\n } else {\n scale = w;\n }\n }\n break;\n case SCALE_ORG: {\n scale = 1;\n }\n break;\n }\n dispImage = null;\n }\n repaint();\n }\n });\n Dimension dim = new Dimension(imgObj.getWidth(), imgObj.getHeight());\n setPreferredSize(dim);\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.DARK_GRAY);\n g.fillRect(0, 0, getWidth(), getHeight());\n if (null == dispImage) {\n int scaledWidth = (int) (imgObj.getWidth() * scale);\n int scaledHeight = (int) (imgObj.getHeight() * scale);\n dispImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = dispImage.createGraphics();\n g2.drawImage(imgObj.getScaledInstance(scaledWidth, scaledHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);\n g2.dispose();\n if (null != lut) {\n dispImage = lut.apply(dispImage);\n }\n if (null != marks) {\n for (Marker marker : marks) {\n marker.mark(dispImage);\n }\n }\n }\n g.drawImage(dispImage, ofsX, ofsY, null);\n if (null != message) {\n if (0 == shownLast) {\n shownLast = System.currentTimeMillis();\n }\n if (shownLast + messageMillis >= System.currentTimeMillis()) {\n g.setFont(messageFont);\n g.setColor(Color.WHITE);\n g.setXORMode(Color.BLACK);\n int ofs = g.getFontMetrics().getHeight();\n System.out.println(message + \" \" + ofs);\n g.drawString(message, ofs, ofs * 2);\n } else {\n message = null;\n shownLast = 0;\n }\n }\n }\n }\n}" } ]
import java.awt.BorderLayout; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.concurrent.ExecutorService; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import nl.infcomtec.simpleimage.ImageObject; import nl.infcomtec.simpleimage.ImageViewer;
5,170
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame; public final ImageObject imgObj; private final Modality worker; public TextImage(final ExecutorService pool, String title, Modality grpMod) throws Exception { worker = grpMod; frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); imgObj = new ImageObject(worker.getImage()); Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); final JTextArea text = new JTextArea(60, 5); AbstractAction updateAction = new AbstractAction("Update") { @Override public void actionPerformed(ActionEvent ae) { worker.setCurrentText(pool, text.getText()); new Thread(new Runnable() { @Override public void run() { imgObj.putImage(worker.getImage()); } }).start(); } };
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame; public final ImageObject imgObj; private final Modality worker; public TextImage(final ExecutorService pool, String title, Modality grpMod) throws Exception { worker = grpMod; frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); imgObj = new ImageObject(worker.getImage()); Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); final JTextArea text = new JTextArea(60, 5); AbstractAction updateAction = new AbstractAction("Update") { @Override public void actionPerformed(ActionEvent ae) { worker.setCurrentText(pool, text.getText()); new Thread(new Runnable() { @Override public void run() { imgObj.putImage(worker.getImage()); } }).start(); } };
cp.add(new ImageViewer(imgObj).addButton(updateAction).getScalePanPanelTools(), BorderLayout.CENTER);
1
2023-11-16 00:37:47+00:00
8k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/DWCore.java
[ { "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": "DWIPortType", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortType.java", "snippet": "public interface DWIPortType {\n /**\n * Port type enum.\n * Implements a conversion to int\n */\n enum DWPortTypeIdentity {\n /**\n * null port.\n */\n NULL_PORT(0),\n /**\n * RS232 serial port.\n */\n SERIAL_PORT(1),\n /**\n * TCP port.\n */\n TCP_PORT(2);\n /**\n * int equivalent of port type.\n */\n private final int type;\n DWPortTypeIdentity(final int portType) {\n this.type = portType;\n }\n\n /**\n * Get enum port type as int.\n * @return port type as int\n */\n public int getPortType() {\n return type;\n }\n }\n\n /**\n * Identify type of port.\n * @return port type\n */\n DWPortTypeIdentity identify();\n\n /**\n * Get map of port definition.\n * @return port definition\n */\n Map<String, Integer> getPortDetail();\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": "SerialPortDef", "path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/SerialPortDef.java", "snippet": "@Getter\n@EqualsAndHashCode(callSuper = true)\n@Data\n@AllArgsConstructor\npublic final class SerialPortDef extends BasePortDef {\n /**\n * RS232 baud rate.\n */\n @Setter\n private int baudRate;\n /**\n * data bits per byte.\n */\n @Setter\n private int dataBits;\n /**\n * RS232 parity type 0/1.\n */\n @Setter\n private int parityType;\n /**\n * Unique port identifier.\n */\n @Setter\n private int portId;\n /**\n * Required port name.\n */\n @Setter\n private String portName;\n /**\n * RS232 stop bits 0/1.\n */\n @Setter\n private int stopBits;\n\n @Override\n public DWPortTypeIdentity identify() {\n return DWPortTypeIdentity.SERIAL_PORT;\n }\n\n @Override\n public Map<String, Integer> getPortDetail() {\n final Map<String, Integer> result = new HashMap<>();\n result.put(\"BaudRate\", baudRate);\n result.put(\"DataBits\", dataBits);\n result.put(\"Identity\", DWPortTypeIdentity.SERIAL_PORT.getPortType());\n result.put(\"ParityType\", parityType);\n result.put(\"PortId\", portId);\n result.put(\"StopBits\", stopBits);\n return result;\n }\n}" }, { "identifier": "Transaction", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/Transaction.java", "snippet": "@Getter\npublic enum Transaction {\n /**\n * RESET1 - $FF.\n */\n OP_RESET1(\"OP_RESET1\", 0xFF, 0, 0),\n /**\n * RESET2 - $FE.\n */\n OP_RESET2(\"OP_RESET2\", 0xFE, 0, 0),\n /**\n * RESET3 - $F8.\n */\n OP_RESET3(\"OP_RESET3\", 0xF8, 0, 0),\n /**\n * RE-READ EXTENDED - $F2.\n */\n OP_REREADEX(\"OP_REREADEX\", 0xF2, 4, 4),\n /**\n * READ EXTENDED - $D2.\n */\n OP_READEX(\"OP_READEX\", 0xD2, 4, 4),\n /**\n * SERIAL TERMINATE - $C5.\n */\n OP_SERTERM(\"OP_SERTERM\", 0xC5, 1, 1),\n /**\n * SERIAL SET STAT - $C4.\n */\n OP_SERSETSTAT(\"OP_SERSETSTAT\", 0xC4, 2, 28),\n /**\n * SERIAL WRITE - $C3.\n */\n OP_SERWRITE(\"OP_SERWRITE\", 0xC3, 2, 2),\n /**\n * FAST WRITE - $80.\n */\n OP_FASTWRITE(\"OP_FASTWRITE\", 0x80, 1, 1),\n /**\n * RE-WRITE - $77.\n */\n OP_REWRITE(\"OP_REWRITE\", 0x77, 262, 262),\n /**\n * RE-READ - $72.\n */\n OP_REREAD(\"OP_REREAD\", 0x72, 4, 4),\n /**\n * SERIAL WRITE MULTI-BYTE - $64.\n */\n OP_SERWRITEM(\"OP_SERWRITEM\", 0x64, 258, 258),\n /**\n * SERIAL READ MULTI-BYTE - $63.\n */\n OP_SERREADM(\"OP_SERREADM\", 0x63, 2, 2),\n /**\n * DRIVEWIRE 4 INIT - $5A.\n */\n OP_DWINIT(\"OP_DWINIT\", 0x5A, 1, 1),\n /**\n * WRITE - $57.\n */\n OP_WRITE(\"OP_WRITE\", 0x57, 262, 262),\n /**\n * TERMINATE - $54.\n */\n OP_TERM(\"OP_TERM\", 0x54, 0, 0),\n /**\n * SET STAT - $53.\n */\n OP_SETSTAT(\"OP_SETSTAT\", 0x53, 2, 2),\n /**\n * READ - $52.\n */\n OP_READ(\"OP_READ\", 0x52, 4, 4),\n /**\n * PRINT (BYTE) - $50.\n */\n OP_PRINT(\"OP_PRINT\", 0x50, 1, 1),\n /**\n * DRIVEWIRE 3 INIT - $49.\n */\n OP_INIT(\"OP_INIT\", 0x49, 0, 0),\n /**\n * GET STAT - $47.\n */\n OP_GETSTAT(\"OP_GETSTAT\", 0x47, 2, 2),\n /**\n * FLUSH PRINT - $46.\n */\n OP_PRINTFLUSH(\"OP_PRINTFLUSH\", 0x46, 0, 0),\n /**\n * SERIAL INIT - $45.\n */\n OP_SERINIT(\"OP_SERINIT\", 0x45, 1, 1),\n /**\n * SERIAL GET STAT - $44.\n */\n OP_SERGETSTAT(\"OP_SERGETSTAT\", 0x44, 2, 2),\n /**\n * SERIAL READ - $43.\n */\n OP_SERREAD(\"OP_SERREAD\", 0x43, 0, 0),\n /**\n * (SYNC) TIME - $43.\n */\n OP_TIME(\"OP_TIME\", 0x23, 0, 0),\n /**\n * CREATE NAMED OBJECT - $02.\n */\n OP_NAMEOBJ_CREATE(\"OP_NAMEOBJ_CREATE\", 0x02, 1, 1),\n /**\n * MOUNT NAMED OBJECT - $01.\n */\n OP_NAMEOBJ_MOUNT(\"OP_NAMEOBJ_MOUNT\", 0x01, 1, 1),\n /**\n * NO OPERATION - $00.\n */\n OP_NOP(\"OP_NOP\", 0x00, 0, 0);\n\n /**\n * operation code (byte).\n * -- GETTER --\n * Get operation code byte.\n *\n * @return opcode byte value\n\n */\n private final int opCode;\n /**\n * Expected remaining bytes to read in message.\n * -- GETTER --\n * Get operation byte length.\n *\n * @return expected number of following bytes\n\n */\n private final int opLength;\n /**\n * Maximum remaining bytes where message is variable.\n * -- GETTER --\n * Get maximum operation byte length where size is variable.\n *\n * @return maximum number of following bytes\n\n */\n private final int opMaxLength;\n /**\n * operation name (as per specification).\n * -- GETTER --\n * Get operation name.\n *\n * @return operation code name\n\n */\n private final String opName;\n Transaction(final String name, final int code, final int len, final int max) {\n this.opName = name;\n this.opCode = code;\n this.opLength = len;\n this.opMaxLength = max;\n }\n\n}" }, { "identifier": "TransactionRouter", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/TransactionRouter.java", "snippet": "@Component\npublic class TransactionRouter {\n /**\n * Map of opcode:transaction pairs.\n * -- GETTER --\n * Get dictionary of drive wire transactions.\n *\n * @return map of opcode to transactions\n */\n @Getter\n private final Map<Integer, Transaction> dictionary;\n /**\n * Map of transaction:operation pairs.\n */\n private final Map<Transaction, Operation> routing;\n\n /**\n * Create transaction router.\n */\n public TransactionRouter() {\n dictionary = new HashMap<>();\n routing = new HashMap<>();\n buildDictionary();\n }\n\n /**\n * Match transaction opCode to a handling function.\n * @param opCode Transaction enum\n * @param opFunction operation implementation\n */\n public void registerOperation(\n final Transaction opCode, final Operation opFunction\n ) {\n routing.put(opCode, opFunction);\n }\n\n private void buildDictionary() {\n for (final Transaction entry : Transaction.values()) {\n dictionary.put(entry.getOpCode(), entry);\n }\n }\n\n private void sendResponse(final RCResponse resultCode, final int[] data) {\n // write result code\n // if data.length > 0 : write result data\n }\n\n private boolean validateOpCode(final int code, final int length) {\n if (!dictionary.containsKey(code)) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return false;\n }\n final Transaction transaction = dictionary.get(code);\n if (length > transaction.getOpMaxLength()\n || length < transaction.getOpLength()) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return false;\n }\n return true;\n }\n\n /**\n * Accepts client request and route to correct handler.\n * @param data request data\n */\n public void processRequest(final int[] data) {\n if (validateOpCode(data[0], data.length - 1)) {\n sendResponse(RCResponse.RC_SYNTAX_ERROR, new int[] {});\n return;\n }\n final Transaction transaction = dictionary.get(data[0]);\n final Operation function = routing.get(transaction);\n function.process(data);\n }\n\n /**\n * Listen for response from request handler.\n *\n * @param event DWMessageEvent response\n */\n @Async\n @EventListener\n public void processResponse(final DWMessageEvent event) {\n sendResponse(RCResponse.RC_SUCCESS, event.getMessage());\n }\n}" }, { "identifier": "DwInit", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwInit.java", "snippet": "@Component\npublic class DwInit extends BaseOp implements Operation {\n /**\n * Log appender.\n */\n private static final Logger LOGGER = LogManager.getLogger(DwInit.class);\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n if (data[0] == OP_INIT.getOpCode()) {\n LOGGER.info(\"DW3 client init\");\n getController().setClientVersion(0);\n return;\n }\n LOGGER.info(\"DW4 client version byte: \" + data[1]);\n getController().setClientVersion(data[1]);\n new DWMessageEvent(\n this,\n new int[] {this.getController().reportCapability()}\n );\n }\n}" }, { "identifier": "DwNop", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwNop.java", "snippet": "public class DwNop extends BaseOp implements Operation {\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n // no operation\n }\n}" }, { "identifier": "DwReset", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwReset.java", "snippet": "public class DwReset extends BaseOp implements Operation {\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n final int code = data[0];\n\n }\n}" }, { "identifier": "DwTime", "path": "src/main/java/org/thelair/dw4/drivewire/transactions/operations/DwTime.java", "snippet": "public class DwTime extends BaseOp implements Operation {\n /**\n * Base year offset.\n */\n public static final int BASE_YEAR = 1900;\n /**\n * Byte size of response data.\n */\n public static final int RESPONSE_SIZE = 6;\n /**\n * Process operation.\n *\n * @param data operation message data\n */\n @Override\n public void process(final int[] data) {\n final LocalDateTime currentTime = LocalDateTime.now();\n int[] response = new int[RESPONSE_SIZE];\n int index = 0;\n response[index++] = currentTime.getYear() - BASE_YEAR;\n response[index++] = currentTime.getMonth().getValue();\n response[index++] = currentTime.getDayOfMonth();\n response[index++] = currentTime.getHour();\n response[index++] = currentTime.getMinute();\n response[index] = currentTime.getSecond();\n new DWMessageEvent(this, response);\n }\n}" } ]
import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortManager; import org.thelair.dw4.drivewire.ports.DWIPortType; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition; import org.thelair.dw4.drivewire.ports.serial.SerialPortDef; import org.thelair.dw4.drivewire.transactions.Transaction; import org.thelair.dw4.drivewire.transactions.TransactionRouter; import org.thelair.dw4.drivewire.transactions.operations.DwInit; import org.thelair.dw4.drivewire.transactions.operations.DwNop; import org.thelair.dw4.drivewire.transactions.operations.DwReset; import org.thelair.dw4.drivewire.transactions.operations.DwTime;
4,925
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */ private final TransactionRouter router; /** * client version. */ @Getter @Setter private int clientVersion; /** * Create core service. * @param manager port manager */ public DWCore(final DWIPortManager manager) { this.router = new TransactionRouter(); this.portManager = manager; this.clientVersion = -1; LOGGER.info("Initialised core"); } private void populateRouter() { router.registerOperation(Transaction.OP_RESET1, new DwReset()); router.registerOperation(Transaction.OP_RESET2, new DwReset()); router.registerOperation(Transaction.OP_RESET3, new DwReset()); router.registerOperation(Transaction.OP_INIT, new DwInit()); router.registerOperation(Transaction.OP_DWINIT, new DwInit()); router.registerOperation(Transaction.OP_TIME, new DwTime()); router.registerOperation(Transaction.OP_NOP, new DwNop()); } /** * Handle application ready event. * * @param event ready event */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { populateRouter(); testPorts(); } /** * Report server capability. * @return register of enabled features */ public int reportCapability() { LOGGER.info("Reported server features: " + DW4_FEATURES); return DW4_FEATURES; } private void testPorts() { LOGGER.info("creating port"); final DWIPort serial = portManager.createPortInstance( DWIPortType.DWPortTypeIdentity.SERIAL_PORT ); LOGGER.info("serial port " + serial.toString()); try { serial.openWith( new SerialPortDef(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, 1, 0, "com1", 1) ); LOGGER.info("port opened " + serial.getPortDefinition());
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */ private final TransactionRouter router; /** * client version. */ @Getter @Setter private int clientVersion; /** * Create core service. * @param manager port manager */ public DWCore(final DWIPortManager manager) { this.router = new TransactionRouter(); this.portManager = manager; this.clientVersion = -1; LOGGER.info("Initialised core"); } private void populateRouter() { router.registerOperation(Transaction.OP_RESET1, new DwReset()); router.registerOperation(Transaction.OP_RESET2, new DwReset()); router.registerOperation(Transaction.OP_RESET3, new DwReset()); router.registerOperation(Transaction.OP_INIT, new DwInit()); router.registerOperation(Transaction.OP_DWINIT, new DwInit()); router.registerOperation(Transaction.OP_TIME, new DwTime()); router.registerOperation(Transaction.OP_NOP, new DwNop()); } /** * Handle application ready event. * * @param event ready event */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { populateRouter(); testPorts(); } /** * Report server capability. * @return register of enabled features */ public int reportCapability() { LOGGER.info("Reported server features: " + DW4_FEATURES); return DW4_FEATURES; } private void testPorts() { LOGGER.info("creating port"); final DWIPort serial = portManager.createPortInstance( DWIPortType.DWPortTypeIdentity.SERIAL_PORT ); LOGGER.info("serial port " + serial.toString()); try { serial.openWith( new SerialPortDef(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, 1, 0, "com1", 1) ); LOGGER.info("port opened " + serial.getPortDefinition());
} catch (InvalidPortTypeDefinition ex) {
3
2023-11-18 11:35:16+00:00
8k
sbmatch/miui_regain_runningserice
app/src/main/java/com/ma/bitchgiveitback/app_process/Main.java
[ { "identifier": "MultiJarClassLoader", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/MultiJarClassLoader.java", "snippet": "public class MultiJarClassLoader extends ClassLoader {\n static MultiJarClassLoader multiJarClassLoader;\n List<DexClassLoader> dexClassLoaders = new ArrayList<>();\n private MultiJarClassLoader(ClassLoader parentClassLoader) {\n super(parentClassLoader);\n }\n\n public synchronized static MultiJarClassLoader getInstance(){\n if (multiJarClassLoader == null){\n multiJarClassLoader = new MultiJarClassLoader(ClassLoader.getSystemClassLoader());\n }\n return multiJarClassLoader;\n }\n\n public void addJar(String jarPath) {\n DexClassLoader dexClassLoader = new DexClassLoader(\n jarPath,\n null,\n null, // 额外的库路径,可以为 null\n getParent() // 父类加载器\n );\n dexClassLoaders.add(dexClassLoader);\n }\n\n @Override\n protected Class<?> findClass(String className) throws ClassNotFoundException {\n // 遍历所有的 DexClassLoader 实例,尝试加载类\n for (DexClassLoader dexClassLoader : dexClassLoaders) {\n try {\n return dexClassLoader.loadClass(className);\n } catch (ClassNotFoundException ignored) {\n // 忽略类未找到的异常,继续下一个 DexClassLoader\n }\n }\n throw new ClassNotFoundException(\"Class not found: \" + className);\n }\n}" }, { "identifier": "Netd", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/Netd.java", "snippet": "public class Netd {\n private IInterface manager;\n public Netd(IInterface netd) {\n this.manager = netd;\n }\n\n public IBinder getOemNetd() {\n try {\n return (IBinder) manager.getClass().getMethod(\"getOemNetd\").invoke(manager);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n}" }, { "identifier": "NotificationManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/NotificationManager.java", "snippet": "public class NotificationManager {\n\n private IInterface manager;\n private Method updateNotificationChannelForPackageMethod;\n private Method unlockFieldsMethod;\n private Method setNotificationsEnabledForPackageMethod;\n private Method areNotificationsEnabledForPackageMethod;\n private Method unlockAllNotificationChannelsMethod;\n private Method unlockNotificationChannelMethod;\n private Method updateNotificationChannelGroupForPackageMethod;\n private Method isImportanceLockedMethod;\n private Method setInterruptionFilterMethod;\n private Method setNotificationPolicyMethod;\n private Method isNotificationPolicyAccessGrantedForPackageMethod;\n private Method setNotificationPolicyAccessGrantedMethod;\n public NotificationManager(IInterface manager){\n this.manager = manager;\n }\n\n private Method getUpdateNotificationChannelForPackageMethod() throws NoSuchMethodException {\n\n if (updateNotificationChannelForPackageMethod == null){\n updateNotificationChannelForPackageMethod = manager.getClass().getMethod(\"updateNotificationChannelForPackage\", String.class , int.class , NotificationChannel.class);\n }\n return updateNotificationChannelForPackageMethod;\n }\n\n private Method getSetNotificationsEnabledForPackageMethod() throws NoSuchMethodException {\n if (setNotificationsEnabledForPackageMethod == null){\n setNotificationsEnabledForPackageMethod = manager.getClass().getMethod(\"setNotificationsEnabledForPackage\", String.class, int.class, boolean.class);\n }\n return setNotificationsEnabledForPackageMethod;\n }\n\n private Method getAreNotificationsEnabledForPackageMethod() throws NoSuchMethodException {\n if (areNotificationsEnabledForPackageMethod == null){\n areNotificationsEnabledForPackageMethod = manager.getClass().getMethod(\"areNotificationsEnabledForPackage\", String.class, int.class);\n }\n return areNotificationsEnabledForPackageMethod;\n }\n\n private Method getUpdateNotificationChannelGroupForPackageMethod() throws NoSuchMethodException {\n if (updateNotificationChannelGroupForPackageMethod == null){\n updateNotificationChannelGroupForPackageMethod = manager.getClass().getMethod(\"updateNotificationChannelGroupForPackage\", String.class, int.class, NotificationChannelGroup.class);\n }\n return updateNotificationChannelGroupForPackageMethod;\n }\n\n private Method getUnlockAllNotificationChannelsMethod() throws NoSuchMethodException {\n if (unlockAllNotificationChannelsMethod == null){\n unlockAllNotificationChannelsMethod = manager.getClass().getMethod(\"unlockAllNotificationChannels\");\n }\n return unlockAllNotificationChannelsMethod;\n }\n\n private Method getIsImportanceLockedMethod() throws NoSuchMethodException {\n if (isImportanceLockedMethod == null){\n isImportanceLockedMethod = manager.getClass().getMethod(\"isImportanceLocked\", String.class, int.class);\n }\n return isImportanceLockedMethod;\n }\n\n private Method getSetInterruptionFilterMethod() throws NoSuchMethodException {\n if (setInterruptionFilterMethod == null){\n setInterruptionFilterMethod = manager.getClass().getMethod(\"setInterruptionFilter\", String.class, int.class);\n }\n return setInterruptionFilterMethod;\n }\n\n private Method getUnlockNotificationChannelMethod() throws NoSuchMethodException {\n if (unlockNotificationChannelMethod == null) unlockNotificationChannelMethod = manager.getClass().getMethod(\"unlockNotificationChannel\", String.class , int.class, String.class);\n return unlockNotificationChannelMethod;\n }\n\n private Method getSetNotificationPolicyMethod() throws NoSuchMethodException {\n if (setNotificationPolicyMethod == null){\n setNotificationPolicyMethod = manager.getClass().getMethod(\"setNotificationPolicy\", System.class, android.app.NotificationManager.Policy.class);\n }\n return setNotificationPolicyMethod;\n }\n\n private Method getIsNotificationPolicyAccessGrantedForPackageMethod() throws NoSuchMethodException {\n if (isNotificationPolicyAccessGrantedForPackageMethod == null){\n isNotificationPolicyAccessGrantedForPackageMethod = manager.getClass().getMethod(\"isNotificationPolicyAccessGrantedForPackage\",String.class);\n }\n return isNotificationPolicyAccessGrantedForPackageMethod;\n }\n\n private Method getSetNotificationPolicyAccessGrantedMethod() throws NoSuchMethodException {\n if (setNotificationPolicyAccessGrantedMethod == null){\n setNotificationPolicyAccessGrantedMethod = manager.getClass().getMethod(\"setNotificationPolicyAccessGranted\", String.class, boolean.class);\n }\n return setNotificationPolicyAccessGrantedMethod;\n }\n\n public List<NotificationChannel> getNotificationChannelsForPackage(String pkg, boolean includeDeleted){\n\n try {\n\n Object parceledListSlice = manager.getClass().getMethod(\"getNotificationChannelsForPackage\",String.class , int.class, boolean.class).invoke(manager ,pkg, ServiceManager.getPackageManager().getApplicationInfo(pkg).uid,includeDeleted);\n\n // 通过反射调用 getList 方法\n assert parceledListSlice != null;\n Method getListMethod = parceledListSlice.getClass().getDeclaredMethod(\"getList\");\n getListMethod.setAccessible(true);\n\n return (List<NotificationChannel>) getListMethod.invoke(parceledListSlice);\n\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void updateNotificationChannelForPackage(String pkg, int uid, NotificationChannel channel){\n try {\n Method updateNotificationChannelForPackage = getUpdateNotificationChannelForPackageMethod();\n updateNotificationChannelForPackage.invoke(manager, pkg, uid, channel);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled){\n try {\n getSetNotificationsEnabledForPackageMethod().invoke(manager, pkg, uid, enabled);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean areNotificationsEnabledForPackage(String pkg, int uid){\n try {\n return (boolean) getAreNotificationsEnabledForPackageMethod().invoke(manager, pkg, uid);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n public void setNotificationPolicy(String pkg, android.app.NotificationManager.Policy policy){\n try {\n getSetNotificationPolicyMethod().invoke(manager, pkg, policy);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean isNotificationPolicyAccessGrantedForPackage(String pkg){\n try {\n return (boolean) getIsNotificationPolicyAccessGrantedForPackageMethod().invoke(manager, pkg);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n public void setNotificationPolicyAccessGranted(String pkg, boolean granted){\n try {\n getSetNotificationPolicyAccessGrantedMethod().invoke(manager, pkg, granted);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void setInterruptionFilter(String pkg, int interruptionFilter){\n try {\n getSetInterruptionFilterMethod().invoke(manager, pkg, interruptionFilter);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void unlockAllNotificationChannels(){\n try {\n getUnlockAllNotificationChannelsMethod().invoke(manager);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void updateNotificationChannelGroupForPackage(String pkg, int uid, NotificationChannelGroup group){\n try {\n getUpdateNotificationChannelGroupForPackageMethod().invoke(manager, pkg, uid, group);\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public boolean isImportanceLocked(String pkg, int uid){\n try {\n return (boolean) getIsImportanceLockedMethod().invoke(manager, pkg, uid);\n }catch (Throwable e){\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n\n public void setImportanceLockedByCriticalDeviceFunction(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getMethod(\"setImportanceLockedByCriticalDeviceFunction\", boolean.class).invoke(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n\n public boolean ismImportanceLockedDefaultApp(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mImportanceLockedDefaultApp\").get(channel);\n }catch (Throwable e){\n return false;\n }\n }\n\n public boolean getmImportanceLockedDefaultApp(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mImportanceLockedDefaultApp\").get(channel);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public void setmImportanceLockedDefaultApp(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getField(\"mImportanceLockedDefaultApp\").set(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public boolean ismBlockableSystem(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getField(\"mBlockableSystem\").get(channel);\n }catch (Throwable e){\n return false;\n }\n }\n\n public boolean getmBlockableSystem(NotificationChannel channel){\n try {\n for (Field field: channel.getClass().getFields()){\n if (field.getName().equals(\"mBlockableSystem\")){\n return (boolean) channel.getClass().getField(\"mBlockableSystem\").get(channel);\n }\n }\n return false;\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n public void setmBlockableSystem(NotificationChannel channel, boolean locked){\n try {\n channel.getClass().getField(\"mBlockableSystem\").set(channel, locked);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n\n public void unlockFields(NotificationChannel channel){\n try {\n if (unlockFieldsMethod == null){\n unlockFieldsMethod = channel.getClass().getMethod(\"unlockFields\", int.class);\n }\n unlockFieldsMethod.invoke(channel, getUserLockedFields(channel));\n }catch (Throwable e){\n e.printStackTrace();\n }\n }\n\n public void setBlockable(NotificationChannel channel ,boolean blockable){\n try {\n channel.getClass().getMethod(\"setBlockable\",boolean.class).invoke(channel, blockable);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n e.printStackTrace();\n }\n }\n\n public boolean isBlockable(NotificationChannel channel){\n try {\n return (boolean) channel.getClass().getMethod(\"isBlockable\").invoke(channel);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public int getUserLockedFields(NotificationChannel channel){\n try {\n return (int) channel.getClass().getMethod(\"getUserLockedFields\").invoke(channel);\n } catch (IllegalAccessException | InvocationTargetException |\n NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void unlockNotificationChannel(String pkg, int uid, String channelId){\n try {\n getUnlockNotificationChannelMethod().invoke(manager, pkg , uid , channelId);\n }catch (Throwable e){\n throw new SecurityException(e);\n }\n }\n\n}" }, { "identifier": "PackageManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/PackageManager.java", "snippet": "public class PackageManager {\n\n private final IInterface manager;\n private Method getInstalledApplicationsMethod;\n private Method getApplicationInfoMethod;\n private Method getNameForUidMethod;\n private Method checkPermissionMethod;\n private Method getPackageInfoMethod;\n private Method isPackageAvailableMethod;\n private Method getHomeActivitiesMethod;\n private Method getChangedPackagesMethod;\n private Method queryIntentActivitiesMethod;\n\n public PackageManager(IInterface manager){\n this.manager = manager;\n }\n\n private Method getInstalledApplicationsMethod() throws NoSuchMethodException {\n if (getInstalledApplicationsMethod == null){\n getInstalledApplicationsMethod = manager.getClass().getMethod(\"getInstalledApplications\", (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getInstalledApplicationsMethod;\n }\n\n private Method getApplicationInfoMethod() throws NoSuchMethodException {\n if (getApplicationInfoMethod == null){\n getApplicationInfoMethod = manager.getClass().getMethod(\"getApplicationInfo\", String.class, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getApplicationInfoMethod;\n }\n\n private Method getGetPackageInfoMethod() throws NoSuchMethodException {\n if (getPackageInfoMethod == null){\n getPackageInfoMethod = manager.getClass().getMethod(\"getPackageInfo\", String.class, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) ? long.class : int.class , int.class);\n }\n return getPackageInfoMethod;\n }\n\n private Method getNameForUidMethod() throws NoSuchMethodException {\n if (getNameForUidMethod == null){\n getNameForUidMethod = manager.getClass().getMethod(\"getNameForUid\", int.class);\n }\n return getNameForUidMethod;\n }\n\n private Method getCheckPermissionMethod() throws NoSuchMethodException {\n if (checkPermissionMethod == null){\n checkPermissionMethod = manager.getClass().getMethod(\"checkPermission\",String.class, String.class, int.class);\n }\n return checkPermissionMethod;\n }\n\n private Method getIsPackageAvailableMethod() throws NoSuchMethodException {\n if (isPackageAvailableMethod == null){\n isPackageAvailableMethod = manager.getClass().getMethod(\"isPackageAvailable\", String.class, int.class);\n }\n return isPackageAvailableMethod;\n }\n\n private Method getQueryIntentActivitiesMethod() throws NoSuchMethodException {\n if (queryIntentActivitiesMethod == null) queryIntentActivitiesMethod = manager.getClass().getMethod(\"queryIntentActivities\", Intent.class, String.class, long.class, int.class);\n return queryIntentActivitiesMethod;\n }\n private Method getGetHomeActivitiesMethod() throws NoSuchMethodException {\n if (getHomeActivitiesMethod == null){\n getHomeActivitiesMethod = manager.getClass().getMethod(\"getHomeActivities\", List.class);\n }\n return getHomeActivitiesMethod;\n }\n\n private Method getGetChangedPackagesMethod() throws NoSuchMethodException {\n if (getChangedPackagesMethod == null){\n getChangedPackagesMethod = manager.getClass().getMethod(\"getChangedPackages\", int.class, int.class);\n }\n return getChangedPackagesMethod;\n }\n\n public ComponentName getHomeActivities(List<ResolveInfo> outHomeCandidates){\n try {\n return (ComponentName) getGetHomeActivitiesMethod().invoke(manager, outHomeCandidates);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public ApplicationInfo getApplicationInfo(String packageName){\n try {\n return (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, long flags){\n try {\n Object obj = getQueryIntentActivitiesMethod().invoke(manager, intent, resolvedType, flags, UserManager.myUserId());\n return (List<ResolveInfo>) obj.getClass().getMethod(\"getList\").invoke(obj);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public static String getApkPath(PackageManager packageManager, String packageName) {\n //获取applicationInfo\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName);\n return applicationInfo.sourceDir;\n }\n public ArraySet<String> getInstalledApplications() {\n\n ArraySet<String> a = new ArraySet<>();\n\n try {\n Object parceledListSlice = getInstalledApplicationsMethod().invoke(manager, 0, UserManager.myUserId());\n // 通过反射调用 getList 方法\n Method getListMethod = parceledListSlice.getClass().getDeclaredMethod(\"getList\");\n getListMethod.setAccessible(true);\n for (ApplicationInfo applicationInfo : (List<ApplicationInfo>) getListMethod.invoke(parceledListSlice)){\n a.add(applicationInfo.packageName);\n }\n return a;\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public List<String> getAllPackages(){\n try {\n return (List<String>) manager.getClass().getMethod(\"getAllPackages\").invoke(manager);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public String getAppNameForPackageName(Context context ,String packageName) {\n try{\n ApplicationInfo appInfo = (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n return (String) appInfo.loadLabel(context.getPackageManager());\n } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public ChangedPackages getChangedPackages(){\n try {\n return (ChangedPackages) getGetChangedPackagesMethod().invoke(manager, 0, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n\n public String getNameForUid(int uid){\n try {\n Method getNameForUid = getNameForUidMethod();\n return (String) getNameForUid.invoke(manager, uid);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public PackageInfo getPackageInfo(String packageName, Object flag){\n try {\n return (PackageInfo) getGetPackageInfoMethod().invoke(manager, packageName, flag, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean isPackageAvailable(String packageName){\n try {\n return (boolean) getIsPackageAvailableMethod().invoke(manager, packageName, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public int checkPermission(String permName, String pkgName){\n try {\n Log.i(\"PackageManager\",\"checkPermission \"+ permName +\" call from pkgName \"+pkgName);\n Method checkPermission = getCheckPermissionMethod();\n return (int) checkPermission.invoke(manager, permName, pkgName, UserManager.myUserId());\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean isSystemApp(String packageName) {\n\n try {\n ApplicationInfo appInfo = (ApplicationInfo) getApplicationInfoMethod().invoke(manager, packageName , 0 , UserManager.myUserId());\n return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public boolean getBlockUninstallForUserReflect(String packageName){\n try {\n // 调用 getBlockUninstallForUser 方法并获取返回值\n return (boolean) manager.getClass().getMethod(\"getBlockUninstallForUser\", String.class, int.class).invoke(manager, packageName, UserManager.myUserId());\n } catch (Exception e2) {\n // 捕获异常并抛出运行时异常\n throw new RuntimeException(e2);\n }\n }\n\n private String getTag(){\n return PackageManager.class.getSimpleName();\n }\n}" }, { "identifier": "ServiceManager", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/ServiceManager.java", "snippet": "public class ServiceManager {\n\n private static ActivityManager activityManager;\n private static PackageManager packageManager;\n private static UserManager userManager;\n private static NotificationManager notificationManager;\n\n private ServiceManager() {\n System.out.println(this.getClass().getSimpleName()+\" 执行私有构造方法\");\n }\n private static IInterface getService(String service, String type){\n try {\n IBinder binder = getIBinderService(service);\n Class<?> clz = Class.forName(type + \"$Stub\");\n Method asInterfaceMethod = clz.getMethod(\"asInterface\", IBinder.class);\n return (IInterface) asInterfaceMethod.invoke(null, binder);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static IBinder getIBinderService(String service){\n try {\n @SuppressLint({\"DiscouragedPrivateApi\", \"PrivateApi\"})\n Method getServiceMethod = Class.forName(\"android.os.ServiceManager\").getMethod(\"getService\", String.class);\n return (IBinder) getServiceMethod.invoke(null, service);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static IBinder checkService(String name){\n try {\n @SuppressLint({\"DiscouragedPrivateApi\", \"PrivateApi\"})\n Method getServiceMethod = Class.forName(\"android.os.ServiceManager\").getMethod(\"checkService\", String.class);\n return (IBinder) getServiceMethod.invoke(null, name);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static String[] listServices() {\n try {\n return (String[]) Class.forName(\"android.os.ServiceManager\").getMethod(\"listServices\").invoke(null);\n } catch (NullPointerException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static ActivityManager getActivityManager(){\n if (activityManager == null) {\n activityManager = new ActivityManager(getService(\"activity\", \"android.app.IActivityManager\"));\n }\n return activityManager;\n }\n\n public static PackageManager getPackageManager(){\n if (packageManager == null){\n packageManager = new PackageManager(getService(\"package\", \"android.content.pm.IPackageManager\"));\n }\n return packageManager;\n }\n\n public static UserManager getUserManager(){\n if (userManager == null){\n userManager = new UserManager(getService(\"user\",\"android.os.IUserManager\"));\n }\n return userManager;\n }\n\n public static NotificationManager getNotificationManager(){\n if (notificationManager == null){\n notificationManager = new NotificationManager(getService(\"notification\",\"android.app.INotificationManager\"));\n }\n\n return notificationManager;\n }\n}" }, { "identifier": "ShellUtils", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/ShellUtils.java", "snippet": "public class ShellUtils {\n private static final String TAG = \"ShellUtils\";\n private ShellUtils() {\n }\n public static String execCommand(String command, boolean isRoot, boolean isSystem) {\n try {\n Process process = isRoot ? (isSystem ? Runtime.getRuntime().exec(new String[]{\"su\",\"system\"}) : Runtime.getRuntime().exec(new String[]{\"su\"})) : Runtime.getRuntime().exec(new String[]{\"sh\"});\n\n OutputStream outputStream = process.getOutputStream();\n outputStream.write((command + \"\\n\").getBytes());\n outputStream.flush();\n outputStream.close();\n\n StringBuilder output = new StringBuilder();\n StringBuilder error = new StringBuilder();\n\n Thread outputThread = new Thread(() -> {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {\n String line;\n while ((line = reader.readLine()) != null) {\n output.append(line).append(\"\\n\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n\n Thread errorThread = new Thread(() -> {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {\n String line;\n while ((line = reader.readLine()) != null) {\n error.append(line).append(\"\\n\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n });\n\n outputThread.start();\n errorThread.start();\n\n int exitCode = process.waitFor();\n outputThread.join();\n errorThread.join();\n\n if (exitCode != 0) {\n return error.toString();\n }\n\n return output.toString();\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n throw new RuntimeException(e);\n }\n }\n\n}" }, { "identifier": "SystemPropertiesUtils", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/SystemPropertiesUtils.java", "snippet": "public class SystemPropertiesUtils {\n private static Class<?> clazz;\n private static Method getMethod;\n private static Method getBooleanMethod;\n private SystemPropertiesUtils(){\n\n }\n\n private static Class<?> getClazz() throws ClassNotFoundException {\n if (clazz == null) clazz = Class.forName(\"android.os.SystemProperties\");\n return clazz;\n }\n\n private static Method getGetMethod() throws ClassNotFoundException, NoSuchMethodException {\n if (getMethod == null) getMethod = getClazz().getMethod(\"get\", String.class);\n return getMethod;\n }\n\n private static Method getGetBooleanMethod() throws ClassNotFoundException, NoSuchMethodException {\n if (getBooleanMethod == null) getBooleanMethod = getClazz().getMethod(\"getBoolean\", String.class, boolean.class);\n return getBooleanMethod;\n }\n\n public static String get(String key){\n try {\n return (String) getGetMethod().invoke(null, key);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n public static boolean getBoolean(String key, boolean def){\n try {\n return (boolean) getGetBooleanMethod().invoke(null, key, def);\n }catch (Throwable e){\n throw new RuntimeException(e);\n }\n }\n\n}" } ]
import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Looper; import android.util.Log; import com.ma.bitchgiveitback.utils.MultiJarClassLoader; import com.ma.bitchgiveitback.utils.Netd; import com.ma.bitchgiveitback.utils.NotificationManager; import com.ma.bitchgiveitback.utils.PackageManager; import com.ma.bitchgiveitback.utils.ServiceManager; import com.ma.bitchgiveitback.utils.ShellUtils; import com.ma.bitchgiveitback.utils.SystemPropertiesUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
6,761
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager(); static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance(); public static void main(String[] args) { if (Looper.getMainLooper() == null) { Looper.prepareMainLooper(); } multiJarClassLoader.addJar("/system/framework/services.jar"); multiJarClassLoader.addJar("/system/system_ext/framework/miui-services.jar"); if (Binder.getCallingUid() == 0 || Binder.getCallingUid() == 1000 || Binder.getCallingUid() == 2000) { if (Binder.getCallingUid() == 2000){ if (packageManager.checkPermission("android.permission.MAINLINE_NETWORK_STACK", packageManager.getNameForUid(Binder.getCallingUid())) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager(); static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance(); public static void main(String[] args) { if (Looper.getMainLooper() == null) { Looper.prepareMainLooper(); } multiJarClassLoader.addJar("/system/framework/services.jar"); multiJarClassLoader.addJar("/system/system_ext/framework/miui-services.jar"); if (Binder.getCallingUid() == 0 || Binder.getCallingUid() == 1000 || Binder.getCallingUid() == 2000) { if (Binder.getCallingUid() == 2000){ if (packageManager.checkPermission("android.permission.MAINLINE_NETWORK_STACK", packageManager.getNameForUid(Binder.getCallingUid())) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
ShellUtils.execCommand("pidof cmdutils_server | xargs kill -9", false, false);
5
2023-11-17 09:58:57+00:00
8k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/mags/SmgExpMag.java
[ { "identifier": "Gunscraft", "path": "src/main/java/sheridan/gunscraft/Gunscraft.java", "snippet": "@Mod(\"gunscraft\")\npublic class Gunscraft {\n\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n\n public static IProxy proxy = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->CommonProxy::new);\n\n public static final String MOD_ID = \"gunscraft\";\n\n public Gunscraft() {\n // Register the setup method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n // Register the enqueueIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);\n // Register the processIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);\n // Register the doClientStuff method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(RenderEvents.class);\n MinecraftForge.EVENT_BUS.register(DebugEvents.class);\n MinecraftForge.EVENT_BUS.register(ControllerEvents.class);\n MinecraftForge.EVENT_BUS.register(ClientTickEvents.class);\n ModItems.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ModContainers.CONTAINERS.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n SoundEvents.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n private void setup(final FMLCommonSetupEvent event) {\n // some preinit code\n LOGGER.info(\"HELLO FROM PREINIT\");\n LOGGER.info(\"DIRT BLOCK >> {}\", Blocks.DIRT.getRegistryName());\n CapabilityHandler.init();\n PacketHandler.register();\n //EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.registerRenderer();\n proxy.commonSetUp(event);\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n // do something that can only be done on the client\n proxy.setUpClient(event);\n }\n\n private void enqueueIMC(final InterModEnqueueEvent event) {\n // some example code to dispatch IMC to another mod\n InterModComms.sendTo(\"gunscraft\", \"helloworld\", () -> {\n LOGGER.info(\"Hello world from the MDK\");\n return \"Hello world\";\n });\n }\n\n private void processIMC(final InterModProcessEvent event) {\n // some example code to receive and process InterModComms from other mods\n LOGGER.info(\"Got IMC {}\", event.getIMCStream().\n map(m -> m.getMessageSupplier().get()).\n collect(Collectors.toList()));\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(FMLServerStartingEvent event) {\n // do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD\n // Event bus for receiving Registry Events)\n @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)\n public static class RegistryEvents {\n @SubscribeEvent\n public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {\n // register a new block here\n LOGGER.info(\"HELLO from Register Block\");\n }\n }\n}" }, { "identifier": "AttachmentRegistry", "path": "src/main/java/sheridan/gunscraft/items/attachments/AttachmentRegistry.java", "snippet": "public class AttachmentRegistry {\n private static Map<Integer, IGenericAttachment> registryMap = new HashMap<>();\n private static Map<String, Integer> IDMap = new HashMap<>();\n private static Map<Integer, IAttachmentModel> modelMap = new HashMap<>();\n private static int ID = -1;\n\n public static void register(int id, IGenericAttachment attachment) {\n if (!registryMap.containsKey(id)) {\n registryMap.put(id, attachment);\n }\n }\n public static int getIdByName(String name) {\n return IDMap.getOrDefault(name, NONE);\n }\n\n public static void registerModel(int id, IAttachmentModel models) {\n if (!modelMap.containsKey(id)) {\n modelMap.put(id, models);\n }\n }\n\n public static IAttachmentModel getModel(int id) {\n return modelMap.getOrDefault(id, null);\n }\n\n public static IGenericAttachment get(int id) {\n return registryMap.getOrDefault(id, null);\n }\n\n public static int getID(String name) {\n synchronized (Object.class) {\n ++ID;\n IDMap.put(name, ID);\n return ID;\n }\n }\n}" }, { "identifier": "GenericAttachment", "path": "src/main/java/sheridan/gunscraft/items/attachments/GenericAttachment.java", "snippet": "public class GenericAttachment extends Item implements IGenericAttachment{\n public static final String MUZZLE = \"muzzle\", GRIP = \"grip\", MAG = \"mag\", SCOPE = \"scope\", STOCK = \"stock\", HAND_GUARD = \"hand_guard\";\n public static final int NONE = -1;\n protected int id;\n protected String type;\n protected String name;\n\n public String getType() {\n return type;\n }\n\n public GenericAttachment(Properties properties, int id, String type, String name) {\n super(properties);\n this.id = id;\n this.type = type;\n this.name = name;\n }\n\n @Override\n public void onAttach(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public void onOff(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public int getId() {\n return this.id;\n }\n\n @Override\n public String getSlotType() {\n return type;\n }\n\n @Override\n public int getID() {\n return id;\n }\n\n @Override\n public String getAttachmentName() {\n return name;\n }\n\n\n @Override\n public void handleParams(GunRenderContext params) {\n switch (this.type) {\n case MUZZLE:\n params.occupiedMuzzle = true;\n break;\n case HAND_GUARD:\n params.occupiedHandGuard = true;\n break;\n case MAG:\n params.occupiedMag = true;\n break;\n case SCOPE:\n params.occupiedIS = true;\n break;\n case STOCK:\n params.occupiedStock = true;\n break;\n case GRIP:\n params.occupiedGrip = true;\n break;\n }\n }\n\n @Override\n public int getItemId() {\n return Item.getIdFromItem(this);\n }\n\n}" }, { "identifier": "GenericMag", "path": "src/main/java/sheridan/gunscraft/items/attachments/GenericMag.java", "snippet": "public class GenericMag extends GenericAttachment{\n public int ammoIncrement;\n\n public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) {\n super(properties, id, type, name);\n this.ammoIncrement = ammoIncrement;\n }\n\n @Override\n public void onAttach(ItemStack stack, IGenericGun gun) {\n gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement);\n }\n\n @Override\n public void onOff(ItemStack stack, IGenericGun gun) {\n gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement);\n int ammoDec = gun.getAmmoLeft(stack);\n ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0;\n gun.setAmmoLeft(stack, ammoDec);\n }\n\n @Override\n public void handleParams(GunRenderContext params) {\n params.occupiedMag = true;\n }\n}" }, { "identifier": "ModelAssaultExpansionMag", "path": "src/main/java/sheridan/gunscraft/model/attachments/mags/ModelAssaultExpansionMag.java", "snippet": "public class ModelAssaultExpansionMag extends EntityModel<Entity> implements IAttachmentModel {\n private final ModelRenderer mag_ar;\n private final ModelRenderer cube_r1;\n private final ModelRenderer cube_r2;\n private final ModelRenderer cube_r3;\n\n\n private final ModelRenderer mag_ak;\n private final ModelRenderer ak_cube_r1;\n private final ModelRenderer ak_cube_r2;\n private final ModelRenderer ak_cube_r3;\n private final ModelRenderer ak_cube_r4;\n private final ModelRenderer ak_cube_r5;\n private final ModelRenderer ak_cube_r6;\n private final ModelRenderer ak_cube_r7;\n private final ModelRenderer ak_cube_r8;\n private final ModelRenderer ak_cube_r9;\n private final ModelRenderer ak_cube_r10;\n\n\n private ArrayList<ResourceLocation> textures;\n\n public ModelAssaultExpansionMag(ArrayList<ResourceLocation> textures) {\n textureWidth = 128;\n textureHeight = 128;\n this.textures = textures;\n mag_ar = new ModelRenderer(this);\n mag_ar.setRotationPoint(3.5F, 24.0F, 0.1F);\n mag_ar.setTextureOffset(44, 22).addBox(-7.0F, 0.0F, 0.0F, 7.0F, 9.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n cube_r1 = new ModelRenderer(this);\n cube_r1.setRotationPoint(-8.0F, 31.6F, -7.8F);\n mag_ar.addChild(cube_r1);\n setRotationAngle(cube_r1, -0.384F, 0.0F, 0.0F);\n cube_r1.setTextureOffset(0, 0).addBox(0.0F, 0.0F, 0.0F, 9.0F, 20.0F, 24.0F, 0.0F, false, true, true, true, true, true, true);\n\n cube_r2 = new ModelRenderer(this);\n cube_r2.setRotationPoint(0.0F, 9.0F, 22.0F);\n mag_ar.addChild(cube_r2);\n setRotationAngle(cube_r2, -0.1571F, 0.0F, 0.0F);\n cube_r2.setTextureOffset(58, 53).addBox(-7.0F, 0.0F, -22.0F, 7.0F, 8.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n cube_r3 = new ModelRenderer(this);\n cube_r3.setRotationPoint(0.0F, 16.9474F, 20.7345F);\n mag_ar.addChild(cube_r3);\n setRotationAngle(cube_r3, -0.2967F, 0.0F, 0.0F);\n cube_r3.setTextureOffset(0, 44).addBox(-7.0F, -0.048F, -22.0F, 7.0F, 25.0F, 22.0F, 0.0F, false, true, true, false, false, true, true);\n\n\n mag_ak = new ModelRenderer(this);\n mag_ak.setRotationPoint(0.0F, 24.0F, 5.0F);\n\n\n ak_cube_r1 = new ModelRenderer(this);\n ak_cube_r1.setRotationPoint(1.9F, 56.1423F, -19.2898F);\n mag_ak.addChild(ak_cube_r1);\n setRotationAngle(ak_cube_r1, -1.0472F, 0.0F, 0.0F);\n ak_cube_r1.setTextureOffset(0, 77).addBox(-5.0F, 0.5F, -16.2F, 6.0F, 19.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r2 = new ModelRenderer(this);\n ak_cube_r2.setRotationPoint(2.9F, 60.6423F, -16.3898F);\n mag_ak.addChild(ak_cube_r2);\n setRotationAngle(ak_cube_r2, -1.0472F, 0.0F, 0.0F);\n ak_cube_r2.setTextureOffset(0, 0).addBox(-7.0F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r3 = new ModelRenderer(this);\n ak_cube_r3.setRotationPoint(1.9F, 43.2865F, -3.9689F);\n mag_ak.addChild(ak_cube_r3);\n setRotationAngle(ak_cube_r3, -0.829F, 0.0F, 0.0F);\n ak_cube_r3.setTextureOffset(83, 29).addBox(-5.0F, 1.1F, -16.8F, 6.0F, 19.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r4 = new ModelRenderer(this);\n ak_cube_r4.setRotationPoint(1.9F, 28.1035F, 5.8027F);\n mag_ak.addChild(ak_cube_r4);\n setRotationAngle(ak_cube_r4, -0.5672F, 0.0F, 0.0F);\n ak_cube_r4.setTextureOffset(26, 87).addBox(-5.0F, 1.0F, -17.0F, 6.0F, 15.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r5 = new ModelRenderer(this);\n ak_cube_r5.setRotationPoint(1.9F, 3.1172F, -3.8964F);\n mag_ak.addChild(ak_cube_r5);\n setRotationAngle(ak_cube_r5, -0.3054F, 0.0F, 0.0F);\n ak_cube_r5.setTextureOffset(93, 87).addBox(-5.0F, 5.0F, 0.0F, 6.0F, 14.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r6 = new ModelRenderer(this);\n ak_cube_r6.setRotationPoint(1.9F, -1.4F, -5.0F);\n mag_ak.addChild(ak_cube_r6);\n setRotationAngle(ak_cube_r6, -0.0436F, 0.0F, 0.0F);\n ak_cube_r6.setTextureOffset(33, 0).addBox(-5.0F, 1.0F, 0.0F, 6.0F, 10.0F, 7.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r7 = new ModelRenderer(this);\n ak_cube_r7.setRotationPoint(2.9F, 47.7865F, -1.0689F);\n mag_ak.addChild(ak_cube_r7);\n setRotationAngle(ak_cube_r7, -0.8727F, 0.0F, 0.0F);\n ak_cube_r7.setTextureOffset(33, 20).addBox(-7.0F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r8 = new ModelRenderer(this);\n ak_cube_r8.setRotationPoint(3.0F, 31.4035F, 10.4027F);\n mag_ak.addChild(ak_cube_r8);\n setRotationAngle(ak_cube_r8, -0.6109F, 0.0F, 0.0F);\n ak_cube_r8.setTextureOffset(0, 40).addBox(-7.1F, 0.0F, -17.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r9 = new ModelRenderer(this);\n ak_cube_r9.setRotationPoint(2.9F, 7.2172F, 0.2036F);\n mag_ak.addChild(ak_cube_r9);\n setRotationAngle(ak_cube_r9, -0.3054F, 0.0F, 0.0F);\n ak_cube_r9.setTextureOffset(50, 57).addBox(-7.0F, 0.0F, 0.0F, 8.0F, 20.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n\n ak_cube_r10 = new ModelRenderer(this);\n ak_cube_r10.setRotationPoint(2.9F, -1.4F, 0.0F);\n mag_ak.addChild(ak_cube_r10);\n setRotationAngle(ak_cube_r10, -0.0436F, 0.0F, 0.0F);\n ak_cube_r10.setTextureOffset(66, 0).addBox(-7.0F, 1.0F, 0.0F, 8.0F, 12.0F, 17.0F, 0.0F, false, true, true, true, true, true, true);\n }\n\n @Override\n public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n //previously the render function, render code was moved to a method below\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 mag_ar.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 @Override\n public void render(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType, int packedLight, int packedOverlay, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode, IGenericGun gun) {\n IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();\n if (gun.getSeriesName().equals(\"ar\")) {\n IVertexBuilder builder = buffer.getBuffer(RenderType.getArmorCutoutNoCull(textures.get(0)));\n mag_ar.render(matrixStack, builder, packedLight, packedOverlay, 1, 1, 1, 1);\n } else if (gun.getSeriesName().equals(\"ak\")) {\n IVertexBuilder builder = buffer.getBuffer(RenderType.getArmorCutoutNoCull(textures.get(1)));\n mag_ak.render(matrixStack, builder, packedLight, packedOverlay, 1, 1, 1, 1);\n }\n buffer.finish();\n }\n}" }, { "identifier": "ModelSmgExpMag", "path": "src/main/java/sheridan/gunscraft/model/attachments/mags/smgExpMag/ModelSmgExpMag.java", "snippet": "public class ModelSmgExpMag extends EntityModel<Entity> implements IAttachmentModel {\n private ModelMp5ExpMag mp5StyleMag;\n private ArrayList<ResourceLocation> textures;\n\n public ModelSmgExpMag(ArrayList<ResourceLocation> textures) {\n mp5StyleMag = new ModelMp5ExpMag();\n this.textures = textures;\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 @Override\n public void setRotationAngles(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {\n\n }\n\n\n @Override\n public void render(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType, int packedLight, int packedOverlay, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode, IGenericGun gun) {\n IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();\n if (gun.getSeriesName().equals(\"mp5\")) {\n mp5StyleMag.render(matrixStack, buffer.getBuffer(RenderType.getArmorCutoutNoCull(textures.get(0))), packedLight, packedOverlay, 1,1,1,1);\n }\n buffer.finish();\n }\n\n @Override\n public void render(MatrixStack matrixStackIn, IVertexBuilder bufferIn, int packedLightIn, int packedOverlayIn, float red, float green, float blue, float alpha) {\n\n }\n}" }, { "identifier": "CreativeTabs", "path": "src/main/java/sheridan/gunscraft/tabs/CreativeTabs.java", "snippet": "public class CreativeTabs {\n public static final ItemGroup REGULAR_GUNS = new ItemGroup(\"guns\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack((IItemProvider) ModItems.PISTOL_9_MM.get());\n }\n };\n public static final ItemGroup REGULAR_ATTACHMENTS = new ItemGroup(\"attachments\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack((IItemProvider) ModItems.AR_EXPANSION_MAG.get());\n }\n };\n}" } ]
import net.minecraft.util.ResourceLocation; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.items.attachments.AttachmentRegistry; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.GenericMag; import sheridan.gunscraft.model.attachments.mags.ModelAssaultExpansionMag; import sheridan.gunscraft.model.attachments.mags.smgExpMag.ModelSmgExpMag; import sheridan.gunscraft.tabs.CreativeTabs; import java.util.ArrayList; import java.util.Arrays;
5,547
package sheridan.gunscraft.items.attachments.mags; public class SmgExpMag extends GenericMag { public SmgExpMag() { super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("smg_expansion_mag"), GenericAttachment.MAG, "smg_expansion_mag", 20); AttachmentRegistry.register(this.id, this); ArrayList<ResourceLocation> textures = new ArrayList<>(Arrays.asList(new ResourceLocation(Gunscraft.MOD_ID, "textures/attachments/mag/smg_exp_mag/smg_exp_mag_mp5.png")));
package sheridan.gunscraft.items.attachments.mags; public class SmgExpMag extends GenericMag { public SmgExpMag() { super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("smg_expansion_mag"), GenericAttachment.MAG, "smg_expansion_mag", 20); AttachmentRegistry.register(this.id, this); ArrayList<ResourceLocation> textures = new ArrayList<>(Arrays.asList(new ResourceLocation(Gunscraft.MOD_ID, "textures/attachments/mag/smg_exp_mag/smg_exp_mag_mp5.png")));
AttachmentRegistry.registerModel(this.id, new ModelSmgExpMag(textures));
5
2023-11-14 14:00:55+00:00
8k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/DriverControls.java
[ { "identifier": "Loop", "path": "src/main/java/com/team5419/frc2023/loops/Loop.java", "snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}" }, { "identifier": "Arm", "path": "src/main/java/com/team5419/frc2023/subsystems/Arm.java", "snippet": "public class Arm extends ServoMotorSubsystem {\n private static Arm mInstance;\n public static Arm getInstance(){\n if (mInstance == null) {\n mInstance = new Arm(kArmConstants);\n }\n return mInstance;\n }\n\n private static final ServoMotorSubsystemConstants kArmConstants = Constants.Arm.kArmServoConstants;\n\n protected Arm(ServoMotorSubsystemConstants constants) {\n super(constants);\n setNeutralBrake(true);\n zeroSensors();\n }\n\n private void setNeutralBrake(boolean isEnabled) {\n NeutralMode mode = isEnabled ? NeutralMode.Brake : NeutralMode.Coast;\n mMaster.setNeutralMode(mode);\n }\n\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n\n }\n\n @Override\n public void onLoop(double timestamp) {\n\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n setNeutralBrake(true);\n }\n });\n }\n\n public Request angleRequest(double angle) {\n return new Request() {\n @Override\n public void act() {\n setSetpointMotionMagic(angle);\n }\n\n @Override\n public boolean isFinished() {\n return Util.epsilonEquals(mPeriodicIO.position_units, angle, Constants.Arm.kAngleTolerance);\n }\n\n };\n }\n\n\n}" }, { "identifier": "Intake", "path": "src/main/java/com/team5419/frc2023/subsystems/Intake.java", "snippet": "public class Intake extends Subsystem {\n\n public static Intake mInstance = null;\n\n public static Intake getInstance() {\n if (mInstance == null) {\n return mInstance = new Intake();\n }\n return mInstance;\n }\n\n protected final TalonFX motor = new TalonFX(Ports.kIntake);\n\n public Intake() {\n\n }\n\n public enum State {\n IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0);\n\n public final double voltage;\n State (double voltage) {\n this.voltage = voltage;\n }\n }\n\n private State currentState = State.IDLE;\n public State getState() {\n return currentState;\n }\n\n public void setState(State wantedState) {\n if (currentState != wantedState) {\n currentState = wantedState;\n }\n }\n\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n stop();\n }\n\n @Override\n public void onLoop(double timestamp) {\n mPeriodicIO.demand = currentState.voltage;\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n }\n });\n }\n\n @Override\n public void stop() {\n motor.stopMotor();\n setState(State.IDLE);\n }\n\n public void setOpenLoop(double voltage) {\n mPeriodicIO.demand = voltage;\n }\n\n public Request stateRequest(State requestedState) {\n return new Request() {\n @Override\n public void act() {\n setState(requestedState);\n }\n\n @Override\n public boolean isFinished() {\n return mPeriodicIO.demand == requestedState.voltage;\n }\n };\n }\n\n public static PeriodicIO mPeriodicIO;\n public static class PeriodicIO {\n // Inputs\n private double timestamp;\n private double voltage;\n private double current;\n\n // Outputs\n private double demand;\n }\n\n @Override\n public void writePeriodicOutputs() {\n motor.setVoltage(mPeriodicIO.demand);\n }\n\n @Override\n public void readPeriodicInputs() {\n mPeriodicIO.timestamp = Timer.getFPGATimestamp();\n mPeriodicIO.voltage = motor.getSupplyVoltage().getValue();\n mPeriodicIO.current = motor.getSupplyCurrent().getValue();\n }\n\n @Override\n public void outputTelemetry() {\n SmartDashboard.putNumber(\"Intake Demand\", mPeriodicIO.demand);\n SmartDashboard.putNumber(\"Intake Supplied Volts\", mPeriodicIO.voltage);\n SmartDashboard.putNumber(\"Intake Current\", mPeriodicIO.current);\n SmartDashboard.putString(\"Intake State\", currentState.toString());\n }\n}" }, { "identifier": "Superstructure", "path": "src/main/java/com/team5419/frc2023/subsystems/Superstructure.java", "snippet": "public class Superstructure extends Subsystem {\n private static Superstructure mInstance = null;\n public static Superstructure getInstance() {\n if (mInstance == null) {\n mInstance = new Superstructure();\n }\n return mInstance;\n }\n\n public final Arm arm = Arm.getInstance();\n public final Wrist wrist = Wrist.getInstance();\n public final Intake intake = Intake.getInstance();\n\n private final RequestExecuter requestExecuter = new RequestExecuter();\n\n public boolean getIsCube() {\n return isCube;\n }\n\n public void setIsCube(boolean isCube) {\n this.isCube = isCube;\n }\n\n public boolean isGroundIntaking() {\n return isGroundIntaking;\n }\n\n public void setGroundIntaking(boolean groundIntaking) {\n isGroundIntaking = groundIntaking;\n }\n\n public synchronized void request(Request r) {\n requestExecuter.request(r);\n }\n\n public boolean areAllRequestsCompleted() {\n return requestExecuter.isFinished();\n }\n\n private final Loop loop = new Loop() {\n @Override\n public void onStart(double timestamp) {\n neutralState();\n }\n\n @Override\n public void onLoop(double timestamp) {\n synchronized (Superstructure.this) {\n requestExecuter.update();\n }\n }\n\n @Override\n public void onStop(double timestamp) {\n\n }\n };\n\n @Override\n public void stop() {\n request(new EmptyRequest());\n }\n\n @Override\n public void registerEnabledLoops(ILooper enabledLooper) {\n enabledLooper.register(loop);\n }\n\n private boolean notifyDrivers = false;\n public boolean needsToNotifyDrivers() {\n if (notifyDrivers) {\n notifyDrivers = false;\n return true;\n }\n return false;\n }\n\n private boolean isCube = false;\n private boolean isGroundIntaking = true;\n\n public void neutralState() {\n request(new ParallelRequest(\n new LambdaRequest(\n () -> {\n arm.stop();\n wrist.stop();\n intake.stop();\n }\n )\n ));\n }\n\n public void stowState() {\n SuperstructureGoal state = SuperstructureGoal.STOW;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist()),\n intake.stateRequest(Intake.State.IDLE)\n ));\n }\n\n public void groundIntakeState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.GROUND_INTAKE_CUBE : SuperstructureGoal.GROUND_INTAKE_CONE;\n request(new SequentialRequest(\n new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ),\n intake.stateRequest(Intake.State.INTAKE)\n ));\n }\n\n public void shelfIntakeState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SHELF_INTAKE_CUBE : SuperstructureGoal.SHELF_INTAKE_CONE;\n request(new SequentialRequest(\n new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ),\n intake.stateRequest(Intake.State.INTAKE)\n ));\n }\n\n public void scoreL1PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L1 : SuperstructureGoal.SCORE_CONE_L1;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n public void scoreL2PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L2 : SuperstructureGoal.SCORE_CONE_L2;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n public void scoreL3PoseState() {\n SuperstructureGoal state = isCube ? SuperstructureGoal.SCORE_CUBE_L3 : SuperstructureGoal.SCORE_CONE_L3;\n request(new ParallelRequest(\n arm.angleRequest(state.getArm()),\n wrist.angleRequest(state.getWrist())\n ));\n }\n\n @Override\n public void outputTelemetry() {\n SmartDashboard.putBoolean(\"Is Cube\", isCube);\n SmartDashboard.putBoolean(\"Is Ground Intaking\", isGroundIntaking);\n }\n\n}" }, { "identifier": "Wrist", "path": "src/main/java/com/team5419/frc2023/subsystems/Wrist.java", "snippet": "public class Wrist extends ServoMotorSubsystem {\n public static Wrist mInstance;\n public static Wrist getInstance() {\n if (mInstance == null) {\n mInstance = new Wrist(kWristConstnats);\n }\n return mInstance;\n }\n public static final ServoMotorSubsystemConstants kWristConstnats = Constants.Wrist.kWristServoConstants;\n protected Wrist(ServoMotorSubsystemConstants constants) {\n super(constants);\n zeroSensors();\n setNeutralBrake(true);\n }\n private void setNeutralBrake(boolean isEnabled) {\n NeutralMode mode = isEnabled ? NeutralMode.Brake : NeutralMode.Coast;\n mMaster.setNeutralMode(mode);\n }\n @Override\n public void registerEnabledLoops(ILooper mEnabledLooper) {\n mEnabledLooper.register(new Loop() {\n @Override\n public void onStart(double timestamp) {\n\n }\n\n @Override\n public void onLoop(double timestamp) {\n\n }\n\n @Override\n public void onStop(double timestamp) {\n stop();\n setNeutralBrake(true);\n }\n });\n }\n\n public Request angleRequest(double angle) {\n return new Request() {\n @Override\n public void act() {\n setSetpointMotionMagic(angle);\n }\n\n @Override\n public boolean isFinished() {\n return Util.epsilonEquals(mPeriodicIO.position_units, angle, Constants.Wrist.kAngleTolerance);\n }\n };\n }\n\n}" }, { "identifier": "Xbox", "path": "src/main/java/com/team5419/lib/io/Xbox.java", "snippet": "public class Xbox extends XboxController{\n private static final double PRESS_THRESHOLD = 0.05;\n private double DEAD_BAND = 0.15;\n private boolean rumbling = false;\n public ButtonCheck aButton, bButton, xButton, yButton, startButton, backButton,\n \tleftBumper, rightBumper, leftCenterClick, rightCenterClick, leftTrigger, \n \trightTrigger, POV0, POV90, POV180, POV270, POV135, POV225;\n public static final int A_BUTTON = 1;\n public static final int B_BUTTON = 2;\n public static final int X_BUTTON = 3;\n public static final int Y_BUTTON = 4;\n public static final int LEFT_BUMPER = 5;\n public static final int RIGHT_BUMPER = 6;\n public static final int BACK_BUTTON = 7;\n public static final int START_BUTTON = 8;\n public static final int LEFT_CENTER_CLICK = 9;\n public static final int RIGHT_CENTER_CLICK = 10;\n public static final int LEFT_TRIGGER = -2;\n public static final int RIGHT_TRIGGER = -3;\n public static final int POV_0 = -4;\n public static final int POV_90 = -5;\n public static final int POV_180 = -6;\n public static final int POV_270 = -7;\n\tpublic static final int POV_135 = -8;\n\tpublic static final int POV_225 = -9;\n \n public void setDeadband(double deadband){\n \tDEAD_BAND = deadband;\n }\n \n public Xbox(int usb) { \n \tsuper(usb);\n \taButton = new ButtonCheck(A_BUTTON);\n bButton = new ButtonCheck(B_BUTTON);\n xButton = new ButtonCheck(X_BUTTON);\n yButton = new ButtonCheck(Y_BUTTON);\n startButton = new ButtonCheck(START_BUTTON);\n backButton = new ButtonCheck(BACK_BUTTON);\n leftBumper = new ButtonCheck(LEFT_BUMPER);\n rightBumper = new ButtonCheck(RIGHT_BUMPER);\n leftCenterClick = new ButtonCheck(LEFT_CENTER_CLICK);\n rightCenterClick = new ButtonCheck(RIGHT_CENTER_CLICK); \n leftTrigger = new ButtonCheck(LEFT_TRIGGER);\n rightTrigger = new ButtonCheck(RIGHT_TRIGGER);\n POV0 = new ButtonCheck(POV_0);\n POV90 = new ButtonCheck(POV_90);\n POV180 = new ButtonCheck(POV_180);\n POV270 = new ButtonCheck(POV_270);\n\t\tPOV135 = new ButtonCheck(POV_135);\n\t\tPOV225 = new ButtonCheck(POV_225);\n }\n \n @Override\n public double getLeftX() {\n\t\treturn Util.deadBand(getRawAxis(0), DEAD_BAND);\n\t}\n\n\t@Override\n\tpublic double getRightX() {\n\t\treturn Util.deadBand(getRawAxis(4), DEAD_BAND);\n\t}\n\n @Override\n public double getLeftY() {\n\t\treturn Util.deadBand(getRawAxis(1), DEAD_BAND);\n\t}\n\n\t@Override\n\tpublic double getRightY() {\n\t\treturn Util.deadBand(getRawAxis(5), DEAD_BAND);\n\t}\n\n @Override\n public double getLeftTriggerAxis() {\n\t\treturn Util.deadBand(getRawAxis(2), PRESS_THRESHOLD);\n\t}\n \n\t@Override\n\tpublic double getRightTriggerAxis() {\n\t\treturn Util.deadBand(getRawAxis(3), PRESS_THRESHOLD);\n\t}\n\n\tpublic Rotation2d getPOVDirection() {\n\t\tSystem.out.println(getPOV());\n\t\treturn Rotation2d.fromDegrees(getPOV());\n\t}\n\n public void rumble(double rumblesPerSecond, double numberOfSeconds){\n \tif(!rumbling){\n \t\tRumbleThread r = new RumbleThread(rumblesPerSecond, numberOfSeconds);\n \t\tr.start();\n \t}\n }\n public boolean isRumbling(){\n \treturn rumbling;\n }\n public class RumbleThread extends Thread{\n \tpublic double rumblesPerSec = 1;\n \tpublic long interval = 500;\n \tpublic double seconds = 1;\n \tpublic double startTime = 0;\n \tpublic RumbleThread(double rumblesPerSecond, double numberOfSeconds){\n \t\trumblesPerSec = rumblesPerSecond;\n \t\tseconds = numberOfSeconds;\n \t\tinterval =(long) (1/(rumblesPerSec*2)*1000);\n \t}\n \tpublic void run(){\n \t\trumbling = true;\n \t\tstartTime = Timer.getFPGATimestamp();\n \t\ttry{\n \t\t\twhile((Timer.getFPGATimestamp() - startTime) < seconds){\n\t\t \t\tsetRumble(RumbleType.kLeftRumble, 1);\n\t\t \t\tsetRumble(RumbleType.kRightRumble, 1);\n\t\t \t\tsleep(interval);\n\t\t \t\tsetRumble(RumbleType.kLeftRumble, 0);\n\t\t \t\tsetRumble(RumbleType.kRightRumble, 0);\n\t\t \t\tsleep(interval);\n \t\t\t}\n \t\t}catch (InterruptedException e) {\n\t\t\t\trumbling = false;\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\trumbling = false;\n \t}\n }\n \n public class ButtonCheck{\n \tboolean buttonCheck = false;\n\t\tboolean buttonActive = false;\n\t\tboolean activationReported = false;\n \tboolean longPressed = false;\n \tboolean longPressActivated = false;\n \tboolean hasBeenPressed = false;\n \tboolean longReleased = false;\n\t\tprivate double buttonStartTime = 0;\n\t\tprivate double longPressDuration = 0.5;\n\t\tpublic void setLongPressDuration(double seconds){\n\t\t\tlongPressDuration = seconds;\n\t\t}\n \tprivate int buttonNumber;\n \t\n \tpublic ButtonCheck(int id){\n \t\tbuttonNumber = id;\n \t}\n \tpublic void update(){\n \t\tif(buttonNumber > 0){\n \t\t\tbuttonCheck = getRawButton(buttonNumber);\n \t\t}else{\n \t\t\tswitch(buttonNumber){\n \t\t\t\tcase LEFT_TRIGGER:\n \t\t\t\t\tbuttonCheck = getLeftTriggerAxis() > 0;\n \t\t\t\t\tbreak;\n \t\t\t\tcase RIGHT_TRIGGER:\n \t\t\t\t\tbuttonCheck = getRightTriggerAxis() > 0;\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_0:\n \t\t\t\t\tbuttonCheck = (getPOV() == 0);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_90:\n \t\t\t\t\tbuttonCheck = (getPOV() == 90);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_180:\n \t\t\t\t\tbuttonCheck = (getPOV() == 180);\n \t\t\t\t\tbreak;\n \t\t\t\tcase POV_270:\n \t\t\t\t\tbuttonCheck = (getPOV() == 270);\n \t\t\t\t\tbreak;\n\t\t\t\t\tcase POV_135:\n\t\t\t\t\t\tbuttonCheck = (getPOV() == 135);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase POV_225:\n\t\t\t\t\t\tbuttonCheck = (getPOV() == 225);\n\t\t\t\t\t\tbreak;\n \t\t\t\tdefault:\n \t\t\t\t\tbuttonCheck = false;\n \t\t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t\tif(buttonCheck){\n\t \t\tif(buttonActive){\n\t \t\t\tif(((Timer.getFPGATimestamp() - buttonStartTime) > longPressDuration) && !longPressActivated){\n\t \t\t\t\tlongPressActivated = true;\n\t\t\t\t\t\tlongPressed = true;\n\t\t\t\t\t\tlongReleased = false;\n\t \t\t\t}\n\t \t\t}else{\n\t\t\t\t\tbuttonActive = true;\n\t\t\t\t\tactivationReported = false;\n\t \t\t\tbuttonStartTime = Timer.getFPGATimestamp();\n\t \t\t}\n \t\t}else{\n \t\t\tif(buttonActive){\n\t\t\t\t\tbuttonActive = false;\n\t\t\t\t\tactivationReported = true;\n \t\t\t\tif(longPressActivated){\n \t\t\t\t\thasBeenPressed = false;\n \t\t\t\t\tlongPressActivated = false;\n \t\t\t\t\tlongPressed = false;\n \t\t\t\t\tlongReleased = true;\n \t\t\t\t}else{\n\t\t\t\t\t\thasBeenPressed = true;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n\t\t}\n\n\t\t/** Returns true once the button is pressed, regardless of\n\t\t * the activation duration. Only returns true one time per\n\t\t * button press, and is reset upon release.\n\t\t */\n\t\tpublic boolean wasActivated(){\n\t\t\tif(buttonActive && !activationReported){\n\t\t\t\tactivationReported = true;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true once the button is released after being\n\t\t * held for 0.5 seconds or less. Only returns true one time\n\t\t * per button press.\n\t\t */\n \tpublic boolean shortReleased(){\n \t\tif(hasBeenPressed){\n \t\t\thasBeenPressed = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true once if the button is pressed for more than 0.5 seconds.\n\t\t * Only true while the button is still depressed; it becomes false once the \n\t\t * button is released.\n\t\t */\n \tpublic boolean longPressed(){\n \t\tif(longPressed){\n \t\t\tlongPressed = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\t\t\n\t\t/** Returns true one time once the button is released after being held for\n\t\t * more than 0.5 seconds.\n\t\t */\n \tpublic boolean longReleased(){\n \t\tif(longReleased){\n \t\t\tlongReleased = false;\n \t\t\treturn true;\n \t\t}\n \t\treturn false;\n\t\t}\n\n\t\t/** Returns true once the button is released, regardless of activation duration. */\n\t\tpublic boolean wasReleased(){\n\t\t\treturn shortReleased() || longReleased();\n\t\t}\n\t\t\n\t\t/** Returns true if the button is currently being pressed. */\n \tpublic boolean isBeingPressed(){\n \t\treturn buttonActive;\n \t}\n }\n public void update(){\n \taButton.update();\n \tbButton.update();\n \txButton.update();\n \tyButton.update();\n \tstartButton.update();\n \tbackButton.update();\n \tleftBumper.update();\n \trightBumper.update();\n \tleftCenterClick.update();\n \trightCenterClick.update();\n \tleftTrigger.update();\n \trightTrigger.update();\n \tPOV0.update();\n \tPOV90.update();\n \tPOV180.update();\n \tPOV270.update();\n }\n}" } ]
import com.team5419.frc2023.loops.Loop; import com.team5419.frc2023.subsystems.Arm; import com.team5419.frc2023.subsystems.Intake; import com.team5419.frc2023.subsystems.Superstructure; import com.team5419.frc2023.subsystems.Wrist; import com.team5419.lib.io.Xbox; import java.util.Arrays;
5,370
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; } Xbox driver, operator; private final Superstructure s = Superstructure.getInstance(); private final SubsystemManager subsystems; public SubsystemManager getSubsystems() {return subsystems;} public DriverControls() { driver = new Xbox(Ports.kDriver); operator = new Xbox(Ports.kOperator); driver.setDeadband(0.0); operator.setDeadband(0.6); Arm arm = Arm.getInstance();
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; } Xbox driver, operator; private final Superstructure s = Superstructure.getInstance(); private final SubsystemManager subsystems; public SubsystemManager getSubsystems() {return subsystems;} public DriverControls() { driver = new Xbox(Ports.kDriver); operator = new Xbox(Ports.kOperator); driver.setDeadband(0.0); operator.setDeadband(0.6); Arm arm = Arm.getInstance();
Wrist wrist = Wrist.getInstance();
4
2023-11-14 06:44:40+00:00
8k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/PostgrestRepositoryGetMockTest.java
[ { "identifier": "Page", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Page.java", "snippet": "public interface Page<T> extends Iterable<T> {\n\n /**\n * Create simple page from items\n *\n * @param items items\n * @param <T> type of items\n * @return one page of items\n */\n @SafeVarargs\n static <T> Page<T> of(T... items) {\n return new PageImpl<>(Arrays.asList(items), Pageable.unPaged(), items.length, 1);\n }\n\n /**\n * Create an empty page\n *\n * @param <T> type of items\n * @return empty page\n */\n static <T> Page<T> empty() {\n return new PageImpl<>(List.of(), Pageable.unPaged(), 0, 0);\n }\n\n /**\n * Get data for a page\n *\n * @return data for a page\n */\n List<T> getData();\n\n /**\n * Get page request infomations\n *\n * @return Pageable information with number of elements, number of the page and sort options\n */\n Pageable getPageable();\n\n /**\n * Get size of page\n *\n * @return size of the data for the current page\n */\n default int size() {\n return getData().size();\n }\n\n /**\n * Get total elements from the datasource\n *\n * @return total elements\n */\n long getTotalElements();\n\n /**\n * Get the total pages\n *\n * @return total pages\n */\n int getTotalPages();\n\n /**\n * Streaming from the page\n *\n * @return stream\n */\n default Stream<T> stream() {\n return getData().stream();\n }\n\n @Override\n default Iterator<T> iterator() {\n return getData().iterator();\n }\n\n /**\n * Convert a page\n *\n * @param converter function that convert type to another\n * @param <U> type of returned object\n * @return page converted\n */\n default <U> Page<U> map(Function<T, U> converter) {\n return new PageImpl<>(stream().map(converter).toList(), getPageable(), getTotalElements(), getTotalPages());\n }\n}" }, { "identifier": "Pageable", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Pageable.java", "snippet": "public interface Pageable {\n\n /**\n * Create a simple pageRequest with size and no declarative sort\n * @param pageSize number of element in one page\n * @return pageable object\n */\n static Pageable ofSize(int pageSize) {\n return ofSize(pageSize, null);\n }\n\n /**\n * Create a simple pageRequest with size and declarative sort\n * @param pageSize number of element in one page\n * @param sort sort information\n * @return pageable object\n */\n static Pageable ofSize(int pageSize, Sort sort) {\n return new PageRequest(0, pageSize, sort);\n }\n\n /**\n * Create an un paged\n * @return pageable object\n */\n static Pageable unPaged() {\n return new PageRequest(0, 0, null);\n }\n\n /**\n * Request page size\n * @return page size\n */\n int getPageSize();\n\n /**\n * Request page number\n * @return page number\n */\n int getPageNumber();\n\n /**\n * Request sort\n * @return sort\n */\n Sort getSort();\n\n /**\n * Transform a Pageable to range representation\n * @return transform a pagination item to range value\n */\n default String toRange() {\n return pageOffset() + \"-\" + pageLimit();\n }\n\n\n /**\n * Calculate the page offset (index of the first item)\n *\n * @return page offset\n */\n default int pageOffset() {\n return getPageNumber() * getPageSize();\n }\n\n /**\n * Calculate the page limit (index of the last item)\n *\n * @return page limit\n */\n default int pageLimit() {\n return pageOffset() + getPageSize() - 1;\n }\n\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": "PostgrestRequestException", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/exceptions/PostgrestRequestException.java", "snippet": "public class PostgrestRequestException extends RuntimeException {\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n */\n public PostgrestRequestException(String resourceName, String message) {\n this(resourceName, message, null);\n }\n\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n * @param cause exception raised\n */\n\n public PostgrestRequestException(String resourceName, String message, Throwable cause) {\n this(\"Error on querying \" + resourceName + \" cause by \" + message, cause);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n */\n public PostgrestRequestException(String message) {\n super(message);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n * @param cause exception raised\n */\n public PostgrestRequestException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "QueryStringUtils", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/utils/QueryStringUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class QueryStringUtils {\n\n /**\n * Allow to transform a Multimap value to queryString\n * @param multimap multimap to transform\n * @return query string representation\n */\n public static String toQueryString(MultiValueMap<String, String> multimap){\n List<String> queryList = new ArrayList<>();\n multimap.forEach((key,values)-> values.forEach(value-> queryList.add(key+\"=\"+value)));\n return String.join(\"&\", queryList);\n }\n\n}" } ]
import fr.ouestfrance.querydsl.postgrest.app.*; import fr.ouestfrance.querydsl.postgrest.model.Page; import fr.ouestfrance.querydsl.postgrest.model.Pageable; import fr.ouestfrance.querydsl.postgrest.model.Sort; import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException; import fr.ouestfrance.querydsl.postgrest.utils.QueryStringUtils; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMapAdapter; import java.time.LocalDate; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when;
3,905
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); assertThrows(PostgrestRequestException.class, () -> repository.findOne(null)); } @Test void shouldFindOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isPresent()); } @Test void shouldFindEmptyOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isEmpty()); } @Test void shouldGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Post one = repository.getOne(null); assertNotNull(one); } @Test void shouldRaiseExceptionOnEmptyGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); assertThrows(PostgrestRequestException.class, () -> repository.getOne(null)); } @Test void shouldSearchWithJoin() { PostRequestWithSize request = new PostRequestWithSize(); request.setSize("25"); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.unPaged()); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue();
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); assertThrows(PostgrestRequestException.class, () -> repository.findOne(null)); } @Test void shouldFindOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isPresent()); } @Test void shouldFindEmptyOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isEmpty()); } @Test void shouldGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Post one = repository.getOne(null); assertNotNull(one); } @Test void shouldRaiseExceptionOnEmptyGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); assertThrows(PostgrestRequestException.class, () -> repository.getOne(null)); } @Test void shouldSearchWithJoin() { PostRequestWithSize request = new PostRequestWithSize(); request.setSize("25"); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.unPaged()); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue();
String queryString = QueryStringUtils.toQueryString(queries);
4
2023-11-14 10:45:54+00:00
8k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/ExportToStorage.java
[ { "identifier": "APKData", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKData.java", "snippet": "public class APKData {\n\n public static List<String> getData(Context context) {\n List<String> mData = new ArrayList<>();\n for (File mFile : getAPKList(context)) {\n if (sCommonUtils.getString(\"apkTypes\", \"apks\", context).equals(\"bundles\")) {\n if (mFile.exists() && mFile.isDirectory() && sFileUtils.exist(new File(mFile.toString(), \"base.apk\"))) {\n if (Common.getSearchWord() == null) {\n mData.add(mFile.getAbsolutePath());\n } else if (Common.isTextMatched(mFile.getAbsolutePath(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n }\n }\n } else {\n if (mFile.exists() && mFile.getName().endsWith(\".apk\")) {\n if (Common.getSearchWord() == null) {\n mData.add(mFile.getAbsolutePath());\n } else if (sAPKUtils.getAPKName(mFile.getAbsolutePath(), context) != null && Common.isTextMatched(Objects.requireNonNull(sAPKUtils.getAPKName(\n mFile.getAbsolutePath(), context)).toString(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n } else if (Common.isTextMatched(mFile.getName(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n }\n }\n }\n }\n Collections.sort(mData);\n if (!sCommonUtils.getBoolean(\"az_order\", true, context)) {\n Collections.reverse(mData);\n }\n return mData;\n }\n\n private static File[] getAPKList(Context context) {\n if (!getExportAPKsPath(context).exists()) {\n sFileUtils.mkdir(getExportAPKsPath(context));\n }\n return getExportAPKsPath(context).listFiles();\n }\n\n public static File getExportAPKsPath(Context context) {\n if (Build.VERSION.SDK_INT < 29 && sCommonUtils.getString(\"exportAPKsPath\", \"externalFiles\", context).equals(\"internalStorage\")) {\n return new File(Environment.getExternalStorageDirectory(), \"/AEE/exportedAPKs\");\n } else {\n return context.getExternalFilesDir(\"\");\n }\n }\n\n public static void signApks(File apk, File signedAPK, Context context) {\n try {\n checkAndPrepareSigningEnvironment(context);\n\n APKSigner apkSigner = new APKSigner(context);\n apkSigner.sign(apk, signedAPK);\n } catch (Exception ignored) {}\n }\n\n private static void checkAndPrepareSigningEnvironment(Context context) {\n File privateKey = new File(getSigningEnvironmentDir(context), \"APKEditor.pk8\");\n\n if (privateKey.exists()) {\n return;\n }\n\n sFileUtils.mkdir(getSigningEnvironmentDir(context));\n\n sFileUtils.copyAssetFile(\"APKEditor.pk8\", privateKey, context);\n }\n\n private static File getSigningEnvironmentDir(Context context) {\n return new File(context.getFilesDir(), \"signing\");\n }\n\n private static String getParentFile(String path) {\n return Objects.requireNonNull(new File(path).getParentFile()).toString();\n }\n\n public static String findPackageName(Context context) {\n String name = null;\n for (String mAPKs : Common.getAPKList()) {\n if (sAPKUtils.getPackageName(mAPKs, context) != null) {\n name = Objects.requireNonNull(sAPKUtils.getPackageName(mAPKs, context));\n }\n }\n return name;\n }\n\n public static List<String> splitApks(String path) {\n List<String> list = new ArrayList<>();\n if (new File(path).getName().equals(\"base.apk\") && new File(path).exists()) {\n for (File mFile : Objects.requireNonNull(new File(getParentFile(path)).listFiles())) {\n if (mFile.getName().endsWith(\".apk\")) {\n list.add(mFile.getAbsolutePath());\n }\n }\n }\n return list;\n }\n\n public static boolean isAppBundle(String path) {\n return splitApks(path).size() > 1;\n }\n\n private static boolean fileToExclude(File file) {\n return file.isDirectory() && file.getName().equals(\".aeeBackup\") || file.isDirectory() && file.getName().equals(\".aeeBuild\")\n || file.isDirectory() && file.getName().equals(\"META-INF\") || file.isDirectory() && file.getName().startsWith(\"classes\")\n && file.getName().endsWith(\".dex\");\n }\n\n public static void shareFile(File file, String type, Context context) {\n Uri uriFile = FileProvider.getUriForFile(context,\n BuildConfig.APPLICATION_ID + \".provider\", file);\n Intent share = new Intent(Intent.ACTION_SEND);\n share.setType(type);\n share.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.share_summary, BuildConfig.VERSION_NAME));\n share.putExtra(Intent.EXTRA_STREAM, uriFile);\n share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n context.startActivity(Intent.createChooser(share, context.getString(R.string.share_with)));\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n public static void prepareSource(File buildDir, File exportPath, File backupPath, Context context) {\n if (!Common.isCancelled()) {\n for (File file : Objects.requireNonNull(exportPath.listFiles())) {\n if (file.isDirectory() && file.getName().startsWith(\"classes\") && file.getName().endsWith(\".dex\")) {\n // Build new dex file if the smali files are modified\n if (APKExplorer.isSmaliEdited(new File(context.getCacheDir(), Common.getAppID() + \"/.aeeBackup/appData\").getAbsolutePath())) {\n Common.setStatus(context.getString(R.string.building, file.getName()));\n new SmaliToDex(file, new File(buildDir, file.getName()), 0, context).execute();\n } else {\n // Otherwise, use the original one from the backup folder\n if (sFileUtils.exist(new File(backupPath, file.getName()))) {\n sFileUtils.copy(new File(backupPath, file.getName()), new File(buildDir, file.getName()));\n }\n }\n } else if (file.isDirectory() && file.getName().equals(\"META-INF\")) {\n if (new File(file, \"services\").exists()) {\n sFileUtils.copyDir(new File(file, \"services\"), new File(buildDir, \"META-INF/services\"));\n }\n } else {\n if (!fileToExclude(file)) {\n if (file.isDirectory()) {\n sFileUtils.copyDir(file, new File(buildDir, file.getName()));\n } else {\n sFileUtils.copy(file, new File(buildDir, file.getName()));\n }\n }\n }\n }\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.Q)\n public static void saveToDownload(File file, String name, Context context) {\n try {\n FileInputStream inputStream = new FileInputStream(file);\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DISPLAY_NAME, name);\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"*/*\");\n values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);\n Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri(\"external\"), values);\n OutputStream outputStream = context.getContentResolver().openOutputStream(uri);\n sFileUtils.copyStream(inputStream, outputStream);\n } catch (IOException ignored) {\n }\n }\n\n}" }, { "identifier": "Common", "path": "app/src/main/java/com/threethan/questpatcher/utils/Common.java", "snippet": "public class Common {\n\n private static AppCompatEditText mSearchWordApks, mSearchWordApps, mSearchWordProjects;\n private static boolean mBuilding = false, mBusy = false, mCancel = false, mFinish = false,\n mPrivateKey = false, mReloading = false, mRSATemplate = false;\n private static List<File> mFile = null;\n private static List<PackageItems> mPackageData = null;\n private static final List<String> mAPKList = new ArrayList<>(), mErrorList = new ArrayList<>();\n private static int mError = 0, mSuccess = 0;\n private static MaterialCardView mSelect;\n private static MaterialTextView mApksTitle, mAppsTitle, mProjectsTitle;\n private static String mAppID, mFilePath = null, mFileToReplace = null, mPackageName = null,\n mPath = null, mSearchWord, mStatus = null;\n\n public static AppCompatEditText getAPKsSearchWord() {\n return mSearchWordApks;\n }\n\n public static AppCompatEditText getAppsSearchWord() {\n return mSearchWordApps;\n }\n\n public static AppCompatEditText getProjectsSearchWord() {\n return mSearchWordProjects;\n }\n\n public static boolean isBuilding() {\n return mBuilding;\n }\n\n public static boolean isBusy() {\n return mBusy;\n }\n\n public static boolean isCancelled() {\n return mCancel;\n }\n\n public static boolean isFinished() {\n return mFinish;\n }\n\n public static boolean isReloading() {\n return mReloading;\n }\n\n public static boolean isTextMatched(String searchText, String searchWord) {\n for (int a = 0; a < searchText.length() - searchWord.length() + 1; a++) {\n if (searchWord.equalsIgnoreCase(searchText.substring(a, a + searchWord.length()))) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean hasPrivateKey() {\n return mPrivateKey;\n }\n\n public static boolean hasRASATemplate() {\n return mRSATemplate;\n }\n\n public static int getError() {\n return mError;\n }\n\n public static int getSuccess() {\n return mSuccess;\n }\n\n public static List<File> getFiles() {\n return mFile;\n }\n\n public static List<PackageItems> getPackageData() {\n return mPackageData;\n }\n\n public static List<String> getAPKList() {\n return mAPKList;\n }\n\n public static List<String> getErrorList() {\n return mErrorList;\n }\n\n public static MaterialCardView getSelectCard() {\n return mSelect;\n }\n\n public static MaterialTextView getAPKsTitle() {\n return mApksTitle;\n }\n\n public static MaterialTextView getAppsTitle() {\n return mAppsTitle;\n }\n\n public static MaterialTextView getProjectsTitle() {\n return mProjectsTitle;\n }\n\n public static String getAppID() {\n return mAppID;\n }\n\n public static String getFilePath() {\n return mFilePath;\n }\n\n public static String getFileToReplace() {\n return mFileToReplace;\n }\n\n public static String getPackageName() {\n return mPackageName;\n }\n\n public static String getPath() {\n return mPath;\n }\n\n public static String getSearchWord() {\n return mSearchWord;\n }\n\n public static String getStatus() {\n return mStatus;\n }\n\n public static void addToFilesList(File file) {\n if (mFile == null) {\n mFile = new ArrayList<>();\n }\n mFile.add(file);\n }\n\n public static void clearFilesList() {\n mFile = null;\n }\n\n public static void initializeAPKsSearchWord(View view, int id) {\n mSearchWordApks = view.findViewById(id);\n }\n\n public static void initializeAPKsTitle(View view, int id) {\n mApksTitle = view.findViewById(id);\n }\n\n public static void initializeAppsSearchWord(View view, int id) {\n mSearchWordApps = view.findViewById(id);\n }\n\n public static void initializeAppsTitle(View view, int id) {\n mAppsTitle = view.findViewById(id);\n }\n\n public static void initializeProjectsSearchWord(View view, int id) {\n mSearchWordProjects = view.findViewById(id);\n }\n\n public static void initializeProjectsTitle(View view, int id) {\n mProjectsTitle = view.findViewById(id);\n }\n\n public static void initializeView(View view, int id) {\n mSelect = view.findViewById(id);\n }\n\n public static void isBuilding(boolean b) {\n mBuilding = b;\n }\n\n public static void isCancelled(boolean b) {\n mCancel = b;\n }\n\n public static void isReloading(boolean b) {\n mReloading = b;\n }\n\n public static void removeFromFilesList(File file) {\n if (mFile == null || mFile.size() == 0) return;\n mFile.remove(file);\n }\n\n public static void setFinishStatus(boolean b) {\n mFinish = b;\n }\n\n public static void setPrivateKeyStatus(boolean b) {\n mPrivateKey = b;\n }\n\n public static void setRSATemplateStatus(boolean b) {\n mRSATemplate = b;\n }\n\n public static void setAppID(String appID) {\n mAppID = appID;\n }\n\n public static void setError(int i) {\n mError = i;\n }\n\n public static void setFilePath(String filePath) {\n mFilePath = filePath;\n }\n\n public static void setFileToReplace(String fileToReplace) {\n mFileToReplace = fileToReplace;\n }\n\n public static void setPackageName(String packageName) {\n mPackageName = packageName;\n }\n\n public static void setPackageData(List<PackageItems> data) {\n mPackageData = data;\n }\n\n public static void setPath(String path) {\n mPath = path;\n }\n\n public static void setProgress(boolean b, View view) {\n mBusy = b;\n view.setVisibility(b ? View.VISIBLE : View.GONE);\n }\n\n public static void setSearchWord(String searchWord) {\n mSearchWord = searchWord;\n }\n\n public static void setStatus(String status) {\n mStatus = status;\n }\n\n public static void setSuccess(int i) {\n mSuccess = i;\n }\n\n}" }, { "identifier": "Projects", "path": "app/src/main/java/com/threethan/questpatcher/utils/Projects.java", "snippet": "public class Projects {\n\n public static List<String> getData(Context context) {\n List<String> mData = new ArrayList<>();\n for (File mFile : Objects.requireNonNull(new File(context.getCacheDir().toString()).listFiles())) {\n if (mFile.exists() && mFile.isDirectory() && new File(mFile, \".aeeBackup/appData\").exists()) {\n if (Common.getSearchWord() == null) {\n mData.add(mFile.getAbsolutePath());\n } else if (Common.isTextMatched(mFile.getName(), Common.getSearchWord())) {\n mData.add(mFile.getAbsolutePath());\n }\n }\n }\n Collections.sort(mData);\n if (!sCommonUtils.getBoolean(\"az_order\", true, context)) {\n Collections.reverse(mData);\n }\n return mData;\n }\n\n public static String getExportPath(Context context) {\n if (Build.VERSION.SDK_INT < 29 && sCommonUtils.getString(\"exportPath\", null, context) != null) {\n return sCommonUtils.getString(\"exportPath\", null, context);\n } else {\n return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();\n }\n }\n\n public static void exportProject(File file, Context context) {\n new EditTextInterface(null, context.getString(R.string.app_name), context) {\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void positiveButtonLister(Editable s) {\n String text = s.toString().trim();\n if (text.isEmpty()) {\n sCommonUtils.toast(context.getString(R.string.name_empty), context).show();\n return;\n }\n if (text.contains(\" \")) {\n text = text.replace(\" \", \"_\");\n }\n String name = text;\n if (sFileUtils.exist(new File(Projects.getExportPath(context), text))) {\n new MaterialAlertDialogBuilder(context)\n .setMessage(context.getString(R.string.export_project_replace, text))\n .setNegativeButton(R.string.cancel, (dialog2, ii) -> {\n })\n .setPositiveButton(R.string.replace, (dialog2, iii) -> new ExportProject(file, name, context).execute())\n .show();\n } else {\n new ExportProject(file, name, context).execute();\n }\n }\n }.show();\n }\n\n}" } ]
import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.os.Build; import com.threethan.questpatcher.R; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.Projects; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.io.File; import java.util.List; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
4,419
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <[email protected]> on January 28, 2023 */ public class ExportToStorage extends sExecutor { private final Context mContext; private final File mSourceFile; private final List<File> mSourceFiles; private ProgressDialog mProgressDialog; private final String mFolder; private String mExportPath = null; public ExportToStorage(File sourceFile, List<File> sourceFiles, String folder, Context context) { mSourceFile = sourceFile; mSourceFiles = sourceFiles; mFolder = folder; mContext = context; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mContext); mProgressDialog.setMessage(mContext.getString(R.string.exporting, mSourceFile != null && mSourceFile.exists() ? mSourceFile.getName() : "")); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { sFileUtils.mkdir(new File(Projects.getExportPath(mContext), mFolder));
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <[email protected]> on January 28, 2023 */ public class ExportToStorage extends sExecutor { private final Context mContext; private final File mSourceFile; private final List<File> mSourceFiles; private ProgressDialog mProgressDialog; private final String mFolder; private String mExportPath = null; public ExportToStorage(File sourceFile, List<File> sourceFiles, String folder, Context context) { mSourceFile = sourceFile; mSourceFiles = sourceFiles; mFolder = folder; mContext = context; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mContext); mProgressDialog.setMessage(mContext.getString(R.string.exporting, mSourceFile != null && mSourceFile.exists() ? mSourceFile.getName() : "")); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { sFileUtils.mkdir(new File(Projects.getExportPath(mContext), mFolder));
mExportPath = Projects.getExportPath(mContext) + "/" + Common.getAppID();
1
2023-11-18 15:13:30+00:00
8k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/client/HarborClientImpl.java
[ { "identifier": "HarborException", "path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java", "snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public HarborException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "Artifact", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Artifact.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class Artifact {\n private long id;\n private String type;\n private String mediaType;\n private String manifestMediaType;\n private String projectId;\n private String repositoryId;\n private String repositoryName;\n private String digest;\n private long size;\n private String icon;\n private Date pushTime;\n private Date pullTime;\n private HashMap<String, Object> extraAttrs;\n private String annotations;\n private String references;\n\n @JsonIgnore\n private String tags;\n\n @JsonIgnore\n private HashMap<String, AdditionLink> additionLinks;\n\n private String labels;\n\n @SuppressWarnings(\"lgtm[jenkins/plaintext-storage]\")\n private String accessories;\n\n private HashMap<String, NativeReportSummary> scanOverview;\n\n public String getMediaType() {\n return mediaType;\n }\n\n @JsonProperty(\"media_type\")\n public void setMediaType(String mediaType) {\n this.mediaType = mediaType;\n }\n\n public long getSize() {\n return size;\n }\n\n public void setSize(long size) {\n this.size = size;\n }\n\n public Date getPushTime() {\n return pushTime;\n }\n\n @JsonProperty(\"push_time\")\n public void setPushTime(Date pushTime) {\n this.pushTime = pushTime;\n }\n\n public String getTags() {\n return tags;\n }\n\n public void setTags(String tags) {\n this.tags = tags;\n }\n\n public HashMap<String, NativeReportSummary> getScanOverview() {\n return scanOverview;\n }\n\n @JsonProperty(\"scan_overview\")\n public void setScanOverview(HashMap<String, NativeReportSummary> scanOverview) {\n this.scanOverview = scanOverview;\n }\n\n public Date getPullTime() {\n return pullTime;\n }\n\n @JsonProperty(\"pull_time\")\n public void setPullTime(Date pullTime) {\n this.pullTime = pullTime;\n }\n\n public String getLabels() {\n return labels;\n }\n\n public void setLabels(String labels) {\n this.labels = labels;\n }\n\n public String getAccessories() {\n return accessories;\n }\n\n public void setAccessories(String accessories) {\n this.accessories = accessories;\n }\n\n public String getReferences() {\n return references;\n }\n\n public void setReferences(String references) {\n this.references = references;\n }\n\n public String getManifestMediaType() {\n return manifestMediaType;\n }\n\n @JsonProperty(\"manifest_media_type\")\n public void setManifestMediaType(String manifestMediaType) {\n this.manifestMediaType = manifestMediaType;\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 getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public String getRepositoryId() {\n return repositoryId;\n }\n\n @JsonProperty(\"repository_id\")\n public void setRepositoryId(String repositoryId) {\n this.repositoryId = repositoryId;\n }\n\n public HashMap<String, AdditionLink> getAdditionLinks() {\n return additionLinks;\n }\n\n @JsonProperty(\"addition_links\")\n public void setAdditionLinks(HashMap<String, AdditionLink> additionLinks) {\n this.additionLinks = additionLinks;\n }\n\n public String getProjectId() {\n return projectId;\n }\n\n @JsonProperty(\"project_id\")\n public void setProjectId(String projectId) {\n this.projectId = projectId;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getAnnotations() {\n return annotations;\n }\n\n public void setAnnotations(String annotations) {\n this.annotations = annotations;\n }\n\n public HashMap<String, Object> getExtraAttrs() {\n return extraAttrs;\n }\n\n @JsonProperty(\"extra_attrs\")\n public void setExtraAttrs(HashMap<String, Object> extraAttrs) {\n this.extraAttrs = extraAttrs;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n @JsonProperty(\"repository_name\")\n public void setRepositoryName(String repositoryName) {\n this.repositoryName = repositoryName;\n }\n}" }, { "identifier": "NativeReportSummary", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/NativeReportSummary.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class NativeReportSummary {\n private String reportId;\n\n private VulnerabilityScanStatus ScanStatus;\n\n private Severity severity;\n\n private long duration;\n\n private VulnerabilitySummary summary;\n\n private ArrayList<String> cvebypassed;\n\n private Date StartTime;\n\n private Date EndTime;\n\n private Scanner scanner;\n\n private int completePercent;\n\n @JsonIgnore\n private int totalCount;\n\n @JsonIgnore\n private int completeCount;\n\n @JsonIgnore\n private VulnerabilityItemList vulnerabilityItemList;\n\n public String getReportId() {\n return reportId;\n }\n\n @JsonProperty(\"report_id\")\n public void setReportId(String reportId) {\n this.reportId = reportId;\n }\n\n public VulnerabilityScanStatus getScanStatus() {\n return ScanStatus;\n }\n\n @JsonProperty(\"scan_status\")\n public void setScanStatus(VulnerabilityScanStatus scanStatus) {\n ScanStatus = scanStatus;\n }\n\n public Severity getSeverity() {\n return severity;\n }\n\n public void setSeverity(Severity severity) {\n this.severity = severity;\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n public VulnerabilitySummary getSummary() {\n return summary;\n }\n\n public void setSummary(VulnerabilitySummary summary) {\n this.summary = summary;\n }\n\n public ArrayList<String> getCvebypassed() {\n return cvebypassed;\n }\n\n @JsonIgnore\n public void setCvebypassed(ArrayList<String> cvebypassed) {\n this.cvebypassed = cvebypassed;\n }\n\n public Date getStartTime() {\n return StartTime;\n }\n\n @JsonProperty(\"start_time\")\n public void setStartTime(Date startTime) {\n StartTime = startTime;\n }\n\n public Date getEndTime() {\n return EndTime;\n }\n\n @JsonProperty(\"end_time\")\n public void setEndTime(Date endTime) {\n EndTime = endTime;\n }\n\n public Scanner getScanner() {\n return scanner;\n }\n\n public void setScanner(Scanner scanner) {\n this.scanner = scanner;\n }\n\n public int getCompletePercent() {\n return completePercent;\n }\n\n @JsonProperty(\"complete_percent\")\n public void setCompletePercent(int completePercent) {\n this.completePercent = completePercent;\n }\n\n public int getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(int totalCount) {\n this.totalCount = totalCount;\n }\n\n public int getCompleteCount() {\n return completeCount;\n }\n\n public void setCompleteCount(int completeCount) {\n this.completeCount = completeCount;\n }\n\n public VulnerabilityItemList getVulnerabilityItemList() {\n return vulnerabilityItemList;\n }\n\n public void setVulnerabilityItemList(VulnerabilityItemList vulnerabilityItemList) {\n this.vulnerabilityItemList = vulnerabilityItemList;\n }\n}" }, { "identifier": "Repository", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Repository.java", "snippet": "public class Repository {\n private Integer id;\n private String name;\n\n @JsonProperty(\"artifact_count\")\n private Integer artifactCount;\n\n @JsonProperty(\"project_id\")\n private Integer projectId;\n\n @JsonProperty(\"pull_count\")\n private Integer pullCount;\n\n @JsonProperty(\"creation_time\")\n private String creationTime;\n\n @JsonProperty(\"update_time\")\n private String updateTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getArtifactCount() {\n return artifactCount;\n }\n\n public void setArtifactCount(Integer artifactCount) {\n this.artifactCount = artifactCount;\n }\n\n public String getCreationTime() {\n return creationTime;\n }\n\n public void setCreationTime(String creationTime) {\n this.creationTime = creationTime;\n }\n\n public Integer getProjectId() {\n return projectId;\n }\n\n public void setProjectId(Integer projectId) {\n this.projectId = projectId;\n }\n\n public Integer getPullCount() {\n return pullCount;\n }\n\n public void setPullCount(Integer pullCount) {\n this.pullCount = pullCount;\n }\n\n public String getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(String updateTime) {\n this.updateTime = updateTime;\n }\n}" }, { "identifier": "HarborConstants", "path": "src/main/java/io/jenkins/plugins/harbor/util/HarborConstants.java", "snippet": "public class HarborConstants {\n public static final String HarborVulnerabilityReportV11MimeType =\n \"application/vnd.security.vulnerability.report; version=1.1\";\n public static final String HarborVulnReportv1MimeType =\n \"application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0\";\n}" }, { "identifier": "JsonParser", "path": "src/main/java/io/jenkins/plugins/harbor/util/JsonParser.java", "snippet": "public final class JsonParser {\n private static final ObjectMapper objectMapper = new ObjectMapper()\n .setDateFormat(new StdDateFormat())\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\n public static <T> T toJava(String data, Class<T> type) throws JsonProcessingException {\n return objectMapper.readValue(data, type);\n }\n}" } ]
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.damnhandy.uri.template.UriTemplate; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.cli.NoCheckTrustManager; import io.jenkins.plugins.harbor.HarborException; import io.jenkins.plugins.harbor.client.models.Artifact; import io.jenkins.plugins.harbor.client.models.NativeReportSummary; import io.jenkins.plugins.harbor.client.models.Repository; import io.jenkins.plugins.harbor.util.HarborConstants; import io.jenkins.plugins.harbor.util.JsonParser; import io.jenkins.plugins.okhttp.api.JenkinsOkHttpClient; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor;
3,782
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) { return null; } @Override public String getPing() throws IOException { UriTemplate template = UriTemplate.fromTemplate(baseUrl + API_PING_PATH); HttpUrl apiUrl = HttpUrl.parse(template.expand()); if (apiUrl != null) { return httpGet(apiUrl); } throw new HarborException(String.format("httpUrl is null, UriTemplate is %s.", template.expand())); } @Override
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) { return null; } @Override public String getPing() throws IOException { UriTemplate template = UriTemplate.fromTemplate(baseUrl + API_PING_PATH); HttpUrl apiUrl = HttpUrl.parse(template.expand()); if (apiUrl != null) { return httpGet(apiUrl); } throw new HarborException(String.format("httpUrl is null, UriTemplate is %s.", template.expand())); } @Override
public Repository[] listAllRepositories() throws IOException {
3
2023-11-11 14:54:53+00:00
8k
Mapty231/SpawnFix
src/main/java/me/tye/spawnfix/PlayerJoin.java
[ { "identifier": "Config", "path": "src/main/java/me/tye/spawnfix/utils/Config.java", "snippet": "public enum Config {\n\n default_worldName(String.class),\n default_x(Double.class),\n default_y(Double.class),\n default_z(Double.class),\n default_yaw(Float.class),\n default_pitch(Float.class),\n\n teleport_times(Integer.class),\n teleport_retryInterval(Integer.class),\n\n login(Occurrence.class),\n onSpawn(Occurrence.class),\n lang(String.class);\n\n\n\n/**\n * @param type Should be set to the class of the object this enum will be parsed as. This checks that the config values entered are valid for the used key.\n */\nConfig(Class type) {\n this.type = type;\n}\n\n/**\n Stores the class this object should be parsed as.\n */\nprivate final Class type;\n\n/**\n * @return The class of the object this enum should be parsed as.\n */\nprivate Class getType() {\n return type;\n}\n\n\n/**\n Stores the configs for this plugin.\n */\nprivate static final HashMap<Config, Object> configs = new HashMap<>();\n\n\n/**\n * @return Gets the config response for the selected enum.\n */\npublic @NotNull Object getConfig() {\n Object response = configs.get(this);\n\n assert response != null;\n\n return response;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with String.valueOf().\n */\npublic @NotNull String getStringConfig() {\n return String.valueOf(getConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Integer.parseInt().\n */\npublic int getIntegerConfig() {\n return Integer.parseInt(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Double.parseDouble().\n */\npublic double getDoubleConfig() {\n return Double.parseDouble(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Float.parseFloat().\n */\npublic float getFloatConfig() {\n return Float.parseFloat(getStringConfig());\n}\n\n/**\n Enum for how often spawnFix should act for a certain feature.\n */\npublic enum Occurrence {\n NEVER,\n FIRST,\n EVERY;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Occurrence.valueOf().\n */\npublic @NotNull Occurrence getOccurrenceConfig() {\n return Occurrence.valueOf(getStringConfig().toUpperCase());\n}\n\n/**\n Loads the default configs.\n */\npublic static void init() {\n //Loads the default values into the config.\n HashMap<String,Object> internalConfig = Util.parseInternalYaml(\"config.yml\");\n\n internalConfig.forEach((String key, Object value) -> {\n String formattedKey = key.replace('.', '_');\n\n try {\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+config+\"\\\" cannot be parsed as given object. - Dev warning\");\n }\n\n configs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+formattedKey + \"\\\" isn't in default config file. - Dev warning\");\n }\n });\n\n //Checks if any default values are missing.\n for (Config config : Config.values()) {\n if (configs.containsKey(config)) continue;\n\n //Dev warning.\n throw new RuntimeException(\"\\\"\"+config+\"\\\" isn't in default config file. - Dev warning\");\n }\n}\n\n/**\n Puts the keys response specified by the user into the configs map.\n */\npublic static void load() {\n //Loads in the user-set configs.\n File externalConfigFile = new File(Util.dataFolder.toPath()+File.separator+\"config.yml\");\n HashMap<String,Object> externalConfigs = Util.parseAndRepairExternalYaml(externalConfigFile, \"config.yml\");\n\n HashMap<Config, Object> userConfigs = new HashMap<>();\n\n //Gets the default keys that the user has entered.\n for (Map.Entry<String, Object> entry : externalConfigs.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n\n String formattedKey = key.replace('.', '_');\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n log.warning(Lang.excepts_invalidValue.getResponse(Key.key.replaceWith(key), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n continue;\n }\n\n //logs an exception if the key doesn't exist.\n try {\n userConfigs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n log.warning(Lang.excepts_invalidKey.getResponse(Key.key.replaceWith(key)));\n }\n }\n\n\n //Warns the user about any config keys they are missing.\n for (Config config : configs.keySet()) {\n if (userConfigs.containsKey(config)) continue;\n\n log.warning(Lang.excepts_missingKey.getResponse(Key.key.replaceWith(config.toString()), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n }\n\n configs.putAll(userConfigs);\n}\n\n/**\n Checks if config can be parsed as its intended object.\n * @param config The config to check.\n * @param value The value of the config.\n * @return True if the config can be parsed as its intended object. False if it can't.\n */\nprivate static boolean validate(Config config, Object value) {\n Class configType = config.getType();\n\n //Strings can always be parsed.\n if (configType.equals(String.class)) return true;\n\n String stringValue = value.toString();\n\n if (configType.equals(Double.class)) {\n try {\n Double.parseDouble(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Occurrence.class)) {\n try {\n Occurrence.valueOf(stringValue.toUpperCase());\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Integer.class)) {\n try {\n Integer.parseInt(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Float.class)) {\n try {\n Float.parseFloat(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n throw new RuntimeException(\"Validation for class \\\"\"+configType+\"\\\" does not exist! - Dev warning.\");\n}\n\n}" }, { "identifier": "Teleport", "path": "src/main/java/me/tye/spawnfix/utils/Teleport.java", "snippet": "public class Teleport implements Runnable{\n\npublic static final HashMap<UUID,BukkitTask> runningTasks = new HashMap<>();\n\nprivate final Player player;\nprivate final Location location;\n\nprivate int timesTeleported = 1;\nprivate final int retryLimit = Config.teleport_times.getIntegerConfig();\n\n/**\n A runnable object that teleports the given player to the given location the amount of times specified by \"teleport.times\" in the config.\n * @param player The given player.\n * @param location The given location.\n */\npublic Teleport(@NonNull Player player, @NonNull Location location) {\n this.player = player;\n this.location = location;\n}\n\n@Override\npublic void run() {\n if (timesTeleported > retryLimit) {\n runningTasks.get(player.getUniqueId()).cancel();\n return;\n }\n\n if (location == null ) {\n plugin.getLogger().warning(Lang.teleport_noLocation.getResponse());\n return;\n }\n\n if (player == null) {\n plugin.getLogger().warning(Lang.teleport_noPlayer.getResponse());\n return;\n }\n\n player.teleport(location);\n timesTeleported++;\n}\n\n}" }, { "identifier": "Util", "path": "src/main/java/me/tye/spawnfix/utils/Util.java", "snippet": "public class Util {\n\n/**\n This plugin.\n */\npublic static final JavaPlugin plugin = JavaPlugin.getPlugin(SpawnFix.class);\n\n\n/**\n The data folder.\n */\npublic static final File dataFolder = plugin.getDataFolder();\n\n/**\n The config file for this plugin.\n */\npublic static final File configFile = new File(dataFolder.toPath() + File.separator + \"config.yml\");\n\n/**\n The lang folder for this plugin.\n */\npublic static File langFolder = new File(dataFolder.toPath() + File.separator + \"langFiles\");\n\n/**\n The logger for this plugin.\n */\npublic static final Logger log = plugin.getLogger();\n\n\n/**\n * @return The default spawn location as set in the config.yml of this plugin.\n */\npublic static Location getDefaultSpawn() {\n return new Location(Bukkit.getWorld(Config.default_worldName.getStringConfig()),\n Config.default_x.getDoubleConfig(),\n Config.default_y.getDoubleConfig(),\n Config.default_z.getDoubleConfig(),\n Config.default_yaw.getFloatConfig(),\n Config.default_pitch.getFloatConfig()\n );\n}\n\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.<br>\n E.G: key: \"example.response\" value: \"test\".\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@Nullable Map<?,?> baseMap) {\n HashMap<String,Object> map = new HashMap<>();\n if (baseMap == null) return map;\n\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(String.valueOf(key), subMap));\n } else {\n map.put(String.valueOf(key), String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.\n @param keyPath The path to append to the starts of the key. (Should only be called internally).\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@NotNull String keyPath, @NotNull Map<?,?> baseMap) {\n if (!keyPath.isEmpty()) keyPath += \".\";\n\n HashMap<String,Object> map = new HashMap<>();\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(keyPath+key, subMap));\n } else {\n map.put(keyPath+key, String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void makeRequiredFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) throws IOException {\n if (file.exists())\n return;\n\n if (isFile) {\n if (!file.createNewFile())\n throw new IOException();\n }\n else {\n if (!file.mkdir())\n throw new IOException();\n }\n\n if (resource != null) {\n String text = new String(resource.readAllBytes());\n FileWriter fw = new FileWriter(file);\n fw.write(text);\n fw.close();\n }\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void createFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) {\n try {\n makeRequiredFile(file, resource, isFile);\n } catch (IOException e) {\n log.log(Level.WARNING, Lang.excepts_fileCreation.getResponse(Key.filePath.replaceWith(file.getAbsolutePath())), e);\n }\n}\n\n\n/**\n Parses & formats data from the given inputStream to a Yaml resource.\n * @param yamlInputStream The given inputStream to a Yaml resource.\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\"<br>\n * Or an empty hashMap if the given inputStream is null.\n * @throws IOException If the data couldn't be read from the given inputStream.\n */\nprivate static @NotNull HashMap<String, Object> parseYaml(@Nullable InputStream yamlInputStream) throws IOException {\n if (yamlInputStream == null) return new HashMap<>();\n\n byte[] resourceBytes = yamlInputStream.readAllBytes();\n\n String resourceContent = new String(resourceBytes, Charset.defaultCharset());\n\n return getKeysRecursive(new Yaml().load(resourceContent));\n}\n\n/**\n Parses the data from an internal YAML file.\n * @param resourcePath The path to the file from /src/main/resource/\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\" <br>\n * Or an empty hashMap if the file couldn't be found or read.\n */\npublic static @NotNull HashMap<String, Object> parseInternalYaml(@NotNull String resourcePath) {\n try (InputStream resourceInputStream = plugin.getResource(resourcePath)) {\n return parseYaml(resourceInputStream);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, \"Unable to parse internal YAML files.\\nConfig & lang might break.\\n\", e);\n return new HashMap<>();\n }\n\n}\n\n\n/**\n Parses the given external file into a hashMap. If the internal file contained keys that the external file didn't then the key-value pare is added to the external file.\n * @param externalFile The external file to parse.\n * @param pathToInternalResource The path to the internal resource to repair it with or fallback on if the external file is broken.\n * @return The key-value pairs from the external file. If any keys were missing from the external file then they are put into the hashMap with their default value.\n */\npublic static @NotNull HashMap<String, Object> parseAndRepairExternalYaml(@NotNull File externalFile, @Nullable String pathToInternalResource) {\n HashMap<String,Object> externalYaml;\n\n //tries to parse the external file.\n try (InputStream externalInputStream = new FileInputStream(externalFile)) {\n externalYaml = parseYaml(externalInputStream);\n\n } catch (FileNotFoundException e) {\n log.log(Level.SEVERE, Lang.excepts_noFile.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, Lang.excepts_parseYaml.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n }\n\n\n //if there is no internal resource to compare against then only the external file data is returned.\n if (pathToInternalResource == null)\n return externalYaml;\n\n HashMap<String,Object> internalYaml = parseInternalYaml(pathToInternalResource);\n\n //gets the values that the external file is missing;\n HashMap<String,Object> missingPairsMap = new HashMap<>();\n internalYaml.forEach((String key, Object value) -> {\n if (externalYaml.containsKey(key))\n return;\n\n missingPairsMap.put(key, value);\n });\n\n //if no values are missing return\n if (missingPairsMap.keySet().isEmpty())\n return externalYaml;\n\n //Adds all the missing key-value pairs to a stringBuilder.\n StringBuilder missingPairs = new StringBuilder(\"\\n\");\n missingPairsMap.forEach((String key, Object value) -> {\n missingPairs.append(key)\n .append(\": \\\"\")\n .append(preserveEscapedQuotes(value))\n .append(\"\\\"\\n\");\n });\n\n //Adds al the missing pairs to the external Yaml.\n externalYaml.putAll(missingPairsMap);\n\n\n //Writes the missing pairs to the external file.\n try (FileWriter externalFileWriter = new FileWriter(externalFile, true)) {\n externalFileWriter.append(missingPairs.toString());\n\n }catch (IOException e) {\n //Logs a warning\n log.log(Level.WARNING, Lang.excepts_fileRestore.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //Logs the keys that couldn't be appended.\n missingPairsMap.forEach((String key, Object value) -> {\n log.log(Level.WARNING, key + \": \" + value);\n });\n }\n\n return externalYaml;\n}\n\n/**\n Object.toString() changes \\\" to \". This method resolves this problem.\n * @param value The object to get the string from.\n * @return The correct string from the given object.\n */\nprivate static String preserveEscapedQuotes(Object value) {\n char[] valueCharArray = value.toString().toCharArray();\n StringBuilder correctString = new StringBuilder();\n\n\n for (char character : valueCharArray) {\n if (character != '\"') {\n correctString.append(character);\n continue;\n }\n\n correctString.append('\\\\');\n correctString.append('\"');\n }\n\n return correctString.toString();\n}\n\n/**\n Writes the new value to the key in the specified external yaml file.\n * @param key The key to replace the value of.\n * @param value The new string to overwrite the old value with.\n * @param externalYaml The external yaml to perform this operation on.\n * @throws IOException If there was an error reading or writing data to the Yaml file.\n */\npublic static void writeYamlData(@NotNull String key, @NotNull String value, @NotNull File externalYaml) throws IOException {\n String fileContent;\n\n //Reads the content from the file.\n try (FileInputStream externalYamlInputStream = new FileInputStream(externalYaml)) {\n fileContent = new String(externalYamlInputStream.readAllBytes());\n }\n\n //Ensures that every key ends with \":\".\n //This avoids false matches where one key contains the starting chars of another.\n String[] keys = key.split(\"\\\\.\");\n for (int i = 0; i < keys.length; i++) {\n String k = keys[i];\n\n if (k.endsWith(\":\")) continue;\n\n k+=\":\";\n keys[i] = k;\n }\n\n\n Integer valueStartPosition = findKeyPosition(keys, fileContent);\n if (valueStartPosition == null) throw new IOException(\"Unable to find \"+key+\" in external Yaml file.\");\n\n int valueLineEnd = valueStartPosition;\n //Finds the index of the end of the line that the key is on.\n while (fileContent.charAt(valueLineEnd) != '\\n') {\n valueLineEnd++;\n }\n\n String firstPart = fileContent.substring(0, valueStartPosition);\n String secondPart = fileContent.substring(valueLineEnd, fileContent.length()-1);\n\n String newFileContent = firstPart.concat(value).concat(secondPart);\n\n try (FileWriter externalYamlWriter = new FileWriter(externalYaml)) {\n externalYamlWriter.write(newFileContent);\n }\n}\n\n/**\n Finds the given key index in the given file content split on each new line.<br>\n The key should be given in the format \"example.key1\".\n * @param keys The given keys.\n * @param fileContent The given file content.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, @NotNull String fileContent) {\n\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int keyLine = 0, splitLength = split.length; keyLine < splitLength; keyLine++) {\n String strippedLine = split[keyLine].stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[0])) {\n continue;\n }\n\n return findKeyPosition(keys, keyLine+1, 1, fileContent);\n\n }\n\n return null;\n}\n\n/**\n Gets the index for the line of the last sub-key given in the given fileContent.<br>\n This method executes recursively.\n * @param keys The keys to find in the file.\n * @param startLine The index of the line to start the search from.\n * @param keyIndex The index of the sub-key that is searched for.\n * @param fileContent The content of the file to search through.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, int startLine, int keyIndex, @NotNull String fileContent) {\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int lineIndex = startLine, splitLength = split.length; lineIndex < splitLength; lineIndex++) {\n\n String line = split[lineIndex];\n\n //returns null if the key doesn't exist as a sub-key of the base key.\n if (!(line.startsWith(\" \") || line.startsWith(\"\\t\"))) {\n return null;\n }\n\n String strippedLine = line.stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[keyIndex])) {\n continue;\n }\n\n keyIndex++;\n\n //returns the char position that the key ends on if it is the last key in the sequence.\n if (keyIndex == keys.length) {\n\n int currentLinePosition = 0;\n //Gets the char position of the current line within the string.\n for (int i = 0; i < lineIndex; i++) {\n currentLinePosition+=split[i].length()+1;\n }\n\n //Finds the char position a space after the key ends.\n for (int i = currentLinePosition; i < fileContent.length(); i++) {\n char character = fileContent.charAt(i);\n\n if (character != ':') continue;\n\n return i+2;\n\n }\n }\n\n return findKeyPosition(keys, startLine, keyIndex, fileContent);\n }\n\n return null;\n}\n\n}" } ]
import me.tye.spawnfix.utils.Config; import me.tye.spawnfix.utils.Teleport; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.bukkit.scheduler.BukkitTask; import java.util.ArrayList; import java.util.UUID; import java.util.logging.Level; import static me.tye.spawnfix.utils.Util.*;
5,687
package me.tye.spawnfix; public class PlayerJoin implements Listener { private static final ArrayList<UUID> joined = new ArrayList<>(); @EventHandler public static void PlayerSpawn(PlayerJoinEvent e) { Player player = e.getPlayer();
package me.tye.spawnfix; public class PlayerJoin implements Listener { private static final ArrayList<UUID> joined = new ArrayList<>(); @EventHandler public static void PlayerSpawn(PlayerJoinEvent e) { Player player = e.getPlayer();
Config.Occurrence login = Config.login.getOccurrenceConfig();
0
2023-11-13 23:53:25+00:00
8k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/controller/ProvController.java
[ { "identifier": "ProvinceEntity", "path": "src/main/java/com/example/servingwebcontent/entity/ProvinceEntity.java", "snippet": "public class ProvinceEntity {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569715+09:00\", comments = \"Source field: public.province.provcode\")\n\tprivate String provcode;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569855+09:00\", comments = \"Source field: public.province.mstcountrycd\")\n\tprivate String mstcountrycd;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569983+09:00\", comments = \"Source field: public.province.provname\")\n\tprivate String provname;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569767+09:00\", comments = \"Source field: public.province.provcode\")\n\tpublic String getProvcode() {\n\t\treturn provcode;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569815+09:00\", comments = \"Source field: public.province.provcode\")\n\tpublic void setProvcode(String provcode) {\n\t\tthis.provcode = provcode;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.5699+09:00\", comments = \"Source field: public.province.mstcountrycd\")\n\tpublic String getMstcountrycd() {\n\t\treturn mstcountrycd;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569945+09:00\", comments = \"Source field: public.province.mstcountrycd\")\n\tpublic void setMstcountrycd(String mstcountrycd) {\n\t\tthis.mstcountrycd = mstcountrycd;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570037+09:00\", comments = \"Source field: public.province.provname\")\n\tpublic String getProvname() {\n\t\treturn provname;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570081+09:00\", comments = \"Source field: public.province.provname\")\n\tpublic void setProvname(String provname) {\n\t\tthis.provname = provname;\n\t}\n}" }, { "identifier": "CountrySearchForm", "path": "src/main/java/com/example/servingwebcontent/form/CountrySearchForm.java", "snippet": "@Data\npublic class CountrySearchForm {\n\n @NotBlank(message = \"ID should not be blank\")\n private String mstCountryCD;\n\n public CountrySearchForm() {\n }\n\n public CountrySearchForm(String mstCountryCd) {\n this.mstCountryCD = mstCountryCd;\n }\n}" }, { "identifier": "ProvinceEntityDynamicSqlSupport", "path": "src/main/java/com/example/servingwebcontent/repository/ProvinceEntityDynamicSqlSupport.java", "snippet": "public final class ProvinceEntityDynamicSqlSupport {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570188+09:00\", comments = \"Source Table: public.province\")\n\tpublic static final ProvinceEntity provinceEntity = new ProvinceEntity();\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570404+09:00\", comments = \"Source field: public.province.provcode\")\n\tpublic static final SqlColumn<String> provcode = provinceEntity.provcode;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570444+09:00\", comments = \"Source field: public.province.mstcountrycd\")\n\tpublic static final SqlColumn<String> mstcountrycd = provinceEntity.mstcountrycd;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570477+09:00\", comments = \"Source field: public.province.provname\")\n\tpublic static final SqlColumn<String> provname = provinceEntity.provname;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570343+09:00\", comments = \"Source Table: public.province\")\n\tpublic static final class ProvinceEntity extends AliasableSqlTable<ProvinceEntity> {\n\t\tpublic final SqlColumn<String> provcode = column(\"provcode\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> mstcountrycd = column(\"mstcountrycd\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> provname = column(\"provname\", JDBCType.VARCHAR);\n\n\t\tpublic ProvinceEntity() {\n\t\t\tsuper(\"public.province\", ProvinceEntity::new);\n\t\t}\n\t}\n}" }, { "identifier": "ProvinceEntityMapper", "path": "src/main/java/com/example/servingwebcontent/repository/ProvinceEntityMapper.java", "snippet": "@Mapper\npublic interface ProvinceEntityMapper extends CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<ProvinceEntity>, CommonUpdateMapper {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571086+09:00\", comments = \"Source Table: public.province\")\n\tBasicColumn[] selectList = BasicColumn.columnList(provcode, mstcountrycd, provname);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570518+09:00\", comments = \"Source Table: public.province\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@Results(id = \"ProvinceEntityResult\", value = {\n\t\t\t@Result(column = \"provcode\", property = \"provcode\", jdbcType = JdbcType.CHAR, id = true),\n\t\t\t@Result(column = \"mstcountrycd\", property = \"mstcountrycd\", jdbcType = JdbcType.CHAR, id = true),\n\t\t\t@Result(column = \"provname\", property = \"provname\", jdbcType = JdbcType.CHAR) })\n\tList<ProvinceEntity> selectMany(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.57059+09:00\", comments = \"Source Table: public.province\")\n\t@SelectProvider(type = SqlProviderAdapter.class, method = \"select\")\n\t@ResultMap(\"ProvinceEntityResult\")\n\tOptional<ProvinceEntity> selectOne(SelectStatementProvider selectStatement);\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570632+09:00\", comments = \"Source Table: public.province\")\n\tdefault long count(CountDSLCompleter completer) {\n\t\treturn MyBatis3Utils.countFrom(this::count, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570673+09:00\", comments = \"Source Table: public.province\")\n\tdefault int delete(DeleteDSLCompleter completer) {\n\t\treturn MyBatis3Utils.deleteFrom(this::delete, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570723+09:00\", comments = \"Source Table: public.province\")\n\tdefault int deleteByPrimaryKey(String provcode_, String mstcountrycd_) {\n\t\treturn delete(c -> c.where(provcode, isEqualTo(provcode_)).and(mstcountrycd, isEqualTo(mstcountrycd_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570773+09:00\", comments = \"Source Table: public.province\")\n\tdefault int insert(ProvinceEntity row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, provinceEntity, c -> c.map(provcode).toProperty(\"provcode\")\n\t\t\t\t.map(mstcountrycd).toProperty(\"mstcountrycd\").map(provname).toProperty(\"provname\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570872+09:00\", comments = \"Source Table: public.province\")\n\tdefault int insertMultiple(Collection<ProvinceEntity> records) {\n\t\treturn MyBatis3Utils.insertMultiple(this::insertMultiple, records, provinceEntity,\n\t\t\t\tc -> c.map(provcode).toProperty(\"provcode\").map(mstcountrycd).toProperty(\"mstcountrycd\").map(provname)\n\t\t\t\t\t\t.toProperty(\"provname\"));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.570967+09:00\", comments = \"Source Table: public.province\")\n\tdefault int insertSelective(ProvinceEntity row) {\n\t\treturn MyBatis3Utils.insert(this::insert, row, provinceEntity,\n\t\t\t\tc -> c.map(provcode).toPropertyWhenPresent(\"provcode\", row::getProvcode).map(mstcountrycd)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"mstcountrycd\", row::getMstcountrycd).map(provname)\n\t\t\t\t\t\t.toPropertyWhenPresent(\"provname\", row::getProvname));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571152+09:00\", comments = \"Source Table: public.province\")\n\tdefault Optional<ProvinceEntity> selectOne(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectOne(this::selectOne, selectList, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.57121+09:00\", comments = \"Source Table: public.province\")\n\tdefault List<ProvinceEntity> select(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectList(this::selectMany, selectList, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571272+09:00\", comments = \"Source Table: public.province\")\n\tdefault List<ProvinceEntity> selectDistinct(SelectDSLCompleter completer) {\n\t\treturn MyBatis3Utils.selectDistinct(this::selectMany, selectList, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571342+09:00\", comments = \"Source Table: public.province\")\n\tdefault Optional<ProvinceEntity> selectByPrimaryKey(String provcode_, String mstcountrycd_) {\n\t\treturn selectOne(c -> c.where(provcode, isEqualTo(provcode_)).and(mstcountrycd, isEqualTo(mstcountrycd_)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571411+09:00\", comments = \"Source Table: public.province\")\n\tdefault int update(UpdateDSLCompleter completer) {\n\t\treturn MyBatis3Utils.update(this::update, provinceEntity, completer);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571468+09:00\", comments = \"Source Table: public.province\")\n\tstatic UpdateDSL<UpdateModel> updateAllColumns(ProvinceEntity row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(provcode).equalTo(row::getProvcode).set(mstcountrycd).equalTo(row::getMstcountrycd).set(provname)\n\t\t\t\t.equalTo(row::getProvname);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571546+09:00\", comments = \"Source Table: public.province\")\n\tstatic UpdateDSL<UpdateModel> updateSelectiveColumns(ProvinceEntity row, UpdateDSL<UpdateModel> dsl) {\n\t\treturn dsl.set(provcode).equalToWhenPresent(row::getProvcode).set(mstcountrycd)\n\t\t\t\t.equalToWhenPresent(row::getMstcountrycd).set(provname).equalToWhenPresent(row::getProvname);\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571611+09:00\", comments = \"Source Table: public.province\")\n\tdefault int updateByPrimaryKey(ProvinceEntity row) {\n\t\treturn update(c -> c.set(provname).equalTo(row::getProvname).where(provcode, isEqualTo(row::getProvcode))\n\t\t\t\t.and(mstcountrycd, isEqualTo(row::getMstcountrycd)));\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.571664+09:00\", comments = \"Source Table: public.province\")\n\tdefault int updateByPrimaryKeySelective(ProvinceEntity row) {\n\t\treturn update(c -> c.set(provname).equalToWhenPresent(row::getProvname)\n\t\t\t\t.where(provcode, isEqualTo(row::getProvcode)).and(mstcountrycd, isEqualTo(row::getMstcountrycd)));\n\t}\n}" } ]
import static org.mybatis.dynamic.sql.SqlBuilder.*; import java.util.List; import java.util.Optional; import org.mybatis.dynamic.sql.render.RenderingStrategies; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.ResponseStatusException; import com.example.servingwebcontent.entity.ProvinceEntity; import com.example.servingwebcontent.form.CountrySearchForm; import com.example.servingwebcontent.repository.ProvinceEntityDynamicSqlSupport; import com.example.servingwebcontent.repository.ProvinceEntityMapper; import com.google.gson.Gson;
3,709
package com.example.servingwebcontent.controller; @Controller public class ProvController { @Autowired private ProvinceEntityMapper mapper; @GetMapping("/prov") public String init(CountrySearchForm countrySearchForm) { return "province/prov"; } @GetMapping("/prov/search/{countryId}") @ResponseBody public String search(@PathVariable("countryId") String countryId) { SelectStatementProvider selectStatement = select(ProvinceEntityMapper.selectList) .from(ProvinceEntityDynamicSqlSupport.provinceEntity) .where(ProvinceEntityDynamicSqlSupport.mstcountrycd, isEqualTo(countryId)) .build() .render(RenderingStrategies.MYBATIS3);
package com.example.servingwebcontent.controller; @Controller public class ProvController { @Autowired private ProvinceEntityMapper mapper; @GetMapping("/prov") public String init(CountrySearchForm countrySearchForm) { return "province/prov"; } @GetMapping("/prov/search/{countryId}") @ResponseBody public String search(@PathVariable("countryId") String countryId) { SelectStatementProvider selectStatement = select(ProvinceEntityMapper.selectList) .from(ProvinceEntityDynamicSqlSupport.provinceEntity) .where(ProvinceEntityDynamicSqlSupport.mstcountrycd, isEqualTo(countryId)) .build() .render(RenderingStrategies.MYBATIS3);
List<ProvinceEntity> list = mapper.selectMany(selectStatement);
0
2023-11-12 08:22:27+00:00
8k
wangxianhui111/xuechengzaixian
xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/service/impl/OrderServiceImpl.java
[ { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private String errMessage;\n\n public XueChengPlusException() {\n super();\n }\n\n public XueChengPlusException(String errMessage) {\n super(errMessage);\n this.errMessage = errMessage;\n }\n\n public String getErrMessage() {\n return errMessage;\n }\n\n public static void cast(CommonError commonError) {\n throw new XueChengPlusException(commonError.getErrMessage());\n }\n\n public static void cast(String errMessage) {\n throw new XueChengPlusException(errMessage);\n }\n}" }, { "identifier": "IdWorkerUtils", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/utils/IdWorkerUtils.java", "snippet": "public final class IdWorkerUtils {\n\n private static final Random RANDOM = new Random();\n\n private static final long WORKER_ID_BITS = 5L;\n\n private static final long DATACENTERIDBITS = 5L;\n\n private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);\n\n private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTERIDBITS);\n\n private static final long SEQUENCE_BITS = 12L;\n\n private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;\n\n private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;\n\n private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTERIDBITS;\n\n private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);\n\n private static final IdWorkerUtils ID_WORKER_UTILS = new IdWorkerUtils();\n\n private final long workerId;\n\n private final long datacenterId;\n\n private final long idepoch;\n\n private long sequence = '0';\n\n private long lastTimestamp = -1L;\n\n private IdWorkerUtils() {\n this(RANDOM.nextInt((int) MAX_WORKER_ID), RANDOM.nextInt((int) MAX_DATACENTER_ID), 1288834974657L);\n }\n\n private IdWorkerUtils(final long workerId, final long datacenterId, final long idepoch) {\n if (workerId > MAX_WORKER_ID || workerId < 0) {\n throw new IllegalArgumentException(String.format(\"worker Id can't be greater than %d or less than 0\", MAX_WORKER_ID));\n }\n if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {\n throw new IllegalArgumentException(String.format(\"datacenter Id can't be greater than %d or less than 0\", MAX_DATACENTER_ID));\n }\n this.workerId = workerId;\n this.datacenterId = datacenterId;\n this.idepoch = idepoch;\n }\n\n /**\n * Gets instance.\n *\n * @return the instance\n */\n public static IdWorkerUtils getInstance() {\n return ID_WORKER_UTILS;\n }\n\n /**\n * 基于雪花算法生成唯一的 id\n *\n * @return id\n */\n public synchronized long nextId() {\n long timestamp = timeGen();\n if (timestamp < lastTimestamp) {\n throw new RuntimeException(String.format(\"Clock moved backwards. Refusing to generate id for %d milliseconds\", lastTimestamp - timestamp));\n }\n if (lastTimestamp == timestamp) {\n sequence = (sequence + 1) & SEQUENCE_MASK;\n if (sequence == 0) {\n timestamp = tilNextMillis(lastTimestamp);\n }\n } else {\n sequence = 0L;\n }\n\n lastTimestamp = timestamp;\n\n return ((timestamp - idepoch) << TIMESTAMP_LEFT_SHIFT)\n | (datacenterId << DATACENTER_ID_SHIFT)\n | (workerId << WORKER_ID_SHIFT) | sequence;\n }\n\n private long tilNextMillis(final long lastTimestamp) {\n long timestamp = timeGen();\n while (timestamp <= lastTimestamp) {\n timestamp = timeGen();\n }\n return timestamp;\n }\n\n private long timeGen() {\n return System.currentTimeMillis();\n }\n\n /**\n * Build part number string.\n *\n * @return the string\n */\n public String buildPartNumber() {\n return String.valueOf(ID_WORKER_UTILS.nextId());\n }\n\n /**\n * Create uuid string.\n *\n * @return the string\n */\n public String createUUID() {\n return String.valueOf(ID_WORKER_UTILS.nextId());\n }\n\n public static void main(String[] args) {\n System.out.println(IdWorkerUtils.getInstance().nextId());\n }\n}" }, { "identifier": "QRCodeUtil", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/utils/QRCodeUtil.java", "snippet": "public class QRCodeUtil {\n /**\n * 生成二维码\n *\n * @param content 二维码对应的URL\n * @param width 二维码图片宽度\n * @param height 二维码图片高度\n * @return string\n */\n public String createQRCode(String content, int width, int height) throws IOException {\n String resultImage = \"\";\n // 除了尺寸,传入内容不能为空\n if (!StringUtils.isEmpty(content)) {\n ServletOutputStream stream = null;\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n // 二维码参数\n @SuppressWarnings(\"rawtypes\")\n HashMap<EncodeHintType, Comparable> hints = new HashMap<>();\n //指定字符编码为“utf-8”\n hints.put(EncodeHintType.CHARACTER_SET, \"utf-8\");\n // L M Q H四个纠错等级从低到高,指定二维码的纠错等级为M\n // 纠错级别越高,可以修正的错误就越多,需要的纠错码的数量也变多,相应的二维吗可储存的数据就会减少\n hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);\n // 设置图片的边距\n hints.put(EncodeHintType.MARGIN, 1);\n\n try {\n // zxing生成二维码核心类\n QRCodeWriter writer = new QRCodeWriter();\n // 把输入文本按照指定规则转成二维吗\n BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);\n //生成二维码图片流\n BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);\n // 输出流\n ImageIO.write(bufferedImage, \"png\", os);\n // 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析,所以加上前缀\n\n resultImage = \"data:image/png;base64,\" + EncryptUtil.encodeBase64(os.toByteArray());\n return resultImage;\n } catch (Exception e) {\n e.printStackTrace();\n throw new RuntimeException(\"生成二维码出错\");\n } finally {\n if (stream != null) {\n stream.flush();\n stream.close();\n }\n }\n }\n return null;\n }\n\n public static void main(String[] args) throws IOException {\n QRCodeUtil qrCodeUtil = new QRCodeUtil();\n System.out.println(qrCodeUtil.createQRCode(\"http://192.168.247.1:63030/orders/alipaytest\", 200, 200));\n }\n}" }, { "identifier": "MqMessageService", "path": "xuecheng-plus-message-sdk/src/main/java/com/xuecheng/messagesdk/service/MqMessageService.java", "snippet": "public interface MqMessageService extends IService<MqMessage> {\n\n /**\n * 扫描消息表记录,采用与扫描视频处理表相同的思路\n *\n * @param shardIndex 分片序号\n * @param shardTotal 分片总数\n * @param count 扫描记录数\n * @return {@link java.util.List}<{@link MqMessage}> 消息记录\n * @author Wuxy\n * @since 2022/9/21 18:55\n */\n List<MqMessage> getMessageList(int shardIndex, int shardTotal, String messageType, int count);\n\n /**\n * 添加消息\n *\n * @param messageType 消息类型(例如:支付结果、课程发布等)\n * @param businessKey1 业务id\n * @param businessKey2 业务id\n * @param businessKey3 业务id\n * @return {@link com.xuecheng.messagesdk.model.po.MqMessage} 消息内容\n * @author Wuxy\n * @since 2022/9/23 13:45\n */\n MqMessage addMessage(String messageType, String businessKey1, String businessKey2, String businessKey3);\n\n /**\n * 完成任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completed(long id);\n\n /**\n * 完成阶段一任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageOne(long id);\n\n /**\n * 完成阶段二任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageTwo(long id);\n\n /**\n * 完成阶段三任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageThree(long id);\n\n /**\n * 完成阶段四任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageFour(long id);\n\n /**\n * 查询阶段一状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n public int getStageOne(long id);\n\n /**\n * 查询阶段二状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageTwo(long id);\n\n /**\n * 查询阶段三状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageThree(long id);\n\n /**\n * 查询阶段四状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageFour(long id);\n\n}" }, { "identifier": "PayNotifyConfig", "path": "xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/config/PayNotifyConfig.java", "snippet": "@Configuration\npublic class PayNotifyConfig {\n\n // 交换机\n public static final String PAYNOTIFY_EXCHANGE_FANOUT = \"paynotify_exchange_fanout\";\n\n // 支付结果处理反馈队列\n public static final String PAYNOTIFY_REPLY_QUEUE = \"paynotify_reply_queue\";\n\n // 支付结果通知消息类型\n public static final String MESSAGE_TYPE = \"payresult_notify\";\n\n // 声明交换机\n @Bean(PAYNOTIFY_EXCHANGE_FANOUT)\n public FanoutExchange paynotify_exchange_fanout() {\n // 三个参数:交换机名称、是否持久化、当没有queue与其绑定时是否自动删除\n return new FanoutExchange(PAYNOTIFY_EXCHANGE_FANOUT, true, false);\n }\n\n // 支付结果回复队列\n @Bean(PAYNOTIFY_REPLY_QUEUE)\n public Queue msgnotify_result_queue() {\n return QueueBuilder.durable(PAYNOTIFY_REPLY_QUEUE).build();\n }\n\n}" }, { "identifier": "XcOrdersGoodsMapper", "path": "xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/mapper/XcOrdersGoodsMapper.java", "snippet": "public interface XcOrdersGoodsMapper extends BaseMapper<XcOrdersGoods> {\n\n}" }, { "identifier": "XcOrdersMapper", "path": "xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/mapper/XcOrdersMapper.java", "snippet": "public interface XcOrdersMapper extends BaseMapper<XcOrders> {\n\n}" }, { "identifier": "XcPayRecordMapper", "path": "xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/mapper/XcPayRecordMapper.java", "snippet": "public interface XcPayRecordMapper extends BaseMapper<XcPayRecord> {\n\n}" }, { "identifier": "AddOrderDto", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/dto/AddOrderDto.java", "snippet": "@Data\n@ToString\npublic class AddOrderDto {\n\n /**\n * 总价\n */\n private Float totalPrice;\n\n /**\n * 订单类型\n */\n private String orderType;\n\n /**\n * 订单名称\n */\n private String orderName;\n /**\n * 订单描述\n */\n private String orderDescrip;\n\n /**\n * 订单明细json,不可为空\n * [{\"goodsId\":\"\",\"goodsType\":\"\",\"goodsName\":\"\",\"goodsPrice\":\"\",\"goodsDetail\":\"\"},{...}]\n */\n private String orderDetail;\n\n /**\n * 外部系统业务id(这里为选课id)\n */\n private String outBusinessId;\n\n}" }, { "identifier": "PayRecordDto", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/dto/PayRecordDto.java", "snippet": "@Data\n@ToString\npublic class PayRecordDto extends XcPayRecord {\n\n //二维码\n private String qrcode;\n\n}" }, { "identifier": "PayStatusDto", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/dto/PayStatusDto.java", "snippet": "@Data\npublic class PayStatusDto {\n\n /**\n * 商户订单号\n */\n String out_trade_no;\n\n /**\n * 支付宝交易号\n */\n String trade_no;\n\n /**\n * 交易状态\n */\n String trade_status;\n\n /**\n * 支付宝的 appid\n */\n String app_id;\n\n /**\n * 总金额\n */\n String total_amount;\n\n}" }, { "identifier": "XcOrders", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/po/XcOrders.java", "snippet": "@Data\n@TableName(\"xc_orders\")\npublic class XcOrders implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 订单号\n */\n private Long id;\n\n /**\n * 总价\n */\n private Float totalPrice;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 交易状态\n */\n private String status;\n\n /**\n * 用户id\n */\n private String userId;\n\n\n /**\n * 订单类型\n */\n private String orderType;\n\n /**\n * 订单名称\n */\n private String orderName;\n\n /**\n * 订单描述\n */\n private String orderDescrip;\n\n /**\n * 订单明细json\n */\n private String orderDetail;\n\n /**\n * 外部系统业务id(这里实际上为选课id)\n */\n private String outBusinessId;\n\n\n}" }, { "identifier": "XcOrdersGoods", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/po/XcOrdersGoods.java", "snippet": "@Data\n@TableName(\"xc_orders_goods\")\npublic class XcOrdersGoods implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 订单号\n */\n private Long orderId;\n\n /**\n * 商品id\n */\n private String goodsId;\n\n /**\n * 商品类型\n */\n private String goodsType;\n\n /**\n * 商品名称\n */\n private String goodsName;\n\n /**\n * 商品交易价,单位分\n */\n private Float goodsPrice;\n\n /**\n * 商品详情json,可为空\n */\n private String goodsDetail;\n\n\n}" }, { "identifier": "XcPayRecord", "path": "xuecheng-plus-orders/xuecheng-plus-orders-model/src/main/java/com/xuecheng/orders/model/po/XcPayRecord.java", "snippet": "@Data\n@TableName(\"xc_pay_record\")\npublic class XcPayRecord implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 支付记录号\n */\n private Long id;\n\n /**\n * 本系统支付交易号\n */\n private Long payNo;\n\n /**\n * 第三方支付交易流水号\n */\n private String outPayNo;\n\n /**\n * 第三方支付渠道编号\n */\n private String outPayChannel;\n\n /**\n * 商品订单号\n */\n private Long orderId;\n\n /**\n * 订单名称\n */\n private String orderName;\n /**\n * 订单总价单位元\n */\n private Float totalPrice;\n\n /**\n * 币种CNY\n */\n private String currency;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 支付状态\n */\n private String status;\n\n /**\n * 支付成功时间\n */\n private LocalDateTime paySuccessTime;\n\n /**\n * 用户id\n */\n private String userId;\n\n\n}" }, { "identifier": "OrderService", "path": "xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/service/OrderService.java", "snippet": "public interface OrderService {\n\n /**\n * 创建商品订单,添加支付记录\n *\n * @param addOrderDto 订单信息\n * @return PayRecordDto 支付交易记录(包括二维码)\n * @author Mr.M\n * @since 2022/10/4 11:02\n */\n PayRecordDto createOrder(String userId, AddOrderDto addOrderDto);\n\n /**\n * 查询支付交易记录\n *\n * @param payNo 交易记录号\n * @return {@link com.xuecheng.orders.model.po.XcPayRecord}\n * @author Wuxy\n * @since 2022/10/20 23:38\n */\n XcPayRecord getPayRecordByPayNo(String payNo);\n\n /**\n * 保存支付宝支付结果(更新【支付记录】以及【订单】状态)\n *\n * @param payStatusDto 支付结果信息\n * @author Wuxy\n * @since 2022/10/4 16:52\n */\n void saveAliPayStatus(PayStatusDto payStatusDto);\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.base.utils.IdWorkerUtils; import com.xuecheng.base.utils.QRCodeUtil; import com.xuecheng.messagesdk.service.MqMessageService; import com.xuecheng.orders.config.PayNotifyConfig; import com.xuecheng.orders.mapper.XcOrdersGoodsMapper; import com.xuecheng.orders.mapper.XcOrdersMapper; import com.xuecheng.orders.mapper.XcPayRecordMapper; import com.xuecheng.orders.model.dto.AddOrderDto; import com.xuecheng.orders.model.dto.PayRecordDto; import com.xuecheng.orders.model.dto.PayStatusDto; import com.xuecheng.orders.model.po.XcOrders; import com.xuecheng.orders.model.po.XcOrdersGoods; import com.xuecheng.orders.model.po.XcPayRecord; import com.xuecheng.orders.service.OrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.LocalDateTime; import java.util.List;
5,463
package com.xuecheng.orders.service.impl; /** * 订单接口实现类 * * @author Wuxy * @version 1.0 * @since 2022/10/25 11:42 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { @Autowired XcOrdersMapper ordersMapper; @Autowired XcOrdersGoodsMapper ordersGoodsMapper; @Autowired XcPayRecordMapper payRecordMapper; @Autowired
package com.xuecheng.orders.service.impl; /** * 订单接口实现类 * * @author Wuxy * @version 1.0 * @since 2022/10/25 11:42 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { @Autowired XcOrdersMapper ordersMapper; @Autowired XcOrdersGoodsMapper ordersGoodsMapper; @Autowired XcPayRecordMapper payRecordMapper; @Autowired
MqMessageService mqMessageService;
3
2023-11-13 11:39:35+00:00
8k
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,654
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() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() { Config settingsConfig = getConfigManager().register("settings", getClass(), "/settings.yml", "settings.yml");
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() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() { Config settingsConfig = getConfigManager().register("settings", getClass(), "/settings.yml", "settings.yml");
getConfigManager().injectKeys(ConfigVariables.class, settingsConfig);
6
2023-11-18 10:12:16+00:00
8k
jensjeflensje/minecraft_typewriter
src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/BaseTypeWriter.java
[ { "identifier": "TypewriterPlugin", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java", "snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n getCommand(\"typewriter\").setExecutor(new SpawnCommand());\n getCommand(\"wc\").setExecutor(new CompleteCommand());\n getCommand(\"wr\").setExecutor(new RemoveCommand());\n getCommand(\"w\").setExecutor(new WriteCommand());\n getCommand(\"w\").setTabCompleter(new WriteTabCompleter());\n\n playerWriters = new HashMap<>();\n\n }\n\n @Override\n public void onDisable() {\n playerWriters.values().forEach(TypeWriter::destroy);\n }\n}" }, { "identifier": "Util", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/Util.java", "snippet": "public class Util {\n\n /**\n * Get the location of an offset from a location, rotated by a yaw.\n * @param baseLocation the origin of the rotation\n * @param offset the offset as a vector. Only uses X and Z coordinates\n * @param baseYaw the yaw for the rotation\n * @param pitch pitch value to add to the location\n * @param yaw yaw value to add to the baseYaw after rotation\n * @return the resulting Location\n */\n public static Location getRotatedLocation(\n Location baseLocation,\n Vector offset,\n float baseYaw,\n float pitch,\n float yaw\n ) {\n Location rotatedLocation = baseLocation.clone();\n rotatedLocation.add(getRotatedVector(offset, baseYaw));\n rotatedLocation.setYaw(baseYaw + yaw);\n rotatedLocation.setPitch(pitch);\n return rotatedLocation;\n }\n\n public static Vector getRotatedVector(\n Vector offset,\n float baseYaw\n ) {\n double sinus = Math.sin(baseYaw / 180 * Math.PI);\n double cosinus = Math.cos(baseYaw / 180 * Math.PI);\n double newX = offset.getX() * cosinus - offset.getZ() * sinus;\n double newZ = offset.getZ() * cosinus + offset.getX() * sinus;\n return new Vector(newX, offset.getY(), newZ);\n }\n\n}" }, { "identifier": "TypeWriterComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/TypeWriterComponent.java", "snippet": "public interface TypeWriterComponent {\n\n void setUp(Location location);\n void destroy();\n\n\n}" }, { "identifier": "BarTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BarTypeWriterButtonComponent.java", "snippet": "public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {\n\n private final double Y_VALUE = -0.15;\n\n private ItemStack skull;\n private List<ItemDisplay> skullDisplays;\n private int amount;\n\n @Getter\n private Location location;\n\n public BarTypeWriterButtonComponent(ItemStack skull, int amount) {\n this.skull = skull;\n this.amount = amount;\n this.skullDisplays = new ArrayList<>();\n }\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n\n for (int i = 0; i < this.amount; i++) {\n Location displayLocation = Util.getRotatedLocation(\n location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0);\n ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(\n displayLocation, EntityType.ITEM_DISPLAY);\n skullDisplay.setItemStack(this.skull);\n\n Transformation skullTransformation = skullDisplay.getTransformation();\n skullTransformation.getScale().set(0.2);\n skullDisplay.setTransformation(skullTransformation);\n\n this.skullDisplays.add(skullDisplay);\n }\n\n }\n\n @Override\n public void destroy() {\n this.skullDisplays.forEach(Entity::remove);\n }\n\n /**\n * Plays pressing animation.\n */\n public void press() {\n new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1);\n this.location.getWorld().playSound(\n this.location, Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.MASTER, 2f, 2f);\n }\n\n /**\n * Teleport each display to a specific offset from its original location.\n * @param offset a vector containing the offset\n */\n public void offsetTeleport(Vector offset) {\n this.skullDisplays.forEach(display -> {\n Location displayLocation = display.getLocation();\n displayLocation.setY(this.location.getY() + Y_VALUE);\n displayLocation.add(offset);\n display.teleport(displayLocation);\n });\n }\n}" }, { "identifier": "BaseTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BaseTypeWriterButtonComponent.java", "snippet": "public abstract class BaseTypeWriterButtonComponent implements TypeWriterComponent, TypeWriterButtonComponent{\n}" }, { "identifier": "CubeTypeWriterButtonComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/CubeTypeWriterButtonComponent.java", "snippet": "public class CubeTypeWriterButtonComponent extends BaseTypeWriterButtonComponent {\n\n private ItemStack skull;\n private ItemDisplay skullDisplay;\n private BlockDisplay pinDisplay;\n\n @Getter\n private Location location;\n private Location pinLocation;\n\n public CubeTypeWriterButtonComponent(ItemStack skull) {\n this.skull = skull;\n }\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n this.pinLocation = this.location.clone().add(\n Util.getRotatedVector(new Vector(-0.05, -0.05, -0.01), this.location.getYaw()));\n\n this.skullDisplay = (ItemDisplay) location.getWorld().spawnEntity(\n location, EntityType.ITEM_DISPLAY);\n this.skullDisplay.setItemStack(this.skull);\n\n Transformation skullTransformation = this.skullDisplay.getTransformation();\n skullTransformation.getScale().set(0.2);\n this.skullDisplay.setTransformation(skullTransformation);\n\n this.pinDisplay = (BlockDisplay) location.getWorld().spawnEntity(\n this.pinLocation, EntityType.BLOCK_DISPLAY);\n this.pinDisplay.setBlock(Material.OAK_FENCE.createBlockData());\n this.pinDisplay.setBrightness(new Display.Brightness(3, 3));\n Transformation transformation = this.pinDisplay.getTransformation();\n transformation.getScale().set(0.1, 0.3, 0.1);\n transformation.getLeftRotation().setAngleAxis(Math.toRadians(90), 1, 0, 0);\n this.pinDisplay.setTransformation(transformation);\n }\n\n @Override\n public void destroy() {\n this.skullDisplay.remove();\n this.pinDisplay.remove();\n }\n\n /**\n * Plays pressing animation.\n */\n public void press() {\n new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1);\n this.location.getWorld().playSound(\n this.location, Sound.BLOCK_WOODEN_TRAPDOOR_OPEN, SoundCategory.MASTER, 2f, 2f);\n }\n\n public void offsetTeleport(Vector offset) {\n this.skullDisplay.teleport(this.location.clone().add(offset));\n this.pinDisplay.teleport(this.pinLocation.clone().add(offset));\n }\n}" }, { "identifier": "MainTypeWriterCasingComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/casing/MainTypeWriterCasingComponent.java", "snippet": "public class MainTypeWriterCasingComponent implements TypeWriterComponent {\n\n private BlockDisplay display;\n private Location location;\n\n @Override\n public void setUp(Location location) {\n this.location = location;\n\n this.display = (BlockDisplay) location.getWorld().spawnEntity(\n location, EntityType.BLOCK_DISPLAY);\n this.display.setBlock(Material.STRIPPED_DARK_OAK_WOOD.createBlockData());\n this.display.setBrightness(new Display.Brightness(15, 15));\n Transformation transformation = this.display.getTransformation();\n transformation.getScale().set(2.5, 1, 1.65);\n transformation.getLeftRotation().setAngleAxis(Math.toRadians(10), 1, 0, 0);\n this.display.setTransformation(transformation);\n }\n\n @Override\n public void destroy() {\n this.display.remove();\n }\n\n}" }, { "identifier": "PaperTypeWriterComponent", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/paper/PaperTypeWriterComponent.java", "snippet": "public class PaperTypeWriterComponent implements TypeWriterComponent {\n\n // 2.16 is just magic\n // this is needed because Display.getWidth() always returns 0.0\n // I know it's stupid... but I haven't figured out what I should do, yet :P\n private final float TEXT_MAGIC = 2.16f;\n private final float PAPER_MAGIC = 4.35f; // another one\n\n private final float TEXT_SIZE = 0.20f;\n private final TextColor TEXT_COLOR = TextColor.color(0);\n private final int LINE_WIDTH = 175;\n private final float LINE_OFFSET = 0.05f;\n\n private ItemDisplay paperDisplay;\n private List<TextDisplay> textDisplays;\n private Location paperLocation;\n private Location textLocation;\n\n @Override\n public void setUp(Location location) {\n this.paperLocation = location.clone().add(Util.getRotatedVector(\n new Vector(\n -0.37, // start writing on the left of the paper\n -0.55, // a bit down so it starts at the top\n 0\n ),\n location.getYaw()\n ));\n\n this.textLocation = location.clone().add(location.getDirection().multiply(-0.1)); // a bit off the paper\n this.textLocation.setYaw(this.textLocation.getYaw() + 180); // flip so it's facing the player\n this.textLocation = Util.getRotatedLocation( // in the middle of the keyboard\n this.textLocation, new Vector(0.05, 0, 0), this.textLocation.getYaw(), 0, 0);\n\n this.paperDisplay = (ItemDisplay) this.paperLocation.getWorld().spawnEntity(\n this.paperLocation, EntityType.ITEM_DISPLAY);\n this.paperDisplay.setItemStack(new ItemStack(Material.PAPER));\n Transformation paperTransformation = this.paperDisplay.getTransformation();\n paperTransformation.getLeftRotation().setAngleAxis(-0.9, 0, 0, 1);\n paperTransformation.getScale().set(2.2);\n this.paperDisplay.setTransformation(paperTransformation);\n\n this.textDisplays = new ArrayList<>();\n\n this.newLine();\n }\n\n @Override\n public void destroy() {\n this.paperDisplay.remove();\n this.textDisplays.forEach(TextDisplay::remove);\n }\n\n public void applyAllEntities(Consumer<Display> func) {\n func.accept(this.paperDisplay);\n this.textDisplays.forEach(func);\n }\n\n public void setAnimation(Vector movement, int delay, int duration) {\n applyAllEntities(display -> display.setInterpolationDelay(delay));\n applyAllEntities(display -> display.setInterpolationDuration(duration));\n applyAllEntities(display -> {\n Transformation transformation = display.getTransformation();\n transformation.getTranslation().set(movement.getX(), movement.getY(), movement.getZ());\n display.setTransformation(transformation);\n });\n }\n\n public void moveUp() {\n this.textDisplays.forEach(display -> display.teleport(display.getLocation().add(0, LINE_OFFSET, 0)));\n this.paperDisplay.teleport(this.paperLocation.add(0, LINE_OFFSET, 0));\n }\n\n public void newLine() {\n // move every line (+ paper) up to make room for the new one\n this.moveUp();\n\n String line = \"\";\n\n TextDisplay textDisplay = (TextDisplay) this.textLocation.getWorld().spawnEntity(\n this.textLocation, EntityType.TEXT_DISPLAY);\n textDisplay.setAlignment(TextDisplay.TextAlignment.LEFT);\n textDisplay.setText(line);\n textDisplay.setLineWidth(LINE_WIDTH);\n textDisplay.setBackgroundColor(Color.fromARGB(0));\n\n Transformation textTransformation = textDisplay.getTransformation();\n textTransformation.getScale().set(TEXT_SIZE);\n textDisplay.setTransformation(textTransformation);\n\n this.textDisplays.add(textDisplay);\n this.moveLeft(line);\n }\n\n public float getFontOffset(String text) {\n int lineWidth = MinecraftFont.Font.getWidth(text);\n return (TEXT_SIZE / LINE_WIDTH) * lineWidth;\n }\n\n /**\n * Move left to account for the text size growing from the center.\n */\n public void moveLeft(String data) {\n float offset = this.getFontOffset(data);\n TextDisplay currentDisplay = this.textDisplays.get(this.textDisplays.size() - 1);\n\n currentDisplay.teleport(\n Util.getRotatedLocation(\n this.textLocation,\n new Vector(-offset * TEXT_MAGIC, 0, 0),\n currentDisplay.getYaw(),\n 0,\n 0\n ));\n\n float paperOffset = offset * PAPER_MAGIC;\n\n this.paperDisplay.teleport(this.paperLocation.clone().add(Util.getRotatedVector(\n // same with 4.35 here...\n new Vector(paperOffset, 0, 0),\n this.paperLocation.getYaw()\n )));\n\n // every line except the current\n for (int i = 0; i < this.textDisplays.size() - 1; i++) {\n TextDisplay textDisplay = this.textDisplays.get(i);\n\n textDisplay.teleport(\n this.textLocation.clone().add(Util.getRotatedVector(\n new Vector(\n -paperOffset + this.getFontOffset(textDisplay.text().toString())\n * TEXT_MAGIC - 3.34f, // another magic value, sorry\n this.LINE_OFFSET * (this.textDisplays.size() - i - 1),\n 0\n ), // negative because paper is flipped\n textDisplay.getLocation().getYaw()\n ))\n );\n }\n }\n\n public void newData(String data) {\n while (MinecraftFont.Font.getWidth(data) > LINE_WIDTH - 4) { // 4 to provide some padding for large words\n data = data.substring(0, data.length() - 1); // can't have longer lines than the paper\n }\n this.textDisplays.get(this.textDisplays.size() - 1).text(Component.text(data, TEXT_COLOR));\n this.moveLeft(data);\n }\n}" } ]
import com.destroystokyo.paper.profile.PlayerProfile; import com.destroystokyo.paper.profile.ProfileProperty; import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin; import dev.jensderuiter.minecrafttypewriter.Util; import dev.jensderuiter.minecrafttypewriter.typewriter.component.TypeWriterComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BarTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BaseTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.CubeTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.casing.MainTypeWriterCasingComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.paper.PaperTypeWriterComponent; import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
4,082
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) { component = new CubeTypeWriterButtonComponent(skull); } else {
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) { component = new CubeTypeWriterButtonComponent(skull); } else {
component = new BarTypeWriterButtonComponent(skull, 10);
3
2023-11-18 20:44:30+00:00
8k
ZhiQinIsZhen/dubbo-springboot3
dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/controller/search/investor/CompanyInvestorController.java
[ { "identifier": "CompanyInvestorDTO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/dto/search/investor/CompanyInvestorDTO.java", "snippet": "@Getter\n@Setter\npublic class CompanyInvestorDTO extends PageDTO {\n @Serial\n private static final long serialVersionUID = 4580544315167900762L;\n\n @Schema(description = \"公司ID\")\n private String companyId;\n}" }, { "identifier": "CompanyInvestorVO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/vo/search/investor/CompanyInvestorVO.java", "snippet": "@Getter\n@Setter\npublic class CompanyInvestorVO implements Serializable {\n @Serial\n private static final long serialVersionUID = 2524475764297876678L;\n\n @Schema(description = \"主键\")\n private String id;\n\n @Schema(description = \"公司ID\")\n private String companyId;\n\n @Schema(description = \"公司名称\")\n private String companyName;\n\n @Schema(description = \"投资机构名称\")\n private String investorName;\n\n @Schema(description = \"机构成立时间\")\n private String establishTime;\n\n @Schema(description = \"机构介绍\")\n private String mark;\n\n @Schema(description = \"logo\")\n private String logo;\n}" }, { "identifier": "PageResult", "path": "dubbo-common/dubbo-common-api-starter/src/main/java/com/liyz/boot3/common/api/result/PageResult.java", "snippet": "@Getter\n@Setter\n@JsonPropertyOrder({\"code\", \"message\", \"total\", \"pages\", \"pageNum\", \"pageSize\", \"hasNextPage\", \"data\"})\npublic class PageResult<T> {\n\n public PageResult() {}\n\n public PageResult(String code, String message) {\n this.code = code;\n this.message = message;\n this.total = 0L;\n this.pageNum = 1L;\n this.pageSize = 10L;\n }\n\n public PageResult(IExceptionService codeEnum) {\n this(codeEnum.getCode(), I18nMessageUtil.getMessage(codeEnum.getName(), codeEnum.getMessage(), null));\n }\n\n public PageResult(RemotePage<T> data) {\n this(CommonExceptionCodeEnum.SUCCESS);\n boolean isNull = data == null;\n this.setData(isNull ? List.of() : data.getList());\n this.total = isNull ? 0L : data.getTotal();\n this.pageNum = isNull ? 1 : data.getPageNum();\n this.pageSize = isNull ? 10 : data.getPageSize();\n }\n\n @Schema(description = \"code码\")\n private String code;\n\n @Schema(description = \"消息\")\n private String message;\n\n @Schema(description = \"总数量\")\n private Long total;\n\n @Schema(description = \"页码\")\n private Long pageNum;\n\n @Schema(description = \"每页条数\")\n private Long pageSize;\n\n @Schema(description = \"数据体\")\n private List<T> data;\n\n public static <T> PageResult<T> success(RemotePage<T> data) {\n return new PageResult<>(data);\n }\n\n public static <T> PageResult<T> error(String code, String message) {\n return new PageResult<T>(code, message);\n }\n\n public static <T> PageResult<T> error(IExceptionService codeEnum) {\n return new PageResult<>(codeEnum);\n }\n\n public void setPageNum(long pageNum) {\n this.pageNum = Math.max(1L, pageNum);\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": "Result", "path": "dubbo-common/dubbo-common-api-starter/src/main/java/com/liyz/boot3/common/api/result/Result.java", "snippet": "@Getter\n@Setter\n@JsonPropertyOrder({\"code\", \"message\", \"data\"})\npublic class Result<T> {\n\n public Result(String code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public Result(T data) {\n this(CommonExceptionCodeEnum.SUCCESS);\n this.data = data;\n }\n\n public Result(IExceptionService codeEnum) {\n this(codeEnum.getCode(), I18nMessageUtil.getMessage(codeEnum.getName(), codeEnum.getMessage(), null));\n }\n\n @Schema(description = \"code码\")\n private String code;\n\n @Schema(description = \"消息\")\n private String message;\n\n @Schema(description = \"数据体\")\n private T data;\n\n public static <E> Result<E> success(E data) {\n return new Result<>(data);\n }\n\n public static <E> Result<E> success() {\n return success(null);\n }\n\n public static <E> Result<E> error(IExceptionService codeEnum) {\n return new Result<>(codeEnum);\n }\n\n public static <E> Result<E> error(String code, String message) {\n return new Result<>(code, message);\n }\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": "CompanyInvestorBO", "path": "dubbo-service/dubbo-service-search/search-remote/src/main/java/com/liyz/boot3/service/search/bo/investor/CompanyInvestorBO.java", "snippet": "@Getter\n@Setter\npublic class CompanyInvestorBO extends BaseBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 2524475764297876678L;\n\n private String companyId;\n\n private String companyName;\n\n private String investorName;\n\n private String establishTime;\n\n private String mark;\n\n private String logo;\n}" }, { "identifier": "PageQuery", "path": "dubbo-service/dubbo-service-search/search-remote/src/main/java/com/liyz/boot3/service/search/query/PageQuery.java", "snippet": "@Getter\n@Setter\npublic class PageQuery implements Serializable {\n @Serial\n private static final long serialVersionUID = -7798227940102881776L;\n\n /**\n * 页码\n */\n private Integer pageNum = 1;\n\n /**\n * 每页数据条数\n */\n private Integer pageSize = 20;\n\n /**\n * 公司ID\n */\n private String companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * list查询最大数量\n */\n private Integer listMaxCount = 50;\n\n /**\n * 跟踪命中数\n */\n private Integer trackTotalHits = 1000;\n\n /**\n * 权重\n */\n private Integer slop;\n}" }, { "identifier": "RemoteCompanyInvestorService", "path": "dubbo-service/dubbo-service-search/search-remote/src/main/java/com/liyz/boot3/service/search/remote/investor/RemoteCompanyInvestorService.java", "snippet": "public interface RemoteCompanyInvestorService {\n\n CompanyInvestorBO getById(String id);\n\n RemotePage<CompanyInvestorBO> page(PageQuery pageQuery);\n}" } ]
import com.liyz.boot3.api.user.dto.search.investor.CompanyInvestorDTO; import com.liyz.boot3.api.user.vo.search.investor.CompanyInvestorVO; import com.liyz.boot3.common.api.result.PageResult; import com.liyz.boot3.common.api.result.Result; import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.security.client.annotation.Anonymous; import com.liyz.boot3.service.search.bo.investor.CompanyInvestorBO; import com.liyz.boot3.service.search.query.PageQuery; import com.liyz.boot3.service.search.remote.investor.RemoteCompanyInvestorService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import org.apache.dubbo.config.annotation.DubboReference; import org.springdoc.core.annotations.ParameterObject; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
3,656
package com.liyz.boot3.api.user.controller.search.investor; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2024/1/8 13:48 */ @Tag(name = "投资机构") @RestController @RequestMapping("/search/investor") public class CompanyInvestorController { @DubboReference private RemoteCompanyInvestorService remoteCompanyInvestorService; @Anonymous @Operation(summary = "根据id查询投资机构信息") @GetMapping("/id") public Result<CompanyInvestorVO> getById(@RequestParam("id") String id) {
package com.liyz.boot3.api.user.controller.search.investor; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2024/1/8 13:48 */ @Tag(name = "投资机构") @RestController @RequestMapping("/search/investor") public class CompanyInvestorController { @DubboReference private RemoteCompanyInvestorService remoteCompanyInvestorService; @Anonymous @Operation(summary = "根据id查询投资机构信息") @GetMapping("/id") public Result<CompanyInvestorVO> getById(@RequestParam("id") String id) {
CompanyInvestorBO investorBO = remoteCompanyInvestorService.getById(id);
6
2023-11-13 01:28:21+00:00
8k
glowingstone124/QAPI3
src/main/java/org/qo/ApiApplication.java
[ { "identifier": "Algorithm", "path": "src/main/java/org/qo/Algorithm.java", "snippet": "public class Algorithm {\n public static String token(String player_name, long qq) {\n String charset = \"qazxswedcvfrtgbnhyujmkiolp0129384756_POILKJMNBUYTHGFVCXREWQDSAZ\";\n ArrayList<Integer> remix = new ArrayList<>();\n if(qq<=0) throw new IllegalArgumentException(\"Invalid QQ ID\");\n long qq_copy = qq;\n for (qq = qq + 707; qq!=0; qq/=64) {\n remix.add((int) (qq%64));\n }\n for (char c:player_name.toCharArray()) {\n if(charset.indexOf(c)==-1) throw new IllegalArgumentException(\"Invalid player name character '\"+c+\"' in \"+player_name);\n remix.add(charset.indexOf(c));\n }\n if(remix.size()%2==1) remix.add((int) (qq_copy%32) * 2);\n String result = \"\";\n double node = 707;\n int size = remix.size()/2;\n for(int i = 0; i < 16; i++) {\n double value = 0;\n for(int j = 0; j < size; j++) {\n value += Math.sin(remix.get(j * 2) * node + remix.get(j * 2 + 1));\n }\n node += value * 707;\n result = result + Integer.toHexString(sigmoid(value));\n }\n return result;\n }\n\n public static int sigmoid(double value) {\n double sigmoid_result = 1d/(1d+Math.exp(0-value));\n int result = (int) Math.floor(sigmoid_result * 256);\n if(result >= 256) return 255;\n else return Math.max(result, 0);\n }\n 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 }\n}" }, { "identifier": "UserProcess", "path": "src/main/java/org/qo/UserProcess.java", "snippet": "public class UserProcess {\n public static final String CODE = \"users/recoverycode/index.json\";\n private static final String FILE_PATH = \"usermap.json\";\n private static final String SERVER_FILE_PATH = \"playermap.json\";\n public static final String SQL_CONFIGURATION = \"data/sql/info.json\";\n public static String jdbcUrl = getDatabaseInfo(\"url\");\n public static String sqlusername = getDatabaseInfo(\"username\");\n public static String sqlpassword = getDatabaseInfo(\"password\");\n\n public static String firstLoginSearch(String name, HttpServletRequest request) {\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM forum WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, name);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n Boolean first = resultSet.getBoolean(\"firstLogin\");\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", 0);\n responseJson.put(\"first\", first);\n resultSet.close();\n preparedStatement.close();\n\n return responseJson.toString();\n }\n String updateQuery = \"UPDATE forum SET firstLogin = ? WHERE username = ?\";\n PreparedStatement apreparedStatement = connection.prepareStatement(updateQuery);\n apreparedStatement.setBoolean(1, false);\n apreparedStatement.setString(2, name);\n Logger.log(IPUtil.getIpAddr(request) + \" username \" + name + \" qureied firstlogin.\", INFO);\n int rowsAffected = apreparedStatement.executeUpdate();\n apreparedStatement.close();\n connection.close();\n resultSet.close();\n preparedStatement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", 1);\n responseJson.put(\"first\", -1);\n Logger.log(IPUtil.getIpAddr(request) + \" username \" + name + \" qureied firstlogin but unsuccessful.\", INFO);\n return responseJson.toString();\n }\n public static String fetchMyinfo(String name, HttpServletRequest request) throws Exception {\n String date;\n Boolean premium;\n Boolean donate;\n if (name.isEmpty()) {\n\n }\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM forum WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, name);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n date = resultSet.getString(\"date\");\n premium = resultSet.getBoolean(\"premium\");\n donate = resultSet.getBoolean(\"donate\");\n String linkto = resultSet.getString(\"linkto\");\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"date\", date);\n responseJson.put(\"premium\", premium);\n responseJson.put(\"donate\", donate);\n responseJson.put(\"code\", 0);\n responseJson.put(\"linkto\", linkto);\n responseJson.put(\"username\", name);\n Logger.log(IPUtil.getIpAddr(request) + \"username \" + name + \" qureied myinfo.\", INFO);\n return responseJson.toString();\n } else {\n // No rows found for the given username\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", -1);\n Logger.log(IPUtil.getIpAddr(request) + \"username \" + name + \" qureied myinfo, but unsuccessful.\", INFO);\n return responseJson.toString();\n }\n\n } catch (SQLException e) {\n e.printStackTrace();\n JSONObject responseJson = new JSONObject();\n Logger.log(\"username \" + name + \" qureied myinfo, but unsuccessful.\", INFO);\n responseJson.put(\"code\", -1);\n return responseJson.toString();\n }\n }\n public static String getDatabaseInfo(String type) {\n JSONObject sqlObject = null;\n try {\n sqlObject = new JSONObject(Files.readString(Path.of(SQL_CONFIGURATION)));\n } catch (IOException e) {\n Logger.log(\"ERROR: SQL CONFIG NOT FOUND\",ERROR);\n }\n switch (type){\n case \"password\":\n return sqlObject.getString(\"password\");\n case \"username\":\n return sqlObject.getString(\"username\");\n case \"url\":\n return sqlObject.getString(\"url\");\n default:\n return null;\n }\n }\n public static void handleTime(String name, int time){\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n\n String query = \"INSERT INTO timeTables (name, time) VALUES (?, ?)\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n\n preparedStatement.setString(1, name);\n preparedStatement.setInt(2, time);\n preparedStatement.executeUpdate();\n preparedStatement.close();\n connection.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n public static JSONObject getTime(String username) {\n JSONObject result = null;\n try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {\n result = new JSONObject();\n String query = \"SELECT * FROM timeTables WHERE name = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n\n preparedStatement.setString(1, username);\n\n ResultSet resultSet = preparedStatement.executeQuery();\n\n if (resultSet.next()) {\n int time = resultSet.getInt(\"time\");\n result.put(\"name\", username);\n result.put(\"time\", time);\n } else {\n result.put(\"error\", -1);\n }\n\n resultSet.close();\n preparedStatement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n result.put(\"error\", e.getMessage());\n }\n\n return result;\n }\n public static boolean SQLAvliable() {\n boolean success = true;\n try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){\n } catch (SQLException e){\n success = false;\n }\n return success;\n }\n public static boolean queryForum(String username) throws Exception {\n boolean resultExists = false;\n\n try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {\n String selectQuery = \"SELECT * FROM forum WHERE username = ?\";\n Logger.log(selectQuery, INFO);\n\n try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {\n preparedStatement.setString(1, username);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n resultExists = resultSet.next();\n }\n }\n }\n return resultExists;\n }\n public static String queryHash(String hash) throws Exception {\n String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8);\n JSONObject codeObject = new JSONObject(jsonContent);\n\n if (codeObject.has(hash)) {\n String username = codeObject.getString(hash);\n String finalOutput = username;\n // codeObject.remove(hash);\n Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8));\n System.out.println(username);\n return finalOutput;\n } else {\n System.out.println(\"mismatched\");\n return null;\n }\n }\n public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception {\n String ArticleSheet;\n switch (ArticleSheets){\n case 0:\n ArticleSheet = \"serverArticles\";\n break;\n case 1:\n ArticleSheet = \"commandArticles\";\n break;\n case 2:\n ArticleSheet = \"attractionsArticles\";\n break;\n case 3:\n ArticleSheet = \"noticeArticles\";\n break;\n default:\n ArticleSheet = null;\n break;\n }\n\n try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {\n String selectQuery = \"SELECT * FROM \" + ArticleSheet +\" WHERE id = ?\";\n\n try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {\n preparedStatement.setInt(1, ArticleID);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n if (resultSet.next()) {\n String resultName = resultSet.getString(\"Name\");\n return resultName;\n } else {\n return null;\n }\n }\n }\n }\n }\n public static String queryReg(String name) throws Exception{\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM users WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, name);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n Long uid = resultSet.getLong(\"uid\");\n Boolean frozen = resultSet.getBoolean(\"frozen\");\n int eco = resultSet.getInt(\"economy\");\n\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", 0);\n responseJson.put(\"frozen\", frozen);\n responseJson.put(\"qq\", uid);\n responseJson.put(\"economy\", eco);\n return responseJson.toString();\n }\n resultSet.close();\n preparedStatement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", 1);\n responseJson.put(\"qq\", -1);\n return responseJson.toString();\n }\n public static void regforum(String username, String password) throws Exception{\n // 解析JSON数据为JSONArray\n Calendar calendar = Calendar.getInstance();\n int year = calendar.get(Calendar.YEAR);\n int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n String date = year + \"-\" + month + \"-\" + day;\n String EncryptedPswd = hashSHA256(password);\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n // 准备插入语句\n String insertQuery = \"INSERT INTO forum (username, date, password, premium, donate, firstLogin, linkto) VALUES (?, ?, ?, ?, ?, ?, ?)\";\n PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);\n // 设置参数值\n preparedStatement.setString(1, username);\n preparedStatement.setString(2, date);\n preparedStatement.setString(3, EncryptedPswd);\n preparedStatement.setBoolean(4, false);\n preparedStatement.setBoolean(5, false);\n preparedStatement.setBoolean(6, true);\n preparedStatement.setString(7, \"EMPTY\");\n preparedStatement.executeUpdate();\n // 关闭资源\n preparedStatement.close();\n connection.close();\n }\n public static String regMinecraftUser(String name, Long uid, HttpServletRequest request){\n if (!UserProcess.dumplicateUID(uid) && name != null && uid != null) {\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String insertQuery = \"INSERT INTO users (username, uid,frozen, remain, economy) VALUES (?, ?, ?, ?, ?)\";\n PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);\n preparedStatement.setString(1, name);preparedStatement.setLong(2, uid);\n preparedStatement.setBoolean(3, false);\n preparedStatement.setInt(4, 3);preparedStatement.setInt(5,0);\n int rowsAffected = preparedStatement.executeUpdate();\n System.out.println(rowsAffected + \" row(s) inserted.\" + \"from \" + IPUtil.getIpAddr(request));\n System.out.println(name + \" Registered.\");\n preparedStatement.close();\n connection.close();UserProcess.insertIp(IPUtil.getIpAddr(request));\n return ReturnInterface.success(\"Success!\");\n } catch (Exception e) {\n e.printStackTrace();\n return ReturnInterface.failed(\"FAILED\");\n }\n }\n return ReturnInterface.failed(\"FAILED\");\n }\n public static String AvatarTrans(String name) throws Exception{\n String apiURL = \"https://api.mojang.com/users/profiles/minecraft/\" + name;\n String avatarURL = \"https://playerdb.co/api/player/minecraft/\";\n if (!AvatarCache.has(name)) {\n JSONObject uuidobj = new JSONObject(Request.sendGetRequest(apiURL));\n String uuid = uuidobj.getString(\"id\");\n JSONObject playerUUIDobj = new JSONObject(Request.sendGetRequest(avatarURL + uuid));\n if (playerUUIDobj.getBoolean(\"success\")) {\n JSONObject player = playerUUIDobj.getJSONObject(\"data\").getJSONObject(\"player\");\n JSONObject returnObject = new JSONObject();\n returnObject.put(\"url\", player.getString(\"avatar\"));\n returnObject.put(\"name\", player.getString(\"username\"));\n AvatarCache.cache(player.getString(\"avatar\"), player.getString(\"username\"));\n return returnObject.toString();\n } else {\n JSONObject returnObject = new JSONObject();\n returnObject.put(\"url\", \"https://crafthead.net/avatar/8667ba71b85a4004af54457a9734eed7\");\n returnObject.put(\"name\", name);\n return returnObject.toString();\n }\n }\n JSONObject returnObject = new JSONObject();\n returnObject.put(\"url\", \"https://crafthead.net/avatar/8667ba71b85a4004af54457a9734eed7\");\n returnObject.put(\"name\", name);\n return returnObject.toString();\n }\n public static String downloadMemorial() throws IOException {\n String filePath = \"data/memorial.json\";\n\n // Read the content of the file and return it as the response\n try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {\n StringBuilder content = new StringBuilder();\n String line;\n while ((line = br.readLine()) != null) {\n content.append(line);\n }\n return content.toString();\n } catch (IOException e) {\n e.printStackTrace();\n throw e;\n }\n }\n public static String readFile(String filename) {\n try {\n BufferedReader reader = new BufferedReader(new FileReader(filename));\n StringBuilder content = new StringBuilder();\n String line;\n\n while ((line = reader.readLine()) != null) {\n content.append(line);\n }\n\n reader.close();\n\n return content.toString();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n public static String Link(String forum, String name){\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT linkto FROM forum WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, forum);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n String resultname = resultSet.getString(\"linkto\");\n if (Objects.equals(resultname, \"EMPTY\")) {\n String updateQuery = \"UPDATE forum SET linkto = ? WHERE username = ?\";\n PreparedStatement updateStatement = connection.prepareStatement(updateQuery);\n while (resultSet.next()) {\n String username = forum;\n String linkAccount = name;\n updateStatement.setString(1, linkAccount);\n updateStatement.setString(2, username);\n updateStatement.executeUpdate();\n }\n return \"DONE\";\n } else {\n return \"ERROR: Already Linked\";\n }\n }\n } catch (Exception e){\n e.printStackTrace();\n }\n return \"failed\";\n }\n public static String queryLink(String forum){\n try{\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM forum WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, forum);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n return resultSet.getString(\"linkto\");\n }\n resultSet.close();\n preparedStatement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n public static boolean hasIp(String ip){\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM iptable WHERE ip = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, ip);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n return true;\n }\n resultSet.close();\n preparedStatement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n public static boolean insertIp(String ip) {\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"INSERT INTO iptable (ip) VALUES (?)\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, ip);\n int rowsAffected = preparedStatement.executeUpdate();\n preparedStatement.close();\n connection.close();\n return rowsAffected > 0;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n\n public static boolean dumplicateUID(long uid){\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM users WHERE uid = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setLong(1, uid);\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n return true;\n }\n resultSet.close();\n preparedStatement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n public static boolean changeHash(String username, String hash) {\n boolean success = false;\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"UPDATE forum SET password = ? WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, hash);\n preparedStatement.setString(2, username);\n int rowsUpdated = preparedStatement.executeUpdate();\n if (rowsUpdated > 0) {\n success = true;\n } else {\n\n }\n preparedStatement.close();\n connection.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return success;\n }\n public static String userLogin(String username, String password, HttpServletRequest request){\n try {\n // 连接到数据库\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n String query = \"SELECT * FROM forum WHERE username = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(query);\n preparedStatement.setString(1, username);\n\n // 执行查询\n ResultSet resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n String storedHashedPassword = resultSet.getString(\"password\");\n String encryptPswd = hashSHA256(password);\n if (Objects.equals(encryptPswd, storedHashedPassword)) {\n Logger.log(IPUtil.getIpAddr(request) + \" \" + username + \" login successful.\", ERROR);\n return ReturnInterface.success(\"成功\");\n }\n } else {\n Logger.log(\"username \" + username + \" login failed.\", ERROR);\n return ReturnInterface.denied(\"登录失败\");\n }\n connection.close();\n preparedStatement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n JSONObject responseJson = new JSONObject();\n responseJson.put(\"code\", -1);\n return responseJson.toString();\n }\n return ReturnInterface.failed(\"NULL\");\n }\n public static String operateEco(String username, int value, opEco operation){\n String updateSql = \"UPDATE users SET economy = economy - ? WHERE username = ?\";\n try {\n Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);\n if (operation == opEco.ADD) {\n updateSql = \"UPDATE users SET economy = economy + ? WHERE username = ?\";\n }\n try (PreparedStatement preparedStatement = connection.prepareStatement(updateSql)) {\n preparedStatement.setInt(1, value);\n preparedStatement.setString(2, username);\n int rowsUpdated = preparedStatement.executeUpdate();\n if (rowsUpdated > 0) {\n return \"success\";\n } else {\n return \"failed\";\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return \"failed\";\n }\n public enum opEco{\n ADD,\n REMOVE,\n MINUS\n }\n}" } ]
import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.catalina.User; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.*; import static org.qo.Algorithm.*; import static org.qo.UserProcess.*;
6,479
package org.qo; @RestController @SpringBootApplication public class ApiApplication implements ErrorController { public static String status; public static String serverStatus; public static int serverAlive; public static long PackTime; public static String CreativeStatus; Path filePath = Paths.get("app/latest/QCommunity-3.0.3-Setup.exe"); Path webdlPath = Paths.get("webs/download.html"); public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static Map<String, Integer> SurvivalMsgList = new HashMap<String, Integer>(); public static Map<String, Integer> CreativeMsgList = new HashMap<String, Integer>(); String jsonData = "data/playermap.json"; public static String noticeData = "data/notice.json"; public ApiApplication() throws IOException { } @RequestMapping("/") public String root() { JSONObject returnObj = new JSONObject(); returnObj.put("code",0); returnObj.put("build", "202312081719"); return returnObj.toString(); } @RequestMapping("/error") public String error(HttpServletRequest request, HttpServletResponse response){ JSONObject returnObj = new JSONObject(); long timeStamp = System.currentTimeMillis(); returnObj.put("timestamp", timeStamp); returnObj.put("error", response.getStatus()); returnObj.put("code", -1); return returnObj.toString(); } @RequestMapping("/introduction") public String introductionMenu() { try { if ((Files.readString(Path.of("forum/introduction/main.json"), StandardCharsets.UTF_8) != null)) { return Files.readString(Path.of("forum/introduction/main.json")); } } catch (IOException e) { return ReturnInterface.failed("ERROR:CONFIGURATION NOT FOUND"); } return ReturnInterface.failed("ERROR"); } @RequestMapping("/introduction/server") public String serverIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception { if (articleID == -1) { return Files.readString(Path.of("forum/introduction/server/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/server/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/server/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @PostMapping("/qo/apihook") public String webhook(@RequestBody String data) { System.out.println(data); return null; } @RequestMapping("/introduction/attractions") public String attractionIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/attractions/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/commands") public String commandIntros(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/commands/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/notice") public String notice(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/notices/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @GetMapping("/forum/login") public String userLogin(@RequestParam(name="username", required = true)String username, @RequestParam(name = "password", required = true)String password , HttpServletRequest request) {
package org.qo; @RestController @SpringBootApplication public class ApiApplication implements ErrorController { public static String status; public static String serverStatus; public static int serverAlive; public static long PackTime; public static String CreativeStatus; Path filePath = Paths.get("app/latest/QCommunity-3.0.3-Setup.exe"); Path webdlPath = Paths.get("webs/download.html"); public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static Map<String, Integer> SurvivalMsgList = new HashMap<String, Integer>(); public static Map<String, Integer> CreativeMsgList = new HashMap<String, Integer>(); String jsonData = "data/playermap.json"; public static String noticeData = "data/notice.json"; public ApiApplication() throws IOException { } @RequestMapping("/") public String root() { JSONObject returnObj = new JSONObject(); returnObj.put("code",0); returnObj.put("build", "202312081719"); return returnObj.toString(); } @RequestMapping("/error") public String error(HttpServletRequest request, HttpServletResponse response){ JSONObject returnObj = new JSONObject(); long timeStamp = System.currentTimeMillis(); returnObj.put("timestamp", timeStamp); returnObj.put("error", response.getStatus()); returnObj.put("code", -1); return returnObj.toString(); } @RequestMapping("/introduction") public String introductionMenu() { try { if ((Files.readString(Path.of("forum/introduction/main.json"), StandardCharsets.UTF_8) != null)) { return Files.readString(Path.of("forum/introduction/main.json")); } } catch (IOException e) { return ReturnInterface.failed("ERROR:CONFIGURATION NOT FOUND"); } return ReturnInterface.failed("ERROR"); } @RequestMapping("/introduction/server") public String serverIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception { if (articleID == -1) { return Files.readString(Path.of("forum/introduction/server/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/server/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/server/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @PostMapping("/qo/apihook") public String webhook(@RequestBody String data) { System.out.println(data); return null; } @RequestMapping("/introduction/attractions") public String attractionIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/attractions/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/commands") public String commandIntros(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/commands/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/notice") public String notice(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/notices/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @GetMapping("/forum/login") public String userLogin(@RequestParam(name="username", required = true)String username, @RequestParam(name = "password", required = true)String password , HttpServletRequest request) {
return UserProcess.userLogin(username,password,request);
1
2023-11-15 13:38:53+00:00
8k
martin-bian/DimpleBlog
dimple-tools/src/main/java/com/dimple/service/impl/PictureServiceImpl.java
[ { "identifier": "Picture", "path": "dimple-tools/src/main/java/com/dimple/domain/Picture.java", "snippet": "@Data\n@Entity\n@Table(name = \"tool_picture\")\npublic class Picture implements Serializable {\n\n @Id\n @Column(name = \"picture_id\")\n @ApiModelProperty(value = \"ID\", hidden = true)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @ApiModelProperty(value = \"文件名\")\n private String filename;\n\n @ApiModelProperty(value = \"图片url\")\n private String url;\n\n @ApiModelProperty(value = \"图片大小\")\n private String size;\n\n @ApiModelProperty(value = \"图片高\")\n private String height;\n\n @ApiModelProperty(value = \"图片宽\")\n private String width;\n\n @Column(name = \"delete_url\")\n @ApiModelProperty(value = \"用于删除的url\")\n private String delete;\n\n @ApiModelProperty(value = \"创建者\")\n private String username;\n\n @CreationTimestamp\n @ApiModelProperty(value = \"创建时间\")\n private Timestamp createTime;\n\n /**\n * 用于检测文件是否重复\n */\n private String md5Code;\n\n @Override\n public String toString() {\n return \"Picture{\" +\n \"filename='\" + filename + '\\'' +\n '}';\n }\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": "PictureRepository", "path": "dimple-tools/src/main/java/com/dimple/repository/PictureRepository.java", "snippet": "public interface PictureRepository extends JpaRepository<Picture, Long>, JpaSpecificationExecutor<Picture> {\n\n /**\n * 根据 Mds 值查询文件\n *\n * @param code 值\n * @return /\n */\n Picture findByMd5Code(String code);\n\n /**\n * 根据连接地址查询\n *\n * @param url /\n * @return /\n */\n boolean existsByUrl(String url);\n}" }, { "identifier": "PictureService", "path": "dimple-tools/src/main/java/com/dimple/service/PictureService.java", "snippet": "public interface PictureService {\n\n /**\n * 分页查询\n *\n * @param criteria 条件\n * @param pageable 分页参数\n * @return /\n */\n Object queryAll(PictureQueryCriteria criteria, Pageable pageable);\n\n /**\n * 查询全部数据\n *\n * @param criteria 条件\n * @return /\n */\n List<Picture> queryAll(PictureQueryCriteria criteria);\n\n /**\n * 上传文件\n *\n * @param file /\n * @param username /\n * @return /\n */\n Picture upload(MultipartFile file, String username);\n\n /**\n * 根据ID查询\n *\n * @param id /\n * @return /\n */\n Picture findById(Long id);\n\n /**\n * 多选删除\n *\n * @param ids /\n */\n void deleteAll(Long[] ids);\n\n /**\n * 导出\n *\n * @param queryAll 待导出的数据\n * @param response /\n * @throws IOException /\n */\n void download(List<Picture> queryAll, HttpServletResponse response) throws IOException;\n\n /**\n * 同步数据\n */\n void synchronize();\n}" }, { "identifier": "PictureQueryCriteria", "path": "dimple-tools/src/main/java/com/dimple/service/dto/PictureQueryCriteria.java", "snippet": "@Data\npublic class PictureQueryCriteria {\n\n @Query(type = Query.Type.INNER_LIKE)\n private String filename;\n\n @Query(type = Query.Type.INNER_LIKE)\n private String username;\n\n @Query(type = Query.Type.BETWEEN)\n private List<Timestamp> createTime;\n}" }, { "identifier": "Constant", "path": "dimple-common/src/main/java/com/dimple/utils/Constant.java", "snippet": "public class Constant {\n\n /**\n * 用于IP定位转换\n */\n public static final String REGION = \"内网IP|内网IP\";\n /**\n * win 系统\n */\n public static final String WIN = \"win\";\n\n /**\n * mac 系统\n */\n public static final String MAC = \"mac\";\n\n /**\n * 常用接口\n */\n public static class Url {\n // 免费图床\n public static final String SM_MS_URL = \"https://sm.ms/api\";\n // IP归属地查询\n public static final String IP_URL = \"http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true\";\n }\n}" }, { "identifier": "FileUtil", "path": "dimple-common/src/main/java/com/dimple/utils/FileUtil.java", "snippet": "public class FileUtil extends cn.hutool.core.io.FileUtil {\n /**\n * 系统临时目录\n * <br>\n * windows 包含路径分割符,但Linux 不包含,\n * 在windows \\\\==\\ 前提下,\n * 为安全起见 同意拼装 路径分割符,\n * <pre>\n * java.io.tmpdir\n * windows : C:\\Users/xxx\\AppData\\Local\\Temp\\\n * linux: /temp\n * </pre>\n */\n public static final String SYS_TEM_DIR = System.getProperty(\"java.io.tmpdir\") + File.separator;\n private static final Logger log = LoggerFactory.getLogger(FileUtil.class);\n /**\n * 定义GB的计算常量\n */\n private static final int GB = 1024 * 1024 * 1024;\n /**\n * 定义MB的计算常量\n */\n private static final int MB = 1024 * 1024;\n /**\n * 定义KB的计算常量\n */\n private static final int KB = 1024;\n\n /**\n * 格式化小数\n */\n private static final DecimalFormat DF = new DecimalFormat(\"0.00\");\n\n /**\n * MultipartFile转File\n */\n public static File toFile(MultipartFile multipartFile) {\n // 获取文件名\n String fileName = multipartFile.getOriginalFilename();\n // 获取文件后缀\n String prefix = \".\" + getExtensionName(fileName);\n File file = null;\n try {\n // 用uuid作为文件名,防止生成的临时文件重复\n file = File.createTempFile(IdUtil.simpleUUID(), prefix);\n // MultipartFile to File\n multipartFile.transferTo(file);\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n return file;\n }\n\n /**\n * 获取文件扩展名,不带 .\n */\n public static String getExtensionName(String filename) {\n if ((filename != null) && (filename.length() > 0)) {\n int dot = filename.lastIndexOf('.');\n if ((dot > -1) && (dot < (filename.length() - 1))) {\n return filename.substring(dot + 1);\n }\n }\n return filename;\n }\n\n /**\n * Java文件操作 获取不带扩展名的文件名\n */\n public static String getFileNameNoEx(String filename) {\n if ((filename != null) && (filename.length() > 0)) {\n int dot = filename.lastIndexOf('.');\n if ((dot > -1) && (dot < (filename.length()))) {\n return filename.substring(0, dot);\n }\n }\n return filename;\n }\n\n /**\n * 文件大小转换\n */\n public static String getSize(long size) {\n String resultSize;\n if (size / GB >= 1) {\n //如果当前Byte的值大于等于1GB\n resultSize = DF.format(size / (float) GB) + \"GB \";\n } else if (size / MB >= 1) {\n //如果当前Byte的值大于等于1MB\n resultSize = DF.format(size / (float) MB) + \"MB \";\n } else if (size / KB >= 1) {\n //如果当前Byte的值大于等于1KB\n resultSize = DF.format(size / (float) KB) + \"KB \";\n } else {\n resultSize = size + \"B \";\n }\n return resultSize;\n }\n\n /**\n * inputStream 转 File\n */\n static File inputStreamToFile(InputStream ins, String name) throws Exception {\n File file = new File(SYS_TEM_DIR + name);\n if (file.exists()) {\n return file;\n }\n OutputStream os = new FileOutputStream(file);\n int bytesRead;\n int len = 8192;\n byte[] buffer = new byte[len];\n while ((bytesRead = ins.read(buffer, 0, len)) != -1) {\n os.write(buffer, 0, bytesRead);\n }\n os.close();\n ins.close();\n return file;\n }\n\n /**\n * 将文件名解析成文件的上传路径\n */\n public static File upload(MultipartFile file, String filePath) {\n Date date = new Date();\n SimpleDateFormat format = new SimpleDateFormat(\"yyyyMMddhhmmssS\");\n String name = getFileNameNoEx(file.getOriginalFilename());\n String suffix = getExtensionName(file.getOriginalFilename());\n String nowStr = \"-\" + format.format(date);\n try {\n String fileName = name + nowStr + \".\" + suffix;\n String path = filePath + fileName;\n // getCanonicalFile 可解析正确各种路径\n File dest = new File(path).getCanonicalFile();\n // 检测是否存在目录\n if (!dest.getParentFile().exists()) {\n if (!dest.getParentFile().mkdirs()) {\n System.out.println(\"was not successful.\");\n }\n }\n // 文件写入\n file.transferTo(dest);\n return dest;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return null;\n }\n\n /**\n * 导出excel\n */\n public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {\n String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + \".xlsx\";\n File file = new File(tempPath);\n BigExcelWriter writer = ExcelUtil.getBigWriter(file);\n // 一次性写出内容,使用默认样式,强制输出标题\n writer.write(list, true);\n //response为HttpServletResponse对象\n response.setContentType(\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8\");\n //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码\n response.setHeader(\"Content-Disposition\", \"attachment;filename=file.xlsx\");\n ServletOutputStream out = response.getOutputStream();\n // 终止后删除临时文件\n file.deleteOnExit();\n writer.flush(out, true);\n //此处记得关闭输出Servlet流\n IoUtil.close(out);\n }\n\n public static String getFileType(String type) {\n String documents = \"txt doc pdf ppt pps xlsx xls docx\";\n String music = \"mp3 wav wma mpa ram ra aac aif m4a\";\n String video = \"avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg\";\n String image = \"bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg\";\n if (image.contains(type)) {\n return \"图片\";\n } else if (documents.contains(type)) {\n return \"文档\";\n } else if (music.contains(type)) {\n return \"音乐\";\n } else if (video.contains(type)) {\n return \"视频\";\n } else {\n return \"其他\";\n }\n }\n\n public static void checkSize(long maxSize, long size) {\n // 1M\n int len = 1024 * 1024;\n if (size > (maxSize * len)) {\n throw new BadRequestException(\"文件超出规定大小\");\n }\n }\n\n /**\n * 判断两个文件是否相同\n */\n public static boolean check(File file1, File file2) {\n String img1Md5 = getMd5(file1);\n String img2Md5 = getMd5(file2);\n return img1Md5.equals(img2Md5);\n }\n\n /**\n * 判断两个文件是否相同\n */\n public static boolean check(String file1Md5, String file2Md5) {\n return file1Md5.equals(file2Md5);\n }\n\n private static byte[] getByte(File file) {\n // 得到文件长度\n byte[] b = new byte[(int) file.length()];\n try {\n InputStream in = new FileInputStream(file);\n try {\n System.out.println(in.read(b));\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n } catch (FileNotFoundException e) {\n log.error(e.getMessage(), e);\n return null;\n }\n return b;\n }\n\n private static String getMd5(byte[] bytes) {\n // 16进制字符\n char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n try {\n MessageDigest mdTemp = MessageDigest.getInstance(\"MD5\");\n mdTemp.update(bytes);\n byte[] md = mdTemp.digest();\n int j = md.length;\n char[] str = new char[j * 2];\n int k = 0;\n // 移位 输出字符串\n for (byte byte0 : md) {\n str[k++] = hexDigits[byte0 >>> 4 & 0xf];\n str[k++] = hexDigits[byte0 & 0xf];\n }\n return new String(str);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return null;\n }\n\n /**\n * 下载文件\n *\n * @param request /\n * @param response /\n * @param file /\n */\n public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {\n response.setCharacterEncoding(request.getCharacterEncoding());\n response.setContentType(\"application/octet-stream\");\n FileInputStream fis = null;\n try {\n fis = new FileInputStream(file);\n response.setHeader(\"Content-Disposition\", \"attachment; filename=\" + file.getName());\n IOUtils.copy(fis, response.getOutputStream());\n response.flushBuffer();\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n } finally {\n if (fis != null) {\n try {\n fis.close();\n if (deleteOnExit) {\n file.deleteOnExit();\n }\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n }\n }\n }\n\n public static String getMd5(File file) {\n return getMd5(getByte(file));\n }\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}" }, { "identifier": "TranslatorUtil", "path": "dimple-common/src/main/java/com/dimple/utils/TranslatorUtil.java", "snippet": "public class TranslatorUtil {\n\n public static String translate(String word) {\n try {\n String url = \"https://translate.googleapis.com/translate_a/single?\" +\n \"client=gtx&\" +\n \"sl=en\" +\n \"&tl=zh-CN\" +\n \"&dt=t&q=\" + URLEncoder.encode(word, \"UTF-8\");\n\n URL obj = new URL(url);\n HttpURLConnection con = (HttpURLConnection) obj.openConnection();\n con.setRequestProperty(\"User-Agent\", \"Mozilla/5.0\");\n\n BufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream()));\n String inputLine;\n StringBuilder response = new StringBuilder();\n\n while ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n }\n in.close();\n return parseResult(response.toString());\n } catch (Exception e) {\n return word;\n }\n }\n\n private static String parseResult(String inputJson) {\n JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);\n StringBuilder result = new StringBuilder();\n for (Object o : jsonArray2) {\n result.append(((JSONArray) o).get(0).toString());\n }\n return result.toString();\n }\n}" }, { "identifier": "ValidationUtil", "path": "dimple-common/src/main/java/com/dimple/utils/ValidationUtil.java", "snippet": "public class ValidationUtil {\n\n /**\n * 验证空\n */\n public static void isNull(Object obj, String entity, String parameter, Object value) {\n if (ObjectUtil.isNull(obj)) {\n String msg = entity + \" 不存在: \" + parameter + \" is \" + value;\n throw new BadRequestException(msg);\n }\n }\n\n /**\n * 验证是否为邮箱\n */\n public static boolean isEmail(String email) {\n return new EmailValidator().isValid(email, null);\n }\n}" } ]
import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.dimple.domain.Picture; import com.dimple.exception.BadRequestException; import com.dimple.repository.PictureRepository; import com.dimple.service.PictureService; import com.dimple.service.dto.PictureQueryCriteria; import com.dimple.utils.Constant; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.TranslatorUtil; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
6,560
package com.dimple.service.impl; /** * @className: PictureServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RequiredArgsConstructor @Service(value = "pictureService") public class PictureServiceImpl implements PictureService { private static final String SUCCESS = "success"; private static final String CODE = "code"; private static final String MSG = "message"; private final PictureRepository pictureRepository; @Value("${smms.token}") private String token; @Override public Object queryAll(PictureQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<Picture> queryAll(PictureQueryCriteria criteria) { return pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Throwable.class) public Picture upload(MultipartFile multipartFile, String username) { File file = FileUtil.toFile(multipartFile); // 验证是否重复上传 Picture picture = pictureRepository.findByMd5Code(FileUtil.getMd5(file)); if (picture != null) { return picture; } HashMap<String, Object> paramMap = new HashMap<>(1); paramMap.put("smfile", file); // 上传文件 String result = HttpRequest.post(Constant.Url.SM_MS_URL + "/v2/upload") .header("Authorization", token) .form(paramMap) .timeout(20000) .execute().body(); JSONObject jsonObject = JSONUtil.parseObj(result); if (!jsonObject.get(CODE).toString().equals(SUCCESS)) {
package com.dimple.service.impl; /** * @className: PictureServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RequiredArgsConstructor @Service(value = "pictureService") public class PictureServiceImpl implements PictureService { private static final String SUCCESS = "success"; private static final String CODE = "code"; private static final String MSG = "message"; private final PictureRepository pictureRepository; @Value("${smms.token}") private String token; @Override public Object queryAll(PictureQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<Picture> queryAll(PictureQueryCriteria criteria) { return pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Throwable.class) public Picture upload(MultipartFile multipartFile, String username) { File file = FileUtil.toFile(multipartFile); // 验证是否重复上传 Picture picture = pictureRepository.findByMd5Code(FileUtil.getMd5(file)); if (picture != null) { return picture; } HashMap<String, Object> paramMap = new HashMap<>(1); paramMap.put("smfile", file); // 上传文件 String result = HttpRequest.post(Constant.Url.SM_MS_URL + "/v2/upload") .header("Authorization", token) .form(paramMap) .timeout(20000) .execute().body(); JSONObject jsonObject = JSONUtil.parseObj(result); if (!jsonObject.get(CODE).toString().equals(SUCCESS)) {
throw new BadRequestException(TranslatorUtil.translate(jsonObject.get(MSG).toString()));
9
2023-11-10 03:30:36+00:00
8k
LazyCoder0101/LazyCoder
service/src/main/java/com/lazycoder/service/service/impl/ModuleServiceImpl.java
[ { "identifier": "ModuleRelatedParam", "path": "database/src/main/java/com/lazycoder/database/common/ModuleRelatedParam.java", "snippet": "@Data\n@AllArgsConstructor\npublic class ModuleRelatedParam {\n\n @JSONField(deserializeUsing = ModuleDeserializer.class)\n private Module module = null;\n\n @JSONField(deserializeUsing = ModuleInfoDeserializer.class)\n private ModuleInfo moduleInfo = null;\n\n}" }, { "identifier": "ModuleMapper", "path": "database/src/main/java/com/lazycoder/database/dao/ModuleMapper.java", "snippet": "@Mapper // 标识为mybatis数据层接口\n@Component(value = \"ModuleMapper\")\npublic interface ModuleMapper extends BaseModel {\n\n /**\n * 添加模块\n *\n * @return\n */\n public void addModule(Module module);\n\n\n /**\n * 获取所有模块\n *\n * @return\n */\n public List<Module> getAllModuleList();\n\n /**\n * 按条件查询对应模块\n *\n * @param className 不需要该值就传null\n * @param usingRangeParam 不需要该值就传null\n * @param useSettingValue 不需要选择该参数就传一个小于-1的值\n * @return\n */\n public List<Module> getModuleList(@Param(\"className\") String className,\n @Param(\"usingRangeParam\") String usingRangeParam,\n @Param(\"useSettingValue\") int useSettingValue);\n\n /**\n * 获取模块\n *\n * @param className\n * @param moduleName\n * @return\n */\n public Module getModule(@Param(\"className\") String className, @Param(\"moduleName\") String moduleName);\n\n /**\n * 根据 moduleId 获取模块\n *\n * @param moduleId\n * @return\n */\n public Module getModuleById(@Param(\"moduleId\") String moduleId);\n\n /**\n * 设置模块信息\n *\n * @param module\n * @throws Exception\n */\n public void setModuleInfo(Module module);\n\n /**\n * 获取所有非必选(设置了“生成程序都要使用该模块”)的模块列表\n */\n public List<Module> getModulesListThatAreNotRequired(int whetherTheChoice);\n\n /**\n * 查询除了输入的模块和非模块以外所有的模块\n */\n public List<Module> getModuleListExceptNonModuleAnd(@Param(\"moduleId\") String moduleId);\n\n /**\n * 查询usingRangeParam字段带有usingObjectParam的所有模块\n *\n * @param usingObjectParam\n * @return\n */\n public List<Module> getAllModulesUsedby(@Param(\"usingObjectParam\") String usingObjectParam);\n\n /**\n * 查询有没有添加过该模块\n *\n * @param moduleName\n * @return\n */\n public Integer selectExist(@Param(\"className\") String className, @Param(\"moduleName\") String moduleName);\n\n /**\n * 获取使用了某某模块的所有模块\n *\n * @return\n */\n public List<Module> getModulesListThatUsedTheModule(@Param(\"moduleId\") String moduleId);\n\n /**\n * 获取已经设置不能使用某某模块的所有模块\n *\n * @param moduleId\n * @return\n */\n public List<Module> getModulesListThatCanNotUsedTheModule(@Param(\"moduleId\") String moduleId);\n\n public List<String> getModuleIdOrderByIndexParamAsc(List<String> moduleIdList);\n\n public void renameClassName(@Param(\"newClassName\") String newClassName, @Param(\"oldClassName\") String oldClassName);\n\n\n /**\n * 更改模块\n *\n * @param module\n */\n public void updateModule(Module module);\n\n\n /**\n * 删除模块\n *\n * @param className\n * @param moduleName\n */\n public void delModule(@Param(\"className\") String className, @Param(\"moduleName\") String moduleName);\n\n\n}" }, { "identifier": "Module", "path": "database/src/main/java/com/lazycoder/database/model/Module.java", "snippet": "@NoArgsConstructor\n@Data\npublic class Module implements BaseModel {\n\n private String moduleId;\n\n /**\n * 新增状态,从来没被编辑过的标记\n */\n public final static String NEW_STATE = \"Not edited(新增)\";\n\n /**\n * 分类\n */\n private String className;\n\n /**\n * 模块名\n */\n private String moduleName;\n\n /**\n * 备注\n */\n private String note;\n\n /**\n * 排序\n */\n private int indexParam = 0;\n\n /**\n * 可使用范围\n */\n private String usingRangeParam = NEW_STATE;\n\n /**\n * 需要调用模块\n */\n private String needModuleParam = NEW_STATE;\n\n /**\n * 不需要用的模块\n */\n private String noUseModuleParam = NEW_STATE;\n\n /**\n * 使用设置参数\n */\n private String useSettingParam = \"[]\";\n\n /**\n * 是否可以使用\n */\n private int enabledState = FALSE_;\n\n}" }, { "identifier": "ModuleInfo", "path": "database/src/main/java/com/lazycoder/database/model/ModuleInfo.java", "snippet": "@NoArgsConstructor\n@Data\npublic class ModuleInfo implements BaseModel {\n\n\tprivate String moduleId;\n\n\t/**\n\t * 分类名\n\t */\n\tprivate String className = \"\";\n\n\t/**\n\t * 模块名\n\t */\n\tprivate String moduleName = \"\";\n\n\t/**\n\t * 引入代码的数量\n\t */\n\tprivate int numOfImport = 0;\n\n\t/**\n\t * 初始化代码的数量\n\t */\n\tprivate int numOfInit = 0;\n\n\t/**\n\t * 模块变量的数量\n\t */\n\tprivate int numOfVariable = 0;\n\n\t/**\n\t * 模块方法名的数量\n\t */\n\tprivate int numOfFunctionName=0;\n\n\t/**\n\t * 是否需要模块控制\n\t */\n\tprivate int whetherModuleControlIsRequired = FALSE_;\n\n\t/**\n\t * 添加文件数量\n\t */\n\tprivate int numOfAddFile = 0;\n\n\t/**\n\t * 添加文件参数\n\t */\n\tprivate String addFileParam = \"[]\";\n\n\t/**\n\t * 附带文件数量\n\t */\n\tprivate int numOfAttachedFile = 0;\n\n\t/**\n\t * 附带文件参数\n\t */\n\tprivate String attachedFileParam = \"[]\";\n\n\t/**\n\t * 设置代码种类数量\n\t */\n\tprivate int numOfSetCodeType = 0;\n\n\t/**\n\t * 设置代码类型列表\n\t */\n\tprivate String setTheTypeOfSetCodeParam = \"[]\";\n\n\t/**\n\t * 功能源码数量\n\t */\n\tprivate int numOfFunctionCodeType = 0;\n\n\t/**\n\t * 功能源码种类列表\n\t */\n\tprivate String functionTheTypeOfSourceCodeParam = \"[]\";\n\n\t/**\n\t * 需要使用的其他代码文件数量\n\t */\n\tprivate int theNumOfAdditionalCodeFilesParamsThatNeedToBeUsed = 0;\n\n\t/**\n\t * 需要使用到的其他代码文件\n\t */\n\tprivate String additionalCodeFilesParamsThatNeedToBeUsed = \"[]\";\n\n}" }, { "identifier": "UsingObject", "path": "database/src/main/java/com/lazycoder/database/model/formodule/UsingObject.java", "snippet": "@JSONType(orders = {\"showName\", \"type\", \"serial\"})\n@NoArgsConstructor\n@Data\npublic class UsingObject implements DataFormatType {\n\n /**\n * 选择必填模板使用范围\n */\n public static final UsingObject MAIN_USING_OBJECT = new UsingObject(\"必填模板\", UsingObject.MAIN_TYPE);\n\n /**\n * 显示名称\n */\n private String showName;\n\n /**\n * 类型\n */\n private int type = MAIN_TYPE;\n\n /**\n * 可选模板序号(可选模板才用,拿来确认是第几个可选模板)\n */\n private int serial = 0;\n\n // 目前仅必填模板使用\n public UsingObject(String showName, int type) {\n this.showName = showName;\n this.type = type;\n }\n\n // 可选模板使用\n public UsingObject(int additionalSerialNumber) {\n this.showName = \"可选模板\" + additionalSerialNumber;\n this.serial = additionalSerialNumber;\n this.type = ADDITIONAL_TYPE;\n }\n\n public static boolean contantOrNot(UsingObject usingObject, List<UsingObject> list) {\n boolean flag = false;\n if (usingObject.getType() == com.lazycoder.database.model.formodule.UsingObject.MAIN_TYPE) {\n for (UsingObject usingObjectTemp : list) {\n if (usingObjectTemp.getType() == com.lazycoder.database.model.formodule.UsingObject.MAIN_TYPE) {\n flag = true;\n break;\n }\n }\n } else if (usingObject.getType() == UsingObject.ADDITIONAL_TYPE) {\n for (UsingObject usingObjectTemp : list) {\n if (usingObjectTemp.getType() == com.lazycoder.database.model.formodule.UsingObject.ADDITIONAL_TYPE) {\n if (usingObjectTemp.getSerial() == usingObject.getSerial()) {\n flag = true;\n break;\n }\n }\n }\n }\n return flag;\n }\n\n\n @Override\n public String toString() {\n return \"UsingObject [showName=\" + showName + \", type=\" + type + \", serial=\" + serial + \"]\";\n }\n\n}" }, { "identifier": "ModuleUseSetting", "path": "service/src/main/java/com/lazycoder/service/ModuleUseSetting.java", "snippet": "public interface ModuleUseSetting {\n\n /**\n * 必选\n */\n// public static final int MUST_USE = 0;\n //取消必选属性,避免两个不一起使用的模块都被选择该属性\n\n\n /**\n * 对用户屏蔽\n */\n public static final int USER_SHIELDING = 1;\n\n}" }, { "identifier": "SysService", "path": "service/src/main/java/com/lazycoder/service/service/SysService.java", "snippet": "public class SysService {\n\n\tpublic final static ClassificationServiceImpl CLASSIFICATION_SERVICE = (ClassificationServiceImpl) SpringUtil\n\t\t\t.getBean(ClassificationServiceImpl.class);\n\n\tpublic final static ImportCodeServicelmpl IMPORT_CODE_SERVICE = (ImportCodeServicelmpl) SpringUtil\n\t\t\t.getBean(ImportCodeServicelmpl.class);\n\n\tpublic final static ModuleInfoServiceImpl MODULE_INFO_SERVICE = (ModuleInfoServiceImpl) SpringUtil\n\t\t\t.getBean(ModuleInfoServiceImpl.class);\n\n\tpublic final static ModuleServiceImpl MODULE_SERVICE = (ModuleServiceImpl) SpringUtil\n\t\t\t.getBean(ModuleServiceImpl.class);\n\n\tpublic final static FunctionServicelmpl FUNCTION_SERVICE = (FunctionServicelmpl) SpringUtil\n\t\t\t.getBean(FunctionServicelmpl.class);\n\n\tpublic final static InitServicelmpl INIT_SERVICE = (InitServicelmpl) SpringUtil.getBean(InitServicelmpl.class);\n\n\tpublic final static ModuleSetServicelmpl MODULE_SET_SERVICE = (ModuleSetServicelmpl) SpringUtil\n\t\t\t.getBean(ModuleSetServicelmpl.class);\n\n\tpublic final static ModuleFileFormatServiceImpl MODULE_FILE_FORMAT_SERVICE = (ModuleFileFormatServiceImpl) SpringUtil\n\t\t\t.getBean(ModuleFileFormatServiceImpl.class);\n\n\tpublic final static ModuleControlServiceImpl MODULE_CONTROL_SERVICE = (ModuleControlServiceImpl) SpringUtil\n\t\t\t.getBean(ModuleControlServiceImpl.class);\n\n\tpublic final static VariableDataServiceImpl VARIABLE_DATA_SERVICE = (VariableDataServiceImpl) SpringUtil\n\t\t\t.getBean(VariableDataServiceImpl.class);\n\n\tpublic final static MainFormatCodeFileServiceImpl MAIN_FORMAT_CODE_FILE_SERVICE = (MainFormatCodeFileServiceImpl) SpringUtil\n\t\t\t.getBean(MainFormatCodeFileServiceImpl.class);\n\n\tpublic final static com.lazycoder.service.service.impl.format.AdditionalFormatFileServiceImpl ADDITIONAL_FORMAT_FILE_SERVICE = (com.lazycoder.service.service.impl.format.AdditionalFormatFileServiceImpl) SpringUtil\n\t\t\t.getBean(com.lazycoder.service.service.impl.format.AdditionalFormatFileServiceImpl.class);\n\n\tpublic final static OptionServiceImpl OPTION_SERVICE = (OptionServiceImpl) SpringUtil\n\t\t\t.getBean(OptionServiceImpl.class);\n\n\tpublic final static DBChangeServiceImpl DB_CHANGE_SERVICE = (DBChangeServiceImpl) SpringUtil\n\t\t\t.getBean(DBChangeServiceImpl.class);\n\n\tpublic final static FormatInfoServiceImpl FORMAT_INFO_SERVICE = (FormatInfoServiceImpl) SpringUtil\n\t\t\t.getBean(FormatInfoServiceImpl.class);\n\n\tpublic final static MainSetServicelmpl MAIN_SET_SERVICE = (MainSetServicelmpl) SpringUtil\n\t\t\t.getBean(MainSetServicelmpl.class);\n\n\tpublic final static AdditionalSetServicelmpl ADDITIONAL_SET_SERVICE = (AdditionalSetServicelmpl) SpringUtil\n\t\t\t.getBean(AdditionalSetServicelmpl.class);\n\n\tpublic final static AdditionalFunctionServicelmpl ADDITIONAL_FUNCTION_SERVICE = (AdditionalFunctionServicelmpl) SpringUtil\n\t\t\t.getBean(AdditionalFunctionServicelmpl.class);\n\n\tpublic final static SysParamServiceImpl SYS_PARAM_SERVICE = (SysParamServiceImpl) SpringUtil\n\t\t\t.getBean(SysParamServiceImpl.class);\n\n\tpublic final static FunctionNameDataServiceImpl FUNCTION_NAME_DATA_SERVICE = (FunctionNameDataServiceImpl) SpringUtil\n\t\t\t.getBean(FunctionNameDataServiceImpl.class);\n\n\tpublic final static AttachedFileServiceImpl ATTACHED_FILE_SERVICE = (AttachedFileServiceImpl) SpringUtil\n\t\t\t.getBean(AttachedFileServiceImpl.class);\n\n\tpublic final static DatabaseNameServiceImpl DATABASE_NAME_SERVICE = (DatabaseNameServiceImpl) SpringUtil\n\t\t\t.getBean(DatabaseNameServiceImpl.class);\n\n\tpublic final static InputDataSaveServiceImpl INPUT_DATA_SAVE_SERVICE = (InputDataSaveServiceImpl) SpringUtil\n\t\t\t.getBean(InputDataSaveServiceImpl.class);\n\n\tpublic final static CodeLabelServiceImpl CODE_LABEL_SERVICE = (CodeLabelServiceImpl) SpringUtil\n\t\t\t.getBean(CodeLabelServiceImpl.class);\n\n\tpublic final static SysServiceImpl SYS_SERVICE_SERVICE = (SysServiceImpl) SpringUtil\n\t\t\t.getBean(SysServiceImpl.class);\n\n}" }, { "identifier": "AssociatedModule", "path": "service/src/main/java/com/lazycoder/service/vo/AssociatedModule.java", "snippet": "@Data\n@NoArgsConstructor\npublic class AssociatedModule {\n\n private Module module = null;\n\n private ArrayList<Module> currentAssociatedModuleList = new ArrayList<>();\n\n public void addAssociatedModuleList(AssociatedModule associatedModule) {\n if (associatedModule != null) {\n boolean flag = false;\n for (Module temp : associatedModule.currentAssociatedModuleList) {\n flag = false;\n for (Module thisTemp : this.currentAssociatedModuleList) {\n if (thisTemp.getModuleId().equals(temp.getModuleId())) {\n flag = true;\n break;\n }\n }\n if (flag == false) {\n this.currentAssociatedModuleList.add(temp);\n }\n }\n }\n }\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.JSON; import com.alibaba.fastjson.TypeReference; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lazycoder.database.common.ModuleRelatedParam; import com.lazycoder.database.dao.ModuleMapper; import com.lazycoder.database.model.Module; import com.lazycoder.database.model.ModuleInfo; import com.lazycoder.database.model.formodule.UsingObject; import com.lazycoder.service.ModuleUseSetting; import com.lazycoder.service.service.SysService; import com.lazycoder.service.vo.AssociatedModule; import com.lazycoder.utils.JsonUtil; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service;
5,436
package com.lazycoder.service.service.impl; @Service @Component(value = "ModuleServiceImpl") public class ModuleServiceImpl implements ModuleUseSetting { @Autowired private ModuleMapper dao;
package com.lazycoder.service.service.impl; @Service @Component(value = "ModuleServiceImpl") public class ModuleServiceImpl implements ModuleUseSetting { @Autowired private ModuleMapper dao;
public void addModule(Module module) {
2
2023-11-16 11:55:06+00:00
8k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/device/HouseMeter.java
[ { "identifier": "DeviceContextBase", "path": "app/src/main/java/kr/or/kashi/hde/DeviceContextBase.java", "snippet": "public abstract class DeviceContextBase implements DeviceStatePollee {\n private static final String TAG = DeviceContextBase.class.getSimpleName();\n private static final boolean DBG = true;\n\n public static final int PARSE_ERROR_MALFORMED_PACKET = -2;\n public static final int PARSE_ERROR_UNKNOWN = -1;\n public static final int PARSE_OK_NONE = 0;\n public static final int PARSE_OK_PEER_DETECTED = 1;\n public static final int PARSE_OK_STATE_UPDATED = 2;\n public static final int PARSE_OK_ACTION_PERFORMED = 3;\n public static final int PARSE_OK_ERROR_RECEIVED = 4;\n\n @IntDef(prefix = {\"PARSE_\"}, value = {\n PARSE_ERROR_MALFORMED_PACKET,\n PARSE_ERROR_UNKNOWN,\n PARSE_OK_NONE,\n PARSE_OK_PEER_DETECTED,\n PARSE_OK_STATE_UPDATED,\n PARSE_OK_ACTION_PERFORMED,\n PARSE_OK_ERROR_RECEIVED,\n })\n @Retention(RetentionPolicy.SOURCE)\n public @interface ParseResult {}\n\n public interface Listener {\n default void onPropertyChanged(List<PropertyValue> props) {}\n default void onErrorOccurred(int error) {}\n }\n\n private final Class<?> mDeviceClass;\n private final Handler mHandler;\n private Runnable mUpdateReqRunnable;\n private Listener mListener;\n\n protected final PropertyMap mBasePropertyMap = new BasicPropertyMap();\n protected final StageablePropertyMap mRxPropertyMap = new StageablePropertyMap(mBasePropertyMap);\n protected final PropertyMap mReadOnlyPropertyMap = new ReadOnlyPropertyMap(mRxPropertyMap, true);\n private final Map<String, PropertyTask> mPropTaskMap = new ConcurrentHashMap<>();\n\n private boolean mIsSlave = false;\n private HomeAddress mAddress;\n protected String mLogPrefix;\n\n protected int mPollPhase = DeviceStatePollee.Phase.INITIAL;\n protected long mPollInterval = 0L;\n protected long mLastUpdateTime = 0L;\n\n protected DeviceContextBase mParent;\n private Map<String, DeviceContextBase> mChildren = new TreeMap<>(); // Always sorted.\n\n public DeviceContextBase(MainContext mainContext, Map defaultProps, Class<?> deviceClass) {\n mDeviceClass = deviceClass;\n mHandler = new Handler(Looper.getMainLooper());\n mRxPropertyMap.putAll(PropertyInflater.inflate(deviceClass)); // Put all default properties as base\n mRxPropertyMap.putAll((Map<String, PropertyValue>)defaultProps); // Overwrite initial properties\n mRxPropertyMap.commit();\n\n if (DBG) Log.d(TAG, mDeviceClass.getSimpleName() + \", default properties: \" + mRxPropertyMap.toString());\n\n mIsSlave = mBasePropertyMap.get(HomeDevice.PROP_IS_SLAVE, Boolean.class);\n\n final String deviceAddress = mBasePropertyMap.get(HomeDevice.PROP_ADDR, String.class);\n mAddress = createAddress(deviceAddress);\n mLogPrefix = \"[\" + mAddress.getDeviceAddress() + \"]\";\n\n if (mIsSlave) {\n // In salve mode, register default property tasks to reflect all property's changes by default.\n for (String propName: mBasePropertyMap.toMap().keySet()) {\n setPropertyTask(propName, new PropertyTask.Reflection(propName));\n }\n } else {\n // Register default property tasks to reflect some property's changes by default.\n setPropertyTask(HomeDevice.PROP_AREA, new PropertyTask.Reflection(HomeDevice.PROP_AREA));\n setPropertyTask(HomeDevice.PROP_NAME, new PropertyTask.Reflection(HomeDevice.PROP_NAME));\n }\n }\n\n public boolean isMaster() {\n return !mIsSlave;\n }\n\n public boolean isSlave() {\n return mIsSlave;\n }\n\n public DeviceContextBase getParent() {\n return mParent;\n }\n\n public boolean hasChild() {\n return mChildren.size() > 0;\n }\n\n public int getChildCount() {\n return mChildren.size();\n }\n\n public Collection<DeviceContextBase> getChildren() {\n return mChildren.values();\n }\n\n public <E> E getChild(Class<E> clazz, String address) {\n return (E) mChildren.get(address);\n }\n\n public <E> E getChildAt(Class<E> clazz, int index) {\n if (index >= getChildCount()) return null;\n return (E) getChildren(clazz).toArray()[index];\n }\n\n public <E> Collection<E> getChildren(Class<E> clazz) {\n return (Collection<E>) mChildren.values();\n }\n\n public void addChild(DeviceContextBase child) {\n if (child != null) {\n child.mParent = this;\n mChildren.put(child.getAddress().getDeviceAddress(), child);\n }\n }\n\n public void removeChild(DeviceContextBase child) {\n if (child != null) {\n String devAddress = child.getAddress().getDeviceAddress();\n if (mChildren.containsKey(devAddress)) {\n mChildren.remove(devAddress);\n child.mParent = null;\n }\n }\n }\n\n public void removeAllChildren() {\n for (DeviceContextBase child: mChildren.values()) {\n child.mParent = null;\n }\n mChildren.clear();\n }\n\n public Class<?> getDeviceClass() {\n return mDeviceClass;\n }\n\n public String getClassName() {\n return mDeviceClass.getName();\n }\n\n public HomeAddress getAddress() {\n return mAddress;\n }\n\n public PropertyValue getProperty(String name) {\n return mBasePropertyMap.get(name);\n }\n\n public PropertyMap getReadPropertyMap() {\n return mReadOnlyPropertyMap;\n }\n\n public void setListener(Listener listener) {\n mListener = listener;\n }\n\n public boolean setProperty(List<PropertyValue> props) {\n if (DBG) {\n final String address = getAddress().getDeviceAddress();\n for (PropertyValue p: props) {\n if (p.getExtraData() != null) {\n Log.d(TAG, mLogPrefix + \" set prop :: \" + p.getName() + \"=\" + p.getValue() + \", extra:\" + p.getExtraData().length);\n } else {\n Log.d(TAG, mLogPrefix + \" set prop :: \" + p.getName() + \"=\" + p.getValue());\n }\n }\n }\n\n List<PropertyTask> currentTasks = new ArrayList();\n\n // Make copy of the property map and update with new properties\n StageablePropertyMap tempMap = new StageablePropertyMap(mBasePropertyMap, true /* allow same */);\n tempMap.putAll(props);\n\n for (PropertyValue prop: props) {\n PropertyTask task = mPropTaskMap.get(prop.getName());\n if (task != null && !currentTasks.contains(task)) {\n currentTasks.add(task);\n }\n }\n\n for (PropertyTask task: currentTasks) {\n task.execTask(tempMap, mRxPropertyMap);\n }\n\n tempMap.clearStaged();\n\n commitPropertyChanges(mRxPropertyMap);\n\n return true; // TODO: Confirm the purpose of this return value, see DeviceContext\n }\n\n public boolean updateProperties(List<PropertyValue> props) {\n mRxPropertyMap.putAll(props);\n commitPropertyChanges(mRxPropertyMap);\n return true;\n }\n\n public void onAttachedToStream() {\n // Override it\n }\n\n public void onDetachedFromStream() {\n // Override it\n }\n\n @Override\n public void setPollPhase(@DeviceStatePollee.Phase int phase, long interval) {\n if (DBG) {\n final String address = getAddress().getDeviceAddress();\n final String phaseStr = phaseToString(phase);\n Log.d(TAG, mLogPrefix + \" new poll phase: \" + phaseStr + \", \" + interval);\n }\n\n mPollPhase = phase;\n mPollInterval = interval;\n\n requestUpdate();\n }\n\n @Override\n public void requestUpdate() {\n if (mUpdateReqRunnable == null) {\n mUpdateReqRunnable = () -> requestUpdate(mRxPropertyMap);\n }\n if (!mHandler.hasCallbacks(mUpdateReqRunnable)) {\n mHandler.postDelayed(mUpdateReqRunnable, 10);\n }\n }\n\n @Override\n public long getUpdateTime() {\n return mLastUpdateTime;\n }\n\n protected void setPropertyTask(String propName, PropertyTask task) {\n mPropTaskMap.put(propName, task);\n }\n\n protected void clearPropertyTask(String propName) {\n mPropTaskMap.remove(propName);\n }\n\n public @ParseResult int parsePacket(HomePacket packet) {\n mLastUpdateTime = SystemClock.uptimeMillis();\n\n int res = parsePayload(packet, mRxPropertyMap);\n if (res <= PARSE_OK_NONE) {\n mRxPropertyMap.clearStaged();\n return res;\n }\n\n commitPropertyChanges(mRxPropertyMap);\n\n return res;\n }\n\n protected void commitPropertyChanges(StageablePropertyMap propMap) {\n if (propMap.isStaging()) {\n final List<PropertyValue> originalValues = new ArrayList<>();\n final List<PropertyValue> stagingValues= new ArrayList<>();\n propMap.getStaging(originalValues, stagingValues);\n propMap.commit();\n\n if (mListener != null) {\n for (PropertyValue prop: stagingValues) {\n Log.d(TAG, mLogPrefix + \" prop changed :: \" + prop.getName() + \"=\" + prop.getValue());\n }\n mListener.onPropertyChanged(stagingValues);\n }\n }\n }\n\n // TODO: Call this according to the result of parsePacket()\n protected void onErrorOccurred(@HomeDevice.Error int errorCode) {\n // TODO: Set error code to PROP_ERROR too.\n if (mListener != null) mListener.onErrorOccurred(errorCode);\n }\n\n protected int clamp(String name, int value, int min, int max) {\n if (value < min) {\n if (DBG) Log.w(TAG, \"warning: \" + name + \" is smaller than \" + min);\n value = min;\n }\n if (value > max) {\n if (DBG) Log.w(TAG, \"warning: \" + name + \" is larger than \" + max);\n value = max;\n }\n return value;\n }\n\n protected boolean check(String name, int value, int min, int max) {\n int res = clamp(name, value, min, max);\n if (res != value) Log.w(TAG, \"error: \" + name + \"(\" + value +\") is out of range (\" + min + \"~\" + max + \")\");\n return (res == value);\n }\n\n protected void assert_(String name, int value, int min, int max) {\n if (!check(name, value, min, max)) {\n throw new RuntimeException(name + \" is out of range!\");\n }\n }\n\n public abstract void requestUpdate(PropertyMap props);\n public abstract HomeAddress createAddress(String deviceAddress);\n public abstract @ParseResult int parsePayload(HomePacket packet, PropertyMap outProps);\n}" }, { "identifier": "HomeDevice", "path": "app/src/main/java/kr/or/kashi/hde/HomeDevice.java", "snippet": "public class HomeDevice {\n private static final String TAG = HomeDevice.class.getSimpleName();\n private static final String PROP_PREFIX = \"0.\";\n\n /**\n * Application registers {@link HomeDevice.Callback} object to receive\n * notifications about the home network.\n */\n public interface Callback {\n /**\n * Called when property has been changed\n * @param device {@link HomeDevice} object that some state has been changed.\n * @param props {@link List} object that contains properties.\n */\n default void onPropertyChanged(HomeDevice device, PropertyMap props) {}\n\n /**\n * Called when an error is occurred.\n * @param device {@link HomeDevice} object where this error has been occurred.\n * @param error Error code.\n */\n default void onErrorOccurred(HomeDevice device, @Error int error) {}\n }\n\n /**\n * Types\n */\n public @interface Type {\n int UNKNOWN = 0;\n int LIGHT = 1;\n int DOOR_LOCK = 2;\n int VENTILATION = 3;\n int GAS_VALVE = 4;\n int HOUSE_METER = 5;\n int CURTAIN = 6;\n int THERMOSTAT = 7;\n int BATCH_SWITCH = 8;\n int SENSOR = 9;\n int AIRCONDITIONER = 10;\n int POWER_SAVER = 11;\n }\n\n /**\n * Areas\n */\n public @interface Area {\n int UNKNOWN = 0;\n int ENTERANCE = 1;\n int LIVING_ROOM = 2;\n int MAIN_ROOM = 3;\n int OTHER_ROOM = 4;\n int KITCHEN = 5;\n }\n\n /**\n * Error codes\n */\n public @interface Error {\n int NONE = 0;\n int UNKNOWN = -1;\n int CANT_CONTROL = -2;\n int NO_RESPONDING = -3;\n int NO_DEVICE = -4;\n }\n\n /** Property of the address */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_ADDR = PROP_PREFIX + \"addr\";\n\n /** Property of the area that the device is installed in */\n @PropertyDef(valueClass=Area.class, defValueI=Area.UNKNOWN)\n public static final String PROP_AREA = PROP_PREFIX + \"area\";\n\n /** Property of the name of device */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_NAME = PROP_PREFIX + \"name\";\n\n /** Property of connection state */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_CONNECTED = PROP_PREFIX + \"connected\";\n\n /** Property of on/off state */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_ONOFF = PROP_PREFIX + \"onoff\";\n\n /** Property of error code that is defined in {@link Error} */\n @PropertyDef(valueClass=Error.class)\n public static final String PROP_ERROR = PROP_PREFIX + \"error\";\n\n /** Property of the numeric code of device vendor */\n @PropertyDef(valueClass=Integer.class)\n public static final String PROP_VENDOR_CODE = PROP_PREFIX + \"vendor.code\";\n\n /** Property of the name of device vendor */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_VENDOR_NAME = PROP_PREFIX + \"vendor.name\";\n\n /** @hide */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_IS_SLAVE = PROP_PREFIX + \"is_salve\";\n\n private static Map<Class, Map<String, PropertyValue>> sDefaultPropertyMap\n = new ConcurrentHashMap<>();\n\n private final DeviceContextBase mDeviceContext;\n\n private final Handler mHandler;\n private final Executor mHandlerExecutor;\n private final Object mLock = new Object();\n private DeviceContextListenerImpl mDeviceListener = null;\n private final List<Pair<Callback,Executor>> mCallbacks = new ArrayList<>();\n private final Map<String, PropertyValue> mStagedProperties = new ConcurrentHashMap<>();\n private final Runnable mCommitPropsRunnable = this::commitStagedProperties;\n\n public HomeDevice(DeviceContextBase deviceContext) {\n mDeviceContext = deviceContext;\n mHandler = new Handler(Looper.getMainLooper());\n mHandlerExecutor = mHandler::post;\n }\n\n /** @hide */\n public DeviceContextBase dc() {\n return mDeviceContext;\n }\n\n /**\n * Returns the {@link Type} of device.\n * @return The type of device.\n */\n public @Type int getType() {\n return Type.UNKNOWN;\n }\n\n /**\n * Returns the name of this device.\n * @return The name of device.\n */\n public String getName() {\n return getProperty(PROP_NAME, String.class);\n }\n\n /**\n * Change the name of this device.\n * @param name New name of device.\n */\n public void setName(String name) {\n setProperty(PROP_NAME, String.class, (name == null ? \"\" : name));\n }\n\n /**\n * Set the {@link Area} where the device is located in.\n * @param area The location of device.\n */\n public void setArea(@Area int area) {\n setProperty(PROP_AREA, Integer.class, area);\n }\n\n /**\n * Returns the address of device.\n * @return Address in string format of {@link InetAddress}.\n */\n public String getAddress() {\n return getProperty(PROP_ADDR, String.class);\n }\n\n /**\n * Whether the device is connected.\n * @return {@code true} if device is connected.\n */\n public boolean isConnected() {\n return getProperty(PROP_CONNECTED, Boolean.class);\n }\n\n /**\n * Whether the device is on\n * @return {@code true} if device is on.\n */\n public boolean isOn() {\n return getProperty(PROP_ONOFF, Boolean.class);\n }\n\n /**\n * Sets the on / off state to device\n * @param on The new state whether if device is on.\n */\n public void setOn(boolean on) {\n setProperty(PROP_ONOFF, Boolean.class, on);\n }\n\n /**\n * Retrives last code of {@link Error}\n */\n public @Error int getError() {\n return getProperty(PROP_ERROR, Integer.class);\n }\n\n /**\n * Register callback. The methods of the callback will be called when new events arrived.\n * @param callback The callback to handle event.\n */\n public void addCallback(Callback callback) {\n addCallback(callback, mHandlerExecutor);\n }\n\n public void addCallback(Callback callback, Executor executor) {\n synchronized (mLock) {\n if (mCallbacks.isEmpty() && mDeviceListener == null) {\n mDeviceListener = new DeviceContextListenerImpl(this);\n mDeviceContext.setListener(mDeviceListener);\n }\n mCallbacks.add(Pair.create(callback, executor));\n }\n }\n\n /**\n * Unregisters callback.\n * @param callback The callback to handle event.\n */\n public void removeCallback(Callback callback) {\n synchronized (mLock) {\n Iterator it = mCallbacks.iterator();\n while (it.hasNext()) {\n Pair<Callback,Executor> cb = (Pair<Callback,Executor>) it.next();\n if (cb.first == callback) {\n it.remove();\n }\n }\n if (mCallbacks.isEmpty() && mDeviceListener != null) {\n mDeviceContext.setListener(null);\n mDeviceListener = null;\n }\n }\n }\n\n /**\n * Get current value of a property.\n *\n * @param propName The name of property.\n * @param valueClass Class type of property value.\n * @return Current value of property.\n */\n public <E> E getProperty(String propName, Class<E> valueClass) {\n PropertyValue<E> prop = mDeviceContext.getProperty(propName);\n return prop.getValue();\n }\n\n /**\n * Set value to a property.\n *\n * @param propName The name of property.\n * @param valueClass Class type of property value.\n * @param value New value to set.\n */\n public <E> void setProperty(String propName, Class<E> valueClass, E value) {\n setProperty(new PropertyValue<E>(propName, value));\n }\n\n public <E> E getStagedProperty(String name, Class<E> clazz) {\n if (mStagedProperties.containsKey(name)) {\n return (E) mStagedProperties.get(name).getValue();\n }\n return getProperty(name, clazz);\n }\n\n public long getPropertyL(String name) {\n return getProperty(name, Long.class);\n }\n\n public PropertyMap getReadPropertyMap() {\n return mDeviceContext.getReadPropertyMap();\n }\n\n public void setProperty(PropertyValue prop) {\n mStagedProperties.put(prop.getName(), prop);\n if (!mHandler.hasCallbacks(mCommitPropsRunnable)) {\n mHandler.postDelayed(mCommitPropsRunnable, 1 /* Minimum delay */);\n }\n }\n\n public void setPropertyNow(PropertyValue prop) {\n mStagedProperties.put(prop.getName(), prop);\n flushProperties();\n }\n\n public void flushProperties() {\n mHandler.removeCallbacks(mCommitPropsRunnable);\n commitStagedProperties();\n }\n\n private void commitStagedProperties() {\n if (mStagedProperties.size() > 0) {\n mDeviceContext.setProperty(new ArrayList<>(mStagedProperties.values()));\n mStagedProperties.clear();\n }\n }\n\n private static class DeviceContextListenerImpl implements DeviceContextBase.Listener {\n private final WeakReference<HomeDevice> mWeakOwner;\n\n DeviceContextListenerImpl(HomeDevice device) {\n mWeakOwner = new WeakReference<>(device);\n }\n\n public void onPropertyChanged(List<PropertyValue> props) {\n HomeDevice device = mWeakOwner.get();\n if (device != null) {\n device.onPropertyChanged(props);\n }\n }\n\n public void onErrorOccurred(int error) {\n HomeDevice device = mWeakOwner.get();\n if (device != null) {\n device.onErrorOccurred(error);\n }\n }\n }\n\n public void onPropertyChanged(List<PropertyValue> props) {\n Collection<Pair<Callback,Executor>> callbacks;\n synchronized (mLock) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n PropertyMap propMap = new ReadOnlyPropertyMap(props);\n\n for (Pair<Callback,Executor> cb : callbacks) {\n cb.second.execute(() -> cb.first.onPropertyChanged(this, propMap));\n }\n }\n\n public void onErrorOccurred(int error) {\n Collection<Pair<Callback,Executor>> callbacks;\n synchronized (mLock) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (Pair<Callback,Executor> cb : callbacks) {\n cb.second.execute(() -> cb.first.onErrorOccurred(this, error));\n }\n }\n\n /** @hide */\n public static String typeToString(@Type int type) {\n switch (type) {\n case Type.UNKNOWN: return \"UNKNOWN\";\n case Type.LIGHT: return \"LIGHT\";\n case Type.DOOR_LOCK: return \"DOOR_LOCK\";\n case Type.VENTILATION: return \"VENTILATION\";\n case Type.GAS_VALVE: return \"GAS_VALVE\";\n case Type.HOUSE_METER: return \"HOUSE_METER\";\n case Type.CURTAIN: return \"CURTAIN\";\n case Type.THERMOSTAT: return \"THERMOSTAT\";\n case Type.BATCH_SWITCH: return \"BATCH_SWITCH\";\n case Type.SENSOR: return \"SENSOR\";\n case Type.AIRCONDITIONER: return \"AIRCONDITIONER\";\n case Type.POWER_SAVER: return \"POWER_SAVER\";\n }\n return \"UNKNOWN\";\n }\n\n /** @hide */\n public static String areaToString(@Area int area) {\n switch (area) {\n case Area.UNKNOWN: return \"UNKNOWN\";\n case Area.ENTERANCE: return \"ENTERANCE\";\n case Area.LIVING_ROOM: return \"LIVING_ROOM\";\n case Area.MAIN_ROOM: return \"MAIN_ROOM\";\n case Area.OTHER_ROOM: return \"OTHER_ROOM\";\n case Area.KITCHEN: return \"KITCHEN\";\n }\n return \"UNKNOWN\";\n }\n\n /** @hide */\n @Override\n public String toString() {\n return \"HomeDevice {\" +\n \" name=\" + getName() +\n \" type=\" + typeToString(getType()) +\n \" address=\" + getAddress().toString() + \" }\";\n }\n}" } ]
import kr.or.kashi.hde.base.PropertyDef; import kr.or.kashi.hde.DeviceContextBase; import kr.or.kashi.hde.HomeDevice;
6,522
/* * 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; /** * A device class for probing meters in the house. */ public class HouseMeter extends HomeDevice { private static final String PROP_PREFIX = "hm."; /** * Types of meter */ public @interface MeterType { int UNKNOWN = 0; int WATER = 1; int GAS = 2; int ELECTRICITY = 3; int HOT_WATER = 4; int HEATING = 5; } /** * Units of measurement */ public @interface MeasureUnit { int UNKNOWN = 0; int m3 = 1; int W = 2; int MW = 3; int kWh = 4; } /** * Measure units of meter */ public static class MeterUnits { /** * One of {@link MeasureUnit} for current measurement * @see #getMeterUnits() * @see #getCurrentMeasure() */ public @MeasureUnit int current; /** * One of {@link MeasureUnit} for total measurement * @see #getMeterUnits() * @see #getTotalMeasure() */ public @MeasureUnit int total; } /** Property: Indicating what type of device */ @PropertyDef(valueClass=MeterType.class) public static final String PROP_METER_TYPE = PROP_PREFIX + "meter_type"; /** Property: The enabled state of meter */ @PropertyDef(valueClass=Boolean.class) public static final String PROP_METER_ENABLED = PROP_PREFIX + "meter_enabled"; /** Property: Unit for current measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_CURRENT_METER_UNIT = PROP_PREFIX + "current_meter.unit"; /** Property: Current measurement value*/ @PropertyDef(valueClass=Double.class) public static final String PROP_CURRENT_METER_VALUE = PROP_PREFIX + "current_meter.value"; /** Property: Unit for total measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_TOTAL_METER_UNIT = PROP_PREFIX + "total_meter.unit"; /** Property: Total measurement value */ @PropertyDef(valueClass=Double.class) public static final String PROP_TOTAL_METER_VALUE = PROP_PREFIX + "total_meter.value"; /** * Construct new instance. Don't call this directly. */
/* * 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; /** * A device class for probing meters in the house. */ public class HouseMeter extends HomeDevice { private static final String PROP_PREFIX = "hm."; /** * Types of meter */ public @interface MeterType { int UNKNOWN = 0; int WATER = 1; int GAS = 2; int ELECTRICITY = 3; int HOT_WATER = 4; int HEATING = 5; } /** * Units of measurement */ public @interface MeasureUnit { int UNKNOWN = 0; int m3 = 1; int W = 2; int MW = 3; int kWh = 4; } /** * Measure units of meter */ public static class MeterUnits { /** * One of {@link MeasureUnit} for current measurement * @see #getMeterUnits() * @see #getCurrentMeasure() */ public @MeasureUnit int current; /** * One of {@link MeasureUnit} for total measurement * @see #getMeterUnits() * @see #getTotalMeasure() */ public @MeasureUnit int total; } /** Property: Indicating what type of device */ @PropertyDef(valueClass=MeterType.class) public static final String PROP_METER_TYPE = PROP_PREFIX + "meter_type"; /** Property: The enabled state of meter */ @PropertyDef(valueClass=Boolean.class) public static final String PROP_METER_ENABLED = PROP_PREFIX + "meter_enabled"; /** Property: Unit for current measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_CURRENT_METER_UNIT = PROP_PREFIX + "current_meter.unit"; /** Property: Current measurement value*/ @PropertyDef(valueClass=Double.class) public static final String PROP_CURRENT_METER_VALUE = PROP_PREFIX + "current_meter.value"; /** Property: Unit for total measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_TOTAL_METER_UNIT = PROP_PREFIX + "total_meter.unit"; /** Property: Total measurement value */ @PropertyDef(valueClass=Double.class) public static final String PROP_TOTAL_METER_VALUE = PROP_PREFIX + "total_meter.value"; /** * Construct new instance. Don't call this directly. */
public HouseMeter(DeviceContextBase deviceContext) {
0
2023-11-10 01:19:44+00:00
8k
Bug1312/dm_locator
src/main/java/com/bug1312/dm_locator/Register.java
[ { "identifier": "LocatorDataWriterItem", "path": "src/main/java/com/bug1312/dm_locator/items/LocatorDataWriterItem.java", "snippet": "public class LocatorDataWriterItem extends Item {\n\n\tprivate static final Predicate<ItemStack> WRITABLE = (stack) -> (\n\t\tstack.getItem() instanceof DataModuleItem && \n\t\t!(\n\t\t\tstack.getItem() == DMItems.DATA_MODULE.get() &&\n\t\t\tstack.getOrCreateTag().contains(\"written\")\n\t\t)\n\t);\n\t\t\t\n\tpublic LocatorDataWriterItem(Properties properties) {\n\t\tsuper(properties);\n\t}\n\t\t\n\t@Override\n\tpublic ActionResult<ItemStack> use(World world, PlayerEntity player, Hand hand) {\n\t\tLocatorDataWriterMode mode = getMode(player.getItemInHand(hand));\n\t\t\n\t\tif (player.isShiftKeyDown()) {\n\t\t\tplayer.getItemInHand(hand).getOrCreateTag().putInt(\"Mode\", (mode.ordinal() + 1) % LocatorDataWriterMode.values().length);\n\t\t\tplayer.displayClientMessage(Register.TEXT_SWAP_MODE.apply(getMode(player.getItemInHand(hand))).setStyle(Style.EMPTY.withColor(TextFormatting.GREEN)), true);\n\t\t\t\n\t\t\treturn ActionResult.consume(player.getItemInHand(hand));\n\t\t}\n\t\t\n\t\tConsumer<TranslationTextComponent> sendError = (text) -> player.displayClientMessage(text.setStyle(Style.EMPTY.withColor(TextFormatting.RED)), true);\n\t\tItemStack module = getModule(player);\n\t\t\n\t\tif (!module.isEmpty()) {\n\t\t\tif (!(module.getItem() == DMItems.DATA_MODULE.get() && module.getOrCreateTag().contains(\"written\"))) {\n\t\t\t\tif (!world.isClientSide()) {\n\t\t\t\t\tswitch (mode) {\n\t\t\t\t\t\tcase STRUCTURE:\n\t\t\t\t\t\t\tOptional<ResourceLocation> structure = StructureHelper.getStructure((ServerPlayerEntity) player);\n\t\t\t\t\t\t\tif (structure.isPresent() && !Config.SERVER_CONFIG.getStructureBlacklist().contains(structure.get())) {\n\t\t\t\t\t\t\t\tItemStack newModule = module.split(1);\n\t\t\t\t\t\t\t\tif (player.abilities.instabuild) module.grow(1);\n\n\t\t\t\t\t\t\t\tCompoundNBT tag = setupModuleTag(newModule.getOrCreateTag());\n\n\t\t\t\t\t\t\t\ttag.putString(\"Structure\", structure.get().toString());\n\t\t\t\t\t\t\t\tString name = StructureHelper.formatResourceLocationName(structure.get());\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tnewModule.setHoverName(Register.TEXT_MODULE_NAME.apply(mode, name).setStyle(Style.EMPTY.withColor(TextFormatting.LIGHT_PURPLE).withItalic(false)));\n\t\t tag.putString(\"cart_name\", name);\n\n\t\t\t\t\t\t\t\tHand otherHand = hand == Hand.MAIN_HAND ? Hand.OFF_HAND : Hand.MAIN_HAND;\n\t\t\t\t\t\t\t\tif (player.getItemInHand(otherHand) == module && module.isEmpty()) player.setItemInHand(otherHand, newModule);\n\t\t\t\t\t\t\t\telse player.addItem(newModule);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tRegister.TRIGGER_WRITE.trigger((ServerPlayerEntity) player, WriteModuleType.STRUCTURE);\n\t\t\t\t\t\t\t} else sendError.accept(Register.TEXT_NO_STRUCTURE);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase BIOME:\n\t\t\t\t\t\t\tResourceLocation biome = world.getBiome(player.blockPosition()).getRegistryName();\n\t\t\t\t\t\t\tif (!Config.SERVER_CONFIG.getBiomeBlacklist().contains(biome)) {\n\t\t\t\t\t\t\t\tItemStack newModule = module.split(1);\n\t\t\t\t\t\t\t\tif (player.abilities.instabuild) module.grow(1);\n\n\t\t\t\t\t\t\t\tCompoundNBT tag = setupModuleTag(newModule.getOrCreateTag());\n\n\t\t\t\t\t\t\t\ttag.putString(\"Biome\", biome.toString());\n\t\t\t\t\t\t\t\tString name = StructureHelper.formatResourceLocationName(biome);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tnewModule.setHoverName(Register.TEXT_MODULE_NAME.apply(mode, name).setStyle(Style.EMPTY.withColor(TextFormatting.LIGHT_PURPLE).withItalic(false)));\n\t\t tag.putString(\"cart_name\", name);\n\n\t\t\t\t\t\t\t\tHand otherHand = hand == Hand.MAIN_HAND ? Hand.OFF_HAND : Hand.MAIN_HAND;\n\t\t\t\t\t\t\t\tif (player.getItemInHand(otherHand) == module && module.isEmpty()) player.setItemInHand(otherHand, newModule);\n\t\t\t\t\t\t\t\telse player.addItem(newModule);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tRegister.TRIGGER_WRITE.trigger((ServerPlayerEntity) player, WriteModuleType.BIOME);\n\t\t\t\t\t\t\t} else sendError.accept(Register.TEXT_INVALID_BIOME);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn ActionResult.sidedSuccess(player.getItemInHand(hand), world.isClientSide());\n\t\t\t} else if (world.isClientSide()) sendError.accept(Register.TEXT_MODULE_WRITTEN);\n\t\t} else if (world.isClientSide()) sendError.accept(Register.TEXT_NO_MODULES);\n\t\t\n\t\treturn ActionResult.fail(player.getItemInHand(hand));\n\t}\n\t\n\t@Override @OnlyIn(Dist.CLIENT)\n\tpublic void appendHoverText(ItemStack stack, World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) {\n\t\tsuper.appendHoverText(stack, worldIn, tooltip, flagIn);\n\t\t\n\t\tItemUtils.addText(tooltip, Register.TEXT_TOOLTIP_MODE.apply(getMode(stack)).getString(), TextFormatting.GREEN);\n\t}\n\t\n\tprivate static LocatorDataWriterMode getMode(ItemStack stack) {\n\t\tCompoundNBT tag = stack.getOrCreateTag();\n\t\treturn LocatorDataWriterMode.values()[tag.getInt(\"Mode\") % LocatorDataWriterMode.values().length];\n\t}\n\t\n\tprivate static ItemStack getModule(PlayerEntity player) {\n\t\t// hands\n\t\tif (player.getItemInHand(Hand.OFF_HAND).getItem() instanceof DataModuleItem) return player.getItemInHand(Hand.OFF_HAND);\n\t\tif (player.getItemInHand(Hand.MAIN_HAND).getItem() instanceof DataModuleItem) return player.getItemInHand(Hand.MAIN_HAND);\n\t\t\n\t\t// inventory\n\t\tList<ItemStack> modules = new ArrayList<>();\n\t\tfor (int i = 0; i < player.inventory.getContainerSize(); ++i) {\n\t\t\tItemStack invStack = player.inventory.getItem(i);\n\t\t\tif (WRITABLE.test(invStack)) {\n\t\t\t\tmodules.add(invStack);\n\t\t\t\tif (!invStack.getOrCreateTag().contains(\"written\")) return invStack;\n\t\t\t}\n\t\t}\n\t\tif (modules.size() > 0) return modules.get(0);\n\t\t\n\t\t// creative mode\n\t\tif (player.abilities.instabuild) return new ItemStack(DMItems.DATA_MODULE.get());\n\t\t\n\t\treturn ItemStack.EMPTY;\n\t}\n\t\n\tprivate static CompoundNBT setupModuleTag(CompoundNBT tag) {\n\t\ttag.putBoolean(\"written\", true);\n\t\ttag.remove(\"location\");\n\t\ttag.remove(\"Structure\");\n\t\ttag.remove(\"Biome\");\n\t\treturn tag;\n\t}\n\t\n\tpublic static enum LocatorDataWriterMode { STRUCTURE, BIOME; };\n\t\n}" }, { "identifier": "LocatorDataWriterMode", "path": "src/main/java/com/bug1312/dm_locator/items/LocatorDataWriterItem.java", "snippet": "public static enum LocatorDataWriterMode { STRUCTURE, BIOME; };" }, { "identifier": "FlightPanelLootModifier", "path": "src/main/java/com/bug1312/dm_locator/loot_modifiers/FlightPanelLootModifier.java", "snippet": "public class FlightPanelLootModifier extends LootModifier {\n\t\n public FlightPanelLootModifier(ILootCondition[] conditionsIn) {\n super(conditionsIn);\n }\n\n @Nonnull @Override\n public List<ItemStack> doApply(List<ItemStack> generatedLoot, LootContext context) {\n \tgeneratedLoot.add(new ItemStack(Register.LOCATOR_ATTACHMENT_ITEM.get(), 1));\n return generatedLoot;\n }\n\n public static class Serializer extends GlobalLootModifierSerializer<FlightPanelLootModifier> {\n @Override\n public FlightPanelLootModifier read(ResourceLocation name, JsonObject json, ILootCondition[] conditionsIn) {\n return new FlightPanelLootModifier(conditionsIn);\n }\n\n @Override\n public JsonObject write(FlightPanelLootModifier instance) {\n return makeConditions(instance.conditions);\n }\n }\n\n}" }, { "identifier": "LocateParticleData", "path": "src/main/java/com/bug1312/dm_locator/particle/LocateParticleData.java", "snippet": "public class LocateParticleData implements IParticleData {\n\tpublic static final Codec<LocateParticleData> CODEC = RecordCodecBuilder.create(\n\t\tinstance -> instance.group(\n\t\t\tCodec.FLOAT.fieldOf(\"destination_x\").forGetter(LocateParticleData -> LocateParticleData.x),\n\t\t\tCodec.FLOAT.fieldOf(\"destination_z\").forGetter(LocateParticleData -> LocateParticleData.z),\n\t\t\tCodec.INT.fieldOf(\"arrival_in_ticks\").forGetter(LocateParticleData -> LocateParticleData.arrivalInTicks)\n\t\t).apply(instance, LocateParticleData::new)\n\t);\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static final IParticleData.IDeserializer<LocateParticleData> DESERIALIZER = new IParticleData.IDeserializer<LocateParticleData>() {\n\t\t@Override\n\t\tpublic LocateParticleData fromCommand(ParticleType<LocateParticleData> particleType, StringReader stringReader) throws CommandSyntaxException {\n\t\t\tstringReader.expect(' ');\n\t\t\tfloat x = stringReader.readFloat();\n\t\t\tstringReader.expect(' ');\n\t\t\tfloat z = stringReader.readFloat();\n\t\t\tstringReader.expect(' ');\n\t\t\tint a = stringReader.readInt();\n\t\t\treturn new LocateParticleData(x, z, a);\n\t\t}\n\n\t\t@Override\n\t\tpublic LocateParticleData fromNetwork(ParticleType<LocateParticleData> particleType, PacketBuffer byteBuff) {\n\t\t\tint x = byteBuff.readVarInt();\n\t\t\tint z = byteBuff.readVarInt();\n\t\t\tint a = byteBuff.readVarInt();\n\n\t\t\treturn new LocateParticleData(x, z, a);\n\t\t}\n\t};\n\n\tpublic final float x;\n\tpublic final float z;\n\tpublic final int arrivalInTicks;\n\n\tpublic LocateParticleData(float x, float z, int arrivalInTicks) {\n\t\tthis.x = x;\n\t\tthis.z = z;\n\t\tthis.arrivalInTicks = arrivalInTicks;\n\t}\n\t\n\t@Override\n\tpublic ParticleType<?> getType() {\n\t\treturn Register.LOCATE_PARTICLE.get();\n\t}\n\n\t@Override\n\tpublic void writeToNetwork(PacketBuffer byteBuff) {\n\t\tbyteBuff.writeFloat(this.x);\n\t\tbyteBuff.writeFloat(this.z);\n\t\tbyteBuff.writeVarInt(this.arrivalInTicks);\n\t}\n\n\t@Override\n\tpublic String writeToString() {\n\t\treturn String.format(Locale.ROOT, \"%d %d %d\", this.x, this.z, this.arrivalInTicks);\n\t}\n\n}" }, { "identifier": "FlightPanelTileEntity", "path": "src/main/java/com/bug1312/dm_locator/tiles/FlightPanelTileEntity.java", "snippet": "public class FlightPanelTileEntity extends DMTileEntityBase {\n\t@Nullable\n\tpublic ItemStack cartridge;\n\t\n\tpublic FlightPanelTileEntity() { super(Register.FLIGHT_PANEL_TILE.get()); }\n\n\t@Override\n\tpublic void load(BlockState state, CompoundNBT compound) {\n\t\tif (compound.contains(\"Item\")) this.cartridge = ItemStack.of(compound.getCompound(DMNBTKeys.ITEM));\n\t\t\n\t\tsuper.load(state, compound);\n\t}\n\n\t@Override\n\tpublic CompoundNBT save(CompoundNBT compound) {\n\t\tif (this.cartridge != null && !this.cartridge.isEmpty()) {\n\t\t\tCompoundNBT tag = new CompoundNBT();\n\t\t\tthis.cartridge.save(tag);\n\t\t\tcompound.put(\"Item\", tag);\n\t\t}\n\t\t\n\t\treturn super.save(compound);\n\t}\n\n}" }, { "identifier": "UseLocatorTrigger", "path": "src/main/java/com/bug1312/dm_locator/triggers/UseLocatorTrigger.java", "snippet": "public class UseLocatorTrigger extends AbstractCriterionTrigger<UseLocatorTrigger.Instance> {\n\tprivate static final ResourceLocation ID = new ResourceLocation(ModMain.MOD_ID, \"use_locator\");\n\n\tpublic ResourceLocation getId() { return ID; }\n\tpublic UseLocatorTrigger.Instance createInstance(JsonObject json, AndPredicate predicate, ConditionArrayParser parser) { return new UseLocatorTrigger.Instance(predicate); }\n\tpublic void trigger(ServerPlayerEntity player) { this.trigger(player, (instance) -> true); }\n\n\tpublic static class Instance extends CriterionInstance {\n\t\tpublic Instance(AndPredicate predicate) { super(UseLocatorTrigger.ID, predicate); }\n\t\tpublic JsonObject serializeToJson(ConditionArraySerializer serializer) { return super.serializeToJson(serializer); }\n\t}\n}" }, { "identifier": "WriteModuleTrigger", "path": "src/main/java/com/bug1312/dm_locator/triggers/WriteModuleTrigger.java", "snippet": "public class WriteModuleTrigger extends AbstractCriterionTrigger<WriteModuleTrigger.Instance> {\n\tprivate static final ResourceLocation ID = new ResourceLocation(ModMain.MOD_ID, \"write_module\");\n\n\tpublic ResourceLocation getId() { return ID; }\n\n\tpublic Instance createInstance(JsonObject json, AndPredicate predicate, ConditionArrayParser parser) {\n\t\treturn new Instance(predicate, WriteModuleType.fromString(JSONUtils.getAsString(json, \"type\")));\n\t}\n\n\tpublic void trigger(ServerPlayerEntity player, WriteModuleType type) {\n\t\tthis.trigger(player, instance -> instance.matches(type));\n\t}\n\n\tpublic static class Instance extends CriterionInstance {\n\t\tprivate final WriteModuleType type;\n\n\t\tpublic Instance(AndPredicate predicate, WriteModuleType type) {\n\t\t\tsuper(ID, predicate);\n\t\t\tthis.type = type;\n\t\t}\n\n\t\tpublic JsonObject serializeToJson(ConditionArraySerializer serializer) {\n\t\t\tJsonObject json = super.serializeToJson(serializer);\n\t\t\tif (this.type != null) json.addProperty(\"exterior\", this.type.toString());\n\t\t\treturn json;\n\t\t}\n\n\t\tpublic boolean matches(WriteModuleType type) {\n\t\t\treturn this.type.equals(type);\n\t\t}\n\t}\n\t\n\tpublic static enum WriteModuleType {\n\t\tWAYPOINT(\"waypoint\"),\n\t\tSTRUCTURE(\"structure\"),\n\t\tBIOME(\"biome\");\n\t\t\n\t\tprivate String string;\n\t\tprivate WriteModuleType(String string) { this.string = string; }\n\t\tpublic String toString() { return string; }\n\t\t\n\t public static WriteModuleType fromString(String string) {\n\t for (WriteModuleType enumValue : WriteModuleType.values()) {\n\t if (enumValue.toString().equalsIgnoreCase(string)) return enumValue;\n\t }\n\t return null;\n\t }\n\t}\n}" } ]
import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import com.bug1312.dm_locator.items.LocatorDataWriterItem; import com.bug1312.dm_locator.items.LocatorDataWriterItem.LocatorDataWriterMode; import com.bug1312.dm_locator.loot_modifiers.FlightPanelLootModifier; import com.bug1312.dm_locator.particle.LocateParticleData; import com.bug1312.dm_locator.tiles.FlightPanelTileEntity; import com.bug1312.dm_locator.triggers.UseLocatorTrigger; import com.bug1312.dm_locator.triggers.WriteModuleTrigger; import com.mojang.serialization.Codec; import com.swdteam.common.init.DMBlocks; import com.swdteam.common.init.DMTabs; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.client.settings.KeyBinding; import net.minecraft.item.Item; import net.minecraft.item.Item.Properties; import net.minecraft.particles.ParticleType; import net.minecraft.tileentity.TileEntityType; import net.minecraft.tileentity.TileEntityType.Builder; import net.minecraft.util.text.KeybindTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.common.loot.GlobalLootModifierSerializer; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistryEntry;
3,668
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator; public class Register { // Items public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID); public static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, "locator_data_writer", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1))); public static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, "locator_attachment", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS))); // Tiles public static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator; public class Register { // Items public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID); public static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, "locator_data_writer", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1))); public static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, "locator_attachment", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS))); // Tiles public static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);
public static final RegistryObject<TileEntityType<?>> FLIGHT_PANEL_TILE = register(TILE_ENTITIES, "flight_panel", () -> Builder.of(FlightPanelTileEntity::new, DMBlocks.FLIGHT_PANEL.get()).build(null));
4
2023-11-13 03:42:37+00:00
8k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/adapter/NacosInstanceRegistryService.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": "IpUtils", "path": "young-im-common/src/main/java/cn/young/im/common/util/IpUtils.java", "snippet": "public final class IpUtils {\n\n /**\n * ip pattern.\n */\n private static final Pattern IP_PATTERN = Pattern.compile(\"^((25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)($|(?!\\\\.$)\\\\.)){4}$\");\n\n /**\n * net card pattern.\n */\n private static final Pattern NET_CARD_PATTERN = Pattern.compile(\"(\\\\d+)$\");\n\n /**\n * System env docker host ip.\n */\n private static final String SYSTEM_ENV_DOCKER_HOST_IP = \"docker_host_ip\";\n\n /**\n * Localhost.\n */\n private static final String LOCALHOST = \"127.0.0.1\";\n\n /**\n * priority of networkInterface when generating client ip.\n */\n private static final String PROPERTY = System.getProperty(\"networkInterface.priority\", \"enp<eth<bond\");\n\n private static final List<String> PREFER_LIST = new ArrayList<>(Arrays.asList(PROPERTY.split(\"<\")));\n\n private static final Comparator<NetCard> BY_NAME = (card1, card2) -> {\n int card1Score = -1;\n int card2Score = -1;\n for (String pre : PREFER_LIST) {\n if (card1.getName().contains(pre)) {\n card1Score = PREFER_LIST.indexOf(pre);\n break;\n }\n }\n for (String pre : PREFER_LIST) {\n if (card2.getName().contains(pre)) {\n card2Score = PREFER_LIST.indexOf(pre);\n break;\n }\n }\n return card2Score - card1Score;\n };\n\n private IpUtils() {\n }\n\n /**\n * Gets host.\n *\n * @return the host\n */\n public static String getHost() {\n return getHost(null);\n }\n\n /**\n * Gets host.\n *\n * @param filterHost host filterHost str\n * @return the host\n */\n public static String getHost(final String filterHost) {\n String hostIp = null;\n String pattern = filterHost;\n // filter matching ip\n if (\"*\".equals(filterHost) || \"\".equals(filterHost)) {\n pattern = null;\n } else if (filterHost != null && !filterHost.contains(\"*\") && !isCompleteHost(filterHost)) {\n pattern = filterHost + \"*\";\n }\n\n // if the progress works under docker environment\n // return the host ip about this docker located from environment value\n String dockerHostIp = System.getenv(SYSTEM_ENV_DOCKER_HOST_IP);\n if (dockerHostIp != null && !\"\".equals(dockerHostIp)) {\n return dockerHostIp;\n }\n\n // Traversal Network interface to scan all network interface\n List<NetCard> ipv4Result = new ArrayList<>();\n List<NetCard> ipv6Result = new ArrayList<>();\n NetCard netCard;\n try {\n Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();\n while (enumeration.hasMoreElements()) {\n final NetworkInterface networkInterface = enumeration.nextElement();\n Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();\n while (addresses.hasMoreElements()) {\n InetAddress inetAddress = addresses.nextElement();\n if (inetAddress != null && !inetAddress.isLoopbackAddress()) {\n if (inetAddress instanceof Inet4Address && isCompleteHost(inetAddress.getHostAddress())) {\n netCard = new NetCard(inetAddress.getHostAddress(),\n getName(networkInterface.getName()),\n getNamePostfix(networkInterface.getName()),\n Integer.parseInt(inetAddress.getHostAddress().split(\"\\\\.\")[3]));\n ipv4Result.add(netCard);\n } else {\n netCard = new NetCard(inetAddress.getHostAddress(),\n getName(networkInterface.getName()),\n getNamePostfix(networkInterface.getName()));\n ipv6Result.add(netCard);\n }\n }\n }\n }\n\n // sort ip\n Comparator<NetCard> byNamePostfix = Comparator.comparing(NetCard::getNamePostfix);\n Comparator<NetCard> byIpv4Postfix = (card1, card2) -> card2.getIpv4Postfix() - card1.getIpv4Postfix();\n ipv4Result.sort(BY_NAME.thenComparing(byNamePostfix).thenComparing(byIpv4Postfix));\n ipv6Result.sort(BY_NAME.thenComparing(byNamePostfix));\n // prefer ipv4\n if (!ipv4Result.isEmpty()) {\n if (pattern != null) {\n for (NetCard card : ipv4Result) {\n if (ipMatch(card.getIp(), pattern)) {\n hostIp = card.getIp();\n break;\n }\n }\n } else {\n hostIp = ipv4Result.get(0).getIp();\n }\n } else if (!ipv6Result.isEmpty()) {\n hostIp = ipv6Result.get(0).getIp();\n }\n // If failed to find,fall back to localhost\n if (Objects.isNull(hostIp)) {\n hostIp = InetAddress.getLocalHost().getHostAddress();\n }\n } catch (SocketException | UnknownHostException ignore) {\n hostIp = LOCALHOST;\n }\n return hostIp;\n }\n\n /**\n * Judge whether host is complete.\n *\n * @param host host ip\n * @return boolean\n */\n public static boolean isCompleteHost(final String host) {\n if (host == null) {\n return false;\n }\n return IP_PATTERN.matcher(host).matches();\n }\n\n /**\n * do ip match.\n *\n * @param ip network ip\n * @param pattern match pattern\n * @return boolean\n */\n private static boolean ipMatch(final String ip, final String pattern) {\n int m = ip.length();\n int n = pattern.length();\n boolean[][] dp = new boolean[m + 1][n + 1];\n dp[0][0] = true;\n for (int i = 1; i <= n; ++i) {\n if (pattern.charAt(i - 1) == '*') {\n dp[0][i] = true;\n } else {\n break;\n }\n }\n for (int i = 1; i <= m; ++i) {\n for (int j = 1; j <= n; ++j) {\n if (pattern.charAt(j - 1) == '*') {\n dp[i][j] = dp[i][j - 1] || dp[i - 1][j];\n } else if (pattern.charAt(j - 1) == '?' || ip.charAt(i - 1) == pattern.charAt(j - 1)) {\n dp[i][j] = dp[i - 1][j - 1];\n }\n }\n }\n return dp[m][n];\n }\n\n /**\n * To obtain a prefix.\n *\n * @param name network interface name\n * @return the name\n */\n private static String getName(final String name) {\n Matcher matcher = NET_CARD_PATTERN.matcher(name);\n if (matcher.find()) {\n return name.replace(matcher.group(), \"\");\n }\n return name;\n }\n\n /**\n * Get the last number.\n *\n * @param name network interface name\n * @return the name postfix\n */\n private static Integer getNamePostfix(final String name) {\n Matcher matcher = NET_CARD_PATTERN.matcher(name);\n if (matcher.find()) {\n return Integer.parseInt(matcher.group());\n }\n return -1;\n }\n\n private static class NetCard implements Serializable {\n\n private String ip;\n\n private String name;\n\n private Integer namePostfix;\n\n private Integer ipv4Postfix;\n\n NetCard(final String ip, final String name, final Integer namePostfix) {\n this.ip = ip;\n this.name = name;\n this.namePostfix = namePostfix;\n }\n\n NetCard(final String ip, final String name, final Integer namePostfix, final Integer postfix) {\n this.ip = ip;\n this.name = name;\n this.namePostfix = namePostfix;\n this.ipv4Postfix = postfix;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(final String ip) {\n this.ip = ip;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public Integer getIpv4Postfix() {\n return ipv4Postfix;\n }\n\n public Integer getNamePostfix() {\n return namePostfix;\n }\n\n public void setNamePostfix(final Integer namePostfix) {\n this.namePostfix = namePostfix;\n }\n\n }\n}" }, { "identifier": "InstanceEntity", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/InstanceEntity.java", "snippet": "@Data\n@Builder\n@Accessors(chain = true)\npublic class InstanceEntity {\n\n /**\n * 主机地址\n */\n private String host;\n\n /**\n * 端口号\n */\n private int port;\n\n /**\n * 实例健康状态\n */\n private Status status;\n\n /**\n * 权重\n */\n private double weight = 1.0D;\n\n /**\n * 客户端名称\n */\n private String serviceName;\n}" }, { "identifier": "InstanceRegistryService", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/InstanceRegistryService.java", "snippet": "@SPI(\"nacos\")\npublic interface InstanceRegistryService {\n\n /**\n * 初始化注册中心\n */\n default void init(RegisterConfig config) {\n\n }\n\n /**\n * 注册\n */\n void registry(InstanceEntity instanceEntity);\n\n\n /**\n * 获取实例\n */\n List<InstanceEntity> listOfInstance(String tenant);\n}" }, { "identifier": "Status", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/Status.java", "snippet": "@AllArgsConstructor\npublic enum Status implements KeyValueEnum<Integer, String> {\n\n HEALTH(1, \"健康\"),\n\n SUBJECTIVE_DOWN_LINE(2, \"主观下线\"),\n\n OBJECTIVE_DOWN(3, \"客观下线\");\n\n\n final int code;\n\n final String desc;\n\n\n @Override\n public Integer getCode() {\n return this.code;\n }\n\n @Override\n public String getDesc() {\n return this.desc;\n }\n}" }, { "identifier": "NacosConfig", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/config/NacosConfig.java", "snippet": "@Data\npublic class NacosConfig {\n\n /**\n * 租户号\n */\n private String namespace;\n\n /**\n * 组\n */\n private String group;\n\n /**\n * 用户名\n */\n private String username;\n\n /**\n * 密码\n */\n private String password;\n}" }, { "identifier": "RegisterConfig", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/config/RegisterConfig.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"young.im.registry\")\npublic class RegisterConfig {\n\n /**\n * 实例刷新模式\n */\n private String mode;\n\n /**\n * 注册类型\n */\n private String registryType;\n\n /**\n * 注册中心列表\n */\n private String serverLists;\n\n /**\n * Nacos\n */\n private NacosConfig nacos;\n}" }, { "identifier": "AnnotationScanner", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-extension/src/main/java/cn/young/im/springboot/starter/extension/util/AnnotationScanner.java", "snippet": "@Slf4j\npublic class AnnotationScanner {\n /**\n * 扫描RefreshConfig注解的类\n *\n * @param basePackage 扫描包\n * @return 返回类与对应注解信息\n */\n public static Map<Class<?>, Annotation> scanClassByAnnotation(String basePackage, Class<? extends Annotation> annotationClas) {\n Map<Class<?>, Annotation> annotatedClassesMap = new HashMap<>();\n try {\n ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);\n scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClas));\n ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(AnnotationScanner.class.getClassLoader());\n MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(resourcePatternResolver);\n for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {\n MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(Objects.requireNonNull(bd.getBeanClassName()));\n String className = metadataReader.getClassMetadata().getClassName();\n Class<?> clazz = Class.forName(className);\n Annotation annotation = clazz.getAnnotation(annotationClas);\n annotatedClassesMap.put(clazz, annotation);\n }\n } catch (IOException | ClassNotFoundException e) {\n log.error(e.getMessage(), e);\n }\n return annotatedClassesMap;\n }\n}" }, { "identifier": "COLONS", "path": "young-im-common/src/main/java/cn/young/im/common/constants/Const.java", "snippet": "public final static String COLONS = \":\";" }, { "identifier": "BASE_PACKAGE", "path": "young-im-common/src/main/java/cn/young/im/common/constants/YoungConst.java", "snippet": "public static final String BASE_PACKAGE = \"cn.young.im\";" }, { "identifier": "DEFAULT", "path": "young-im-common/src/main/java/cn/young/im/common/constants/YoungConst.java", "snippet": "public static final String DEFAULT = \"#\";" } ]
import cn.young.im.common.exception.YoungImException; import cn.young.im.common.util.IpUtils; import cn.young.im.spi.Join; import cn.young.im.springboot.starter.adapter.registry.InstanceEntity; import cn.young.im.springboot.starter.adapter.registry.InstanceRegistryService; import cn.young.im.springboot.starter.adapter.registry.Status; import cn.young.im.springboot.starter.adapter.registry.annotation.AutomaticRegistry; import cn.young.im.springboot.starter.adapter.registry.config.NacosConfig; import cn.young.im.springboot.starter.adapter.registry.config.RegisterConfig; import cn.young.im.springboot.starter.extension.util.AnnotationScanner; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import static cn.young.im.common.constants.Const.COLONS; import static cn.young.im.common.constants.YoungConst.BASE_PACKAGE; import static cn.young.im.common.constants.YoungConst.DEFAULT;
4,247
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements InstanceRegistryService, EnvironmentAware { private ConfigurableEnvironment environment; private NamingService namingService; private String group; @Override public void init(RegisterConfig config) { // 1. 提取配置 NacosConfig nacos = config.getNacos(); this.group = nacos.getGroup(); // 2. 装填配置 Properties properties = new Properties(); properties.put("serverAddr", config.getServerLists()); properties.put("namespace", nacos.getNamespace()); properties.put("username", nacos.getUsername()); properties.put("password", nacos.getPassword()); properties.put("group", group); try { // 3. 实例化 this.namingService = NamingFactory.createNamingService(properties); } catch (NacosException e) { log.error("init nacos registry center occur error"); throw new YoungImException(e); } // 4. 提取注解发起注册 Map<Class<?>, Annotation> classAnnotationMap = AnnotationScanner.scanClassByAnnotation(BASE_PACKAGE, AutomaticRegistry.class); for (Annotation annotation : classAnnotationMap.values()) { AutomaticRegistry registry = (AutomaticRegistry) annotation; String serviceName = registry.serviceName().equals(DEFAULT) ? environment.getProperty("spring.application.name") : registry.serviceName(); String port = registry.port().equals(DEFAULT) ? environment.getProperty("local.server.port") : registry.port();
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements InstanceRegistryService, EnvironmentAware { private ConfigurableEnvironment environment; private NamingService namingService; private String group; @Override public void init(RegisterConfig config) { // 1. 提取配置 NacosConfig nacos = config.getNacos(); this.group = nacos.getGroup(); // 2. 装填配置 Properties properties = new Properties(); properties.put("serverAddr", config.getServerLists()); properties.put("namespace", nacos.getNamespace()); properties.put("username", nacos.getUsername()); properties.put("password", nacos.getPassword()); properties.put("group", group); try { // 3. 实例化 this.namingService = NamingFactory.createNamingService(properties); } catch (NacosException e) { log.error("init nacos registry center occur error"); throw new YoungImException(e); } // 4. 提取注解发起注册 Map<Class<?>, Annotation> classAnnotationMap = AnnotationScanner.scanClassByAnnotation(BASE_PACKAGE, AutomaticRegistry.class); for (Annotation annotation : classAnnotationMap.values()) { AutomaticRegistry registry = (AutomaticRegistry) annotation; String serviceName = registry.serviceName().equals(DEFAULT) ? environment.getProperty("spring.application.name") : registry.serviceName(); String port = registry.port().equals(DEFAULT) ? environment.getProperty("local.server.port") : registry.port();
String host = registry.host().equals(DEFAULT) ? IpUtils.getHost() : registry.host();
1
2023-11-10 06:21:17+00:00
8k
erhenjt/twoyi2
app/src/main/java/io/twoyi/ui/SettingsActivity.java
[ { "identifier": "AppKV", "path": "app/src/main/java/io/twoyi/utils/AppKV.java", "snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NOT_SHOW_ADDED = \"add_app_not_show_added\";\n public static final String SHOW_ANDROID12_TIPS = \"show_android12_tips_v2\";\n public static final String ADD_APP_NOT_SHOW_32BIT = \"add_app_not_show_32bit\";\n\n // 是否应该重新安装 ROM\n // 1. 恢复出厂设置\n // 2. 替换 ROM\n public static final String FORCE_ROM_BE_RE_INSTALL = \"rom_should_be_re_install\";\n\n // 是否应该使用第三方 ROM\n public static final String SHOULD_USE_THIRD_PARTY_ROM = \"should_use_third_party_rom\";\n public static boolean getBooleanConfig(Context context, String key, boolean fallback) {\n return getPref(context).getBoolean(key, fallback);\n }\n\n @SuppressLint(\"ApplySharedPref\")\n public static void setBooleanConfig(Context context, String key, boolean value) {\n getPref(context).edit().putBoolean(key, value).commit();\n }\n\n private static SharedPreferences getPref(Context context) {\n return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n }\n}" }, { "identifier": "RomManager", "path": "app/src/main/java/io/twoyi/utils/RomManager.java", "snippet": "public final class RomManager {\n\n private static final String TAG = \"RomManager\";\n\n private static final String ROOTFS_NAME = \"rootfs.7z\";\n\n private static final String ROM_INFO_FILE = \"rom.ini\";\n\n private static final String DEFAULT_INFO = \"unknown\";\n\n private static final String LOADER_FILE = \"libloader.so\";\n\n private static final String CUSTOM_ROM_FILE_NAME = \"rootfs_3rd.7z\";\n\n private RomManager() {\n }\n\n public static void initRootfs(Context context) {\n File propFile = getVendorPropFile(context);\n String language = Locale.getDefault().getLanguage();\n String country = Locale.getDefault().getCountry();\n\n Properties properties = new Properties();\n\n properties.setProperty(\"persist.sys.language\", language);\n properties.setProperty(\"persist.sys.country\", country);\n\n TimeZone timeZone = TimeZone.getDefault();\n String timeZoneID = timeZone.getID();\n Log.i(TAG, \"timezone: \" + timeZoneID);\n properties.setProperty(\"persist.sys.timezone\", timeZoneID);\n\n properties.setProperty(\"ro.sf.lcd_density\", String.valueOf(DisplayMetrics.DENSITY_DEVICE_STABLE));\n\n try (Writer writer = new FileWriter(propFile)) {\n properties.store(writer, null);\n } catch (IOException ignored) {\n }\n }\n\n public static void ensureBootFiles(Context context) {\n\n // <rootdir>/dev/\n File devDir = new File(getRootfsDir(context), \"dev\");\n ensureDir(new File(devDir, \"input\"));\n ensureDir(new File(devDir, \"socket\"));\n ensureDir(new File(devDir, \"maps\"));\n\n ensureDir(new File(context.getDataDir(), \"socket\"));\n\n createLoaderSymlink(context);\n\n killOrphanProcess();\n }\n\n private static void createLoaderSymlink(Context context) {\n Path loaderSymlink = new File(context.getDataDir(), \"loader64\").toPath();\n String loaderPath = getLoaderPath(context);\n try {\n Files.deleteIfExists(loaderSymlink);\n Files.createSymbolicLink(loaderSymlink, Paths.get(loaderPath));\n } catch (IOException e) {\n throw new RuntimeException(\"symlink loader failed.\", e);\n }\n }\n\n private static void killOrphanProcess() {\n Shell shell = ShellUtil.newSh();\n shell.newJob().add(\"ps -ef | awk '{if($3==1) print $2}' | xargs kill -9\").exec();\n }\n\n public static class RomInfo {\n public String author = DEFAULT_INFO;\n public String version = DEFAULT_INFO;\n public String desc = DEFAULT_INFO;\n public String md5 = \"\";\n public long code = 0;\n\n @Override\n public String toString() {\n return \"RomInfo{\" +\n \"author='\" + author + '\\'' +\n \", version='\" + version + '\\'' +\n \", md5='\" + md5 + '\\'' +\n \", code=\" + code +\n '}';\n }\n\n public boolean isValid() {\n return this != DEFAULT_ROM_INFO;\n }\n }\n\n public static final RomInfo DEFAULT_ROM_INFO = new RomInfo();\n\n public static boolean romExist(Context context) {\n File initFile = new File(getRootfsDir(context), \"init\");\n return initFile.exists();\n }\n\n public static boolean needsUpgrade(Context context) {\n RomInfo currentRomInfo = getCurrentRomInfo(context);\n Log.i(TAG, \"current rom: \" + currentRomInfo);\n if (currentRomInfo.equals(DEFAULT_ROM_INFO)) {\n return true;\n }\n\n RomInfo romInfoFromAssets = getRomInfoFromAssets(context);\n Log.i(TAG, \"asset rom: \" + romInfoFromAssets);\n return romInfoFromAssets.code > currentRomInfo.code;\n }\n\n public static RomInfo getCurrentRomInfo(Context context) {\n File infoFile = new File(getRootfsDir(context), ROM_INFO_FILE);\n try (FileInputStream inputStream = new FileInputStream(infoFile)) {\n return getRomInfo(inputStream);\n } catch (Throwable e) {\n return DEFAULT_ROM_INFO;\n }\n }\n\n public static String getLoaderPath(Context context) {\n ApplicationInfo applicationInfo = context.getApplicationInfo();\n return new File(applicationInfo.nativeLibraryDir, LOADER_FILE).getAbsolutePath();\n }\n\n public static RomInfo getRomInfo(File rom) {\n try (SevenZFile zFile = new SevenZFile(rom)) {\n\n SevenZArchiveEntry entry;\n\n while ((entry = zFile.getNextEntry()) != null) {\n if (entry.getName().equals(\"rootfs/rom.ini\")) {\n byte[] content = new byte[(int) entry.getSize()];\n zFile.read(content, 0, content.length);\n ByteArrayInputStream bais = new ByteArrayInputStream(content);\n return getRomInfo(bais);\n }\n }\n } catch (Throwable ignored) {}\n return DEFAULT_ROM_INFO;\n }\n\n public static RomInfo getRomInfoFromAssets(Context context) {\n AssetManager assets = context.getAssets();\n try (InputStream open = assets.open(ROM_INFO_FILE)) {\n return getRomInfo(open);\n } catch (Throwable ignored) {\n }\n return DEFAULT_ROM_INFO;\n }\n\n public static void extractRootfs(Context context, boolean romExist, boolean needsUpgrade, boolean forceInstall, boolean use3rdRom) {\n\n // force remove system dir to avoiding wired issues\n removeSystemPartition(context);\n removeVendorPartition(context);\n\n if (!romExist) {\n // first init\n extractRootfsInAssets(context);\n return;\n }\n\n if (forceInstall) {\n if (use3rdRom) {\n // install 3rd rom\n boolean success = extract3rdRootfs(context);\n if (!success) {\n showRootfsInstallationFailure(context);\n return;\n }\n } else {\n // factory reset!!\n if (!extractRootfsInAssets(context)) {\n showRootfsInstallationFailure(context);\n return;\n }\n }\n\n // force install finish, reset the state.\n AppKV.setBooleanConfig(context, AppKV.FORCE_ROM_BE_RE_INSTALL, false);\n } else {\n if (use3rdRom) {\n Log.w(TAG, \"WTF? 3rd ROM must be force install!\");\n }\n if (needsUpgrade) {\n Log.i(TAG, \"upgrade factory rom..\");\n if (!extractRootfsInAssets(context)) {\n showRootfsInstallationFailure(context);\n }\n }\n }\n }\n\n private static void showRootfsInstallationFailure(Context context) {\n // TODO\n }\n\n public static void reboot(Context context) {\n Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());\n context.getApplicationContext().startActivity(intent);\n\n shutdown(context);\n }\n\n public static void shutdown(Context context) {\n System.exit(0);\n Process.killProcess(Process.myPid());\n }\n\n public static boolean extract3rdRootfs(Context context) {\n File rootfs3rd = get3rdRootfsFile(context);\n if (!rootfs3rd.exists()) {\n return false;\n }\n int err = extractRootfs(context, rootfs3rd);\n return err == 0;\n }\n\n public static int extractRootfs(Context context, File rootfs7z) {\n\n int cpu = Runtime.getRuntime().availableProcessors();\n return P7ZipApi.executeCommand(String.format(Locale.US, \"7z x -mmt=%d -aoa '%s' '-o%s'\",\n cpu, rootfs7z, context.getDataDir()));\n }\n\n public static boolean extractRootfsInAssets(Context context) {\n\n // read assets\n long t1 = SystemClock.elapsedRealtime();\n File rootfs7z = context.getFileStreamPath(ROOTFS_NAME);\n try (InputStream inputStream = new BufferedInputStream(context.getAssets().open(ROOTFS_NAME));\n OutputStream os = new BufferedOutputStream(new FileOutputStream(rootfs7z))) {\n byte[] buffer = new byte[10240];\n int count;\n while ((count = inputStream.read(buffer)) > 0) {\n os.write(buffer, 0, count);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n long t2 = SystemClock.elapsedRealtime();\n\n int ret = extractRootfs(context, rootfs7z);\n\n long t3 = SystemClock.elapsedRealtime();\n\n Log.i(TAG, \"extract rootfs, read assets: \" + (t2 - t1) + \" un7z: \" + (t3 - t2) + \"ret: \" + ret);\n\n return ret == 0;\n }\n\n public static File getRootfsDir(Context context) {\n return new File(context.getDataDir(), \"rootfs\");\n }\n\n public static File getRomSdcardDir(Context context) {\n return new File(getRootfsDir(context), \"sdcard\");\n }\n\n public static File getVendorDir(Context context) {\n return new File(getRootfsDir(context), \"vendor\");\n }\n\n public static File getVendorPropFile(Context context) {\n return new File(getVendorDir(context), \"default.prop\");\n }\n\n public static File get3rdRootfsFile(Context context) {\n return context.getFileStreamPath(CUSTOM_ROM_FILE_NAME);\n }\n\n public static boolean isAndroid12() {\n return Build.VERSION.PREVIEW_SDK_INT + Build.VERSION.SDK_INT == Build.VERSION_CODES.S;\n }\n\n private static void removePartition(Context context, String partition) {\n File rootfsDir = getRootfsDir(context);\n File systemDir = new File(rootfsDir, partition);\n\n IOUtils.deleteDirectory(systemDir);\n }\n\n private static void removeSystemPartition(Context context) {\n removePartition(context, \"system\");\n }\n\n private static void removeVendorPartition(Context context) {\n removePartition(context, \"vendor\");\n }\n\n private static RomInfo getRomInfo(InputStream in) {\n Properties prop = new Properties();\n try {\n prop.load(in);\n\n RomInfo info = new RomInfo();\n info.author = prop.getProperty(\"author\");\n info.code = Long.parseLong(prop.getProperty(\"code\"));\n info.version = prop.getProperty(\"version\");\n info.desc = prop.getProperty(\"desc\", DEFAULT_INFO);\n info.md5 = prop.getProperty(\"md5\");\n return info;\n } catch (Throwable e) {\n Log.e(TAG, \"read rom info err\", e);\n return DEFAULT_ROM_INFO;\n }\n }\n\n private static void ensureDir(File file) {\n if (file.exists()) {\n return;\n }\n //noinspection ResultOfMethodCallIgnored\n file.mkdirs();\n }\n}" }, { "identifier": "UIHelper", "path": "app/src/main/java/io/twoyi/utils/UIHelper.java", "snippet": "public class UIHelper {\n private static final AndroidDeferredManager gDM = new AndroidDeferredManager();\n\n public static ExecutorService GLOBAL_EXECUTOR = Executors.newCachedThreadPool();\n\n public static AndroidDeferredManager defer() {\n return gDM;\n }\n\n public static void dismiss(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.dismiss();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void openWeiXin(Context context, String weixin) {\n try {\n // 获取剪贴板管理服务\n ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (cm == null) {\n return;\n }\n cm.setText(weixin);\n\n Intent intent = new Intent(Intent.ACTION_MAIN);\n ComponentName cmp = new ComponentName(\"com.tencent.mm\", \"com.tencent.mm.ui.LauncherUI\");\n intent.addCategory(Intent.CATEGORY_LAUNCHER);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setComponent(cmp);\n\n context.startActivity(intent);\n Toast.makeText(context, R.string.wechat_public_account_tips, Toast.LENGTH_LONG).show();\n } catch (Throwable e) {\n Toast.makeText(context, \"WeChat is not installed.\", Toast.LENGTH_SHORT).show();\n }\n }\n\n public static void show(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.show();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static AlertDialog.Builder getDialogBuilder(Context context) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context, com.google.android.material.R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog);\n builder.setIcon(R.mipmap.ic_launcher);\n return builder;\n }\n\n public static AlertDialog.Builder getWebViewBuilder(Context context, String title, String url) {\n AlertDialog.Builder dialogBuilder = getDialogBuilder(context);\n if (!TextUtils.isEmpty(title)) {\n dialogBuilder.setTitle(title);\n }\n WebView webView = new WebView(context);\n webView.loadUrl(url);\n dialogBuilder.setView(webView);\n dialogBuilder.setPositiveButton(R.string.i_know_it, null);\n return dialogBuilder;\n }\n\n public static ProgressDialog getProgressDialog(Context context) {\n ProgressDialog dialog = new ProgressDialog(context);\n dialog.setIcon(R.mipmap.ic_launcher);\n dialog.setTitle(R.string.progress_dialog_title);\n return dialog;\n }\n\n public static MaterialDialog getNumberProgressDialog(Context context) {\n return new MaterialDialog.Builder(context)\n .title(R.string.progress_dialog_title)\n .iconRes(R.mipmap.ic_launcher)\n .progress(false, 0, true)\n .build();\n }\n\n public static void showPrivacy(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/privacy\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static void showFAQ(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/guide\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void goWebsite(Context context) {\n visitSite(context, \"https://twoyi.app\");\n }\n\n public static void goTelegram(Context context) {\n visitSite(context, \"https://t.me/twoyi\");\n }\n\n public static void visitSite(Context context, String url) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setData(Uri.parse(url));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static int dpToPx(Context context, int dp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,\n context.getResources().getDisplayMetrics());\n }\n\n public static List<ApplicationInfo> getInstalledApplications(PackageManager packageManager) {\n if (packageManager == null) {\n return Collections.emptyList();\n }\n\n @SuppressLint(\"WrongConstant\")\n List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES\n | PackageManager.GET_DISABLED_COMPONENTS);\n int userApp = 0;\n for (ApplicationInfo installedApplication : installedApplications) {\n if ((installedApplication.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n if (userApp++ > 3) {\n return installedApplications;\n }\n }\n }\n\n List<ApplicationInfo> applicationInfos = new ArrayList<>();\n for (int uid = 0; uid <= Process.LAST_APPLICATION_UID; uid++) {\n String[] packagesForUid = packageManager.getPackagesForUid(uid);\n if (packagesForUid == null || packagesForUid.length == 0) {\n continue;\n }\n for (String pkg : packagesForUid) {\n try {\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(pkg, 0);\n applicationInfos.add(applicationInfo);\n } catch (PackageManager.NameNotFoundException ignored) {\n }\n }\n }\n\n return applicationInfos;\n }\n\n public static String toModuleScope(Set<String> scopes) {\n if (scopes == null || scopes.isEmpty()) {\n return \"\";\n }\n\n StringBuilder sb = new StringBuilder();\n int size = scopes.size();\n\n int i = 0;\n for (String scope : scopes) {\n sb.append(scope);\n\n if (i++ < size - 1) {\n sb.append(',');\n }\n\n }\n return sb.toString();\n }\n\n public static void shareText(Context context, @StringRes int shareTitle, String extraText) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"text/plain\");\n intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(shareTitle));\n intent.putExtra(Intent.EXTRA_TEXT, extraText);//extraText为文本的内容\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//为Activity新建一个任务栈\n context.startActivity(\n Intent.createChooser(intent, context.getString(shareTitle)));\n }\n\n public static String paste(Context context) {\n ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (manager == null) {\n return null;\n }\n boolean hasPrimaryClip = manager.hasPrimaryClip();\n if (!hasPrimaryClip) {\n return null;\n }\n ClipData primaryClip = manager.getPrimaryClip();\n if (primaryClip == null) {\n return null;\n }\n if (primaryClip.getItemCount() <= 0) {\n return null;\n }\n CharSequence addedText = primaryClip.getItemAt(0).getText();\n return String.valueOf(addedText);\n }\n\n public static void startActivity(Context context, Class<?> clazz) {\n if (context == null) {\n return;\n }\n\n Intent intent = new Intent(context, clazz);\n\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n\n try {\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n private static boolean isVM64(Set<String> supportedABIs) {\n if (Build.SUPPORTED_64_BIT_ABIS.length == 0) {\n return false;\n }\n\n if (supportedABIs == null || supportedABIs.isEmpty()) {\n return true;\n }\n\n for (String supportedAbi : supportedABIs) {\n if (\"arm64-v8a\".endsWith(supportedAbi) || \"x86_64\".equals(supportedAbi) || \"mips64\".equals(supportedAbi)) {\n return true;\n }\n }\n\n return false;\n }\n\n private static Set<String> getABIsFromApk(String apk) {\n try (ZipFile apkFile = new ZipFile(apk)) {\n Enumeration<? extends ZipEntry> entries = apkFile.entries();\n Set<String> supportedABIs = new HashSet<String>();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (name.contains(\"../\")) {\n continue;\n }\n if (name.startsWith(\"lib/\") && !entry.isDirectory() && name.endsWith(\".so\")) {\n String supportedAbi = name.substring(name.indexOf(\"/\") + 1, name.lastIndexOf(\"/\"));\n supportedABIs.add(supportedAbi);\n }\n }\n return supportedABIs;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static boolean isApk64(String apk) {\n long start = SystemClock.elapsedRealtime();\n Set<String> abIsFromApk = getABIsFromApk(apk);\n return isVM64(abIsFromApk);\n }\n\n @SuppressWarnings(\"JavaReflectionMemberAccess\")\n @SuppressLint(\"DiscouragedPrivateApi\")\n public static boolean isAppSupport64bit(ApplicationInfo info) {\n try {\n // fast path, the isApk64 is too heavy!\n Field primaryCpuAbiField = ApplicationInfo.class.getDeclaredField(\"primaryCpuAbi\");\n String primaryCpuAbi = (String) primaryCpuAbiField.get(info);\n if (primaryCpuAbi == null) {\n // no native libs, support!\n return true;\n }\n\n return Arrays.asList(\"arm64-v8a\", \"x86_64\").contains(primaryCpuAbi.toLowerCase());\n } catch (Throwable e) {\n return isApk64(info.sourceDir);\n }\n }\n}" } ]
import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.provider.DocumentsContract; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.util.Pair; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import io.twoyi.R; import io.twoyi.utils.AppKV; import io.twoyi.utils.RomManager; import io.twoyi.utils.UIHelper;
5,963
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package io.twoyi.ui; /** * @author weishu * @date 2022/1/2. */ public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_GET_FILE = 1000; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); SettingsFragment settingsFragment = new SettingsFragment(); getFragmentManager().beginTransaction() .replace(R.id.settingsFrameLayout, settingsFragment) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.title_settings); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_settings); } private Preference findPreference(@StringRes int id) { String key = getString(id); return findPreference(key); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Preference importApp = findPreference(R.string.settings_key_import_app); Preference export = findPreference(R.string.settings_key_manage_files); Preference shutdown = findPreference(R.string.settings_key_shutdown); Preference reboot = findPreference(R.string.settings_key_reboot); Preference replaceRom = findPreference(R.string.settings_key_replace_rom); Preference factoryReset = findPreference(R.string.settings_key_factory_reset); Preference about = findPreference(R.string.settings_key_about); importApp.setOnPreferenceClickListener(preference -> {
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package io.twoyi.ui; /** * @author weishu * @date 2022/1/2. */ public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_GET_FILE = 1000; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); SettingsFragment settingsFragment = new SettingsFragment(); getFragmentManager().beginTransaction() .replace(R.id.settingsFrameLayout, settingsFragment) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.title_settings); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_settings); } private Preference findPreference(@StringRes int id) { String key = getString(id); return findPreference(key); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Preference importApp = findPreference(R.string.settings_key_import_app); Preference export = findPreference(R.string.settings_key_manage_files); Preference shutdown = findPreference(R.string.settings_key_shutdown); Preference reboot = findPreference(R.string.settings_key_reboot); Preference replaceRom = findPreference(R.string.settings_key_replace_rom); Preference factoryReset = findPreference(R.string.settings_key_factory_reset); Preference about = findPreference(R.string.settings_key_about); importApp.setOnPreferenceClickListener(preference -> {
UIHelper.startActivity(getContext(), SelectAppActivity.class);
2
2023-11-11 22:08:20+00:00
8k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/plugin/Metadata.java
[ { "identifier": "PluginManager", "path": "src/main/java/io/xlorey/FluxLoader/shared/PluginManager.java", "snippet": "@UtilityClass\npublic class PluginManager {\n /**\n * General plugin loader\n */\n private static PluginClassLoader pluginClassLoader;\n\n /**\n * All loaded information about plugins\n * Key: plugin file\n * Value: information about the plugin\n */\n private static final HashMap<File, Metadata> pluginsInfoRegistry = new HashMap<>();\n\n /**\n * Registry of icons of loaded plugins\n * Key: plugin id\n *Value: texture object\n */\n private static final HashMap<String, Texture> pluginIconRegistry = new HashMap<>();\n\n /**\n * Register of loaded plugin controls\n * Key: plugin id\n * Value: Controls widget\n */\n private static final HashMap<String, IControlsWidget> pluginControlsRegistry = new HashMap<>();\n\n /**\n * Register of all loaded client plugins\n * Key: \"entryPoint:ID:Version\"\n * Value: plugin instance\n */\n private static final HashMap<String, Plugin> clientPluginsRegistry = new HashMap<>();\n\n /**\n * Register of all loaded server plugins\n * Key: \"entryPoint:ID:Version\"\n * Value: plugin instance\n */\n private static final HashMap<String, Plugin> serverPluginsRegistry = new HashMap<>();\n\n /**\n * Retrieves the list of loaded client plugins controls\n * @return HashMap containing information about loaded client plugin icons, where the key is the plugin ID.\n * and the value is the corresponding ControlsWidget instance.\n */\n public static HashMap<String, IControlsWidget> getPluginControlsRegistry() {\n return pluginControlsRegistry;\n }\n\n /**\n * Retrieves the list of loaded client plugins icons\n * @return HashMap containing information about loaded client plugin icons, where the key is the plugin ID.\n * and the value is the corresponding texture instance.\n */\n public static HashMap<String, Texture> getPluginIconRegistry() {\n return pluginIconRegistry;\n }\n\n /**\n * Retrieves the list of loaded client plugins\n * @return A HashMap containing information about loaded client plugins, where the key is \"entryPoint:ID:Version\"\n * and the value is the corresponding Plugin instance.\n */\n public static HashMap<String, Plugin> getLoadedClientPlugins() {\n return clientPluginsRegistry;\n }\n /**\n * Retrieves the list of loaded server plugins\n * @return A HashMap containing information about loaded server plugins, where the key is \"entryPoint:ID:Version\"\n * and the value is the corresponding Plugin instance.\n */\n public static HashMap<String, Plugin> getLoadedServerPlugins() {\n return serverPluginsRegistry;\n }\n\n /**\n * Initializing the class loader\n */\n public static void initializePluginClassLoader() {\n List<URL> urls = new ArrayList<>();\n pluginClassLoader = new PluginClassLoader(urls.toArray(new URL[0]), PluginManager.class.getClassLoader());\n }\n\n /**\n * Starts the execution of all plugins specified in the past registry.\n * This method iterates through all the plugins in the provided registry and calls their onExecute method.\n * During the execution of each plugin, messages about the start and successful completion are logged.\n * If exceptions occur during plugin execution, the method also logs the corresponding errors.\n * @param pluginsRegistry A registry of plugins, each of which will be executed.\n */\n public static void executePlugins(HashMap<String, Plugin> pluginsRegistry) {\n for (Map.Entry<String, Plugin> entry : pluginsRegistry.entrySet()) {\n Plugin pluginInstance = entry.getValue();\n String pluginId = pluginInstance.getMetadata().getId();\n\n Logger.printLog(String.format(\"Plugin '%s' started trying to execute...\", pluginId));\n\n try {\n pluginInstance.onExecute();\n } catch (Exception e) {\n Logger.printLog(String.format(\"Plugin '%s' failed to execute correctly due to: %s\", pluginId, e));\n }\n\n Logger.printLog(String.format(\"Plugin '%s' has been successfully executed. All internal processes have been successfully launched.\", pluginId));\n }\n }\n\n /**\n * Stops all plugins specified in the past registry.\n * This method iterates through all the plugins in the provided registry and calls their onTerminate method.\n * During the process of stopping each plugin, messages about the start and successful completion are logged.\n * If exceptions occur when stopping the plugin, the method also logs the corresponding errors.\n * @param pluginsRegistry A registry of plugins, each of which will be stopped.\n */\n public static void terminatePlugins(HashMap<String, Plugin> pluginsRegistry) {\n for (Map.Entry<String, Plugin> entry : pluginsRegistry.entrySet()) {\n Plugin pluginInstance = entry.getValue();\n String pluginId = pluginInstance.getMetadata().getId();\n\n Logger.printLog(String.format(\"Plugin '%s' is starting to shut down...\", pluginId));\n\n try {\n pluginInstance.onTerminate();\n } catch (Exception e) {\n Logger.printLog(String.format(\"Plugin '%s' failed to shut down correctly due to: %s\", pluginId, e));\n }\n\n Logger.printLog(String.format(\"Plugin '%s' has been successfully terminated. All internal processes have been completed.\", pluginId));\n }\n }\n\n /**\n * Loading plugins into the game context\n * @param isClient flag indicating whether loading occurs on the client side\n * @throws IOException in cases of input/output problems\n */\n public static void loadPlugins(boolean isClient) throws Exception {\n Logger.printLog(\"Loading plugins into the environment...\");\n\n /*\n Checking the presence of a folder for plugins and validating it\n */\n checkPluginFolder();\n\n /*\n Getting a list of plugins\n */\n ArrayList<File> pluginFiles = getPluginFiles();\n\n /*\n Searching for plugins in a directory\n */\n for (File plugin : pluginFiles) {\n Metadata metadata = Metadata.getInfoFromFile(plugin);\n\n if (metadata == null) {\n Logger.printLog(String.format(\"No metadata found for potential plugin '%s'. Skipping...\", plugin.getName()));\n continue;\n }\n pluginsInfoRegistry.put(plugin, metadata);\n }\n\n /*\n Checking for dependency availability and versions\n */\n dependencyVerification();\n\n /*\n Sorting plugins by load order and Circular dependency check\n */\n ArrayList<File> sortedOrder = sortPluginsByLoadOrder();\n\n /*\n Loading the plugin\n */\n for (File plugin : sortedOrder) {\n Metadata metadata = pluginsInfoRegistry.get(plugin);\n\n List<String> clientEntryPoints = metadata.getEntrypoints().get(\"client\");\n List<String> serverEntryPoints = metadata.getEntrypoints().get(\"server\");\n\n // Checking for empty entry points\n if (!isValidEntryPoints(clientEntryPoints, \"client\", metadata) || !isValidEntryPoints(serverEntryPoints, \"server\", metadata)) {\n continue;\n }\n\n // creating a folder for configs\n File configFolder = metadata.getConfigFolder();\n if (!configFolder.exists()) {\n try {\n configFolder.mkdir();\n } catch (Exception e) {\n e.printStackTrace();\n Logger.printLog(String.format(\"An error occurred while creating the config folder for plugin '%s'\", metadata.getId()));\n }\n }\n\n initializePluginClassLoader();\n\n // Creating a URL for the plugin\n URL pluginUrl = plugin.toURI().toURL();\n PluginClassLoader classLoader = new PluginClassLoader(new URL[]{pluginUrl}, pluginClassLoader);\n\n loadEntryPoints(true, clientEntryPoints, clientPluginsRegistry, metadata, classLoader);\n loadEntryPoints(false, serverEntryPoints, serverPluginsRegistry, metadata, classLoader);\n\n if (isClient) {\n String controlsClassName = metadata.getControlsEntrypoint();\n if (controlsClassName != null && !controlsClassName.isEmpty()) {\n Class<?> controlsClass = Class.forName(controlsClassName, true, classLoader);\n IControlsWidget controlsInstance = (IControlsWidget) controlsClass.getDeclaredConstructor().newInstance();\n\n pluginControlsRegistry.put(metadata.getId(), controlsInstance);\n }\n\n String iconPath = metadata.getIcon();\n URL iconUrl = classLoader.getResource(iconPath);\n\n if (iconUrl != null) {\n try (BufferedInputStream bis = new BufferedInputStream(iconUrl.openStream())) {\n Texture texture = new Texture(iconPath, bis, true);\n pluginIconRegistry.put(metadata.getId(), texture);\n } catch (IOException e) {\n e.printStackTrace();\n throw new Exception(String.format(\"Failed to load plugin '%s' icon texture\", metadata.getId()));\n }\n }\n }\n }\n }\n\n /**\n * Loads plugin input points using the provided class loader.\n * This method is designed to load and initialize plugin classes based on lists of input points.\n * For each input point in the list, the method tries to load the corresponding class, create an instance\n * plugin and add it to the specified plugin registry. In case of errors during class loading process\n * or creating instances, the method throws an exception.\n * @param isClient flag indicating whether client or server entry points are loaded\n * @param entryPoints List of string identifiers of the plugin classes' entry points.\n * @param targetRegistry The registry to which loaded plugin instances should be added.\n * @param metadata Plugin information used to log and associate instances with plugin data.\n * @param classLoader {@link PluginClassLoader} for loading plugin classes.\n * @throws Exception If errors occur while loading classes or creating instances.\n */\n private static void loadEntryPoints(boolean isClient, List<String> entryPoints, HashMap<String, Plugin> targetRegistry, Metadata metadata, PluginClassLoader classLoader) throws Exception {\n String pluginType = isClient ? \"client\" : \"server\";\n\n if (entryPoints == null || entryPoints.isEmpty()) {\n Logger.printLog(String.format(\"There are no %s entry points for plugin '%s'\", pluginType, metadata.getId()));\n return;\n }\n\n int totalEntryPoints = entryPoints.size();\n int currentEntryPointIndex = 0;\n\n for (String entryPoint : entryPoints) {\n currentEntryPointIndex++;\n\n Class<?> pluginClass = Class.forName(entryPoint, true, classLoader);\n Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();\n\n pluginInstance.setMetadata(metadata);\n\n Logger.printLog(String.format(\"Loading %s plugin entry point %d/%d: '%s'(ID: '%s', Version: %s)...\",\n pluginType, currentEntryPointIndex, totalEntryPoints, metadata.getName(), metadata.getId(), metadata.getVersion()));\n\n pluginInstance.onInitialize();\n\n String registryKey = String.format(\"%s:%s:%s\", entryPoint, metadata.getId(), metadata.getVersion());\n\n if (!targetRegistry.containsKey(registryKey)) {\n targetRegistry.put(registryKey, pluginInstance);\n }\n\n EventManager.subscribe(pluginInstance);\n }\n }\n\n /**\n * Checks for the presence of a list of entry points for the plugin.\n * This method is used to check if entry points are defined for a plugin.\n * If the list of entry points is null, the method writes a message about skipping loading the plugin\n * and returns false. An empty list is considered valid.\n *\n * @param entryPoints List of plugin entry points. Can be null.\n * @param type The type of entry points (e.g. \"client\" or \"server\").\n * @param metadata Plugin information used for logging.\n * @return true if the list of entry points is not null, false otherwise.\n */\n private static boolean isValidEntryPoints(List<String> entryPoints, String type, Metadata metadata) {\n if (entryPoints == null) {\n Logger.printLog(String.format(\"Entry points list is null for %s plugin '%s' (ID: '%s', Version: %s). Skipping...\",\n type, metadata.getName(), metadata.getId(), metadata.getVersion()));\n return false;\n }\n return true;\n }\n\n /**\n * Sorts plugins by load order using topological sorting.\n * This method takes into account the dependencies between plugins and arranges them in such a way\n * so that each plugin is loaded after all the plugins it depends on have been loaded.\n *\n * @return List of plugin files, sorted in download order.\n * @throws Exception in case a cyclic dependency or other error is detected.\n */\n private static ArrayList<File> sortPluginsByLoadOrder() throws Exception {\n HashMap<String, List<String>> graph = new HashMap<>();\n HashMap<String, Integer> state = new HashMap<>();\n ArrayList<String> sortedOrder = new ArrayList<>();\n HashMap<String, File> pluginFilesMap = new HashMap<>();\n\n // Initializing the graph and states\n for (Map.Entry<File, Metadata> entry : pluginsInfoRegistry.entrySet()) {\n String pluginId = entry.getValue().getId();\n pluginFilesMap.put(pluginId, entry.getKey());\n state.put(pluginId, 0); // 0 - not visited, 1 - on the stack, 2 - visited\n\n if (!pluginId.equals(\"project-zomboid\") && !pluginId.equals(\"flux-loader\")) {\n graph.putIfAbsent(pluginId, new ArrayList<>());\n\n for (String dependency : entry.getValue().getDependencies().keySet()) {\n if (!dependency.equals(\"project-zomboid\") && !dependency.equals(\"flux-loader\")) {\n graph.putIfAbsent(dependency, new ArrayList<>());\n graph.get(dependency).add(pluginId);\n }\n }\n }\n }\n\n // Topological sorting and checking for cyclic dependencies\n for (String pluginId : graph.keySet()) {\n if (state.get(pluginId) == 0 && topologicalSortDFS(pluginId, graph, state, sortedOrder)) {\n throw new Exception(\"Cyclic dependency detected: \" + pluginId);\n }\n }\n\n // Convert to file list\n ArrayList<File> sortedPluginFiles = new ArrayList<>();\n for (String pluginId : sortedOrder) {\n sortedPluginFiles.add(pluginFilesMap.get(pluginId));\n }\n\n return sortedPluginFiles;\n }\n\n /**\n * Helps perform topological sorting using the DFS algorithm.\n * This method also checks for circular dependencies between plugins.\n *\n * @param current The current node being processed (plugin ID).\n * @param graph Dependency graph, where the key is the plugin identifier and the value is a list of dependencies.\n * @param state A dictionary to keep track of the state of each node during the traversal process.\n * @param sortedOrder A list to store the sorted order of nodes.\n * @return Returns `true` if no circular dependencies are found, `false` otherwise.\n */\n private static boolean topologicalSortDFS(String current, HashMap<String, List<String>> graph, HashMap<String, Integer> state, ArrayList<String> sortedOrder) {\n if (state.get(current) == 1) {\n return true; // Cyclic dependency detected\n }\n if (state.get(current) == 2) {\n return false; // Already visited\n }\n\n state.put(current, 1); // Mark the node as in the stack\n for (String neighbour : graph.getOrDefault(current, new ArrayList<>())) {\n if (topologicalSortDFS(neighbour, graph, state, sortedOrder)) {\n return true;\n }\n }\n state.put(current, 2); // Mark the node as visited\n sortedOrder.add(0, current);\n\n return false;\n }\n\n /**\n * Checking plugins for their dependencies and ensuring that their versions meet the requirements\n * @throws Exception in case the dependent plugin is not found among those found or its version does not meet the requirements\n */\n private static void dependencyVerification() throws Exception {\n for (Map.Entry<File, Metadata> entry : pluginsInfoRegistry.entrySet()) {\n Map<String, String> dependencies = entry.getValue().getDependencies();\n\n for (Map.Entry<String, String> depEntry : dependencies.entrySet()) {\n String depId = depEntry.getKey();\n String depVersion = depEntry.getValue();\n\n switch (depId) {\n case \"project-zomboid\" -> {\n if (!VersionChecker.isVersionCompatible(depVersion, Core.getInstance().getVersion())) {\n throw new Exception(String.format(\"Incompatible game version for plugin id '%s'\", entry.getValue().getId()));\n }\n }\n case \"flux-loader\" -> {\n if (!VersionChecker.isVersionCompatible(depVersion, Constants.FLUX_VERSION)) {\n throw new Exception(String.format(\"Incompatible flux-loader version for plugin id '%s'\", entry.getValue().getId()));\n }\n }\n default -> {\n // Checking the presence of the plugin in the directory\n boolean hasPlugin = false;\n\n for (Map.Entry<File, Metadata> checkEntry : pluginsInfoRegistry.entrySet()) {\n String id = checkEntry.getValue().getId();\n String version = checkEntry.getValue().getVersion();\n\n if (depId.equals(id) && VersionChecker.isVersionCompatible(depVersion, version)){\n hasPlugin = true;\n break;\n }\n }\n\n if (!hasPlugin) {\n throw new Exception(String.format(\"Plugin '%s' does not have a dependent plugin '%s' or its version does not meet the requirements\",\n entry.getValue().getId(),\n depId\n ));\n }\n }\n }\n }\n }\n }\n\n /**\n * Finds all JAR plugins in the specified directory.\n * @return List of JAR files.\n */\n public static ArrayList<File> getPluginFiles() {\n ArrayList<File> jarFiles = new ArrayList<>();\n File folder = getPluginsDirectory();\n\n File[] files = folder.listFiles((File pathname) -> pathname.isFile() && pathname.getName().endsWith(\".jar\"));\n if (files != null) {\n Collections.addAll(jarFiles, files);\n }\n\n return jarFiles;\n }\n\n /**\n * Gets the directory for plugins.\n * This method creates and returns a File object that points to the directory\n * defined in the constant Constants.PLUGINS_FOLDER_NAME. Directory in use\n * for storing plugins. The method does not check whether the directory exists or is\n * it is a valid directory; it simply returns a File object with the corresponding path.\n * The folder is checked and validated when loading plugins.\n * @return A File object representing the plugins folder.\n */\n public static File getPluginsDirectory() {\n return new File(Constants.PLUGINS_FOLDER_NAME);\n }\n\n /**\n * Checking for availability and creating a folder for plugins\n * @throws IOException in cases of input/output problems\n */\n private static void checkPluginFolder() throws IOException {\n Logger.printLog(\"Checking for plugins folder...\");\n\n File folder = getPluginsDirectory();\n\n if (!folder.exists()) {\n if (!folder.mkdir()) {\n Logger.printLog(\"Failed to create folder...\");\n }\n }\n\n if (!folder.isDirectory()) {\n throw new IOException(\"Path is not a directory: \" + folder.getPath());\n }\n }\n}" }, { "identifier": "Logger", "path": "src/main/java/io/xlorey/FluxLoader/utils/Logger.java", "snippet": "@UtilityClass\npublic class Logger {\n /**\n * Outputting a message to the console installer\n * @param text message\n */\n public static void printSystem(String text) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm:ss\");\n String time = LocalDateTime.now().format(formatter);\n System.out.println(String.format(\"<%s> [%s]: %s\", time, Constants.FLUX_NAME, text));\n }\n\n /**\n * Outputting a message to the console/logs\n * @param text message\n */\n public static void printLog(String text) {\n ZLogger fluxLogger = LoggerManager.getLogger(GameServer.bServer ? \"FluxLog-server\" : \"FluxLog-client\");\n fluxLogger.write(text, \"FluxLogger\");\n }\n\n /**\n * Outputting a message to the console/logs\n * @param logger custom logger\n * @param text message\n */\n public static void printLog(ZLogger logger, String text) {\n logger.write(text);\n }\n\n /**\n * Displaying basic information about the project\n */\n public static void printCredits() {\n int width = 50;\n char symbol = '#';\n printFilledLine(symbol, width);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.FLUX_NAME, true);\n printCenteredText(symbol, width, String.format(\"v%s\",Constants.FLUX_VERSION), true);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.GITHUB_LINK, true);\n printCenteredText(symbol, width, Constants.DISCORD_LINK, true);\n printCenteredText(symbol, width, \"\", true);\n printFilledLine(symbol, width);\n\n System.out.println();\n }\n\n /**\n * Display a message in the middle with a given line width\n * @param symbol border symbol\n * @param width line width\n * @param text message\n * @param isBordered use boundaries\n */\n public static void printCenteredText(char symbol, int width, String text, boolean isBordered) {\n String border = isBordered ? String.valueOf(symbol) : \"\";\n int textWidth = text.length() + (isBordered ? 2 : 0);\n int leftPadding = (width - textWidth) / 2;\n int rightPadding = width - leftPadding - textWidth;\n\n String paddedString = String.format(\"%s%\" + leftPadding + \"s%s%\" + rightPadding + \"s%s\", border, \"\", text, \"\", border);\n System.out.println(paddedString);\n }\n\n /**\n * Outputting the completed line to the console\n * @param symbol fill character\n * @param width fill width\n */\n public static void printFilledLine(char symbol, int width) {\n System.out.println(symbol + String.format(\"%\" + (width - 2) + \"s\", \"\").replace(' ', symbol) + symbol);\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Logger; import lombok.Data; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.jar.JarFile; import java.util.zip.ZipEntry;
5,659
package io.xlorey.FluxLoader.plugin; /** * The Metadata class represents plugin data loaded from the metadata.json file. */ @Data public class Metadata { /** * Tool for working with JSON files */ private static final Gson gson = new Gson(); /** * Plugin name */ private String name; /** * Description of the plugin */ private String description; /** * Unique identifier of the plugin */ private String id; /** * Plugin version */ private String version; /** * List of plugin authors */ private List<String> authors; /** * Contact information for the plugin authors */ private List<String> contact; /** * The license under which the plugin is distributed */ private String license; /** * Path to the plugin icon */ private String icon; /** * Plugin entry points for client and server parts */ private Map<String, List<String>> entrypoints; /** * Entry point for rendering controls in the plugin configuration menu */ private String controlsEntrypoint; /** * Plugin dependencies on other projects or libraries */ private Map<String, String> dependencies; /** * Returns a File object representing the configuration directory for this plugin. * The directory path is normalized to prevent problems with various file systems. * @return A File object pointing to the normalized path to the plugin configuration directory. */ public File getConfigFolder() {
package io.xlorey.FluxLoader.plugin; /** * The Metadata class represents plugin data loaded from the metadata.json file. */ @Data public class Metadata { /** * Tool for working with JSON files */ private static final Gson gson = new Gson(); /** * Plugin name */ private String name; /** * Description of the plugin */ private String description; /** * Unique identifier of the plugin */ private String id; /** * Plugin version */ private String version; /** * List of plugin authors */ private List<String> authors; /** * Contact information for the plugin authors */ private List<String> contact; /** * The license under which the plugin is distributed */ private String license; /** * Path to the plugin icon */ private String icon; /** * Plugin entry points for client and server parts */ private Map<String, List<String>> entrypoints; /** * Entry point for rendering controls in the plugin configuration menu */ private String controlsEntrypoint; /** * Plugin dependencies on other projects or libraries */ private Map<String, String> dependencies; /** * Returns a File object representing the configuration directory for this plugin. * The directory path is normalized to prevent problems with various file systems. * @return A File object pointing to the normalized path to the plugin configuration directory. */ public File getConfigFolder() {
File pluginsDirectory = PluginManager.getPluginsDirectory();
0
2023-11-16 09:05:44+00:00
8k
EmonerRobotics/2023Robot
src/main/java/frc/robot/poseestimation/PoseEstimation.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": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends TimedRobot {\n\n //Compressor compressor = new Compressor(0, PneumaticsModuleType.CTREPCM);\n \n private Command m_autonomousCommand;\n private RobotContainer m_robotContainer;\n //private PneumaticSubsystem pneumaticSubsystem;\n\n /**\n * This function is run when the robot is first started up and should be used for any\n * initialization code.\n */\n @Override\n public void robotInit() {\n m_robotContainer = new RobotContainer();\n\n // Instantiate our RobotContainer. This will perform all our button bindings, and put our\n // autonomous chooser on the dashboard.\n }\n\n /**\n * This function is called every 20 ms, no matter the mode. Use this for items like diagnostics\n * that you want ran during disabled, autonomous, teleoperated and test.\n *\n * <p>This runs after the mode specific periodic functions, but before LiveWindow and\n * SmartDashboard integrated updating.\n */\n @Override\n public void robotPeriodic() {\n RobotContainer.poseEstimation.periodic();\n // Runs the Scheduler. This is responsible for polling buttons, adding newly-scheduled\n // commands, running already-scheduled commands, removing finished or interrupted commands,\n // and running subsystem periodic() methods. This must be called from the robot's periodic\n // block in order for anything in the Command-based framework to work.\n CommandScheduler.getInstance().run();\n\n \n }\n\n /** This function is called once each time the robot enters Disabled mode. */\n @Override\n public void disabledInit() {}\n\n @Override\n public void disabledPeriodic() {}\n\n /** This autonomous runs the autonomous command selected by your {@link RobotContainer} class. */\n @Override\n public void autonomousInit() {\n m_autonomousCommand = m_robotContainer.getAutonomousCommand();\n\n if (m_autonomousCommand != null) {\n m_autonomousCommand.schedule();\n }\n\n // schedule the autonomous command (example)*/\n }\n\n /** This function is called periodically during autonomous. */\n @Override\n public void autonomousPeriodic() {\n }\n\n @Override\n public void teleopInit() {\n\n \n/* \n if(m_autonomousCommand != null){\n m_autonomousCommand.cancel();\n }\n // This makes sure that the autonomous stops running when\n // teleop starts running. If you want the autonomous to\n // continue until interrupted by another command, remove\n // this line or comment it out.*/\n }\n\n /** This function is called periodically during operator control. */\n @Override\n public void teleopPeriodic() {\n }\n\n @Override\n public void testInit() {\n // Cancels all running commands at the start of test mode.\n CommandScheduler.getInstance().cancelAll();\n }\n\n /** This function is called periodically during test mode. */\n @Override\n public void testPeriodic() {}\n\n /** This function is called once when the robot is first started up. */\n @Override\n public void simulationInit() {}\n\n /** This function is called periodically whilst in simulation. */\n @Override\n public void simulationPeriodic() {}\n}" }, { "identifier": "RobotContainer", "path": "src/main/java/frc/robot/RobotContainer.java", "snippet": "public class RobotContainer {\n\n //Limelight\n public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem();\n //Intake\n public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem();\n\n //Pneumatic\n public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem();\n\n //Lift\n public static final LiftSubsystem liftSubsystem = new LiftSubsystem();\n\n\n public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab(\"Drive Settings\");\n public static final ShuffleboardTab autoTab = Shuffleboard.getTab(\"Auto\");\n public static final ShuffleboardTab swerveTab = Shuffleboard.getTab(\"Swerve\");\n public static final Joystick joystick1 = new Joystick(0);\n public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController);\n \n public static final Drivetrain drivetrain = new Drivetrain();\n\n public static final PoseEstimation poseEstimation = new PoseEstimation();\n\n public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>();\n\n public static Field2d field = new Field2d();\n public static Field2d nodeSelector = new Field2d();\n\n private final FieldObject2d startingPosition = field.getObject(\"Starting Position\");\n private final FieldObject2d autoBalanceStartingPosition = field.getObject(\"Auto Balance Starting Position\");\n\n private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1);\n private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain);\n \n public static SendableChooser<String> autoSelector;\n\n //private static AutoElevator autoElevator;\n \n\n /** The container for the robot. Contains subsystems, OI devices, and commands. */\n public RobotContainer() {\n\n //autoElevator = new AutoElevator(liftSubsystem, 0);\n //Intake\n intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, \n () -> -joystick2.getRawAxis(IntakeConstants.AngleController)));\n\n //Pneumatic\n //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true));\n\n //Lift\n liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5)));\n\n\n if (!DriverStation.isFMSAttached()) {\n PathPlannerServer.startServer(5811);\n }\n\n drivetrain.setDefaultCommand(driveCommand);\n\n if (autoBalanceStartingPosition.getPoses().isEmpty()) {\n autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d())));\n }\n\n configureBindings();\n\n autoSelector = new SendableChooser<>();\n\n autoSelector.setDefaultOption(\"grid1\", \"grid1\"); // 1 kup en yukari kisa taxi\n //autoSelector.setDefaultOption(\"grid2\", \"grid2\"); // 1 kup en yukari kisa taxi denge\n\n //autoSelector.setDefaultOption(\"grid3\", \"grid3\"); // 1 kup en yukari ortadan denge\n //autoSelector.setDefaultOption(\"grid4\", \"grid4\"); //1 kup en yukari uzun taxi denge\n //autoSelector.setDefaultOption(\"grid5\", \"grid5\"); //1 kup en yukari uzun taxi \n }\n\n \n\n \n\n /**\n * Use this method to define your trigger->command mappings. Triggers can be created via the\n * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary\n * predicate, or via the named factories in {@link\n * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link\n * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller\n * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight\n * joysticks}.\n */\n private void configureBindings() {\n\n //setPoint type is inches\n //limelight sets 111 cm\n new JoystickButton(joystick1, 2).\n whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive));\n\n \n //with Y or 4 button goes to the top\n new JoystickButton(joystick2, IntakeConstants.TopLevelB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT)));\n\n //with B or 2 button goes to the human closes intake and goes to down\n new JoystickButton(joystick2, IntakeConstants.HumanPB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD),\n new PneumaticCommand(pneumaticSubsystem, true, false),\n new WaitCommand(1),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED),\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND)));\n\n //with A or 1 button goes to the down\n new JoystickButton(joystick2, IntakeConstants.GroundLevelB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED),\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND)\n ));\n\n new JoystickButton(joystick2, 3).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF)\n ));\n\n\n\n\n //Pneumatic\n new JoystickButton(joystick2, IntakeConstants.SolenoidOnB).\n onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor\n\n new JoystickButton(joystick2, IntakeConstants.SolenoidOffB).\n onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor\n\n // Pose Estimation\n \n new JoystickButton(joystick1, 6)\n .onTrue(new InstantCommand(driveCommand::resetFieldOrientation));\n new JoystickButton(joystick1, 7)\n .onTrue(new InstantCommand(() -> poseEstimation.resetPose(\n new Pose2d(\n poseEstimation.getEstimatedPose().getTranslation(),\n new Rotation2d())))); \n\n // Driving \n \n new JoystickButton(joystick1, 1)\n .whileTrue(new RunCommand(\n drivetrain::setX,\n drivetrain)); \n\n\n new JoystickButton(joystick1, 3)\n .whileTrue(autoBalanceCommand);\n \n }\n\n public Command getAutonomousCommand() {\n Pose2d startingPose = startingPosition.getPose();\n return new SequentialCommandGroup(\n new InstantCommand(() -> poseEstimation.resetPose(startingPose)),\n new OnePieceCharge(),\n AutoCommand.makeAutoCommand(drivetrain, poseEstimation, autoSelector.getSelected()),\n new InstantCommand(() -> poseEstimation.resetPose(startingPose))\n );\n }\n\n public static Drivetrain getSwerveSubsystem() {\n return drivetrain;\n }\n\n public static LiftSubsystem getLiftSubsystem(){\n return liftSubsystem;\n }\n\n public static IntakeSubsystem getIntakeSubsystem(){\n return intakeSubsystem;\n }\n\n public static PneumaticSubsystem getPneumaticSubsystem(){\n return pneumaticSubsystem;\n }\n}" }, { "identifier": "DriveConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "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}" } ]
import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.interpolation.TimeInterpolatableBuffer; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.networktables.GenericEntry; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.shuffleboard.BuiltInWidgets; import frc.robot.Constants; import frc.robot.Robot; import frc.robot.RobotContainer; import frc.robot.Constants.DriveConstants;
6,709
package frc.robot.poseestimation; public class PoseEstimation { private PhotonVisionBackend photonVision; private SwerveDrivePoseEstimator poseEstimator; private GenericEntry usePhotonVisionEntry = RobotContainer.autoTab.add("Use PhotonVision", true).withWidget(BuiltInWidgets.kToggleButton).getEntry(); private TimeInterpolatableBuffer<Pose2d> poseHistory = TimeInterpolatableBuffer.createBuffer(1.5); private static final double DIFFERENTIATION_TIME = Robot.kDefaultPeriod; public PoseEstimation() { poseEstimator = new SwerveDrivePoseEstimator( DriveConstants.DRIVE_KINEMATICS, RobotContainer.drivetrain.getRotation(), RobotContainer.drivetrain.getModulePositions(), new Pose2d(),
package frc.robot.poseestimation; public class PoseEstimation { private PhotonVisionBackend photonVision; private SwerveDrivePoseEstimator poseEstimator; private GenericEntry usePhotonVisionEntry = RobotContainer.autoTab.add("Use PhotonVision", true).withWidget(BuiltInWidgets.kToggleButton).getEntry(); private TimeInterpolatableBuffer<Pose2d> poseHistory = TimeInterpolatableBuffer.createBuffer(1.5); private static final double DIFFERENTIATION_TIME = Robot.kDefaultPeriod; public PoseEstimation() { poseEstimator = new SwerveDrivePoseEstimator( DriveConstants.DRIVE_KINEMATICS, RobotContainer.drivetrain.getRotation(), RobotContainer.drivetrain.getModulePositions(), new Pose2d(),
Constants.DriveConstants.ODOMETRY_STD_DEV,
0
2023-11-18 14:02:20+00:00
8k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/items/types/end/armor/SuperiorHelmet.java
[ { "identifier": "Rarity", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/Rarity.java", "snippet": "@Getter\npublic enum Rarity {\n COMMON(\"§f\"),\n UNCOMMON(\"§a\"),\n RARE(\"§9\"),\n EPIC(\"§5\"),\n LEGENDARY(\"§6\"),\n MYTHIC(\"§d\"),\n DIVINE(\"§b\"),\n SPECIAL(\"§c\"),\n VERY_SPECIAL(\"§c\");\n\n private final String color;\n\n Rarity(String color) {\n this.color = color;\n }\n\n public Rarity getUpgraded(){\n int current = this.ordinal();\n if (current == Rarity.values().length - 1)\n return Rarity.values()[current];\n\n return Rarity.values()[current + 1];\n }\n}" }, { "identifier": "SkyblockItem", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/SkyblockItem.java", "snippet": "@Getter\npublic abstract class SkyblockItem {\n private final String id;\n private final String displayName;\n private final Material material;\n private final List<String> staticLore;\n private final Map<Stats, Double> stats;\n private final Rarity rarity;\n private final SkyblockItemType itemType;\n\n /**\n * @param id \"diamond_sword\"\n * @param displayName \"Diamond Sword\"\n * @param material Material.DIAMOND_SWORD\n * @param staticLore List.of(\" $7This is a diamond sword\"), Use $ as a placeholder\n * @param stats Map.of(Stats.DAMAGE, 35d)\n * @param baseRarity Rarity.RARE\n * @param itemType SkyblockItemType.SWORD\n */\n public SkyblockItem(String id, String displayName, Material material, @Nullable List<String> staticLore, Map<Stats, Double> stats, Rarity baseRarity, SkyblockItemType itemType) {\n this.id = id;\n this.displayName = displayName;\n this.material = material;\n this.staticLore = staticLore;\n this.stats = new HashMap<>();\n Arrays.stream(Stats.values()).toList().forEach(stat -> this.stats.put(stat, stats.getOrDefault(stat, 0d)));\n this.rarity = baseRarity;\n this.itemType = itemType;\n }\n\n public static SkyblockItem fromItemStack(ItemStack item) {\n String id = PDCHelper.getString(item, \"id\");\n return ItemManager.ITEMS_LIST.getOrDefault(id, null);\n }\n\n public static SkyblockItem get(String id) {\n return ItemManager.ITEMS_LIST.getOrDefault(id, null);\n }\n\n public static List<String> buildStatsLore(Map<Stats, Double> stats, @Nullable Reforge reforge, Rarity rarity) {\n List<String> lore = new ArrayList<>();\n\n Map<Stats, Double> reforgeStats = (reforge != null) ? reforge.getReforgeStats(rarity) : Collections.emptyMap();\n Arrays.stream(Stats.values()).toList().forEach(stat -> {\n double value = stats.getOrDefault(stat, 0.0);\n StringBuilder stringBuilder = new StringBuilder();\n\n double reforgeValue = reforgeStats.getOrDefault(stat, 0.0);\n double combinedValue = value + reforgeValue;\n\n if (combinedValue == 0) return;\n\n\n stringBuilder.append(\"$7\");\n stringBuilder.append(stat.getName());\n stringBuilder.append(\": \");\n stringBuilder.append(stat.getItemBuilderColor());\n stringBuilder.append((combinedValue > 0) ? \"+\" : \"-\");\n String combinedValueStr = String.valueOf(Math.abs(combinedValue)).replace(\".0\", \"\");\n stringBuilder.append(combinedValueStr);\n\n if (reforgeValue != 0) {\n stringBuilder.append(\" $9(\");\n stringBuilder.append((reforgeValue > 0) ? \"+\" : \"-\");\n stringBuilder.append(String.valueOf(Math.abs(reforgeValue)).replace(\".0\", \"\"));\n if (stat.isPercentage()) {\n stringBuilder.append(\"%\");\n }\n stringBuilder.append(\")\");\n }\n\n if (stat.isPercentage() && reforgeValue == 0) {\n stringBuilder.append(\"%\");\n }\n String statLine = PlaceholderFormatter.format(stringBuilder.toString());\n lore.add(statLine);\n });\n return lore;\n }\n\n private static void buildStatsPDC(ItemStack item, Map<Stats, Double> stats) {\n stats.forEach((stat, value) -> PDCHelper.setDouble(item, \"stat.\" + stat.name().toLowerCase(), value));\n }\n public static ItemStack updateItemStack(SkyblockPlayer skyblockPlayer) {\n return updateItemStack(skyblockPlayer, null);\n }\n @SuppressWarnings(\"ReplaceAll\")\n public static ItemStack updateItemStack(SkyblockPlayer skyblockPlayer, @Nullable ItemStack item) {\n ItemStack itemStack = item == null ? skyblockPlayer.getInventoryManager().getItemInHand() : item;\n\n String id = PDCHelper.getString(itemStack, \"id\");\n\n if (id == null) return itemStack;\n\n SkyblockItem skyblockItem = ItemManager.ITEMS_LIST.get(id);\n\n Map<Stats, Double> stats = getStatsFromItemStack(itemStack);\n String reforgeStr = PDCHelper.getOrDefault(itemStack, \"reforge\", \"None\");\n Reforge reforge = ReforgeManager.getReforge(reforgeStr);\n String rarityStr = PDCHelper.getString(itemStack, \"rarity\");\n Rarity rarity = Rarity.valueOf(rarityStr);\n boolean upgraded = skyblockItem.getRarity().getUpgraded().name().equals(rarityStr);\n\n ItemMeta meta = itemStack.getItemMeta();\n assert meta != null;\n meta.setDisplayName(skyblockItem.__getDisplayName(upgraded, reforge));\n\n List<String> lore = new ArrayList<>(\n buildStatsLore(stats, reforge, rarity)\n );\n\n if (skyblockItem instanceof IShortBow) {\n // Shot Cooldown: 0.3s\n String builder = \"$7Shot Cooldown: $a\" +\n DamageCalculator.getShortbowCooldownFmt(skyblockPlayer);\n\n lore.add(PlaceholderFormatter.format(builder));\n }\n\n if (!lore.isEmpty()) lore.add(\"§7\");\n\n lore.addAll(buildEnchantmentsLore(itemStack));\n\n if (!lore.isEmpty()) lore.add(\"§7\");\n\n lore.addAll(skyblockItem.__getStaticLore());\n\n if (skyblockItem.getStaticLore() != null) lore.add(\"§7\");\n\n if (skyblockItem instanceof IShortBow shortBow) {\n lore.add(rarity.getColor() + \"Shortbow: Instantly shoots!\");\n lore.addAll(PlaceholderFormatter.format(shortBow.getShortBowDescription()));\n lore.add(\"§7\");\n }\n\n String ultimateWise = \"ultimate_wise\";\n int reduceBy = EnchantManager.getEnchantment(itemStack, ultimateWise).orElse(0) * 10;\n lore.addAll(skyblockItem.__getAbilityLore(reduceBy));\n\n lore.addAll(ReforgeManager.getReforgeLore(reforge));\n\n if (reforge instanceof IAdvancedReforge) lore.add(\"§7\"); // Will automatically check if the reforge isn't null\n\n lore.addAll(skyblockItem.__getRarityLine(upgraded));\n\n meta.setLore(lore);\n\n itemStack.setItemMeta(meta);\n return itemStack;\n }\n\n public static Map<Stats, Double> getStatsFromItemStack(ItemStack itemStack) {\n Map<Stats, Double> stats = new HashMap<>();\n Arrays.stream(Stats.values()).toList().forEach(stat -> stats.put(stat, PDCHelper.getOrDefault(itemStack, \"stat.\" + stat.name().toLowerCase(), 0d)));\n return stats;\n }\n\n// private static List<String> buildEnchantmentsLore(ItemStack item) {\n// List<String> lore = new ArrayList<>();\n//\n// int amount = 0;\n// StringBuilder line = new StringBuilder();\n//\n// List<Tuple<Enchantment, Integer>> enchantments = EnchantManager.getEnchantments(item);\n//\n// // order by if enchantment is ultimate or not,\n// // ultimate will be first\n// enchantments.sort((o1, o2) -> {\n// if (o1.a() instanceof UltimateEnchantment) return -1;\n// if (o2.a() instanceof UltimateEnchantment) return 1;\n//\n// return 0;\n// });\n//\n// boolean showDescription = enchantments.size() < 3;\n//\n// for (Tuple<Enchantment, Integer> enchantmentTuple : enchantments) {\n// Enchantment enchantment = enchantmentTuple.a();\n//\n// String name = enchantment.getName();\n//\n// if (enchantmentTuple.b() < 1) continue;\n//\n// String formatted = enchantment instanceof UltimateEnchantment ? \"$d$l\" : \"$9\";\n//\n// String toRomanNumeral;\n// try {\n// toRomanNumeral = PlaceholderFormatter.toRomanNumeral(enchantmentTuple.b());\n// } catch (Exception e) {\n// toRomanNumeral = \">\" + PlaceholderFormatter.toRomanNumeral(3999); // 3999 is the max\n// }\n//\n// formatted += name + \" \" + toRomanNumeral;\n//\n// if (amount++ % 2 == 0) { // new line\n// line = new StringBuilder(formatted);\n//\n// } else { // add to previous line\n// line.append(\", \").append(formatted);\n// lore.add(line.toString());\n// line = new StringBuilder();\n// }\n// }\n//\n// if (!line.isEmpty()) {\n// lore.add(line.toString());\n// }\n//\n// return PlaceholderFormatter.format(lore);\n// }\n\n private static List<String> buildEnchantmentsLore(ItemStack item) {\n List<String> lore = new ArrayList<>();\n\n List<Tuple<Enchantment, Integer>> enchantments = EnchantManager.getEnchantments(item);\n\n // Sort by if enchantment is ultimate or not, ultimate will be first\n enchantments.sort((o1, o2) -> {\n if (o1.a() instanceof UltimateEnchantment) return -1;\n if (o2.a() instanceof UltimateEnchantment) return 1;\n return 0;\n });\n\n boolean showDescription = enchantments.size() <= 3;\n StringBuilder line = new StringBuilder();\n\n for (Tuple<Enchantment, Integer> enchantmentTuple : enchantments) {\n Enchantment enchantment = enchantmentTuple.a();\n int level = enchantmentTuple.b();\n\n if (level < 1) continue;\n\n String formatted = (enchantment instanceof UltimateEnchantment ? \"$d$l\" : \"$9\") +\n enchantment.getName() + \" \" + PlaceholderFormatter.toRomanNumeral(level);\n\n if (showDescription) {\n // Add enchantment name and level\n lore.add(formatted);\n // Add description below the enchantment\n List<String> description = enchantment.getDescription(level);\n description.forEach(desc -> lore.add(\"$7\" + desc));\n } else {\n // If not showing descriptions, format enchantments in pairs\n if (line.length() == 0) {\n line = new StringBuilder(formatted);\n } else {\n line.append(\", \").append(formatted);\n lore.add(line.toString());\n line = new StringBuilder(); // Reset the line after adding to lore\n }\n }\n }\n\n // If there's a remaining enchantment that hasn't been added to the lore\n if (line.length() > 0) {\n lore.add(line.toString());\n }\n\n return PlaceholderFormatter.format(lore);\n }\n\n public ItemStack toItemStack() {\n ItemStack item;\n if (this instanceof IHeadHelmet headHelmet && headHelmet.getTexture() != null) {\n item = headHelmet.getHeadItemStack();\n } else {\n item = new ItemStack(this.material);\n }\n\n ItemMeta meta = item.getItemMeta();\n\n assert meta != null;\n\n if (this instanceof IDyedArmor dyedArmor) {\n ((LeatherArmorMeta) meta).setColor(dyedArmor.getColor());\n }\n\n // ------- DISPLAY NAME -------\n meta.setDisplayName(__getDisplayName());\n // ------- DISPLAY NAME -------\n\n // ------- LORE -------\n List<String> lore = buildLore();\n meta.setLore(lore);\n // ------- LORE -------\n\n Arrays.stream(ItemFlag.values()).toList().forEach(meta::addItemFlags);\n meta.spigot().setUnbreakable(true);\n\n item.setItemMeta(meta);\n\n // ------- STATS -------\n buildStatsPDC(item);\n // ------- STATS -------\n\n // ------- PERSISTENT DATA CONTAINER -------\n PDCHelper.set(item, \"id\", this.id);\n// PDCHelper.set(item, \"lore\", singleLineLore.toString()); // Implement later when making Dctr Space Helmet\n PDCHelper.set(item, \"rarity\", this.rarity.name());\n // ------- PERSISTENT DATA CONTAINER -------\n\n return item;\n }\n\n private List<String> buildLore() {\n Map<Stats, Double> stats = this.stats;\n List<String> lore = new ArrayList<>(\n buildStatsLore(stats)\n );\n if (!lore.isEmpty()) lore.add(\"§7\");\n\n lore.addAll(__getStaticLore());\n\n if (this.staticLore != null) lore.add(\"§7\");\n\n if (this instanceof IShortBow shortBow) {\n lore.add(\"§6Shortbow: Instantly shoots!\");\n lore.addAll(PlaceholderFormatter.format(shortBow.getShortBowDescription()));\n lore.add(\"§7\");\n }\n\n lore.addAll(__getAbilityLore());\n\n lore.addAll(__getRarityLine());\n\n return lore;\n }\n\n private List<String> buildStatsLore(Map<Stats, Double> stats) {\n return buildStatsLore(stats, null, this.rarity);\n }\n\n\n /* ------------------ GETTERS & SETTERS ------------------ */\n\n private void buildStatsPDC(ItemStack item) {\n buildStatsPDC(item, this.stats);\n }\n\n private List<String> __getAbilityLore() {\n return __getAbilityLore(0);\n }\n\n private List<String> __getAbilityLore(int reduceBy) {\n List<String> lore = new ArrayList<>();\n if (this instanceof IHasAbility iHasAbility) {\n iHasAbility.getAbilities().forEach(ability -> {\n if (!ability.nameVisible()) return;\n if (!(ability instanceof ITriggerableAbility triggerable)) return;\n String abilityName = ability.getName();\n final String[] triggerType = {\"\"};\n if (triggerable.getTriggerType() == TriggerType.NONE) {\n triggerType[0] = \"\";\n } else {\n triggerType[0] = triggerable.getTriggerType().name().replace(\"_\", \" \");\n }\n String abilityType = ability instanceof FullSetBonus ? \"Full Set Bonus\" : \"Ability\";\n String abilityLine = \"$6\" + abilityType + \": $6\" + abilityName + \" $e$l\" + triggerType[0];\n abilityLine = PlaceholderFormatter.format(abilityLine);\n lore.add(abilityLine);\n lore.addAll(PlaceholderFormatter.format(ability.getDescription()));\n if (ability instanceof IUsageCost cost) {\n cost.getCost().forEach((_stat, _value) -> {\n String costLine = \"$8\";\n costLine += PlaceholderFormatter.capitalize(_stat.name()).replace(\"Intelligence\", \"Mana\");\n costLine += \" Cost:\";\n costLine += \" $3\";\n double newValue = _value * (1 - reduceBy / 100.0);\n newValue = Math.max(0, newValue);\n costLine += PlaceholderFormatter.formatDouble(newValue);\n costLine = PlaceholderFormatter.format(costLine);\n lore.add(costLine);\n });\n }\n lore.add(\"§7\");\n });\n }\n return lore;\n }\n\n /**\n * This is made to be overridden;\n * In dungeon item, you can display stars and things with the name by overriding.\n *\n * @return \"§l§6Diamond Sword\"\n */\n public String __getDisplayName() {\n return __getDisplayName(false, null);\n }\n\n private String __getDisplayName(boolean upgraded, @Nullable Reforge reforge) {\n Rarity rarity = this.rarity; // Mutable copy\n if (upgraded) rarity = rarity.getUpgraded();\n String finalName = rarity.getColor();\n if (reforge != null) finalName += reforge.getName() + \" \";\n finalName += this.displayName;\n return finalName;\n }\n\n private List<String> __getStaticLore() {\n return this.staticLore == null ? new ArrayList<>() : PlaceholderFormatter.format(this.staticLore);\n }\n\n public List<String> __getRarityLine(boolean upgraded) {\n List<String> lore = new ArrayList<>();\n\n Rarity rarity = this.rarity; // Mutable copy\n\n if (upgraded) rarity = rarity.getUpgraded();\n\n String canBeReforged = \"§8This item can be reforged!\";\n if (!upgraded && this.itemType != SkyblockItemType.NONE) lore.add(canBeReforged);\n\n String type = this.itemType == SkyblockItemType.NONE ? \"\" : String.valueOf(this.itemType);\n\n String upgradedObfuscationMark = \"§l§kU\";\n\n String rarityLine = \"\";\n if (upgraded) rarityLine += rarity.getColor() + upgradedObfuscationMark;\n rarityLine += rarity.getColor() + \"§l\" + (upgraded ? \" \" : \"\") + rarity + \" \" + type;\n if (upgraded) rarityLine += \" \" + upgradedObfuscationMark;\n\n lore.add(rarityLine);\n return lore;\n }\n\n private List<String> __getRarityLine() {\n return __getRarityLine(false);\n }\n}" }, { "identifier": "SkyblockItemType", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/SkyblockItemType.java", "snippet": "@Getter\npublic enum SkyblockItemType {\n SWORD,\n BOW,\n HELMET(EquipmentSlot.HEAD),\n CHESTPLATE(EquipmentSlot.CHEST),\n LEGGINGS(EquipmentSlot.LEGS),\n BOOTS(EquipmentSlot.FEET),\n ACCESSORY(null),\n WAND,\n PICKAXE,\n DRILL,\n AXE,\n NONE(null);\n\n @Nullable\n private final EquipmentSlot slot;\n SkyblockItemType(@Nullable EquipmentSlot slot) {\n this.slot = slot;\n }\n SkyblockItemType() {\n this.slot = EquipmentSlot.HAND;\n }\n\n public static List<SkyblockItemType> getHandheld() {\n return Arrays.stream(SkyblockItemType.values()).filter(type -> type.getSlot() == EquipmentSlot.HAND).toList();\n }\n\n public static List<SkyblockItemType> getArmor() {\n return Arrays.stream(SkyblockItemType.values()).filter(type -> type.getSlot() != EquipmentSlot.HAND && type.getSlot() != null).toList();\n }\n}" }, { "identifier": "Ability", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/abilities/Ability.java", "snippet": "public interface Ability {\n String getName();\n default boolean nameVisible(){\n return true;\n }\n List<String> getDescription();\n\n void apply(Event event);\n}" }, { "identifier": "IHasAbility", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/abilities/IHasAbility.java", "snippet": "public interface IHasAbility {\n List<Ability> getAbilities();\n}" }, { "identifier": "IHeadHelmet", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/armor/IHeadHelmet.java", "snippet": "public interface IHeadHelmet {\n String getTexture();\n\n /**\n * @return the head generated through the texture value\n */\n default ItemStack getHeadItemStack() {\n return MozangStuff.getHeadItemStack(getTexture());\n }\n\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}" } ]
import com.sweattypalms.skyblock.core.items.builder.Rarity; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.Ability; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.armor.IHeadHelmet; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import org.bukkit.Material; import java.util.List; import java.util.Map;
5,689
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorHelmet extends SkyblockItem implements IHasAbility, IHeadHelmet { public static final String ID = "superior_dragon_helmet";
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorHelmet extends SkyblockItem implements IHasAbility, IHeadHelmet { public static final String ID = "superior_dragon_helmet";
private static final Map<Stats, Double> stats = Map.of(
6
2023-11-15 15:05:58+00:00
8k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/context/I18nConfiguration.java
[ { "identifier": "CompositeServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java", "snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider;\n\n private List<ServiceMessageSource> serviceMessageSources;\n\n public CompositeServiceMessageSource(ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider) {\n super(\"Composite\");\n this.serviceMessageSourcesProvider = serviceMessageSourcesProvider;\n }\n\n @Override\n public void afterSingletonsInstantiated() {\n List<ServiceMessageSource> serviceMessageSources = initServiceMessageSources();\n setServiceMessageSources(serviceMessageSources);\n\n Locale defaultLocale = initDefaultLocale(serviceMessageSources);\n setDefaultLocale(defaultLocale);\n\n List<Locale> supportedLocales = initSupportedLocales(serviceMessageSources);\n setSupportedLocales(supportedLocales);\n }\n\n public void setServiceMessageSources(List<ServiceMessageSource> serviceMessageSources) {\n this.serviceMessageSources = serviceMessageSources;\n logger.debug(\"Source '{}' sets ServiceMessageSource list: {}\", serviceMessageSources);\n }\n\n protected Locale resolveLocale(Locale locale) {\n\n Locale defaultLocale = getDefaultLocale();\n\n if (locale == null || Objects.equals(defaultLocale, locale)) { // If it's the default Locale\n return defaultLocale;\n }\n\n if (supports(locale)) { // If it matches the supported Locale list\n return locale;\n }\n\n Locale resolvedLocale = null;\n\n List<Locale> derivedLocales = resolveDerivedLocales(locale);\n for (Locale derivedLocale : derivedLocales) {\n if (supports(derivedLocale)) {\n resolvedLocale = derivedLocale;\n break;\n }\n }\n\n return resolvedLocale == null ? defaultLocale : resolvedLocale;\n }\n\n @Override\n protected String getInternalMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object... args) {\n String message = null;\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n message = serviceMessageSource.getMessage(resolvedCode, resolvedLocale, args);\n if (message != null) {\n break;\n }\n }\n\n if (message == null) {\n Locale defaultLocale = getDefaultLocale();\n if (!Objects.equals(defaultLocale, resolvedLocale)) { // Use the default Locale as the bottom pocket\n message = getInternalMessage(resolvedCode, resolvedCode, defaultLocale, defaultLocale, args);\n }\n }\n\n return message;\n }\n\n private Locale initDefaultLocale(List<ServiceMessageSource> serviceMessageSources) {\n return serviceMessageSources.isEmpty() ? super.getDefaultLocale() : serviceMessageSources.get(0).getDefaultLocale();\n }\n\n private List<Locale> initSupportedLocales(List<ServiceMessageSource> serviceMessageSources) {\n List<Locale> allSupportedLocales = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n for (Locale supportedLocale : serviceMessageSource.getSupportedLocales()) {\n allSupportedLocales.add(supportedLocale);\n }\n }\n return unmodifiableList(allSupportedLocales);\n }\n\n private List<ServiceMessageSource> initServiceMessageSources() {\n List<ServiceMessageSource> serviceMessageSources = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSourcesProvider) {\n if (serviceMessageSource != this) {\n serviceMessageSources.add(serviceMessageSource);\n }\n }\n AnnotationAwareOrderComparator.sort(serviceMessageSources);\n logger.debug(\"Initializes the ServiceMessageSource Bean list : {}\", serviceMessageSources);\n return unmodifiableList(serviceMessageSources);\n }\n\n @Override\n public String toString() {\n return \"CompositeServiceMessageSource{\" +\n \"serviceMessageSources=\" + serviceMessageSources +\n '}';\n }\n}" }, { "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": "ServiceMessageSourceFactoryBean", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/beans/factory/ServiceMessageSourceFactoryBean.java", "snippet": "public final class ServiceMessageSourceFactoryBean extends AbstractServiceMessageSource implements FactoryBean<ServiceMessageSource>,\n ApplicationListener<ResourceServiceMessageSourceChangedEvent>, InitializingBean, EnvironmentAware, BeanClassLoaderAware, DisposableBean, Ordered {\n\n private static final Logger logger = LoggerFactory.getLogger(ServiceMessageSourceFactoryBean.class);\n\n private ClassLoader classLoader;\n\n private ConfigurableEnvironment environment;\n\n private List<AbstractServiceMessageSource> serviceMessageSources;\n\n private int order;\n\n public ServiceMessageSourceFactoryBean(String source) {\n super(source);\n }\n\n @Override\n public ServiceMessageSource getObject() throws Exception {\n return this;\n }\n\n @Override\n public Class<?> getObjectType() {\n return ServiceMessageSource.class;\n }\n\n @Override\n public void init() {\n if (this.serviceMessageSources == null) {\n this.serviceMessageSources = loadServiceMessageSources();\n }\n }\n\n @Override\n public void destroy() {\n serviceMessageSources.forEach(ServiceMessageSource::destroy);\n }\n\n @Override\n protected String getInternalMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object... args) {\n String message = null;\n for (AbstractServiceMessageSource serviceMessageSource : serviceMessageSources) {\n message = serviceMessageSource.getMessage(resolvedCode, resolvedLocale, args);\n if (message != null) {\n break;\n }\n }\n if (message == null && logger.isDebugEnabled()) {\n logger.debug(\"Source '{}' Message not found[code : '{}' , resolvedCode : '{}' , locale : '{}' , resolvedLocale : '{}', args : '{}']\",\n source, code, resolvedCode, locale, resolvedLocale, arrayToCommaDelimitedString(args));\n }\n return message;\n }\n\n @Override\n public void afterPropertiesSet() throws Exception {\n init();\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n this.classLoader = classLoader;\n }\n\n @Override\n public void setEnvironment(Environment environment) {\n Assert.isInstanceOf(ConfigurableEnvironment.class, environment, \"The 'environment' parameter must be of type ConfigurableEnvironment\");\n this.environment = (ConfigurableEnvironment) environment;\n }\n\n @Override\n public int getOrder() {\n return order;\n }\n\n public void setOrder(int order) {\n this.order = order;\n }\n\n private List<AbstractServiceMessageSource> loadServiceMessageSources() {\n List<String> factoryNames = SpringFactoriesLoader.loadFactoryNames(AbstractServiceMessageSource.class, classLoader);\n\n Locale defaultLocale = initDefaultLocale(environment);\n List<Locale> supportedLocales = initSupportedLocales(environment);\n\n setDefaultLocale(defaultLocale);\n setSupportedLocales(supportedLocales);\n\n List<AbstractServiceMessageSource> serviceMessageSources = new ArrayList<>(factoryNames.size());\n\n for (String factoryName : factoryNames) {\n Class<?> factoryClass = resolveClassName(factoryName, classLoader);\n Constructor constructor = getConstructorIfAvailable(factoryClass, String.class);\n AbstractServiceMessageSource serviceMessageSource = (AbstractServiceMessageSource) instantiateClass(constructor, source);\n serviceMessageSources.add(serviceMessageSource);\n\n if (serviceMessageSource instanceof EnvironmentAware) {\n ((EnvironmentAware) serviceMessageSource).setEnvironment(environment);\n }\n serviceMessageSource.setDefaultLocale(defaultLocale);\n serviceMessageSource.setSupportedLocales(supportedLocales);\n serviceMessageSource.init();\n }\n\n AnnotationAwareOrderComparator.sort(serviceMessageSources);\n\n return serviceMessageSources;\n }\n\n private Locale initDefaultLocale(ConfigurableEnvironment environment) {\n String propertyName = I18nConstants.DEFAULT_LOCALE_PROPERTY_NAME;\n String localeValue = environment.getProperty(propertyName);\n final Locale locale;\n if (!hasText(localeValue)) {\n locale = super.getDefaultLocale();\n logger.debug(\"Default Locale configuration property [name : '{}'] not found, use default value: '{}'\", propertyName, locale);\n } else {\n locale = StringUtils.parseLocale(localeValue);\n logger.debug(\"Default Locale : '{}' parsed by configuration properties [name : '{}']\", propertyName, locale);\n }\n return locale;\n }\n\n private List<Locale> initSupportedLocales(ConfigurableEnvironment environment) {\n final List<Locale> supportedLocales;\n String propertyName = I18nConstants.SUPPORTED_LOCALES_PROPERTY_NAME;\n List<String> locales = environment.getProperty(propertyName, List.class, emptyList());\n if (locales.isEmpty()) {\n supportedLocales = super.getSupportedLocales();\n logger.debug(\"Support Locale list configuration property [name : '{}'] not found, use default value: {}\", propertyName, supportedLocales);\n } else {\n supportedLocales = locales.stream().map(StringUtils::parseLocale).collect(Collectors.toList());\n logger.debug(\"List of supported Locales parsed by configuration property [name : '{}']: {}\", propertyName, supportedLocales);\n }\n return unmodifiableList(supportedLocales);\n }\n\n @Override\n public void onApplicationEvent(ResourceServiceMessageSourceChangedEvent event) {\n Iterable<String> changedResources = event.getChangedResources();\n logger.debug(\"Receive event change resource: {}\", changedResources);\n for (AbstractServiceMessageSource serviceMessageSource : serviceMessageSources) {\n if (serviceMessageSource instanceof ReloadableResourceServiceMessageSource) {\n ReloadableResourceServiceMessageSource reloadableResourceServiceMessageSource = (ReloadableResourceServiceMessageSource) serviceMessageSource;\n if (reloadableResourceServiceMessageSource.canReload(changedResources)) {\n reloadableResourceServiceMessageSource.reload();\n logger.debug(\"change resource [{}] activate {} reloaded\", changedResources, reloadableResourceServiceMessageSource);\n }\n }\n }\n }\n\n @Override\n public String toString() {\n return \"ServiceMessageSourceFactoryBean{\" +\n \"serviceMessageSources=\" + serviceMessageSources +\n \", order=\" + order +\n '}';\n }\n}" }, { "identifier": "I18nUtils", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/I18nUtils.java", "snippet": "public class I18nUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(I18nUtils.class);\n\n private static volatile ServiceMessageSource serviceMessageSource;\n\n 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 }\n\n public static void setServiceMessageSource(ServiceMessageSource serviceMessageSource) {\n I18nUtils.serviceMessageSource = serviceMessageSource;\n logger.debug(\"serviceMessageSource is initialized\");\n }\n\n public static void destroyServiceMessageSource() {\n serviceMessageSource = null;\n logger.debug(\"serviceMessageSource is destroyed\");\n }\n}" } ]
import io.microsphere.i18n.CompositeServiceMessageSource; import io.microsphere.i18n.ServiceMessageSource; import io.microsphere.i18n.constants.I18nConstants; import io.microsphere.i18n.spring.beans.factory.ServiceMessageSourceFactoryBean; import io.microsphere.i18n.util.I18nUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import java.util.List; import java.util.Locale; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_ORDER; import static io.microsphere.i18n.constants.I18nConstants.DEFAULT_ENABLED; import static io.microsphere.i18n.constants.I18nConstants.ENABLED_PROPERTY_NAME; import static io.microsphere.i18n.constants.I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME;
3,832
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired @Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME) public void init(ServiceMessageSource serviceMessageSource) {
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired @Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME) public void init(ServiceMessageSource serviceMessageSource) {
I18nUtils.setServiceMessageSource(serviceMessageSource);
4
2023-11-17 11:35:59+00:00
8k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerEntity.java
[ { "identifier": "RecipeRegistry", "path": "src/main/java/createbicyclesbitterballen/index/RecipeRegistry.java", "snippet": "public enum RecipeRegistry implements IRecipeTypeInfo {\n\n DEEP_FRYING(DeepFryingRecipe::new);\n\n private final ResourceLocation id = new ResourceLocation(\"create_bic_bit\");\n private final RegistryObject<RecipeSerializer<?>> serializerObject;\n @Nullable\n private final RegistryObject<RecipeType<?>> typeObject;\n private final Supplier<RecipeType<?>> type;\n\n RecipeRegistry(Supplier<RecipeSerializer<?>> serializerSupplier) {\n String name = Lang.asId(name());\n serializerObject = Registers.SERIALIZER_REGISTER.register(name, serializerSupplier);\n typeObject = Registers.TYPE_REGISTER.register(name, () -> RecipeType.simple(id));\n type = typeObject;\n }\n RecipeRegistry(ProcessingRecipeBuilder.ProcessingRecipeFactory<?> processingFactory) {\n this(() -> new ProcessingRecipeSerializer<>(processingFactory));\n }\n public static void register(IEventBus modEventBus) {\n Registers.SERIALIZER_REGISTER.register(modEventBus);\n Registers.TYPE_REGISTER.register(modEventBus);\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public <T extends RecipeSerializer<?>> T getSerializer() {\n\n return (T) serializerObject.get();\n }\n\n @Override\n public <T extends RecipeType<?>> T getType() {\n\n return (T) type.get();\n }\n\n private static class Registers {\n private static final DeferredRegister<RecipeSerializer<?>> SERIALIZER_REGISTER = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, \"create_bic_bit\");\n private static final DeferredRegister<RecipeType<?>> TYPE_REGISTER = DeferredRegister.create(Registries.RECIPE_TYPE, \"create_bic_bit\");\n }\n}" }, { "identifier": "SoundsRegistry", "path": "src/main/java/createbicyclesbitterballen/index/SoundsRegistry.java", "snippet": "public class SoundsRegistry {\n public static final Map<ResourceLocation, SoundEntry> ALL = new HashMap<>();\n\n public static final SoundEntry\n\n\n\n FRYING = create(\"frying\").subtitle(\"Frying noises\")\n\t\t\t.playExisting(SoundEvents.WEATHER_RAIN, .125f, 1.6f)\n\t\t\t.category(SoundSource.BLOCKS)\n\t\t\t.build();\n private static SoundEntryBuilder create(String name) {\n return create(CreateBicBitMod.asResource(name));\n }\n\n public static SoundEntryBuilder create(ResourceLocation id) {\n return new SoundEntryBuilder(id);\n }\n\n public static void prepare() {\n for (SoundEntry entry : ALL.values())\n entry.prepare();\n }\n\n public static void register(RegisterEvent event) {\n event.register(Registries.SOUND_EVENT, helper -> {\n for (SoundEntry entry : ALL.values())\n entry.register(helper);\n });\n }\n\n public static void provideLang(BiConsumer<String, String> consumer) {\n for (SoundEntry entry : ALL.values())\n if (entry.hasSubtitle())\n consumer.accept(entry.getSubtitleKey(), entry.getSubtitle());\n }\n\n public static SoundEntryProvider provider(DataGenerator generator) {\n return new SoundEntryProvider(generator);\n }\n\n public static void playItemPickup(Player player) {\n player.level().playSound(null, player.blockPosition(), SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, .2f,\n 1f + CreateBicBitMod.RANDOM.nextFloat());\n }private static class SoundEntryProvider implements DataProvider {\n\n private PackOutput output;\n\n public SoundEntryProvider(DataGenerator generator) {\n output = generator.getPackOutput();\n }\n\n @Override\n public CompletableFuture<?> run(CachedOutput cache) {\n return generate(output.getOutputFolder(), cache);\n }\n\n @Override\n public String getName() {\n return \"Create Custom Sounds\";\n }\n\n public CompletableFuture<?> generate(Path path, CachedOutput cache) {\n path = path.resolve(\"assets/create_bic_bit\");\n JsonObject json = new JsonObject();\n ALL.entrySet()\n .stream()\n .sorted(Map.Entry.comparingByKey())\n .forEach(entry -> {\n entry.getValue()\n .write(json);\n });\n return DataProvider.saveStable(cache, json, path.resolve(\"sounds.json\"));\n }\n\n }\n\n public record ConfiguredSoundEvent(Supplier<SoundEvent> event, float volume, float pitch) {\n }\n\n public static class SoundEntryBuilder {\n\n protected ResourceLocation id;\n protected String subtitle = \"unregistered\";\n protected SoundSource category = SoundSource.BLOCKS;\n protected List<ConfiguredSoundEvent> wrappedEvents;\n protected List<ResourceLocation> variants;\n protected int attenuationDistance;\n\n public SoundEntryBuilder(ResourceLocation id) {\n wrappedEvents = new ArrayList<>();\n variants = new ArrayList<>();\n this.id = id;\n }\n\n public SoundEntryBuilder subtitle(String subtitle) {\n this.subtitle = subtitle;\n return this;\n }\n\n public SoundEntryBuilder attenuationDistance(int distance) {\n this.attenuationDistance = distance;\n return this;\n }\n\n public SoundEntryBuilder noSubtitle() {\n this.subtitle = null;\n return this;\n }\n\n public SoundEntryBuilder category(SoundSource category) {\n this.category = category;\n return this;\n }\n\n public SoundEntryBuilder addVariant(String name) {\n return addVariant(CreateBicBitMod.asResource(name));\n }\n\n public SoundEntryBuilder addVariant(ResourceLocation id) {\n variants.add(id);\n return this;\n }\n\n public SoundEntryBuilder playExisting(Supplier<SoundEvent> event, float volume, float pitch) {\n wrappedEvents.add(new ConfiguredSoundEvent(event, volume, pitch));\n return this;\n }\n\n public SoundEntryBuilder playExisting(SoundEvent event, float volume, float pitch) {\n return playExisting(() -> event, volume, pitch);\n }\n\n public SoundEntryBuilder playExisting(SoundEvent event) {\n return playExisting(event, 1, 1);\n }\n\n public SoundEntryBuilder playExisting(Holder<SoundEvent> event) {\n return playExisting(event::get, 1, 1);\n }\n\n public SoundEntry build() {\n SoundEntry entry =\n wrappedEvents.isEmpty() ? new CustomSoundEntry(id, variants, subtitle, category, attenuationDistance)\n : new WrappedSoundEntry(id, subtitle, wrappedEvents, category, attenuationDistance);\n ALL.put(entry.getId(), entry);\n return entry;\n }\n\n }\n\n public static abstract class SoundEntry {\n\n protected ResourceLocation id;\n protected String subtitle;\n protected SoundSource category;\n protected int attenuationDistance;\n\n public SoundEntry(ResourceLocation id, String subtitle, SoundSource category, int attenuationDistance) {\n this.id = id;\n this.subtitle = subtitle;\n this.category = category;\n this.attenuationDistance = attenuationDistance;\n }\n\n public abstract void prepare();\n\n public abstract void register(RegisterEvent.RegisterHelper<SoundEvent> registry);\n\n public abstract void write(JsonObject json);\n\n public abstract SoundEvent getMainEvent();\n\n public String getSubtitleKey() {\n return id.getNamespace() + \".subtitle.\" + id.getPath();\n }\n\n public ResourceLocation getId() {\n return id;\n }\n\n public boolean hasSubtitle() {\n return subtitle != null;\n }\n\n public String getSubtitle() {\n return subtitle;\n }\n\n public void playOnServer(Level world, Vec3i pos) {\n playOnServer(world, pos, 1, 1);\n }\n\n public void playOnServer(Level world, Vec3i pos, float volume, float pitch) {\n play(world, null, pos, volume, pitch);\n }\n\n public void play(Level world, Player entity, Vec3i pos) {\n play(world, entity, pos, 1, 1);\n }\n\n public void playFrom(Entity entity) {\n playFrom(entity, 1, 1);\n }\n\n public void playFrom(Entity entity, float volume, float pitch) {\n if (!entity.isSilent())\n play(entity.level(), null, entity.blockPosition(), volume, pitch);\n }\n\n public void play(Level world, Player entity, Vec3i pos, float volume, float pitch) {\n play(world, entity, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, volume, pitch);\n }\n\n public void play(Level world, Player entity, Vec3 pos, float volume, float pitch) {\n play(world, entity, pos.x(), pos.y(), pos.z(), volume, pitch);\n }\n\n public abstract void play(Level world, Player entity, double x, double y, double z, float volume, float pitch);\n\n public void playAt(Level world, Vec3i pos, float volume, float pitch, boolean fade) {\n playAt(world, pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5, volume, pitch, fade);\n }\n\n public void playAt(Level world, Vec3 pos, float volume, float pitch, boolean fade) {\n playAt(world, pos.x(), pos.y(), pos.z(), volume, pitch, fade);\n }\n\n public abstract void playAt(Level world, double x, double y, double z, float volume, float pitch, boolean fade);\n\n }\n\n private static class WrappedSoundEntry extends SoundEntry {\n\n private List<ConfiguredSoundEvent> wrappedEvents;\n private List<CompiledSoundEvent> compiledEvents;\n\n public WrappedSoundEntry(ResourceLocation id, String subtitle,\n List<ConfiguredSoundEvent> wrappedEvents, SoundSource category, int attenuationDistance) {\n super(id, subtitle, category, attenuationDistance);\n this.wrappedEvents = wrappedEvents;\n compiledEvents = new ArrayList<>();\n }\n\n @Override\n public void prepare() {\n for (int i = 0; i < wrappedEvents.size(); i++) {\n ConfiguredSoundEvent wrapped = wrappedEvents.get(i);\n ResourceLocation location = getIdOf(i);\n RegistryObject<SoundEvent> event = RegistryObject.create(location, ForgeRegistries.SOUND_EVENTS);\n compiledEvents.add(new CompiledSoundEvent(event, wrapped.volume(), wrapped.pitch()));\n }\n }\n\n @Override\n public void register(RegisterEvent.RegisterHelper<SoundEvent> helper) {\n for (CompiledSoundEvent compiledEvent : compiledEvents) {\n ResourceLocation location = compiledEvent.event().getId();\n helper.register(location, SoundEvent.createVariableRangeEvent(location));\n }\n }\n\n @Override\n public SoundEvent getMainEvent() {\n return compiledEvents.get(0)\n .event().get();\n }\n\n protected ResourceLocation getIdOf(int i) {\n return new ResourceLocation(id.getNamespace(), i == 0 ? id.getPath() : id.getPath() + \"_compounded_\" + i);\n }\n\n @Override\n public void write(JsonObject json) {\n for (int i = 0; i < wrappedEvents.size(); i++) {\n ConfiguredSoundEvent event = wrappedEvents.get(i);\n JsonObject entry = new JsonObject();\n JsonArray list = new JsonArray();\n JsonObject s = new JsonObject();\n s.addProperty(\"name\", event.event()\n .get()\n .getLocation()\n .toString());\n s.addProperty(\"type\", \"event\");\n if (attenuationDistance != 0)\n s.addProperty(\"attenuation_distance\", attenuationDistance);\n list.add(s);\n entry.add(\"sounds\", list);\n if (i == 0 && hasSubtitle())\n entry.addProperty(\"subtitle\", getSubtitleKey());\n json.add(getIdOf(i).getPath(), entry);\n }\n }\n\n @Override\n public void play(Level world, Player entity, double x, double y, double z, float volume, float pitch) {\n for (CompiledSoundEvent event : compiledEvents) {\n world.playSound(entity, x, y, z, event.event().get(), category, event.volume() * volume,\n event.pitch() * pitch);\n }\n }\n\n @Override\n public void playAt(Level world, double x, double y, double z, float volume, float pitch, boolean fade) {\n for (CompiledSoundEvent event : compiledEvents) {\n world.playLocalSound(x, y, z, event.event().get(), category, event.volume() * volume,\n event.pitch() * pitch, fade);\n }\n }\n\n private record CompiledSoundEvent(RegistryObject<SoundEvent> event, float volume, float pitch) {\n }\n\n }\n\n private static class CustomSoundEntry extends SoundEntry {\n\n protected List<ResourceLocation> variants;\n protected RegistryObject<SoundEvent> event;\n\n public CustomSoundEntry(ResourceLocation id, List<ResourceLocation> variants, String subtitle,\n SoundSource category, int attenuationDistance) {\n super(id, subtitle, category, attenuationDistance);\n this.variants = variants;\n }\n\n @Override\n public void prepare() {\n event = RegistryObject.create(id, ForgeRegistries.SOUND_EVENTS);\n }\n\n @Override\n public void register(RegisterEvent.RegisterHelper<SoundEvent> helper) {\n ResourceLocation location = event.getId();\n helper.register(location, SoundEvent.createVariableRangeEvent(location));\n }\n\n @Override\n public SoundEvent getMainEvent() {\n return event.get();\n }\n\n @Override\n public void write(JsonObject json) {\n JsonObject entry = new JsonObject();\n JsonArray list = new JsonArray();\n\n JsonObject s = new JsonObject();\n s.addProperty(\"name\", id.toString());\n s.addProperty(\"type\", \"file\");\n if (attenuationDistance != 0)\n s.addProperty(\"attenuation_distance\", attenuationDistance);\n list.add(s);\n\n for (ResourceLocation variant : variants) {\n s = new JsonObject();\n s.addProperty(\"name\", variant.toString());\n s.addProperty(\"type\", \"file\");\n if (attenuationDistance != 0)\n s.addProperty(\"attenuation_distance\", attenuationDistance);\n list.add(s);\n }\n\n entry.add(\"sounds\", list);\n if (hasSubtitle())\n entry.addProperty(\"subtitle\", getSubtitleKey());\n json.add(id.getPath(), entry);\n }\n\n @Override\n public void play(Level world, Player entity, double x, double y, double z, float volume, float pitch) {\n world.playSound(entity, x, y, z, event.get(), category, volume, pitch);\n }\n\n @Override\n public void playAt(Level world, double x, double y, double z, float volume, float pitch, boolean fade) {\n world.playLocalSound(x, y, z, event.get(), category, volume, pitch, fade);\n }\n\n }\n\n}" } ]
import java.util.List; import java.util.Optional; import com.simibubi.create.content.fluids.FluidFX; import com.simibubi.create.content.processing.basin.BasinBlockEntity; import com.simibubi.create.content.processing.basin.BasinOperatingBlockEntity; import com.simibubi.create.content.processing.recipe.ProcessingRecipe; import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour; import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour.TankSegment; import com.simibubi.create.foundation.utility.AnimationTickHolder; import com.simibubi.create.foundation.utility.Couple; import com.simibubi.create.foundation.utility.VecHelper; import createbicyclesbitterballen.index.RecipeRegistry; import createbicyclesbitterballen.index.SoundsRegistry; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction.Axis; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.nbt.CompoundTag; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.world.Container; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler;
5,412
|| !tanks.getSecond() .isEmpty()) level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP, SoundSource.BLOCKS, .75f, 1.6f); } } else { processingTicks--; if (processingTicks == 0) { runningTicks++; processingTicks = -1; applyBasinRecipe(); sendData(); } } } if (runningTicks != 20) runningTicks++; } } public void renderParticles() { Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent() || level == null) return; for (SmartFluidTankBehaviour behaviour : basin.get() .getTanks()) { if (behaviour == null) continue; for (TankSegment tankSegment : behaviour.getTanks()) { if (tankSegment.isEmpty(0)) continue; spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid())); } } } protected void spillParticle(ParticleOptions data) { float angle = level.random.nextFloat() * 360; Vec3 offset = new Vec3(0, 0, 0.25f); offset = VecHelper.rotate(offset, angle, Axis.Y); Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y) .add(0, .25f, 0); Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition)); target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f); level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z); } @Override protected List<Recipe<?>> getMatchingRecipes() { List<Recipe<?>> matchingRecipes = super.getMatchingRecipes(); Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent()) return matchingRecipes; BasinBlockEntity basinBlockEntity = basin.get(); if (basin.isEmpty()) return matchingRecipes; IItemHandler availableItems = basinBlockEntity .getCapability(ForgeCapabilities.ITEM_HANDLER) .orElse(null); if (availableItems == null) return matchingRecipes; return matchingRecipes; } @Override protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) { return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType(); } @Override public void startProcessingBasin() { if (running && runningTicks <= 20) return; super.startProcessingBasin(); running = true; runningTicks = 0; } @Override public boolean continueWithPreviousRecipe() { runningTicks = 20; return true; } @Override protected void onBasinRemoved() { if (!running) return; runningTicks = 40; running = false; } @Override protected Object getRecipeCacheKey() { return DeepFryingRecipesKey; } @Override protected boolean isRunning() { return running; } @Override @OnlyIn(Dist.CLIENT) public void tickAudio() { super.tickAudio(); boolean slow = Math.abs(getSpeed()) < 65; if (slow && AnimationTickHolder.getTicks() % 2 == 0) return; if (runningTicks == 20)
package createbicyclesbitterballen.block.mechanicalfryer; public class MechanicalFryerEntity extends BasinOperatingBlockEntity { private static final Object DeepFryingRecipesKey = new Object(); public int runningTicks; public int processingTicks; public boolean running; public MechanicalFryerEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); } public float getRenderedHeadOffset(float partialTicks) { int localTick; float offset = 0; if (running) { if (runningTicks < 20) { localTick = runningTicks; float num = (localTick + partialTicks) / 20f; num = ((2 - Mth.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } else if (runningTicks <= 20) { offset = 1; } else { localTick = 40 - runningTicks; float num = (localTick - partialTicks) / 20f; num = ((2 - Mth.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } } return offset + 7 / 16f; } @Override protected AABB createRenderBoundingBox() { return new AABB(worldPosition).expandTowards(0, -1.5, 0); } @Override protected void read(CompoundTag compound, boolean clientPacket) { running = compound.getBoolean("Running"); runningTicks = compound.getInt("Ticks"); super.read(compound, clientPacket); if (clientPacket && hasLevel()) getBasin().ifPresent(bte -> bte.setAreFluidsMoving(running && runningTicks <= 20)); } @Override public void write(CompoundTag compound, boolean clientPacket) { compound.putBoolean("Running", running); compound.putInt("Ticks", runningTicks); super.write(compound, clientPacket); } @Override public void tick() { super.tick(); if (runningTicks >= 40) { running = false; runningTicks = 0; basinChecker.scheduleUpdate(); return; } float speed = Math.abs(getSpeed()); if (running && level != null) { if (level.isClientSide && runningTicks == 20) renderParticles(); if ((!level.isClientSide || isVirtual()) && runningTicks == 20) { if (processingTicks < 0) { float recipeSpeed = 1; if (currentRecipe instanceof ProcessingRecipe) { int t = ((ProcessingRecipe<?>) currentRecipe).getProcessingDuration(); if (t != 0) recipeSpeed = t / 100f; } processingTicks = Mth.clamp((Mth.log2((int) (512 / speed))) * Mth.ceil(recipeSpeed * 15) + 1, 1, 512); Optional<BasinBlockEntity> basin = getBasin(); if (basin.isPresent()) { Couple<SmartFluidTankBehaviour> tanks = basin.get() .getTanks(); if (!tanks.getFirst() .isEmpty() || !tanks.getSecond() .isEmpty()) level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP, SoundSource.BLOCKS, .75f, 1.6f); } } else { processingTicks--; if (processingTicks == 0) { runningTicks++; processingTicks = -1; applyBasinRecipe(); sendData(); } } } if (runningTicks != 20) runningTicks++; } } public void renderParticles() { Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent() || level == null) return; for (SmartFluidTankBehaviour behaviour : basin.get() .getTanks()) { if (behaviour == null) continue; for (TankSegment tankSegment : behaviour.getTanks()) { if (tankSegment.isEmpty(0)) continue; spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid())); } } } protected void spillParticle(ParticleOptions data) { float angle = level.random.nextFloat() * 360; Vec3 offset = new Vec3(0, 0, 0.25f); offset = VecHelper.rotate(offset, angle, Axis.Y); Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y) .add(0, .25f, 0); Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition)); target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f); level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z); } @Override protected List<Recipe<?>> getMatchingRecipes() { List<Recipe<?>> matchingRecipes = super.getMatchingRecipes(); Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent()) return matchingRecipes; BasinBlockEntity basinBlockEntity = basin.get(); if (basin.isEmpty()) return matchingRecipes; IItemHandler availableItems = basinBlockEntity .getCapability(ForgeCapabilities.ITEM_HANDLER) .orElse(null); if (availableItems == null) return matchingRecipes; return matchingRecipes; } @Override protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) { return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType(); } @Override public void startProcessingBasin() { if (running && runningTicks <= 20) return; super.startProcessingBasin(); running = true; runningTicks = 0; } @Override public boolean continueWithPreviousRecipe() { runningTicks = 20; return true; } @Override protected void onBasinRemoved() { if (!running) return; runningTicks = 40; running = false; } @Override protected Object getRecipeCacheKey() { return DeepFryingRecipesKey; } @Override protected boolean isRunning() { return running; } @Override @OnlyIn(Dist.CLIENT) public void tickAudio() { super.tickAudio(); boolean slow = Math.abs(getSpeed()) < 65; if (slow && AnimationTickHolder.getTicks() % 2 == 0) return; if (runningTicks == 20)
SoundsRegistry.FRYING.playAt(level, worldPosition, .75f, 1, true);
1
2023-11-12 13:05:18+00:00
8k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java
[ { "identifier": "TableCellHaveNotIndexException", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/exceptions/TableCellHaveNotIndexException.java", "snippet": "public class TableCellHaveNotIndexException extends RuntimeException {\n public TableCellHaveNotIndexException() {\n super();\n }\n public TableCellHaveNotIndexException(String s) {\n super(s);\n }\n}" }, { "identifier": "Border", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Border.java", "snippet": "public class Border {\n public RectF size;\n public ColorRect color;\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n */\n public Border(){\n size = new RectF(0,0,0,0);\n color = new ColorRect(Color.WHITE,Color.WHITE,Color.WHITE,Color.WHITE);\n }\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(float size,@ColorInt int color){\n this.size = new RectF(\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density);\n this.color = new ColorRect(color, color, color, color);\n }\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(RectF size, ColorRect color){\n size.left *= Zoomable.getInstance().density;\n size.top *= Zoomable.getInstance().density;\n size.right *= Zoomable.getInstance().density;\n size.bottom *= Zoomable.getInstance().density;\n this.size = size;\n this.color = color;\n }\n\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(RectF size,@ColorInt int color){\n size.left *= Zoomable.getInstance().density;\n size.top *= Zoomable.getInstance().density;\n size.right *= Zoomable.getInstance().density;\n size.bottom *= Zoomable.getInstance().density;\n this.size = size;\n this.color = new ColorRect(color, color, color, color);\n }\n\n public void copy(@Nullable Border b){\n if(b != null){\n size = b.size;\n color = b.color;\n }\n }\n\n public Border setLeft(float size,@ColorInt int color){\n this.size.left = size * Zoomable.getInstance().density;\n this.color.left = color;\n return this;\n }\n public Border setTop(float size,@ColorInt int color){\n this.size.top = size * Zoomable.getInstance().density;\n this.color.top = color;\n return this;\n }\n public Border setRight(float size,@ColorInt int color){\n this.size.right = size * Zoomable.getInstance().density;\n this.color.right = color;\n return this;\n }\n public Border setBottom(float size,@ColorInt int color){\n this.size.bottom = size * Zoomable.getInstance().density;\n this.color.bottom = color;\n return this;\n }\n\n public void draw(Canvas canvas, float measureX, float measureY, int measureWidth, int measureHeight){\n Paint paint = new Paint();\n paint.setFlags(TextPaint.FILTER_BITMAP_FLAG | TextPaint.LINEAR_TEXT_FLAG | TextPaint.ANTI_ALIAS_FLAG);\n float gap;\n if(size.left > 0) {\n gap = size.left*0.5f;\n paint.setStrokeWidth(size.left);\n paint.setColor(color.left);\n canvas.drawLine(measureX+gap, measureY,\n measureX+gap, measureY+measureHeight, paint);\n }\n if(size.top > 0) {\n gap = size.top*0.5f;\n paint.setStrokeWidth(size.top);\n paint.setColor(color.top);\n canvas.drawLine(measureX, measureY+gap,\n measureX+measureWidth, measureY+gap, paint);\n }\n if(size.right > 0) {\n gap = size.right*0.5f;\n paint.setStrokeWidth(size.right);\n paint.setColor(color.right);\n canvas.drawLine(measureX+measureWidth-gap, measureY,\n measureX+measureWidth-gap, measureY+measureHeight, paint);\n }\n if(size.bottom > 0) {\n gap = size.bottom*0.5f;\n paint.setStrokeWidth(size.bottom);\n paint.setColor(color.bottom);\n canvas.drawLine(measureX, measureY+measureHeight-gap,\n measureX+measureWidth, measureY+measureHeight-gap, paint);\n }\n }\n\n @Override\n public String toString() {\n return size.toString() + \", \" + color.toString();\n }\n\n /**\n * 왼쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the left border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderLeft(float size,@ColorInt int color){\n return new Border(new RectF(size * Zoomable.getInstance().density,0,0, 0), new ColorRect(color, Color.WHITE, Color.WHITE, Color.WHITE));\n }\n /**\n * 위쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the top border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderTop(float size,@ColorInt int color){\n return new Border(new RectF(0,size * Zoomable.getInstance().density,0, 0), new ColorRect(Color.WHITE, color, Color.WHITE, Color.WHITE));\n }\n /**\n * 오른쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the right border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderRight(float size,@ColorInt int color){\n return new Border(new RectF(0,0,size * Zoomable.getInstance().density, 0), new ColorRect(Color.WHITE, Color.WHITE, color, Color.WHITE));\n }\n /**\n * 아래쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the bottom border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderBottom(float size,@ColorInt int color){\n return new Border(new RectF(0,0,0, size * Zoomable.getInstance().density), new ColorRect(Color.WHITE, Color.WHITE, Color.WHITE, color));\n }\n}" }, { "identifier": "Action", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/listener/Action.java", "snippet": "public interface Action<T, R> {\n R invoke(T t);\n}" }, { "identifier": "Zoomable", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Zoomable.java", "snippet": "public class Zoomable {\n private static Zoomable instance = null;\n\n public static Zoomable getInstance(){\n if(instance == null){\n instance = new Zoomable();\n }\n return instance;\n }\n\n /**\n * PDF 내에 들어가는 요소를 전부 이미지로 변환 후 집어 넣기 때문에<br>\n * density 를 통해 전체적으로 이미지 파일 크기 자체를 키워서<br>\n * 디바이스에 구애 받지 않고 dpi 를 늘리는 효과를 만든다. <br>\n * Since all elements in the PDF are converted into images and inserted,<br>\n * Through density, the image file size itself is increased as a whole,<br>\n * creating the effect of increasing dpi regardless of device.\n */\n public float density = 1.0f;\n\n private RectF contentRect = null;\n\n public void setContentRect(RectF contentRect){\n this.contentRect = contentRect;\n }\n\n public RectF getContentRect() {\n return contentRect;\n }\n public float getZoomWidth() {\n return contentRect.width() * density;\n }\n public float getZoomHeight() {\n return contentRect.height() * density;\n }\n}" } ]
import android.graphics.Canvas; import android.graphics.Rect; import com.hangyeolee.androidpdfwriter.exceptions.TableCellHaveNotIndexException; import com.hangyeolee.androidpdfwriter.utils.Border; import java.util.ArrayList; import com.hangyeolee.androidpdfwriter.listener.Action; import com.hangyeolee.androidpdfwriter.utils.Zoomable;
4,682
return this; } public PDFGridLayout setChildMargin(int left, int top, int right, int bottom) { this.childMargin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } public PDFGridLayout setChildMargin(int all) { return setChildMargin(all, all, all, all); } public PDFGridLayout setChildMargin(int horizontal, int vertical) { return setChildMargin(horizontal, vertical, horizontal, vertical); } @Override @Deprecated public PDFGridLayout addChild(PDFComponent component) throws TableCellHaveNotIndexException { throw new TableCellHaveNotIndexException(); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, PDFComponent component) throws ArrayIndexOutOfBoundsException{ return addChild(x, y, 1, 1, component); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, int rowSpan, int columnSpan, PDFComponent component) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; component.setParent(this); if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { child.set(index, component); } else { throw new ArrayIndexOutOfBoundsException(); } return setChildSpan(x,y,rowSpan,columnSpan); } @Override public PDFGridLayout setSize(Float width, Float height) { super.setSize(width, height); return this; } @Override public PDFGridLayout setBackgroundColor(int color) { super.setBackgroundColor(color); return this; } @Override public PDFGridLayout setMargin(Rect margin) { super.setMargin(margin); return this; } @Override public PDFGridLayout setMargin(int left, int top, int right, int bottom) { super.setMargin(left, top, right, bottom); return this; } @Override public PDFGridLayout setMargin(int all) { super.setMargin(all); return this; } @Override public PDFGridLayout setMargin(int horizontal, int vertical) { super.setMargin(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(int all) { super.setPadding(all); return this; } @Override public PDFGridLayout setPadding(int horizontal, int vertical) { super.setPadding(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(Rect padding) { super.setPadding(padding); return this; } @Override public PDFGridLayout setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); return this; } @Override
package com.hangyeolee.androidpdfwriter.components; public class PDFGridLayout extends PDFLayout{ int rows, columns; ArrayList<Integer> span; final int[] gaps; final Rect childMargin = new Rect(0,0,0,0); public PDFGridLayout(int rows, int columns){ super(); if(rows < 1) rows = 1; if(columns < 1) columns = 1; this.rows = rows; this.columns = columns; int length = rows*columns; child = new ArrayList<>(length); span = new ArrayList<>(length); gaps = new int[rows]; for(int i = 0; i < length; i++){ child.add(PDFEmpty.build().setParent(this)); span.add(i); } } @Override public void measure(float x, float y) { super.measure(x, y); int i, j; float totalHeight = 0; int gapWidth = 0; int index; int zero_count = 0; int lastWidth = Math.round (measureWidth - border.size.left - padding.left - border.size.right - padding.right); // 가로 길이 자동 조절 for(i = 0; i < gaps.length ; i++) { if(gaps[i] > lastWidth) gaps[i] = 0; lastWidth -= childMargin.left + childMargin.right; if(lastWidth < 0) gaps[i] = 0; if(gaps[i] == 0){ zero_count += 1; }else{ lastWidth -= gaps[i]; } } for(i = 0; i < gaps.length; i++) { if(gaps[i] == 0){ gaps[i] = lastWidth/zero_count; lastWidth -= lastWidth/zero_count; zero_count -= 1; } } int[] maxHeights = new int[columns]; int columnSpanCount; // Cell 당 높이 계산 for(i = 0; i < columns; i++){ int totalWidth = 0; for(j = 0; j < rows; j++){ index = i*rows + j; gapWidth = gaps[j]; if(index == span.get(index)) { columnSpanCount = 1; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(i*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } // 세로 span 개수 for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ columnSpanCount++; }else break; } child.get(index).width = gapWidth; // 자식 컴포넌트의 Margin 무시 child.get(i).margin.set(childMargin); if(columnSpanCount == 1) { child.get(index).measure(totalWidth, totalHeight); if (maxHeights[i] < child.get(index).measureHeight) { maxHeights[i] = child.get(index).measureHeight; } } totalWidth += gapWidth + childMargin.left + childMargin.right; }else{ index = span.get(index); int origin_x = index % rows; if(origin_x == j) { int origin_y = index / rows; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(origin_y*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } totalWidth += gapWidth + childMargin.left + childMargin.right; } } } totalHeight += maxHeights[i] + childMargin.top + childMargin.bottom; measureHeight = Math.round(totalHeight); } totalHeight = 0; int maxHeight; int maxSpanHeight = 0; float lastTotalHeight = 0; boolean repeatIfor = false; for(i = 0; i < columns; i++) { int totalWidth = 0; maxSpanHeight = 0; // 세로 Span 존재 탐지 for(j = 0; j < rows; j++){ index = i*rows + j; maxHeight = maxHeights[i]; for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ maxHeight += maxHeights[yy] + childMargin.top + childMargin.bottom; }else break; } if(maxHeight > maxSpanHeight) maxSpanHeight = maxHeight; } // 페이지 넘기는 Grid Cell 이 있는 경우 다음 페이지로 float zoomHeight = Zoomable.getInstance().getZoomHeight(); float lastHeight = totalHeight + measureY; while(lastHeight > zoomHeight){ lastHeight -= zoomHeight; } lastTotalHeight = totalHeight; if(lastHeight < zoomHeight && zoomHeight < lastHeight + maxSpanHeight + childMargin.top + childMargin.bottom){ float gap = zoomHeight - lastHeight; if(i == 0) { margin.top += Math.round(gap); updateHeight(gap); int d = 0; if (parent != null) d += parent.measureY + parent.border.size.top + parent.padding.top; measureY = relativeY + margin.top + d; } else totalHeight += gap; } for(j = 0; j < rows; j++){ index = i*rows + j; gapWidth = gaps[j]; if(index == span.get(index)) { columnSpanCount = 1; //Span 계산 maxHeight = maxHeights[i]; for(int xx = j+1; xx < rows; xx++){ if(index == span.get(i*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ columnSpanCount++; maxHeight += maxHeights[yy] + childMargin.top + childMargin.bottom; }else break; } child.get(index).width = gapWidth; //measure child.get(index).measure(totalWidth, totalHeight); //Span 이후 span 된 컴포넌트의 높이가 주어진 높이보다 클 경우 if(child.get(index).height > maxHeight){ int gapHeight = child.get(index).height - maxHeight; zero_count = columnSpanCount; for(int yy = i; yy < i+columnSpanCount; yy++) { maxHeights[yy] += gapHeight / zero_count; gapHeight -= gapHeight / zero_count; zero_count -= 1; } repeatIfor = true; break; } child.get(index).force(gapWidth, maxHeight, childMargin); totalWidth += gapWidth + childMargin.left + childMargin.right; }else{ index = span.get(index); int origin_x = index % rows; if(origin_x == j) { int origin_y = index / rows; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(origin_y*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } totalWidth += gapWidth + childMargin.left + childMargin.right; } } } if(repeatIfor){ i--; totalHeight = lastTotalHeight; repeatIfor = false; continue; } totalHeight += maxHeights[i] + childMargin.top + childMargin.bottom; } measureHeight = Math.round(totalHeight + border.size.top + border.size.bottom + padding.top + padding.bottom); } @Override public void draw(Canvas canvas) { super.draw(canvas); for(int i = 0; i < child.size(); i++) { // Span에 의해 늘어난 만큼 관련 없는 부분은 draw 하지 않는 다. if(i == span.get(i)) { child.get(i).draw(canvas); } } } /** * 자식 컴포넌트가 차지하는 가로 길이 설정 * @param xIndex 설정할 Row * @param width 가로 길이 * @return 자기자신 */ public PDFGridLayout setChildWidth(int xIndex, int width){ if(width < 0) width = 0; if(xIndex < gaps.length) gaps[xIndex] = Math.round(width * Zoomable.getInstance().density); return this; } public PDFGridLayout setChildSpan(int x, int y, int rowSpan, int columnSpan) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { int spanIdx; for(int i = 0; i < columnSpan; i++){ for(int j = 0; j < rowSpan; j++){ spanIdx = (y+i)*rows + x+j; span.set(spanIdx, index); } } } else { throw new ArrayIndexOutOfBoundsException("Span Size is Out of Bounds"); } return this; } public PDFGridLayout setChildMargin(Rect margin) { this.childMargin.set(new Rect( Math.round(margin.left * Zoomable.getInstance().density), Math.round(margin.top * Zoomable.getInstance().density), Math.round(margin.right * Zoomable.getInstance().density), Math.round(margin.bottom * Zoomable.getInstance().density)) ); return this; } public PDFGridLayout setChildMargin(int left, int top, int right, int bottom) { this.childMargin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } public PDFGridLayout setChildMargin(int all) { return setChildMargin(all, all, all, all); } public PDFGridLayout setChildMargin(int horizontal, int vertical) { return setChildMargin(horizontal, vertical, horizontal, vertical); } @Override @Deprecated public PDFGridLayout addChild(PDFComponent component) throws TableCellHaveNotIndexException { throw new TableCellHaveNotIndexException(); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, PDFComponent component) throws ArrayIndexOutOfBoundsException{ return addChild(x, y, 1, 1, component); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, int rowSpan, int columnSpan, PDFComponent component) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; component.setParent(this); if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { child.set(index, component); } else { throw new ArrayIndexOutOfBoundsException(); } return setChildSpan(x,y,rowSpan,columnSpan); } @Override public PDFGridLayout setSize(Float width, Float height) { super.setSize(width, height); return this; } @Override public PDFGridLayout setBackgroundColor(int color) { super.setBackgroundColor(color); return this; } @Override public PDFGridLayout setMargin(Rect margin) { super.setMargin(margin); return this; } @Override public PDFGridLayout setMargin(int left, int top, int right, int bottom) { super.setMargin(left, top, right, bottom); return this; } @Override public PDFGridLayout setMargin(int all) { super.setMargin(all); return this; } @Override public PDFGridLayout setMargin(int horizontal, int vertical) { super.setMargin(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(int all) { super.setPadding(all); return this; } @Override public PDFGridLayout setPadding(int horizontal, int vertical) { super.setPadding(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(Rect padding) { super.setPadding(padding); return this; } @Override public PDFGridLayout setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); return this; } @Override
public PDFGridLayout setBorder(Action<Border, Border> action) {
1
2023-11-15 08:05:28+00:00
8k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/abilities/NetherSpawn.java
[ { "identifier": "OriginSwapper", "path": "src/main/java/com/starshootercity/OriginSwapper.java", "snippet": "public class OriginSwapper implements Listener {\n private final static NamespacedKey displayKey = new NamespacedKey(OriginsReborn.getInstance(), \"display-item\");\n private final static NamespacedKey confirmKey = new NamespacedKey(OriginsReborn.getInstance(), \"confirm-select\");\n private final static NamespacedKey originKey = new NamespacedKey(OriginsReborn.getInstance(), \"origin-name\");\n private final static NamespacedKey swapTypeKey = new NamespacedKey(OriginsReborn.getInstance(), \"swap-type\");\n private final static NamespacedKey pageSetKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-set\");\n private final static NamespacedKey pageScrollKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-scroll\");\n private final static Random random = new Random();\n\n public static String getInverse(String string) {\n StringBuilder result = new StringBuilder();\n for (char c : string.toCharArray()) {\n result.append(getInverse(c));\n }\n return result.toString();\n }\n\n public static void openOriginSwapper(Player player, PlayerSwapOriginEvent.SwapReason reason, int slot, int scrollAmount, boolean forceRandom) {\n if (OriginLoader.origins.size() == 0) return;\n boolean enableRandom = OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.random-option.enabled\");\n while (slot > OriginLoader.origins.size() || slot == OriginLoader.origins.size() && !enableRandom) {\n slot -= OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n while (slot < 0) {\n slot += OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n ItemStack icon;\n String name;\n char impact;\n LineData data;\n if (slot == OriginLoader.origins.size()) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n icon = OrbOfOrigin.orb;\n name = \"Random\";\n impact = '\\uE002';\n StringBuilder names = new StringBuilder(\"You'll be assigned one of the following:\\n\\n\");\n for (Origin origin : OriginLoader.origins) {\n if (!excludedOrigins.contains(origin.getName())) {\n names.append(origin.getName()).append(\"\\n\");\n }\n }\n data = new LineData(LineData.makeLineFor(\n names.toString(),\n LineData.LineComponent.LineType.DESCRIPTION\n ));\n } else {\n Origin origin = OriginLoader.origins.get(slot);\n icon = origin.getIcon();\n name = origin.getName();\n impact = origin.getImpact();\n data = new LineData(origin);\n }\n StringBuilder compressedName = new StringBuilder(\"\\uF001\");\n for (char c : name.toCharArray()) {\n compressedName.append(c);\n compressedName.append('\\uF000');\n }\n Component component = Component.text(\"\\uF000\\uE000\\uF001\\uE001\\uF002\" + impact)\n .font(Key.key(\"minecraft:origin_selector\"))\n .color(NamedTextColor.WHITE)\n .append(Component.text(compressedName.toString())\n .font(Key.key(\"minecraft:origin_title_text\"))\n .color(NamedTextColor.WHITE)\n )\n .append(Component.text(getInverse(name) + \"\\uF000\")\n .font(Key.key(\"minecraft:reverse_text\"))\n .color(NamedTextColor.WHITE)\n );\n for (Component c : data.getLines(scrollAmount)) {\n component = component.append(c);\n }\n Inventory swapperInventory = Bukkit.createInventory(null, 54,\n component\n );\n ItemMeta meta = icon.getItemMeta();\n meta.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name.toLowerCase());\n if (meta instanceof SkullMeta skullMeta) {\n skullMeta.setOwningPlayer(player);\n }\n meta.getPersistentDataContainer().set(displayKey, PersistentDataType.BOOLEAN, true);\n meta.getPersistentDataContainer().set(swapTypeKey, PersistentDataType.STRING, reason.getReason());\n icon.setItemMeta(meta);\n swapperInventory.setItem(1, icon);\n ItemStack confirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack invisibleConfirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta confirmMeta = confirm.getItemMeta();\n ItemMeta invisibleConfirmMeta = invisibleConfirm.getItemMeta();\n\n confirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n confirmMeta.setCustomModelData(5);\n confirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n invisibleConfirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n invisibleConfirmMeta.setCustomModelData(6);\n invisibleConfirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n if (!forceRandom) {\n ItemStack left = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack right = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack up = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack down = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta leftMeta = left.getItemMeta();\n ItemMeta rightMeta = right.getItemMeta();\n ItemMeta upMeta = up.getItemMeta();\n ItemMeta downMeta = down.getItemMeta();\n\n leftMeta.displayName(Component.text(\"Previous origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n leftMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot - 1);\n leftMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n leftMeta.setCustomModelData(1);\n\n\n rightMeta.displayName(Component.text(\"Next origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n rightMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot + 1);\n rightMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n rightMeta.setCustomModelData(2);\n\n int scrollSize = OriginsReborn.getInstance().getConfig().getInt(\"origin-selection.scroll-amount\", 1);\n\n upMeta.displayName(Component.text(\"Up\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (scrollAmount != 0) {\n upMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n upMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.max(scrollAmount - scrollSize, 0));\n }\n upMeta.setCustomModelData(3 + (scrollAmount == 0 ? 6 : 0));\n\n\n int size = data.lines.size() - scrollAmount - 6;\n boolean canGoDown = size > 0;\n\n downMeta.displayName(Component.text(\"Down\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (canGoDown) {\n downMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n downMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.min(scrollAmount + scrollSize, scrollAmount + size));\n }\n downMeta.setCustomModelData(4 + (!canGoDown ? 6 : 0));\n\n left.setItemMeta(leftMeta);\n right.setItemMeta(rightMeta);\n up.setItemMeta(upMeta);\n down.setItemMeta(downMeta);\n\n swapperInventory.setItem(47, left);\n swapperInventory.setItem(51, right);\n swapperInventory.setItem(52, up);\n swapperInventory.setItem(53, down);\n }\n\n confirm.setItemMeta(confirmMeta);\n invisibleConfirm.setItemMeta(invisibleConfirmMeta);\n swapperInventory.setItem(48, confirm);\n swapperInventory.setItem(49, invisibleConfirm);\n swapperInventory.setItem(50, invisibleConfirm);\n player.openInventory(swapperInventory);\n }\n\n @EventHandler\n public void onInventoryClick(InventoryClickEvent event) {\n ItemStack item = event.getWhoClicked().getOpenInventory().getItem(1);\n if (item != null) {\n if (item.getItemMeta() == null) return;\n if (item.getItemMeta().getPersistentDataContainer().has(displayKey)) {\n event.setCancelled(true);\n }\n if (event.getWhoClicked() instanceof Player player) {\n ItemStack currentItem = event.getCurrentItem();\n if (currentItem == null) return;\n Integer page = currentItem.getItemMeta().getPersistentDataContainer().get(pageSetKey, PersistentDataType.INTEGER);\n if (page != null) {\n Integer scroll = currentItem.getItemMeta().getPersistentDataContainer().get(pageScrollKey, PersistentDataType.INTEGER);\n if (scroll == null) return;\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n openOriginSwapper(player, getReason(item), page, scroll, false);\n }\n if (currentItem.getItemMeta().getPersistentDataContainer().has(confirmKey)) {\n String originName = item.getItemMeta().getPersistentDataContainer().get(originKey, PersistentDataType.STRING);\n if (originName == null) return;\n Origin origin;\n if (originName.equalsIgnoreCase(\"random\")) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n List<Origin> origins = new ArrayList<>(OriginLoader.origins);\n origins.removeIf(origin1 -> excludedOrigins.contains(origin1.getName()));\n if (origins.isEmpty()) {\n origin = OriginLoader.origins.get(0);\n } else {\n origin = origins.get(random.nextInt(origins.size()));\n }\n } else {\n origin = OriginLoader.originNameMap.get(originName);\n }\n PlayerSwapOriginEvent.SwapReason reason = getReason(item);\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n player.closeInventory();\n\n ItemMeta meta = player.getInventory().getItemInMainHand().getItemMeta();\n\n if (reason == PlayerSwapOriginEvent.SwapReason.ORB_OF_ORIGIN) {\n EquipmentSlot hand = null;\n if (meta != null) {\n if (meta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.HAND;\n }\n }\n if (hand == null) {\n ItemMeta offhandMeta = player.getInventory().getItemInOffHand().getItemMeta();\n if (offhandMeta != null) {\n if (offhandMeta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.OFF_HAND;\n }\n }\n }\n if (hand == null) return;\n orbCooldown.put(player, System.currentTimeMillis());\n player.swingHand(hand);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.consume\")) {\n player.getInventory().getItem(hand).setAmount(player.getInventory().getItem(hand).getAmount() - 1);\n }\n }\n boolean resetPlayer = shouldResetPlayer(reason);\n setOrigin(player, origin, reason, resetPlayer);\n }\n }\n }\n }\n\n public boolean shouldResetPlayer(PlayerSwapOriginEvent.SwapReason reason) {\n return switch (reason) {\n case COMMAND -> OriginsReborn.getInstance().getConfig().getBoolean(\"swap-command.reset-player\");\n case ORB_OF_ORIGIN -> OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.reset-player\");\n default -> false;\n };\n }\n\n public static int getWidth(char c) {\n return switch (c) {\n case ':', '.', '\\'', 'i', ';', '|', '!', ',', '\\uF00A' -> 2;\n case 'l', '`' -> 3;\n case '(', '}', ')', '*', '[', ']', '{', '\"', 'I', 't', ' ' -> 4;\n case '<', 'k', '>', 'f' -> 5;\n case '^', '/', 'X', 'W', 'g', 'h', '=', 'x', 'J', '\\\\', 'n', 'y', 'w', 'L', 'j', 'Z', '1', '?', '-', 'G', 'H', 'K', 'N', '0', '7', '8', 'O', 'V', 'p', 'Y', 'z', '+', 'A', '2', 'd', 'T', 'B', 'b', 'R', 'q', 'F', 'Q', 'a', '6', 'e', 'C', 'U', '3', 'S', '#', 'P', 'M', '9', 'v', '_', 'o', 'm', '&', 'u', 'c', 'D', 'E', '4', '5', 'r', 's', '$', '%' -> 6;\n case '@', '~' -> 7;\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static int getWidth(String s) {\n int result = 0;\n for (char c : s.toCharArray()) {\n result += getWidth(c);\n }\n return result;\n }\n\n public static char getInverse(char c) {\n return switch (getWidth(c)) {\n case 2 -> '\\uF001';\n case 3 -> '\\uF002';\n case 4 -> '\\uF003';\n case 5 -> '\\uF004';\n case 6 -> '\\uF005';\n case 7 -> '\\uF006';\n case 8 -> '\\uF007';\n case 9 -> '\\uF008';\n case 10 -> '\\uF009';\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static Map<Player, Long> orbCooldown = new HashMap<>();\n\n public static void resetPlayer(Player player, boolean full) {\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n speedInstance.removeModifier(player.getUniqueId());\n }\n ClientboundSetBorderWarningDistancePacket warningDistancePacket = new ClientboundSetBorderWarningDistancePacket(new WorldBorder() {{\n setWarningBlocks(player.getWorld().getWorldBorder().getWarningDistance());\n }});\n ((CraftPlayer) player).getHandle().connection.send(warningDistancePacket);\n player.setCooldown(Material.SHIELD, 0);\n player.setAllowFlight(false);\n player.setFlying(false);\n for (Player otherPlayer : Bukkit.getOnlinePlayers()) {\n AbilityRegister.updateEntity(player, otherPlayer);\n }\n AttributeInstance instance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n double maxHealth = getMaxHealth(player);\n if (instance != null) {\n instance.setBaseValue(maxHealth);\n }\n for (PotionEffect effect : player.getActivePotionEffects()) {\n if (effect.getAmplifier() == -1 || effect.getDuration() == PotionEffect.INFINITE_DURATION) player.removePotionEffect(effect.getType());\n }\n if (!full) return;\n player.getInventory().clear();\n player.getEnderChest().clear();\n player.setSaturation(5);\n player.setFallDistance(0);\n player.setRemainingAir(player.getMaximumAir());\n player.setFoodLevel(20);\n player.setFireTicks(0);\n player.setHealth(maxHealth);\n ShulkerInventory.getInventoriesConfig().set(player.getUniqueId().toString(), null);\n for (PotionEffect effect : player.getActivePotionEffects()) {\n player.removePotionEffect(effect.getType());\n }\n World world = getRespawnWorld(getOrigin(player));\n player.teleport(world.getSpawnLocation());\n player.setBedSpawnLocation(null);\n }\n\n public static @NotNull World getRespawnWorld(@Nullable Origin origin) {\n if (origin != null) {\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof DefaultSpawnAbility defaultSpawnAbility) {\n World world = defaultSpawnAbility.getWorld();\n if (world != null) return world;\n }\n }\n }\n String overworld = OriginsReborn.getInstance().getConfig().getString(\"worlds.world\");\n if (overworld == null) {\n overworld = \"world\";\n OriginsReborn.getInstance().getConfig().set(\"worlds.world\", \"world\");\n OriginsReborn.getInstance().saveConfig();\n }\n World world = Bukkit.getWorld(overworld);\n if (world == null) return Bukkit.getWorlds().get(0);\n return world;\n }\n\n public static double getMaxHealth(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 20;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof HealthModifierAbility healthModifierAbility) {\n return healthModifierAbility.getHealth();\n }\n }\n return 20;\n }\n\n public static double getSpeedIncrease(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 0;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof SpeedModifierAbility speedModifierAbility) {\n return speedModifierAbility.getSpeedIncrease();\n }\n }\n return 0;\n }\n\n @EventHandler\n public void onServerTickEnd(ServerTickEndEvent event) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (getOrigin(player) == null) {\n if (player.isDead()) continue;\n if (player.getOpenInventory().getType() != InventoryType.CHEST) {\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(player, PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(player, PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n } else {\n AttributeInstance healthInstance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n if (healthInstance != null) healthInstance.setBaseValue(getMaxHealth(player));\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n AttributeModifier modifier = speedInstance.getModifier(player.getUniqueId());\n if (modifier == null) {\n modifier = new AttributeModifier(player.getUniqueId(), \"speed-increase\", getSpeedIncrease(player), AttributeModifier.Operation.MULTIPLY_SCALAR_1);\n speedInstance.addModifier(modifier);\n }\n }\n player.setAllowFlight(AbilityRegister.canFly(player));\n player.setFlySpeed(AbilityRegister.getFlySpeed(player));\n player.setInvisible(AbilityRegister.isInvisible(player));\n }\n }\n }\n\n public void selectRandomOrigin(Player player, PlayerSwapOriginEvent.SwapReason reason) {\n Origin origin = OriginLoader.origins.get(random.nextInt(OriginLoader.origins.size()));\n setOrigin(player, origin, reason, shouldResetPlayer(reason));\n openOriginSwapper(player, reason, OriginLoader.origins.indexOf(origin), 0, true);\n }\n\n @EventHandler\n public void onPlayerRespawn(PlayerRespawnEvent event) {\n if (event.getPlayer().getBedSpawnLocation() == null) {\n World world = getRespawnWorld(getOrigin(event.getPlayer()));\n event.setRespawnLocation(world.getSpawnLocation());\n }\n if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) return;\n FileConfiguration config = OriginsReborn.getInstance().getConfig();\n if (config.getBoolean(\"origin-selection.death-origin-change\")) {\n setOrigin(event.getPlayer(), null, PlayerSwapOriginEvent.SwapReason.DIED, false);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n }\n\n public PlayerSwapOriginEvent.SwapReason getReason(ItemStack icon) {\n return PlayerSwapOriginEvent.SwapReason.get(icon.getItemMeta().getPersistentDataContainer().get(swapTypeKey, PersistentDataType.STRING));\n }\n\n public static Origin getOrigin(Player player) {\n if (player.getPersistentDataContainer().has(originKey)) {\n return OriginLoader.originNameMap.get(player.getPersistentDataContainer().get(originKey, PersistentDataType.STRING));\n } else {\n String name = originFileConfiguration.getString(player.getUniqueId().toString());\n if (name == null) return null;\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name);\n return OriginLoader.originNameMap.get(name);\n }\n }\n public static void setOrigin(Player player, @Nullable Origin origin, PlayerSwapOriginEvent.SwapReason reason, boolean resetPlayer) {\n PlayerSwapOriginEvent swapOriginEvent = new PlayerSwapOriginEvent(player, reason, resetPlayer, getOrigin(player), origin);\n if (!swapOriginEvent.callEvent()) return;\n if (swapOriginEvent.getNewOrigin() == null) {\n originFileConfiguration.set(player.getUniqueId().toString(), null);\n player.getPersistentDataContainer().remove(originKey);\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n return;\n }\n originFileConfiguration.set(player.getUniqueId().toString(), swapOriginEvent.getNewOrigin().getName().toLowerCase());\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, swapOriginEvent.getNewOrigin().getName().toLowerCase());\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n }\n\n\n private static File originFile;\n private static FileConfiguration originFileConfiguration;\n public OriginSwapper() {\n originFile = new File(OriginsReborn.getInstance().getDataFolder(), \"selected-origins.yml\");\n if (!originFile.exists()) {\n boolean ignored = originFile.getParentFile().mkdirs();\n OriginsReborn.getInstance().saveResource(\"selected-origins.yml\", false);\n }\n originFileConfiguration = new YamlConfiguration();\n try {\n originFileConfiguration.load(originFile);\n } catch (IOException | InvalidConfigurationException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void saveOrigins() {\n try {\n originFileConfiguration.save(originFile);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static class LineData {\n public static List<LineComponent> makeLineFor(String text, LineComponent.LineType type) {\n StringBuilder result = new StringBuilder();\n List<LineComponent> list = new ArrayList<>();\n List<String> splitLines = new ArrayList<>(Arrays.stream(text.split(\"\\n\", 2)).toList());\n StringBuilder otherPart = new StringBuilder();\n String firstLine = splitLines.remove(0);\n if (firstLine.contains(\" \") && getWidth(firstLine) > 140) {\n List<String> split = new ArrayList<>(Arrays.stream(firstLine.split(\" \")).toList());\n StringBuilder firstPart = new StringBuilder(split.get(0));\n split.remove(0);\n boolean canAdd = true;\n for (String s : split) {\n if (canAdd && getWidth(firstPart + \" \" + s) <= 140) {\n firstPart.append(\" \");\n firstPart.append(s);\n } else {\n canAdd = false;\n if (otherPart.length() > 0) otherPart.append(\" \");\n otherPart.append(s);\n }\n }\n firstLine = firstPart.toString();\n }\n for (String s : splitLines) {\n if (otherPart.length() > 0) otherPart.append(\"\\n\");\n otherPart.append(s);\n }\n if (type == LineComponent.LineType.DESCRIPTION) firstLine = '\\uF00A' + firstLine;\n for (char c : firstLine.toCharArray()) {\n result.append(c);\n result.append('\\uF000');\n }\n String finalText = firstLine;\n list.add(new LineComponent(\n Component.text(result.toString())\n .color(type == LineComponent.LineType.TITLE ? NamedTextColor.WHITE : TextColor.fromHexString(\"#CACACA\"))\n .append(Component.text(getInverse(finalText))),\n type\n ));\n if (otherPart.length() != 0) {\n list.addAll(makeLineFor(otherPart.toString(), type));\n }\n return list;\n }\n public static class LineComponent {\n public enum LineType {\n TITLE,\n DESCRIPTION\n }\n private final Component component;\n private final LineType type;\n\n public LineComponent(Component component, LineType type) {\n this.component = component;\n this.type = type;\n }\n\n public LineComponent() {\n this.type = LineType.DESCRIPTION;\n this.component = Component.empty();\n }\n\n public Component getComponent(int lineNumber) {\n @Subst(\"minecraft:text_line_0\") String formatted = \"minecraft:%stext_line_%s\".formatted(type == LineType.DESCRIPTION ? \"\" : \"title_\", lineNumber);\n return component.font(\n Key.key(formatted)\n );\n }\n }\n private final List<LineComponent> lines;\n public LineData(Origin origin) {\n lines = new ArrayList<>();\n lines.addAll(origin.getLineData());\n List<VisibleAbility> visibleAbilities = origin.getVisibleAbilities();\n int size = visibleAbilities.size();\n int count = 0;\n if (size > 0) lines.add(new LineComponent());\n for (VisibleAbility visibleAbility : visibleAbilities) {\n count++;\n lines.addAll(visibleAbility.getTitle());\n lines.addAll(visibleAbility.getDescription());\n if (count < size) lines.add(new LineComponent());\n }\n }\n public LineData(List<LineComponent> lines) {\n this.lines = lines;\n }\n\n public List<Component> getLines(int startingPoint) {\n List<Component> resultLines = new ArrayList<>();\n for (int i = startingPoint; i < startingPoint + 6 && i < lines.size(); i++) {\n resultLines.add(lines.get(i).getComponent(i - startingPoint));\n }\n return resultLines;\n }\n }\n}" }, { "identifier": "OriginsReborn", "path": "src/main/java/com/starshootercity/OriginsReborn.java", "snippet": "public class OriginsReborn extends JavaPlugin {\n private static OriginsReborn instance;\n\n public static OriginsReborn getInstance() {\n return instance;\n }\n\n private Economy economy;\n\n public Economy getEconomy() {\n return economy;\n }\n\n private boolean setupEconomy() {\n try {\n RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);\n if (economyProvider != null) {\n economy = economyProvider.getProvider();\n }\n return (economy != null);\n } catch (NoClassDefFoundError e) {\n return false;\n }\n }\n\n private boolean vaultEnabled;\n\n public boolean isVaultEnabled() {\n return vaultEnabled;\n }\n\n @Override\n public void onEnable() {\n instance = this;\n\n if (getConfig().getBoolean(\"swap-command.vault.enabled\")) {\n vaultEnabled = setupEconomy();\n if (!vaultEnabled) {\n getLogger().warning(\"Vault is not missing, origin swaps will not cost currency\");\n }\n } else vaultEnabled = false;\n saveDefaultConfig();\n PluginCommand command = getCommand(\"origin\");\n if (command != null) command.setExecutor(new OriginCommand());\n OriginLoader.loadOrigins();\n Bukkit.getPluginManager().registerEvents(new OriginSwapper(), this);\n Bukkit.getPluginManager().registerEvents(new OrbOfOrigin(), this);\n Bukkit.getPluginManager().registerEvents(new BreakSpeedModifierAbility.BreakSpeedModifierAbilityListener(), this);\n\n //<editor-fold desc=\"Register abilities\">\n List<Ability> abilities = new ArrayList<>() {{\n add(new PumpkinHate());\n add(new FallImmunity());\n add(new WeakArms());\n add(new Fragile());\n add(new SlowFalling());\n add(new FreshAir());\n add(new Vegetarian());\n add(new LayEggs());\n add(new Unwieldy());\n add(new MasterOfWebs());\n add(new Tailwind());\n add(new Arthropod());\n add(new Climbing());\n add(new Carnivore());\n add(new WaterBreathing());\n add(new WaterVision());\n add(new CatVision());\n add(new NineLives());\n add(new BurnInDaylight());\n add(new WaterVulnerability());\n add(new Phantomize());\n add(new Invisibility());\n add(new ThrowEnderPearl());\n add(new PhantomizeOverlay());\n add(new FireImmunity());\n add(new AirFromPotions());\n add(new SwimSpeed());\n add(new LikeWater());\n add(new LightArmor());\n add(new MoreKineticDamage());\n add(new DamageFromPotions());\n add(new DamageFromSnowballs());\n add(new Hotblooded());\n add(new BurningWrath());\n add(new SprintJump());\n add(new AerialCombatant());\n add(new Elytra());\n add(new LaunchIntoAir());\n add(new HungerOverTime());\n add(new MoreExhaustion());\n add(new Aquatic());\n add(new NetherSpawn());\n add(new Claustrophobia());\n add(new VelvetPaws());\n add(new AquaAffinity());\n add(new FlameParticles());\n add(new EnderParticles());\n add(new Phasing());\n add(new ScareCreepers());\n add(new StrongArms());\n add(new StrongArmsBreakSpeed());\n }};\n for (Ability ability : abilities) {\n AbilityRegister.registerAbility(ability);\n }\n //</editor-fold>\n }\n}" } ]
import com.starshootercity.OriginSwapper; import com.starshootercity.OriginsReborn; import net.kyori.adventure.key.Key; import org.bukkit.Bukkit; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
7,191
package com.starshootercity.abilities; public class NetherSpawn implements DefaultSpawnAbility, VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:nether_spawn"); } @Override public @Nullable World getWorld() {
package com.starshootercity.abilities; public class NetherSpawn implements DefaultSpawnAbility, VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:nether_spawn"); } @Override public @Nullable World getWorld() {
String nether = OriginsReborn.getInstance().getConfig().getString("worlds.world_nether");
1
2023-11-10 21:39:16+00:00
8k
SoBadFish/Report
src/main/java/org/sobadfish/report/command/ReportCommand.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": "DisplayCustomForm", "path": "src/main/java/org/sobadfish/report/form/DisplayCustomForm.java", "snippet": "public class DisplayCustomForm {\n\n private final int id;\n\n public static int getRid(){\n return Utils.rand(11900,21000);\n }\n\n public DisplayCustomForm(int id){\n this.id = id;\n }\n\n\n\n public int getId() {\n return id;\n }\n\n public static LinkedHashMap<Player, DisplayCustomForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n public void disPlay(Player player, String target){\n\n FormWindowCustom formWindowCustom = new FormWindowCustom(TextFormat.colorize('&',\"&b举报系统\"));\n Config msg = ReportMainClass.getMainClass().getMessageConfig();\n formWindowCustom.addElement(new ElementLabel(TextFormat.colorize('&'\n ,msg.getString(\"report-form-msg\"))));\n List<String> onLinePlayers = new ArrayList<>();\n for(Player online: Server.getInstance().getOnlinePlayers().values()){\n if(online.equals(player)){\n continue;\n }\n onLinePlayers.add(online.getName());\n }\n if(target != null){\n onLinePlayers.add(target);\n }\n\n if(onLinePlayers.size() == 0){\n ReportMainClass.sendMessageToObject(\"&c没有可以举报的玩家\",player);\n return;\n }\n\n formWindowCustom.addElement(new ElementDropdown(\"请选择举报的玩家\",onLinePlayers,onLinePlayers.size()-1));\n List<String> showMsg = new ArrayList<>();\n for(String s:msg.getStringList(\"report-list\") ){\n showMsg.add(TextFormat.colorize('&',s));\n }\n formWindowCustom.addElement(new ElementDropdown(\"请选择举报原因\",showMsg));\n formWindowCustom.addElement(new ElementInput(\"请输入举报理由\"));\n\n player.showFormWindow(formWindowCustom,getId());\n DISPLAY_FROM.put(player,this);\n\n }\n\n public void onListener(Player player,FormResponseCustom responseCustom){\n PlayerInfo info = ReportMainClass.getMainClass().getPlayerInfoManager().getInfo(player.getName());\n String playerName = responseCustom.getDropdownResponse(1).getElementContent();\n String msg = responseCustom.getDropdownResponse(2).getElementContent()+\"&\"+TextFormat.colorize('&',responseCustom.getInputResponse(3));\n if(info != null){\n switch (info.addReport(playerName)){\n case SUCCESS:\n ReportMainClass.getDataManager().pullReport(playerName,msg,player.getName());\n ReportMainClass.sendMessageToObject(\"&b举报成功! 感谢你对服务器建设的支持 &7(等待管理员处理)\",player);\n break;\n case COLD:\n ReportMainClass.sendMessageToObject(\"&c举报太频繁了,请在 &r \"+info.getCold()+\" &c秒后重试\",player);\n break;\n case DAY_MAX:\n ReportMainClass.sendMessageToObject(\"&c今日举报次数达到上限,请明天再进行举报吧\",player);\n break;\n case HAS_TARGET:\n ReportMainClass.sendMessageToObject(\"&c你今日已经举报过他了\",player);\n break;\n case MY:\n ReportMainClass.sendMessageToObject(\"&c你不能举报自己\",player);\n break;\n default:break;\n }\n }\n\n }\n\n\n\n}" }, { "identifier": "DisplayForm", "path": "src/main/java/org/sobadfish/report/form/DisplayForm.java", "snippet": "public class DisplayForm {\n\n private static final int ITEM_SIZE = 6;\n\n public static LinkedHashMap<Player, DisplayForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n private ArrayList<BaseClickButton> clickButtons = new ArrayList<>();\n\n private List<String> players = new ArrayList<>();\n\n private int page = 1;\n\n private int id;\n\n public DisplayForm(int id){\n this.id = id;\n }\n\n public void setClickButtons(ArrayList<BaseClickButton> clickButtons) {\n this.clickButtons = clickButtons;\n }\n\n public ArrayList<BaseClickButton> getClickButtons() {\n return clickButtons;\n }\n\n public int getId() {\n return id;\n }\n\n public static int getRid(){\n return Utils.rand(1890,118025);\n }\n\n public void disPlay(Player player){\n FormWindowSimple simple = new FormWindowSimple(TextFormat.colorize('&',\"&b举报系统\"),\"\");\n ArrayList<BaseClickButton> buttons = new ArrayList<>();\n if(players.size() == 0) {\n players = ReportMainClass.getDataManager().getPlayers();\n }\n if(players.size() > 0){\n for(String s: getArrayListByPage(page,players)){\n List<Report> reports = ReportMainClass.getDataManager().getReports(s);\n if(reports.size() == 0){\n continue;\n }\n Report nRepot = reports.get(0);\n String str = s.trim();\n str += \"\\n&4[New] &c\"+nRepot.getTime()+\" &r \"+reports.size()+\" &2条相关记录\";\n buttons.add(new BaseClickButton(new ElementButton(TextFormat.colorize('&',str),new ElementButtonImageData(\"path\"\n ,\"textures/ui/Friend2\")),s) {\n @Override\n public void onClick(Player player) {\n DisplayManageForm fromButton = new DisplayManageForm(DisplayManageForm.getRid());\n fromButton.disPlay(player,getTarget());\n\n }\n });\n }\n }else{\n ReportMainClass.sendMessageToObject(\"&c无举报记录\",player);\n return;\n }\n if(mathPage((ArrayList<?>) players) > 1) {\n if (page == 1) {\n addNext(buttons);\n }else if(page != mathPage((ArrayList<?>) players)){\n addLast(buttons);\n addNext(buttons);\n\n }else{\n addLast(buttons);\n\n }\n }\n for(BaseClickButton button: buttons){\n simple.addButton(button.getButton());\n }\n player.showFormWindow(simple,getId());\n setClickButtons(buttons);\n DISPLAY_FROM.put(player,this);\n\n }\n\n private void addLast(ArrayList<BaseClickButton> buttons){\n buttons.add(new BaseClickButton(new ElementButton(\"上一页\", new ElementButtonImageData(\"path\", \"textures/ui/arrow_dark_left_stretch\")), null) {\n @Override\n public void onClick(Player player) {\n DisplayForm from = DISPLAY_FROM.get(player);\n from.setId(getRid());\n from.page--;\n from.disPlay(player);\n\n\n }\n });\n }\n\n private void addNext(ArrayList<BaseClickButton> buttons){\n buttons.add(new BaseClickButton(new ElementButton(\"下一页\", new ElementButtonImageData(\"path\", \"textures/ui/arrow_dark_right_stretch\")), null) {\n @Override\n public void onClick(Player player) {\n DisplayForm from = DISPLAY_FROM.get(player);\n from.setId(getRid());\n from.page++;\n from.disPlay(player);\n }\n });\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public <T> ArrayList<T> getArrayListByPage(int page, List<T> list){\n ArrayList<T> button = new ArrayList<>();\n for(int i = (page - 1) * ITEM_SIZE; i < ITEM_SIZE + ((page - 1) * ITEM_SIZE);i++){\n if(list.size() > i){\n button.add(list.get(i));\n }\n }\n return button;\n }\n\n public int mathPage(ArrayList<?> button){\n if(button.size() == 0){\n return 1;\n }\n return (int) Math.ceil(button.size() / (double)ITEM_SIZE);\n }\n\n\n\n}" }, { "identifier": "DisplayHistoryForm", "path": "src/main/java/org/sobadfish/report/form/DisplayHistoryForm.java", "snippet": "public class DisplayHistoryForm {\n\n private ArrayList<BaseClickButton> clickButtons = new ArrayList<>();\n\n public static LinkedHashMap<Player, DisplayHistoryForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n private final int id;\n\n public static int getRid(){\n return Utils.rand(31000,41000);\n }\n\n public ArrayList<BaseClickButton> getClickButtons() {\n return clickButtons;\n }\n\n public String target;\n\n public DisplayHistoryForm(int id){\n this.id = id;\n }\n\n\n public int getId() {\n return id;\n }\n\n public void disPlay(Player player,String target) {\n FormWindowSimple simple = new FormWindowSimple(TextFormat.colorize('&', \"&b举报系统 &7—— &e记录\"), \"\");\n\n int reportsSize = ReportMainClass.getDataManager().getHistoryPlayers(player.getName(),target).size();\n\n List<String> reportsList = ReportMainClass.getDataManager().getHistoryPlayers(null,target);\n\n if(reportsList.size() == 0){\n ReportMainClass.sendMessageToObject(\"&c暂无处理记录\",player);\n return;\n }\n ArrayList<BaseClickButton> buttons = new ArrayList<>();\n String str = \"服务器累计处理 \"+reportsList.size()+\" 条举报! 您已处理 \"+reportsSize+\" 条\";\n simple.setContent(str);\n for(String s:reportsList){\n List<Report> reps = ReportMainClass.getDataManager().getHistoryReports(s);\n Report rp = reps.get(0);\n String s2 = s+\"\\n&c[New]\"+rp.getManagerTime()+\" &r\"+reps.size()+\" &2条举报记录\";\n buttons.add(new BaseClickButton(new ElementButton(TextFormat.colorize('&',s2),new ElementButtonImageData(\"path\"\n ,\"textures/ui/Friend2\")),s) {\n @Override\n public void onClick(Player player) {\n FormWindowSimple simple1 = new FormWindowSimple(TextFormat.colorize('&',\"&b举报系统 &7—— &e记录 &7—— &2\"+getTarget())\n ,\"\");\n String target = getTarget();\n StringBuilder stringBuilder = new StringBuilder();\n List<Report> reports = ReportMainClass.getDataManager().getHistoryReports(target);\n stringBuilder.append(\"&l&r被举报玩家: &r&a\").append(target).append(\"&r\\n\\n\");\n stringBuilder.append(\"&r&l举报原因:&r \\n\");\n for(Report report: reports){\n String[] rel = Utils.splitMsg(report.getReportMessage());\n\n stringBuilder.append(\" &7[\").append(report.getTime()).append(\"]&r &e\")\n .append(report.getTarget()).append(\" &7:>>&r\\n\").append(\"&7(&l\")\n .append(rel[0]).append(\"&r&7)&r: \").append(rel[1]).append(\"&r\\n\");\n }\n stringBuilder.append(\"\\n&r&l处理记录: \").append(\"\\n\");\n StringBuilder mg = new StringBuilder();\n for(Report report: reports){\n if(!\"\".equalsIgnoreCase(report.getManager())){\n mg.append(\" &l&7[&e\").append(report.getManagerTime()).append(\"&7] &2\")\n .append(report.getManager()).append(\"&r: \").append(report.getManagerMsg()).append(\"&r\\n\");\n }\n\n }\n stringBuilder.append(mg);\n simple1.setContent(TextFormat.colorize('&',stringBuilder.toString()));\n player.showFormWindow(simple1,getRid());\n }\n });\n\n }\n for(BaseClickButton button: buttons){\n simple.addButton(button.getButton());\n }\n\n setClickButtons(buttons);\n player.showFormWindow(simple,getId());\n DISPLAY_FROM.put(player,this);\n\n\n }\n\n public void setClickButtons(ArrayList<BaseClickButton> clickButtons) {\n this.clickButtons = clickButtons;\n }\n\n}" } ]
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import org.sobadfish.report.ReportMainClass; import org.sobadfish.report.form.DisplayCustomForm; import org.sobadfish.report.form.DisplayForm; import org.sobadfish.report.form.DisplayHistoryForm; import java.util.List;
4,542
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){ DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid()); displayFrom.disPlay((Player) commandSender); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } break; case "p": if(commandSender.isOp()){ if(strings.length > 1){ String player = strings[1]; Player online = Server.getInstance().getPlayer(player); if(online != null){ player = online.getName(); } List<String> players = ReportMainClass.getMainClass().getAdminPlayers(); if(players.contains(player)){ players.remove(player); if(online != null){ ReportMainClass.sendMessageToObject("&c你已不是协管!",online); } ReportMainClass.sendMessageToObject("&a成功取消玩家 "+player+" 的协管身份", commandSender); ReportMainClass.getMainClass().saveAdminPlayers(); }else{ players.add(player); ReportMainClass.getMainClass().saveAdminPlayers(); if(online != null){ ReportMainClass.sendMessageToObject("&a你已成为协管!",online); ReportMainClass.sendMessageToObject("&a成功增加玩家 "+player+" 的协管身份", commandSender); } } } } break; case "m": if(strings.length > 2){ String player = strings[1]; String msg = strings[2]; Player online = Server.getInstance().getPlayer(player); if(online != null){ ReportMainClass.sendMessageToObject("&c您已被警告!&7 (&r"+msg+"&r&7)",online); } } break; case "h": if(commandSender instanceof Player){ String player = null; if(strings.length > 1){ player = strings[1]; }
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){ DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid()); displayFrom.disPlay((Player) commandSender); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } break; case "p": if(commandSender.isOp()){ if(strings.length > 1){ String player = strings[1]; Player online = Server.getInstance().getPlayer(player); if(online != null){ player = online.getName(); } List<String> players = ReportMainClass.getMainClass().getAdminPlayers(); if(players.contains(player)){ players.remove(player); if(online != null){ ReportMainClass.sendMessageToObject("&c你已不是协管!",online); } ReportMainClass.sendMessageToObject("&a成功取消玩家 "+player+" 的协管身份", commandSender); ReportMainClass.getMainClass().saveAdminPlayers(); }else{ players.add(player); ReportMainClass.getMainClass().saveAdminPlayers(); if(online != null){ ReportMainClass.sendMessageToObject("&a你已成为协管!",online); ReportMainClass.sendMessageToObject("&a成功增加玩家 "+player+" 的协管身份", commandSender); } } } } break; case "m": if(strings.length > 2){ String player = strings[1]; String msg = strings[2]; Player online = Server.getInstance().getPlayer(player); if(online != null){ ReportMainClass.sendMessageToObject("&c您已被警告!&7 (&r"+msg+"&r&7)",online); } } break; case "h": if(commandSender instanceof Player){ String player = null; if(strings.length > 1){ player = strings[1]; }
DisplayHistoryForm displayHistoryForm = new DisplayHistoryForm(DisplayHistoryForm.getRid());
3
2023-11-15 03:08:23+00:00
8k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/InventoryAPIImpl.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": "PluginReloadEndEvent", "path": "api/src/main/java/kor/toxicity/inventory/api/event/PluginReloadEndEvent.java", "snippet": "public final class PluginReloadEndEvent extends Event implements InventoryAPIEvent {\n public PluginReloadEndEvent() {\n super(true);\n }\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return HANDLER_LIST;\n }\n public static HandlerList getHandlerList() {\n return HANDLER_LIST;\n }\n}" }, { "identifier": "PluginReloadStartEvent", "path": "api/src/main/java/kor/toxicity/inventory/api/event/PluginReloadStartEvent.java", "snippet": "public final class PluginReloadStartEvent extends Event implements InventoryAPIEvent {\n public PluginReloadStartEvent() {\n super(true);\n }\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return HANDLER_LIST;\n }\n public static HandlerList getHandlerList() {\n return HANDLER_LIST;\n }\n}" }, { "identifier": "InventoryManager", "path": "api/src/main/java/kor/toxicity/inventory/api/manager/InventoryManager.java", "snippet": "public interface InventoryManager {\n void reload();\n}" }, { "identifier": "FontManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/FontManagerImpl.java", "snippet": "public class FontManagerImpl implements FontManager {\n private final FontRegistryImpl fontRegistry = new FontRegistryImpl();\n @Override\n public void reload() {\n fontRegistry.clear();\n PluginUtil.loadFolder(\"fonts\", f -> {\n var name = PluginUtil.getFileName(f);\n switch (name.extension().toLowerCase()) {\n case \"ttf\", \"oft\" -> {\n try (var stream = new BufferedInputStream(new FileInputStream(f))) {\n fontRegistry.register(name.name(), Font.createFont(Font.TRUETYPE_FONT, stream));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to read this font: \" + f.getName());\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n }\n }\n });\n }\n\n @Override\n public @NotNull Registry<Font> getRegistry() {\n return fontRegistry;\n }\n}" }, { "identifier": "ImageManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/ImageManagerImpl.java", "snippet": "public class ImageManagerImpl implements ImageManager {\n private final ImageRegistryImpl imageRegistry = new ImageRegistryImpl();\n @Override\n public void reload() {\n imageRegistry.clear();\n PluginUtil.loadFolder(\"images\", f -> {\n var name = PluginUtil.getFileName(f);\n if (name.extension().equalsIgnoreCase(\"png\")) {\n try {\n imageRegistry.register(name.name(), ImageIO.read(f));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to read this image: \" + f.getName());\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n }\n });\n }\n\n @Override\n public @NotNull Registry<BufferedImage> getRegistry() {\n return imageRegistry;\n }\n}" }, { "identifier": "ResourcePackManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/ResourcePackManagerImpl.java", "snippet": "public class ResourcePackManagerImpl implements ResourcePackManager {\n private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();\n private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();\n private final List<ImageObjectGeneratorImpl> images = new ArrayList<>();\n @Getter\n private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR;\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @Override\n public void reload() {\n var topFolder = getFile(getFile(InventoryAPI.getInstance().getDataFolder(), \".generated\"), \"assets\");\n var assets = getFile(topFolder, \"inventory\");\n var font = getFile(assets, \"font\");\n var fontFont = getFile(font, \"font\");\n var textures = getFile(assets, \"textures\");\n var texturesFont = getFile(textures, \"font\");\n var texturesFontGui = getFile(texturesFont, \"gui\");\n var texturesFontFont = getFile(texturesFont, \"font\");\n var models = getFile(getFile(getFile(topFolder, \"minecraft\"), \"models\"),\"item\");\n\n var config = new File(InventoryAPI.getInstance().getDataFolder(), \"config.yml\");\n if (!config.exists()) InventoryAPI.getInstance().saveResource(\"config.yml\", false);\n try {\n var yaml = YamlConfiguration.loadConfiguration(config).getString(\"default-empty-material\");\n if (yaml != null) emptyMaterial = Material.valueOf(yaml.toUpperCase());\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to load config.yml\");\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n var emptyMaterialLowerCase = emptyMaterial.name().toLowerCase();\n var modelsFile = new File(models, emptyMaterialLowerCase + \".json\");\n var modelsJson = new JsonObjectBuilder()\n .add(\"parent\", \"item/generated\")\n .add(\"textures\", new JsonObjectBuilder()\n .add(\"layer0\", \"minecraft:item/\" + emptyMaterialLowerCase)\n .build()\n )\n .add(\"overrides\", new JsonArrayBuilder()\n .add(new JsonObjectBuilder()\n .add(\"predicate\", new JsonObjectBuilder()\n .add(\"custom_model_data\", 1)\n .build())\n .add(\"model\", \"inventory:item/empty\")\n .build()\n )\n .build()\n )\n .build();\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(modelsFile)))) {\n gson.toJson(modelsJson, writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to make a empty material file.\");\n }\n\n fonts.forEach(f -> {\n var targetFolder = new File(texturesFontFont, f.getFont().getName());\n var jsonFolder = new File(fontFont, f.getFontTitle() + \".json\");\n var guiFont = f.getFont();\n var available = guiFont.getAvailableChar();\n if (!targetFolder.exists()) {\n targetFolder.mkdir();\n var i = 0;\n var n = 1;\n var yAxis = (float) GuiFont.VERTICAL_SIZE * guiFont.getMetrics().getHeight();\n while (i < available.size()) {\n var image = new BufferedImage(16 * guiFont.getSize(), (int) (yAxis * 16), BufferedImage.TYPE_INT_ARGB);\n var graphics = image.createGraphics();\n graphics.setFont(guiFont.getFont());\n graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));\n graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);\n find: for (int i1 = 0; i1 < 16; i1++) {\n for (int i2 = 0; i2 < 16; i2++) {\n var getIndex = i + i1 * 16 + i2;\n if (getIndex >= available.size()) break find;\n graphics.drawString(Character.toString(available.get(getIndex)), (float) (i2 * guiFont.getSize()), (i1 + 0.75F) * yAxis);\n }\n }\n graphics.dispose();\n var pngName = f.getFont().getName() + \"_\" + (n++) + \".png\";\n try {\n ImageIO.write(image, \"png\", new File(targetFolder, pngName));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save this file: \" + pngName);\n }\n i += 256;\n }\n }\n if (!jsonFolder.exists()) {\n var i = 0;\n var n = 1;\n var json = new JsonArrayBuilder()\n .add(new JsonObjectBuilder()\n .add(\"type\", \"space\")\n .add(\"advances\", new JsonObjectBuilder()\n .add(\" \", 4)\n .build())\n .build())\n .build();\n while (i < available.size()) {\n var charArray = new JsonArray();\n find: for (int i1 = 0; i1 < 16; i1++) {\n var sb = new StringBuilder();\n for (int i2 = 0; i2 < 16; i2++) {\n var getIndex = i + i1 * 16 + i2;\n if (getIndex >= available.size()) break find;\n sb.append(available.get(getIndex));\n }\n charArray.add(sb.toString());\n }\n var pngName = f.getFont().getName() + \"_\" + (n++) + \".png\";\n json.add(new JsonObjectBuilder()\n .add(\"type\", \"bitmap\")\n .add(\"file\", \"inventory:font/font/\" + f.getFont().getName() + \"/\" + pngName)\n .add(\"ascent\", f.getAscent())\n .add(\"height\", f.getHeight())\n .add(\"chars\", charArray)\n .build());\n i += 256;\n }\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(jsonFolder)))) {\n gson.toJson(new JsonObjectBuilder()\n .add(\"providers\", json)\n .build(), writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save gui.json.\");\n }\n }\n });\n\n var array = new JsonArray();\n images.stream().sorted().forEach(i -> {\n var name = i.getImage().name() + \".png\";\n try {\n ImageIO.write(i.getImage().image(), \"png\", new File(texturesFontGui, name));\n array.add(new JsonObjectBuilder()\n .add(\"type\", \"bitmap\")\n .add(\"file\", \"inventory:font/gui/\" + name)\n .add(\"ascent\", i.getAscent())\n .add(\"height\", i.getHeight())\n .add(\"chars\", new JsonArrayBuilder()\n .add(i.getSerialChar())\n .build())\n .build());\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save this image: \" + name);\n }\n });\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(new File(font, \"gui.json\"))))) {\n gson.toJson(new JsonObjectBuilder()\n .add(\"providers\", array)\n .build(), writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save gui.json.\");\n }\n\n ImageObjectGeneratorImpl.initialize();\n fonts.clear();\n images.clear();\n }\n\n @Override\n public @NotNull GuiObjectGenerator registerTask(@NotNull GuiResource resource, int height, int ascent) {\n if (resource instanceof GuiFont guiFont) {\n var generator = new FontObjectGeneratorImpl(guiFont, height, ascent);\n fonts.add(generator);\n return generator;\n } else if (resource instanceof GuiImage image) {\n var generator = new ImageObjectGeneratorImpl(image, height, ascent);\n images.add(generator);\n return generator;\n } else throw new UnsupportedOperationException(\"unsupported type found.\");\n }\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n private static File getFile(File mother, String dir) {\n var file = new File(mother, dir);\n if (!file.exists()) file.mkdir();\n return file;\n }\n}" }, { "identifier": "AdventureUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/AdventureUtil.java", "snippet": "public class AdventureUtil {\n private static final Key SPACE_KEY = Key.key(\"inventory:space\");\n private AdventureUtil() {\n throw new SecurityException();\n }\n public static String parseChar(int i) {\n if (i <= 0xFFFF) return Character.toString((char) i);\n else {\n var t = i - 0x10000;\n return Character.toString((t >>> 10) + 0xD800) + Character.toString((t & ((1 << 10) - 1)) + 0xDC00);\n }\n }\n\n public static Component getSpaceFont(int i) {\n return Component.text(parseChar(i + 0xD0000)).font(SPACE_KEY);\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 kor.toxicity.inventory.api.InventoryAPI; import kor.toxicity.inventory.api.event.PluginReloadEndEvent; import kor.toxicity.inventory.api.event.PluginReloadStartEvent; import kor.toxicity.inventory.api.gui.*; import kor.toxicity.inventory.api.manager.InventoryManager; import kor.toxicity.inventory.manager.FontManagerImpl; import kor.toxicity.inventory.manager.ImageManagerImpl; import kor.toxicity.inventory.manager.ResourcePackManagerImpl; import kor.toxicity.inventory.util.AdventureUtil; import kor.toxicity.inventory.util.PluginUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.minimessage.Context; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.*; import java.util.List; import java.util.jar.JarFile;
4,353
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager();
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager();
var fontManager = new FontManagerImpl();
4
2023-11-13 00:19:46+00:00
8k